flattify 2.0.1 → 2.0.2
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/README.md +128 -83
- package/dist/{flatten-DWk2mUxV.cjs → flatten-BzHEOWOi.cjs} +7 -12
- package/dist/{flatten-CYe7gyYE.js → flatten-DD3D_40K.js} +7 -12
- package/dist/index.cjs +4 -5
- package/dist/index.d.cts +17 -7
- package/dist/index.d.ts +17 -7
- package/dist/index.js +4 -5
- package/dist/{path-types-BjuDIcLg.d.cts → path-types-CKfz-km1.d.cts} +0 -8
- package/dist/{path-types-BjuDIcLg.d.ts → path-types-CKfz-km1.d.ts} +0 -8
- package/dist/path.cjs +4 -5
- package/dist/path.d.cts +15 -5
- package/dist/path.d.ts +15 -5
- package/dist/path.js +4 -5
- package/package.json +11 -11
package/README.md
CHANGED
|
@@ -1,44 +1,69 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<a href="https://github.com/NandoMB/flattify">
|
|
4
|
+
<picture>
|
|
5
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/NandoMB/flattify/main/.github/assets/logo-dark.svg">
|
|
6
|
+
<img alt="flattify" src="https://raw.githubusercontent.com/NandoMB/flattify/main/.github/assets/logo-light.svg" height="76">
|
|
7
|
+
</picture>
|
|
8
|
+
</a>
|
|
9
|
+
|
|
10
|
+
<h3>Flatten nested objects into <code>path → value</code> pairs and back. Nothing gets lost, and TypeScript knows every path.</h3>
|
|
11
|
+
|
|
12
|
+
[](https://www.npmjs.com/package/flattify)
|
|
4
13
|
[](https://jsr.io/@nandomb/flattify)
|
|
5
14
|
[](https://jsr.io/@nandomb/flattify)
|
|
6
|
-
[](https://github.com/NandoMB/flattify/actions/workflows/main.yml)
|
|
16
|
+
[](https://bundlejs.com/?q=flattify)
|
|
17
|
+
[](https://www.npmjs.com/package/flattify)
|
|
18
|
+
[](#types)
|
|
19
|
+
[](./LICENSE)
|
|
9
20
|
[](https://socket.dev/npm/package/flattify)
|
|
10
21
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
22
|
+
<p>
|
|
23
|
+
<a href="#installation"><b>Install</b></a> ·
|
|
24
|
+
<a href="#quick-start"><b>Quick start</b></a> ·
|
|
25
|
+
<a href="#data-integrity"><b>Data integrity</b></a> ·
|
|
26
|
+
<a href="#why-flattify"><b>Why Flattify?</b></a> ·
|
|
27
|
+
<a href="#use-cases"><b>Use cases</b></a> ·
|
|
28
|
+
<a href="#api"><b>API</b></a> ·
|
|
29
|
+
<a href="#security"><b>Security</b></a>
|
|
30
|
+
</p>
|
|
31
|
+
|
|
32
|
+
<br>
|
|
33
|
+
|
|
34
|
+
<picture>
|
|
35
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/NandoMB/flattify/main/.github/assets/demo-dark.gif">
|
|
36
|
+
<img alt="flatten turns a nested object into path → value pairs, unflatten rebuilds the same object, and TypeScript infers every path" src="https://raw.githubusercontent.com/NandoMB/flattify/main/.github/assets/demo-light.gif" width="760">
|
|
37
|
+
</picture>
|
|
38
|
+
|
|
39
|
+
</div>
|
|
40
|
+
|
|
41
|
+
<br>
|
|
42
|
+
|
|
43
|
+
<table>
|
|
44
|
+
<tr>
|
|
45
|
+
<td width="33%" valign="top"><b>Lossless round trip</b><br><sub>Dates, class instances, <code>null</code>, empty objects, keys with dots and key order come back the way they went in. <a href="#data-integrity">See how</a>.</sub></td>
|
|
46
|
+
<td width="33%" valign="top"><b>Safe on untrusted input</b><br><sub>Hostile keys can't pollute prototypes or allocate huge arrays, and deep or circular objects can't overflow the stack.</sub></td>
|
|
47
|
+
<td width="33%" valign="top"><b>Typed end to end</b><br><sub>Hover the result to see every path. <code>get</code> and <code>set</code> autocomplete paths and check values.</sub></td>
|
|
48
|
+
</tr>
|
|
49
|
+
<tr>
|
|
50
|
+
<td valign="top"><b>Three notations</b><br><sub><code>a.b.0</code>, <code>a.b[0]</code> for HTML forms, and <code>/a/b/0</code> for JSON Pointer.</sub></td>
|
|
51
|
+
<td valign="top"><b>Tested in CI</b><br><sub>100% test coverage, thousands of random round trips per run, and a test behind every <a href="#why-flattify">comparison</a> with other libraries.</sub></td>
|
|
52
|
+
<td valign="top"><b>Zero dependencies</b><br><sub>ESM and CommonJS. Runs on Node.js, Bun, Deno, browsers and Cloudflare Workers.</sub></td>
|
|
53
|
+
</tr>
|
|
54
|
+
</table>
|
|
55
|
+
|
|
56
|
+
> [!TIP]
|
|
20
57
|
> Upgrading from Flattify 1.x? See [Migrating](#migrating).
|
|
21
58
|
|
|
22
|
-
## Contents
|
|
23
|
-
|
|
24
|
-
- [Installation](#installation)
|
|
25
|
-
- [Quick start](#quick-start)
|
|
26
|
-
- [Data integrity](#data-integrity)
|
|
27
|
-
- [Why Flattify?](#why-flattify)
|
|
28
|
-
- [Use cases](#use-cases)
|
|
29
|
-
- [API](#api): [`flatten`](#flatteninput-options), [`unflatten`](#unflatteninput-options), [notations](#notations), [`flattify/path`](#flattifypath)
|
|
30
|
-
- [Types](#types)
|
|
31
|
-
- [Limitations](#limitations)
|
|
32
|
-
- [Compatibility](#compatibility)
|
|
33
|
-
- [Migrating](#migrating)
|
|
34
|
-
- [Security](#security)
|
|
35
|
-
|
|
36
59
|
## Installation
|
|
37
60
|
|
|
38
61
|
```sh
|
|
39
62
|
npm add flattify # or: pnpm add flattify / yarn add flattify
|
|
40
63
|
```
|
|
41
|
-
|
|
64
|
+
|
|
65
|
+
From JSR (Deno, Bun and Node.js):
|
|
66
|
+
|
|
42
67
|
```sh
|
|
43
68
|
deno add jsr:@nandomb/flattify
|
|
44
69
|
npx jsr add @nandomb/flattify # or: bunx jsr add @nandomb/flattify
|
|
@@ -76,7 +101,7 @@ const flat = flatten(order);
|
|
|
76
101
|
const back = unflatten(flat); // equals `order` again
|
|
77
102
|
```
|
|
78
103
|
|
|
79
|
-
Both results are typed
|
|
104
|
+
Both results are typed:
|
|
80
105
|
|
|
81
106
|
```ts
|
|
82
107
|
flat['items.0.sku']; // string
|
|
@@ -84,11 +109,11 @@ flat['customer.phone']; // ❌ Property 'customer.phone' does not exist
|
|
|
84
109
|
back.items[0].sku; // string
|
|
85
110
|
```
|
|
86
111
|
|
|
87
|
-
|
|
112
|
+
It works like serializing and deserializing, except that both sides are JavaScript objects and only the shape changes. Data that arrives flat, such as form fields, query strings, environment variables or CSV columns, can go straight into `unflatten`, which is safe to use on it.
|
|
88
113
|
|
|
89
114
|
## Data integrity
|
|
90
115
|
|
|
91
|
-
|
|
116
|
+
Many libraries lose something on the way. A `Date` or a `null` is dropped, a class instance is taken apart, an empty list vanishes, or `'utm.source'` is split in two. Flattify keeps all of it:
|
|
92
117
|
|
|
93
118
|
```ts
|
|
94
119
|
const input = {
|
|
@@ -113,19 +138,21 @@ back['utm.source']; // 'newsletter', still one key
|
|
|
113
138
|
1 in back.sizes; // false: the hole is still a hole
|
|
114
139
|
```
|
|
115
140
|
|
|
116
|
-
|
|
117
|
-
- **Nothing is dropped:** `null`, `undefined`, empty objects and empty arrays are kept
|
|
118
|
-
- **Keys stay whole:** a key that contains the delimiter is escaped (`'utm\\.source'`); keys without it are never changed
|
|
119
|
-
- **Order is kept:** keys come out depth first, in the order of the input, and come back in the same order
|
|
120
|
-
- **Your input is never modified:** `unflatten` copies the objects it finds in its input before adding keys to them
|
|
121
|
-
- **No surprise arrays:** only indices such as `0` or `42` build arrays, up to [`arrayLimit`](#unflatteninput-options); `'01'` or `'1e3'` stay object keys
|
|
122
|
-
- **Circular data is reported** with its path, instead of freezing or crashing the process; **any depth** is handled, even 100,000 levels
|
|
141
|
+
In detail:
|
|
123
142
|
|
|
124
|
-
|
|
143
|
+
- Flattify only walks plain objects and arrays. `Date`, `Map`, `Set`, `RegExp`, typed arrays, functions and class instances are kept by reference and never converted.
|
|
144
|
+
- `null`, `undefined`, empty objects and empty arrays are all kept.
|
|
145
|
+
- A key that contains the delimiter is escaped (`'utm\\.source'`). Other keys are never changed.
|
|
146
|
+
- Keys come out depth first in input order, and `unflatten` puts them back in the same order.
|
|
147
|
+
- Your input is never modified. `unflatten` copies any object it finds in its input before adding keys to it.
|
|
148
|
+
- Only indices like `0` or `42` build arrays, up to [`arrayLimit`](#unflatteninput-options). Keys like `'01'` or `'1e3'` stay object keys.
|
|
149
|
+
- A circular reference throws an error that names its path. Depth has no limit; 100,000 levels work.
|
|
150
|
+
|
|
151
|
+
The test suite covers each of these, and every run checks the round trip on thousands of random objects with [fast-check](https://fast-check.dev), in every notation.
|
|
125
152
|
|
|
126
153
|
## Why Flattify?
|
|
127
154
|
|
|
128
|
-
|
|
155
|
+
[`bench/claims.spec.ts`](./bench/claims.spec.ts) checks every row of this table against flat 6.0.1, flattie 1.1.1, nestie 1.0.3, es-toolkit 1.53.2 and radashi 13.0.4 on each CI run (`pnpm claims`).
|
|
129
156
|
|
|
130
157
|
| | Flattify | [flat](https://www.npmjs.com/package/flat) | [flattie](https://www.npmjs.com/package/flattie) / [nestie](https://www.npmjs.com/package/nestie) | [es-toolkit](https://www.npmjs.com/package/es-toolkit) | [radashi](https://www.npmjs.com/package/radashi) |
|
|
131
158
|
| --- | --- | --- | --- | --- | --- |
|
|
@@ -133,7 +160,7 @@ Every row is checked by [`bench/claims.spec.ts`](./bench/claims.spec.ts) against
|
|
|
133
160
|
| Keeps `Date` and `Map` as values | ✅ | ✅ | ❌ dropped | ✅ | ✅ |
|
|
134
161
|
| Keeps class instances as values | ✅ | ❌ | ❌ | ✅ | ❌ |
|
|
135
162
|
| Keeps `null` values | ✅ | ✅ | ❌ dropped | ✅ | ✅ |
|
|
136
|
-
| Keeps empty objects and arrays | ✅ | ✅ | ❌ dropped | ✅ |
|
|
163
|
+
| Keeps empty objects and arrays | ✅ | ✅ | ❌ dropped | ✅ | ✅ |
|
|
137
164
|
| Circular references | ✅ clear error | ❌ stack overflow | ❌ stack overflow | ❌ stack overflow | ❌ stack overflow |
|
|
138
165
|
| Deeply nested input (100k levels) | ✅ | ❌ stack overflow | ❌ stack overflow | ❌ stack overflow | ❌ stack overflow |
|
|
139
166
|
| Limit on array indices when unflattening | ✅ | ❌ | ❌ | – | ❌ |
|
|
@@ -144,18 +171,22 @@ Every row is checked by [`bench/claims.spec.ts`](./bench/claims.spec.ts) against
|
|
|
144
171
|
| ESM and CommonJS | ✅ | ❌ v6 is ESM only | ✅ | ✅ | ✅ |
|
|
145
172
|
| Size (min + gzip) | 2.3 kB | 0.7 kB | 0.35 kB | 0.34 kB | 0.8 kB |
|
|
146
173
|
|
|
147
|
-
|
|
174
|
+
The extra size pays for the checks above, the three notations, key escaping and the error messages. `flattify/path` is a separate import, so it only adds to your bundle when you use it.
|
|
148
175
|
|
|
149
176
|
## Use cases
|
|
150
177
|
|
|
151
|
-
|
|
178
|
+
### HTML forms
|
|
179
|
+
|
|
180
|
+
Field names like `address[city]` or `items[0][qty]` become a nested object. Keys like `__proto__[isAdmin]` from a malicious client are ignored.
|
|
152
181
|
|
|
153
182
|
```ts
|
|
154
183
|
const body = unflatten(Object.fromEntries(new FormData(form)), { notation: 'bracket' });
|
|
155
184
|
// { name: 'Ada', address: { city: 'London' }, items: [{ sku: 'BOOK-1', qty: '2' }] }
|
|
156
185
|
```
|
|
157
186
|
|
|
158
|
-
|
|
187
|
+
### Query strings
|
|
188
|
+
|
|
189
|
+
From an object to a query string and back:
|
|
159
190
|
|
|
160
191
|
```ts
|
|
161
192
|
const flat = flatten({ status: 'open', tags: ['a', 'b'] }, { notation: 'bracket' });
|
|
@@ -166,70 +197,78 @@ unflatten(Object.fromEntries(new URLSearchParams(location.search)), { notation:
|
|
|
166
197
|
// { status: 'open', tags: ['a', 'b'] }
|
|
167
198
|
```
|
|
168
199
|
|
|
169
|
-
|
|
200
|
+
### Environment variables
|
|
201
|
+
|
|
202
|
+
With `'__'` as the delimiter, `APP__DB__MAX_CONN` becomes `app.db.max_conn`:
|
|
170
203
|
|
|
171
204
|
```ts
|
|
172
205
|
const env = unflatten(process.env, { delimiter: '__', transformKey: (key) => key.toLowerCase() });
|
|
173
206
|
env.app; // { db: { host: 'localhost', max_conn: '10' } }
|
|
174
207
|
```
|
|
175
208
|
|
|
176
|
-
|
|
209
|
+
### CSV and spreadsheets
|
|
210
|
+
|
|
211
|
+
Flatten each record into one row, and the keys become the headers:
|
|
177
212
|
|
|
178
213
|
```ts
|
|
179
214
|
const rows = users.map((user) => flatten(user));
|
|
180
215
|
// [{ id: 1, name: 'Ada', 'address.city': 'London' }, ...]
|
|
181
216
|
|
|
182
|
-
// Or flatten the whole list into one object
|
|
217
|
+
// Or flatten the whole list into one object and get the list back:
|
|
183
218
|
const same = unflatten(flatten(users), { asArray: true });
|
|
184
219
|
```
|
|
185
220
|
|
|
186
|
-
|
|
221
|
+
### MongoDB partial updates
|
|
222
|
+
|
|
223
|
+
`$set` with flat paths changes only those fields:
|
|
187
224
|
|
|
188
225
|
```ts
|
|
189
226
|
await users.updateOne({ _id }, { $set: flatten({ profile: { name: 'Ada' } }) });
|
|
190
227
|
// $set: { 'profile.name': 'Ada' }: the other profile fields are kept
|
|
191
228
|
```
|
|
192
229
|
|
|
193
|
-
|
|
230
|
+
### JSON Schema errors
|
|
231
|
+
|
|
232
|
+
Validators like Ajv report errors as JSON Pointers, and `get` reads them directly:
|
|
194
233
|
|
|
195
234
|
```ts
|
|
196
235
|
get(data, error.instancePath, { notation: 'pointer' }); // e.g. '/items/0/qty'
|
|
197
236
|
```
|
|
198
237
|
|
|
199
|
-
|
|
238
|
+
People also use it for typed translation files (`messages['home.title']`), structured logs for Datadog or Elasticsearch, and diffing two objects by comparing their flat forms.
|
|
200
239
|
|
|
201
240
|
## API
|
|
202
241
|
|
|
203
242
|
### `flatten(input, options?)`
|
|
204
243
|
|
|
205
|
-
Takes a plain object or
|
|
244
|
+
Takes a plain object or array and returns a new flat object. Values are not cloned.
|
|
206
245
|
|
|
207
246
|
| Option | Default | |
|
|
208
247
|
| --- | --- | --- |
|
|
209
248
|
| `delimiter` | `'.'` | Joins the keys: `{ delimiter: '__' }` → `db__host` |
|
|
210
|
-
| `notation` | `'dot'` | `'dot'`, `'bracket'` or `'pointer'
|
|
211
|
-
| `maxDepth` | `Infinity` | Levels to walk
|
|
249
|
+
| `notation` | `'dot'` | `'dot'`, `'bracket'` or `'pointer'` (see [notations](#notations)) |
|
|
250
|
+
| `maxDepth` | `Infinity` | Levels to walk; deeper objects are kept as values. `1` keeps only top-level keys |
|
|
212
251
|
| `safe` | `false` | Keeps arrays as values: `{ 'user.tags': ['a', 'b'] }` instead of `user.tags.0`, `user.tags.1` |
|
|
213
252
|
| `keepEmpty` | `true` | Keeps empty objects and arrays; `false` drops them |
|
|
214
|
-
| `escape` | `true` | Escapes keys
|
|
215
|
-
| `circular` | `'throw'` | On a circular reference, throws a `TypeError` with its path
|
|
253
|
+
| `escape` | `true` | Escapes keys containing the delimiter (`'utm\\.source'`); `false` leaves them as is |
|
|
254
|
+
| `circular` | `'throw'` | On a circular reference, throws a `TypeError` with its path; `'skip'` leaves the key out |
|
|
216
255
|
| `transformKey` | | Renames each object key: `(key) => key.toUpperCase()`. Keys are then typed as `string` |
|
|
217
256
|
| `preserve` | | `(path, value) => boolean`: `true` keeps that object or array as a value |
|
|
218
257
|
|
|
219
|
-
With a longer delimiter, only keys that would
|
|
258
|
+
With a longer delimiter, Flattify escapes only the keys that would be ambiguous. With `'__'`, `MAX_CONN` stays as is, but `MAX_` is escaped because its trailing `_` would merge with the delimiter.
|
|
220
259
|
|
|
221
260
|
### `unflatten(input, options?)`
|
|
222
261
|
|
|
223
|
-
Takes a flat object
|
|
262
|
+
Takes a flat object and returns a new nested object. Index keys build arrays in any order. The top level is always an object unless `asArray` is set.
|
|
224
263
|
|
|
225
264
|
| Option | Default | |
|
|
226
265
|
| --- | --- | --- |
|
|
227
|
-
| `delimiter` | `'.'` | Splits
|
|
228
|
-
| `notation` | `'dot'` | `'dot'`, `'bracket'` or `'pointer'
|
|
229
|
-
| `asArray` | `false` | Returns an array: `{ '0.id': 1, '1.id': 2 }` → `[{ id: 1 }, { id: 2 }]`. A top-level key that
|
|
266
|
+
| `delimiter` | `'.'` | Splits keys into paths |
|
|
267
|
+
| `notation` | `'dot'` | `'dot'`, `'bracket'` or `'pointer'` (see [notations](#notations)) |
|
|
268
|
+
| `asArray` | `false` | Returns an array: `{ '0.id': 1, '1.id': 2 }` → `[{ id: 1 }, { id: 2 }]`. A top-level key that isn't an index throws |
|
|
230
269
|
| `object` | `false` | Never builds arrays: `{ 'list.0': 'a' }` → `{ list: { 0: 'a' } }` |
|
|
231
270
|
| `overwrite` | `false` | When a path goes through a value (`{ a: 1, 'a.b': 2 }`), replaces it (`{ a: { b: 2 } }`) instead of skipping the path |
|
|
232
|
-
| `arrayLimit` | `1000` | Larger indices
|
|
271
|
+
| `arrayLimit` | `1000` | Larger indices become object keys, so `'a.4294967294'` can't allocate a huge array |
|
|
233
272
|
| `escape` | `true` | Reads `\` as an escape, as `flatten` writes it |
|
|
234
273
|
| `transformKey` | | Renames each key of the path (not array indices) |
|
|
235
274
|
|
|
@@ -259,19 +298,19 @@ set(config, 'db.prot', 6543); // ❌ type error: no such path
|
|
|
259
298
|
|
|
260
299
|
| Function | |
|
|
261
300
|
| --- | --- |
|
|
262
|
-
| `get(obj, path)` | The value at `path`, or `undefined`
|
|
301
|
+
| `get(obj, path)` | The value at `path`, or `undefined` if a key is missing |
|
|
263
302
|
| `set(obj, path, value)` | Sets the value, creating missing objects and arrays; returns `obj` |
|
|
264
|
-
| `has(obj, path)` | `true`
|
|
265
|
-
| `del(obj, path)` | Deletes the key; `true`
|
|
303
|
+
| `has(obj, path)` | `true` if every key of the path exists |
|
|
304
|
+
| `del(obj, path)` | Deletes the key; `true` if it existed |
|
|
266
305
|
| `paths(obj)` | The paths `flatten` produces |
|
|
267
306
|
| `parsePath(path)` / `stringifyPath(keys)` | `'a\\.b.c'` ↔ `['a.b', 'c']` |
|
|
268
307
|
| `escapeKey(key)` | Escapes one key: `` `user.${escapeKey(field)}` `` |
|
|
269
308
|
|
|
270
|
-
|
|
309
|
+
Each function takes `delimiter`, `notation` and `escape` as its last argument, and each is safe to call with untrusted paths.
|
|
271
310
|
|
|
272
311
|
## Types
|
|
273
312
|
|
|
274
|
-
|
|
313
|
+
The types compute paths and values for every option that changes them:
|
|
275
314
|
|
|
276
315
|
```ts
|
|
277
316
|
flatten({ user: { tags: ['admin'] } });
|
|
@@ -281,16 +320,18 @@ flatten({ a: { b: 1 } }, { notation: 'pointer' });
|
|
|
281
320
|
// { '/a/b': number }
|
|
282
321
|
```
|
|
283
322
|
|
|
284
|
-
Arrays give `` `${number}` `` keys and tuples exact indices
|
|
323
|
+
Arrays give `` `${number}` `` keys and tuples give exact indices. Optional or nullable objects give optional paths, and unions are merged. `Date`, `Map` and other built-ins stay as values. For plain data, `Unflatten<Flatten<T>>` gives back `T`.
|
|
324
|
+
|
|
325
|
+
When an option is only known at runtime (a `string` delimiter, `transformKey` or `preserve`), keys are typed as `string`.
|
|
285
326
|
|
|
286
|
-
Exported types: `Flatten<T, Options
|
|
327
|
+
Exported types: `Flatten<T, Options>` and `Unflatten<T, Options>`, plus `Path<T>`, `Get<T, Path>` and `SetValue<T, Path>` from `flattify/path`.
|
|
287
328
|
|
|
288
329
|
## Limitations
|
|
289
330
|
|
|
290
|
-
-
|
|
291
|
-
-
|
|
292
|
-
-
|
|
293
|
-
-
|
|
331
|
+
- Some round trips can't be exact. An object with only index keys (`{ '0': 'a' }`) comes back as an array. An array given to `flatten` comes back as an object unless `unflatten` gets `{ asArray: true }`. And `transformKey` needs its inverse on the way back.
|
|
332
|
+
- Symbol keys are ignored, as `JSON.stringify` ignores them.
|
|
333
|
+
- TypeScript can't tell a class instance from a plain object, so class instances are typed as if they were flattened. Paths are typed down to 10 levels, and as `unknown` below that.
|
|
334
|
+
- In bracket notation, an empty top-level key holding an array (`{ '': [1] }`) looks the same as the array itself.
|
|
294
335
|
|
|
295
336
|
## Compatibility
|
|
296
337
|
|
|
@@ -300,13 +341,13 @@ Exported types: `Flatten<T, Options>`, `Unflatten<T, Options>`, and from `flatti
|
|
|
300
341
|
| Modules | ESM and CommonJS |
|
|
301
342
|
| TypeScript | 5.0+, any `moduleResolution` |
|
|
302
343
|
|
|
303
|
-
CI runs the tests on Node.js 22, 24 and 26, Bun, Deno, Chromium, Firefox, WebKit and workerd (the Cloudflare Workers runtime)
|
|
344
|
+
CI runs the tests on Node.js 22, 24 and 26, Bun, Deno, Chromium, Firefox, WebKit and workerd (the Cloudflare Workers runtime). It also checks the package with [publint](https://publint.dev) and [Are the Types Wrong?](https://arethetypeswrong.github.io).
|
|
304
345
|
|
|
305
346
|
## Migrating
|
|
306
347
|
|
|
307
348
|
### From `flat`
|
|
308
349
|
|
|
309
|
-
|
|
350
|
+
The options have the same names (`delimiter`, `maxDepth`, `safe`, `object`, `overwrite`, `transformKey`), but some defaults are safer:
|
|
310
351
|
|
|
311
352
|
| | `flat` | Flattify |
|
|
312
353
|
| --- | --- | --- |
|
|
@@ -329,19 +370,23 @@ Same option names (`delimiter`, `maxDepth`, `safe`, `object`, `overwrite`, `tran
|
|
|
329
370
|
| `flattify(array)` (each item flattened) | `array.map((item) => flatten(item))` |
|
|
330
371
|
| `flattify(jsonString)` | `flatten(JSON.parse(jsonString))` |
|
|
331
372
|
|
|
332
|
-
|
|
373
|
+
2.0 also fixes nested arrays losing their path: `{ a: { tags: [1] } }` gave `{ tags: '[1]' }` and now gives `{ 'a.tags.0': 1 }`.
|
|
333
374
|
|
|
334
375
|
## Security
|
|
335
376
|
|
|
336
|
-
-
|
|
337
|
-
-
|
|
338
|
-
-
|
|
339
|
-
-
|
|
377
|
+
- `unflatten` and `set` only create own properties, and they skip any path through `__proto__` in every notation, so they can't pollute prototypes. (`flat` had this flaw as [CVE-2020-36632](https://nvd.nist.gov/vuln/detail/CVE-2020-36632), fixed in 5.0.1.)
|
|
378
|
+
- Objects are walked with an explicit stack instead of recursion, so deep input can't overflow the stack, and a circular reference throws an error that names its path.
|
|
379
|
+
- `arrayLimit` caps the indices that `unflatten` turns into arrays, so a key like `'a.4294967294'` can't allocate a huge one.
|
|
380
|
+
- The bracket parser takes linear time, even on hostile input like `a[[[[...`.
|
|
340
381
|
|
|
341
|
-
|
|
382
|
+
The test suite covers all of this, and it fuzzes `unflatten` with random paths built from `__proto__`, `constructor` and `prototype`. Releases are published from GitHub Actions with [npm provenance](https://docs.npmjs.com/generating-provenance-statements), and each one is [staged](https://docs.npmjs.com/staged-publishing/) until it is approved with 2FA.
|
|
342
383
|
|
|
343
|
-
Found a vulnerability? Please report it privately,
|
|
384
|
+
Found a vulnerability? Please report it privately, as described in [SECURITY.md](./SECURITY.md).
|
|
344
385
|
|
|
345
386
|
## License
|
|
346
387
|
|
|
347
|
-
|
|
388
|
+
<p align="center">
|
|
389
|
+
<img src="https://raw.githubusercontent.com/NandoMB/flattify/main/.github/assets/mark.svg" alt="" width="40"><br>
|
|
390
|
+
<a href="./LICENSE">MIT</a> © 2016 <a href="https://github.com/NandoMB">Fernando Machado Bernardino</a><br>
|
|
391
|
+
<sub>If Flattify saves you time, a ⭐ on <a href="https://github.com/NandoMB/flattify">GitHub</a> helps others find it.</sub>
|
|
392
|
+
</p>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/shared/guards.ts
|
|
2
2
|
/**
|
|
3
3
|
* Plain objects are the ones created by `{}`, `Object.create(null)` or `JSON.parse`, including those
|
|
4
4
|
* from another realm (iframe, `vm`): their prototype is `null` or a root prototype. Dates, maps, class
|
|
@@ -26,8 +26,7 @@ function assign(target, key, value) {
|
|
|
26
26
|
});
|
|
27
27
|
else target[key] = value;
|
|
28
28
|
}
|
|
29
|
-
|
|
30
|
-
//#region src/shared/path.ts
|
|
29
|
+
// src/shared/path.ts
|
|
31
30
|
/**
|
|
32
31
|
* Builds the function that escapes a single key so the path can be split back. Keys that are already
|
|
33
32
|
* unambiguous are returned as they are; the others get `\` before every `\`, every first character of the
|
|
@@ -143,8 +142,7 @@ function splitPointer(pointer) {
|
|
|
143
142
|
if (!pointer.startsWith("/")) throw new TypeError(`A JSON Pointer must start with "/", got "${pointer}"`);
|
|
144
143
|
return pointer.slice(1).split("/").map((segment) => segment.includes("~") ? segment.replace(/~1/g, "/").replace(/~0/g, "~") : segment);
|
|
145
144
|
}
|
|
146
|
-
|
|
147
|
-
//#region src/shared/notation.ts
|
|
145
|
+
// src/shared/notation.ts
|
|
148
146
|
function validateNotation(notation) {
|
|
149
147
|
if (notation !== "dot" && notation !== "bracket" && notation !== "pointer") throw new TypeError("`notation` must be 'dot', 'bracket' or 'pointer'");
|
|
150
148
|
}
|
|
@@ -164,14 +162,12 @@ function pathFormat(notation, delimiter, escape) {
|
|
|
164
162
|
split: notation === "bracket" ? (path) => splitBracketPath(path, delimiter, escape) : (path) => splitPath(path, delimiter, escape)
|
|
165
163
|
};
|
|
166
164
|
}
|
|
167
|
-
|
|
168
|
-
//#region src/shared/validate.ts
|
|
165
|
+
// src/shared/validate.ts
|
|
169
166
|
function validate(delimiter, escape) {
|
|
170
167
|
if (typeof delimiter !== "string" || delimiter === "") throw new TypeError("`delimiter` must be a non-empty string");
|
|
171
168
|
if (escape && delimiter.includes("\\")) throw new RangeError("`delimiter` cannot contain `\\` while `escape` is enabled: it is the escape character");
|
|
172
169
|
}
|
|
173
|
-
|
|
174
|
-
//#region src/flatten/flatten.ts
|
|
170
|
+
// src/flatten/flatten.ts
|
|
175
171
|
function frame(value, path, depth) {
|
|
176
172
|
return {
|
|
177
173
|
value,
|
|
@@ -183,11 +179,11 @@ function frame(value, path, depth) {
|
|
|
183
179
|
};
|
|
184
180
|
}
|
|
185
181
|
function validateWalk(maxDepth, circular) {
|
|
186
|
-
if (maxDepth !==
|
|
182
|
+
if (maxDepth !== 1e400 && (!Number.isInteger(maxDepth) || maxDepth < 1)) throw new RangeError("`maxDepth` must be a positive integer or Infinity");
|
|
187
183
|
if (circular !== "throw" && circular !== "skip") throw new TypeError("`circular` must be 'throw' or 'skip'");
|
|
188
184
|
}
|
|
189
185
|
function flatten(input, options = {}) {
|
|
190
|
-
const { delimiter = ".", notation = "dot", maxDepth =
|
|
186
|
+
const { delimiter = ".", notation = "dot", maxDepth = 1e400, safe = false, keepEmpty = true, escape = true, circular = "throw", transformKey, preserve } = options;
|
|
191
187
|
validateNotation(notation);
|
|
192
188
|
if (notation !== "pointer") validate(delimiter, escape);
|
|
193
189
|
validateWalk(maxDepth, circular);
|
|
@@ -224,7 +220,6 @@ function flatten(input, options = {}) {
|
|
|
224
220
|
}
|
|
225
221
|
return result;
|
|
226
222
|
}
|
|
227
|
-
//#endregion
|
|
228
223
|
Object.defineProperty(exports, "assign", {
|
|
229
224
|
enumerable: true,
|
|
230
225
|
get: function() {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/shared/guards.ts
|
|
2
2
|
/**
|
|
3
3
|
* Plain objects are the ones created by `{}`, `Object.create(null)` or `JSON.parse`, including those
|
|
4
4
|
* from another realm (iframe, `vm`): their prototype is `null` or a root prototype. Dates, maps, class
|
|
@@ -26,8 +26,7 @@ function assign(target, key, value) {
|
|
|
26
26
|
});
|
|
27
27
|
else target[key] = value;
|
|
28
28
|
}
|
|
29
|
-
|
|
30
|
-
//#region src/shared/path.ts
|
|
29
|
+
// src/shared/path.ts
|
|
31
30
|
/**
|
|
32
31
|
* Builds the function that escapes a single key so the path can be split back. Keys that are already
|
|
33
32
|
* unambiguous are returned as they are; the others get `\` before every `\`, every first character of the
|
|
@@ -143,8 +142,7 @@ function splitPointer(pointer) {
|
|
|
143
142
|
if (!pointer.startsWith("/")) throw new TypeError(`A JSON Pointer must start with "/", got "${pointer}"`);
|
|
144
143
|
return pointer.slice(1).split("/").map((segment) => segment.includes("~") ? segment.replace(/~1/g, "/").replace(/~0/g, "~") : segment);
|
|
145
144
|
}
|
|
146
|
-
|
|
147
|
-
//#region src/shared/notation.ts
|
|
145
|
+
// src/shared/notation.ts
|
|
148
146
|
function validateNotation(notation) {
|
|
149
147
|
if (notation !== "dot" && notation !== "bracket" && notation !== "pointer") throw new TypeError("`notation` must be 'dot', 'bracket' or 'pointer'");
|
|
150
148
|
}
|
|
@@ -164,14 +162,12 @@ function pathFormat(notation, delimiter, escape) {
|
|
|
164
162
|
split: notation === "bracket" ? (path) => splitBracketPath(path, delimiter, escape) : (path) => splitPath(path, delimiter, escape)
|
|
165
163
|
};
|
|
166
164
|
}
|
|
167
|
-
|
|
168
|
-
//#region src/shared/validate.ts
|
|
165
|
+
// src/shared/validate.ts
|
|
169
166
|
function validate(delimiter, escape) {
|
|
170
167
|
if (typeof delimiter !== "string" || delimiter === "") throw new TypeError("`delimiter` must be a non-empty string");
|
|
171
168
|
if (escape && delimiter.includes("\\")) throw new RangeError("`delimiter` cannot contain `\\` while `escape` is enabled: it is the escape character");
|
|
172
169
|
}
|
|
173
|
-
|
|
174
|
-
//#region src/flatten/flatten.ts
|
|
170
|
+
// src/flatten/flatten.ts
|
|
175
171
|
function frame(value, path, depth) {
|
|
176
172
|
return {
|
|
177
173
|
value,
|
|
@@ -183,11 +179,11 @@ function frame(value, path, depth) {
|
|
|
183
179
|
};
|
|
184
180
|
}
|
|
185
181
|
function validateWalk(maxDepth, circular) {
|
|
186
|
-
if (maxDepth !==
|
|
182
|
+
if (maxDepth !== 1e400 && (!Number.isInteger(maxDepth) || maxDepth < 1)) throw new RangeError("`maxDepth` must be a positive integer or Infinity");
|
|
187
183
|
if (circular !== "throw" && circular !== "skip") throw new TypeError("`circular` must be 'throw' or 'skip'");
|
|
188
184
|
}
|
|
189
185
|
function flatten(input, options = {}) {
|
|
190
|
-
const { delimiter = ".", notation = "dot", maxDepth =
|
|
186
|
+
const { delimiter = ".", notation = "dot", maxDepth = 1e400, safe = false, keepEmpty = true, escape = true, circular = "throw", transformKey, preserve } = options;
|
|
191
187
|
validateNotation(notation);
|
|
192
188
|
if (notation !== "pointer") validate(delimiter, escape);
|
|
193
189
|
validateWalk(maxDepth, circular);
|
|
@@ -224,5 +220,4 @@ function flatten(input, options = {}) {
|
|
|
224
220
|
}
|
|
225
221
|
return result;
|
|
226
222
|
}
|
|
227
|
-
//#endregion
|
|
228
223
|
export { escapeKey as a, assign as c, validateNotation as i, isContainer as l, validate as n, escapePointer as o, pathFormat as r, isIndex as s, flatten as t, isPlainObject as u };
|
package/dist/index.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_flatten = require("./flatten-
|
|
3
|
-
|
|
2
|
+
const require_flatten = require("./flatten-BzHEOWOi.cjs");
|
|
3
|
+
// src/unflatten/unflatten.ts
|
|
4
4
|
const hasOwn = (target, key) => Object.prototype.hasOwnProperty.call(target, key);
|
|
5
5
|
function validateArrayLimit(arrayLimit) {
|
|
6
|
-
if (arrayLimit !==
|
|
6
|
+
if (arrayLimit !== 1e400 && (!Number.isInteger(arrayLimit) || arrayLimit < 0)) throw new RangeError("`arrayLimit` must be a non-negative integer or Infinity");
|
|
7
7
|
}
|
|
8
8
|
/**
|
|
9
9
|
* Walks from `parent` into `key`, creating the object when it is missing. Returns `undefined` when a
|
|
@@ -57,7 +57,7 @@ function unflatten(input, options = {}) {
|
|
|
57
57
|
if (segments.length === 0) throw new TypeError("The JSON Pointer \"\" (the whole document) cannot be a key of a flat object");
|
|
58
58
|
if (segments.includes("__proto__")) continue;
|
|
59
59
|
if (transformKey) {
|
|
60
|
-
for (let i = 0; i < segments.length; i++) if (!require_flatten.isIndex(segments[i],
|
|
60
|
+
for (let i = 0; i < segments.length; i++) if (!require_flatten.isIndex(segments[i], 1e400)) segments[i] = transformKey(segments[i]);
|
|
61
61
|
}
|
|
62
62
|
let target = result;
|
|
63
63
|
for (let i = 0; i < segments.length - 1; i++) {
|
|
@@ -84,6 +84,5 @@ function toRootArray(result, arrayLimit) {
|
|
|
84
84
|
}
|
|
85
85
|
return array;
|
|
86
86
|
}
|
|
87
|
-
//#endregion
|
|
88
87
|
exports.flatten = require_flatten.flatten;
|
|
89
88
|
exports.unflatten = unflatten;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Flatten and unflatten nested objects, with the resulting keys inferred by TypeScript.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { flatten, unflatten } from 'flattify';
|
|
7
|
+
*
|
|
8
|
+
* const flat = flatten({ user: { name: 'Ada', tags: ['admin'] } });
|
|
9
|
+
* // { 'user.name': 'Ada', 'user.tags.0': 'admin' }
|
|
10
|
+
*
|
|
11
|
+
* unflatten(flat);
|
|
12
|
+
* // { user: { name: 'Ada', tags: ['admin'] } }
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* @module
|
|
16
|
+
*/
|
|
17
|
+
import { _ as Notation, c as FlattenOptions, g as Prettify, h as Option, m as IsUnion, p as IsAny, r as Split, s as Flatten } from "./path-types-CKfz-km1.cjs";
|
|
3
18
|
/**
|
|
4
19
|
* Flattens a nested object (or array) into a single-level object whose keys are the paths to each value.
|
|
5
20
|
*
|
|
@@ -40,8 +55,6 @@ export declare function flatten<T extends object>(input: T): Flatten<T>;
|
|
|
40
55
|
* ```
|
|
41
56
|
*/
|
|
42
57
|
export declare function flatten<T extends object, const O extends FlattenOptions>(input: T, options: O): Flatten<T, O>;
|
|
43
|
-
//#endregion
|
|
44
|
-
//#region src/unflatten/types.d.ts
|
|
45
58
|
/** Options of `unflatten`. Each one also changes the inferred type of the result. */
|
|
46
59
|
interface UnflattenOptions {
|
|
47
60
|
/** Splits the keys into paths. Default: `'.'`. */
|
|
@@ -123,8 +136,6 @@ type RootArray<R> = [keyof R] extends [never] ? [] : string extends keyof R ? R[
|
|
|
123
136
|
object: false;
|
|
124
137
|
}> : never;
|
|
125
138
|
type UnflattenWith<T, C extends Context> = IsWide<C> extends true ? Record<string, unknown> : T extends unknown ? Build<T, C> : never;
|
|
126
|
-
//#endregion
|
|
127
|
-
//#region src/unflatten/unflatten.d.ts
|
|
128
139
|
/**
|
|
129
140
|
* Rebuilds a nested object from a flat object whose keys are paths: the reverse of `flatten`.
|
|
130
141
|
*
|
|
@@ -168,5 +179,4 @@ export declare function unflatten<T extends object>(input: T): Unflatten<T>;
|
|
|
168
179
|
* ```
|
|
169
180
|
*/
|
|
170
181
|
export declare function unflatten<T extends object, const O extends UnflattenOptions>(input: T, options: O): Unflatten<T, O>;
|
|
171
|
-
//#endregion
|
|
172
182
|
export type { Flatten, FlattenOptions, Notation, Prettify, Unflatten, UnflattenOptions };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Flatten and unflatten nested objects, with the resulting keys inferred by TypeScript.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { flatten, unflatten } from 'flattify';
|
|
7
|
+
*
|
|
8
|
+
* const flat = flatten({ user: { name: 'Ada', tags: ['admin'] } });
|
|
9
|
+
* // { 'user.name': 'Ada', 'user.tags.0': 'admin' }
|
|
10
|
+
*
|
|
11
|
+
* unflatten(flat);
|
|
12
|
+
* // { user: { name: 'Ada', tags: ['admin'] } }
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* @module
|
|
16
|
+
*/
|
|
17
|
+
import { _ as Notation, c as FlattenOptions, g as Prettify, h as Option, m as IsUnion, p as IsAny, r as Split, s as Flatten } from "./path-types-CKfz-km1.js";
|
|
3
18
|
/**
|
|
4
19
|
* Flattens a nested object (or array) into a single-level object whose keys are the paths to each value.
|
|
5
20
|
*
|
|
@@ -40,8 +55,6 @@ export declare function flatten<T extends object>(input: T): Flatten<T>;
|
|
|
40
55
|
* ```
|
|
41
56
|
*/
|
|
42
57
|
export declare function flatten<T extends object, const O extends FlattenOptions>(input: T, options: O): Flatten<T, O>;
|
|
43
|
-
//#endregion
|
|
44
|
-
//#region src/unflatten/types.d.ts
|
|
45
58
|
/** Options of `unflatten`. Each one also changes the inferred type of the result. */
|
|
46
59
|
interface UnflattenOptions {
|
|
47
60
|
/** Splits the keys into paths. Default: `'.'`. */
|
|
@@ -123,8 +136,6 @@ type RootArray<R> = [keyof R] extends [never] ? [] : string extends keyof R ? R[
|
|
|
123
136
|
object: false;
|
|
124
137
|
}> : never;
|
|
125
138
|
type UnflattenWith<T, C extends Context> = IsWide<C> extends true ? Record<string, unknown> : T extends unknown ? Build<T, C> : never;
|
|
126
|
-
//#endregion
|
|
127
|
-
//#region src/unflatten/unflatten.d.ts
|
|
128
139
|
/**
|
|
129
140
|
* Rebuilds a nested object from a flat object whose keys are paths: the reverse of `flatten`.
|
|
130
141
|
*
|
|
@@ -168,5 +179,4 @@ export declare function unflatten<T extends object>(input: T): Unflatten<T>;
|
|
|
168
179
|
* ```
|
|
169
180
|
*/
|
|
170
181
|
export declare function unflatten<T extends object, const O extends UnflattenOptions>(input: T, options: O): Unflatten<T, O>;
|
|
171
|
-
//#endregion
|
|
172
182
|
export type { Flatten, FlattenOptions, Notation, Prettify, Unflatten, UnflattenOptions };
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { c as assign, i as validateNotation, l as isContainer, n as validate, r as pathFormat, s as isIndex, t as flatten, u as isPlainObject } from "./flatten-
|
|
2
|
-
|
|
1
|
+
import { c as assign, i as validateNotation, l as isContainer, n as validate, r as pathFormat, s as isIndex, t as flatten, u as isPlainObject } from "./flatten-DD3D_40K.js";
|
|
2
|
+
// src/unflatten/unflatten.ts
|
|
3
3
|
const hasOwn = (target, key) => Object.prototype.hasOwnProperty.call(target, key);
|
|
4
4
|
function validateArrayLimit(arrayLimit) {
|
|
5
|
-
if (arrayLimit !==
|
|
5
|
+
if (arrayLimit !== 1e400 && (!Number.isInteger(arrayLimit) || arrayLimit < 0)) throw new RangeError("`arrayLimit` must be a non-negative integer or Infinity");
|
|
6
6
|
}
|
|
7
7
|
/**
|
|
8
8
|
* Walks from `parent` into `key`, creating the object when it is missing. Returns `undefined` when a
|
|
@@ -56,7 +56,7 @@ function unflatten(input, options = {}) {
|
|
|
56
56
|
if (segments.length === 0) throw new TypeError("The JSON Pointer \"\" (the whole document) cannot be a key of a flat object");
|
|
57
57
|
if (segments.includes("__proto__")) continue;
|
|
58
58
|
if (transformKey) {
|
|
59
|
-
for (let i = 0; i < segments.length; i++) if (!isIndex(segments[i],
|
|
59
|
+
for (let i = 0; i < segments.length; i++) if (!isIndex(segments[i], 1e400)) segments[i] = transformKey(segments[i]);
|
|
60
60
|
}
|
|
61
61
|
let target = result;
|
|
62
62
|
for (let i = 0; i < segments.length - 1; i++) {
|
|
@@ -83,5 +83,4 @@ function toRootArray(result, arrayLimit) {
|
|
|
83
83
|
}
|
|
84
84
|
return array;
|
|
85
85
|
}
|
|
86
|
-
//#endregion
|
|
87
86
|
export { flatten, unflatten };
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/shared/notation.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* How paths are written:
|
|
4
3
|
* - `'dot'`: `items.0.id`
|
|
@@ -6,8 +5,6 @@
|
|
|
6
5
|
* - `'pointer'`: `/items/0/id`, a JSON Pointer (RFC 6901); `delimiter` and `escape` do not apply
|
|
7
6
|
*/
|
|
8
7
|
type Notation = "dot" | "bracket" | "pointer";
|
|
9
|
-
//#endregion
|
|
10
|
-
//#region src/shared/types.d.ts
|
|
11
8
|
/** Flattens intersections so editors show the resulting keys instead of the type expression. */
|
|
12
9
|
type Prettify<T> = { [K in keyof T]: T[K]; } & {};
|
|
13
10
|
type UnionToIntersection<U> = (U extends unknown ? (x: U) => void : never) extends ((x: infer I) => void) ? I : never;
|
|
@@ -34,8 +31,6 @@ type KeysOf<U> = U extends unknown ? keyof U : never;
|
|
|
34
31
|
type ValueIn<U, K extends PropertyKey> = U extends unknown ? (K extends keyof U ? U[K & keyof U] : never) : never;
|
|
35
32
|
type RequiredKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? never : K; }[keyof T];
|
|
36
33
|
type IsRequiredInAll<U, K extends PropertyKey> = [U extends unknown ? (K extends RequiredKeys<U> ? never : 1) : never] extends [never] ? true : false;
|
|
37
|
-
//#endregion
|
|
38
|
-
//#region src/flatten/types.d.ts
|
|
39
34
|
/** Options of `flatten`. Each one also changes the inferred keys of the result. */
|
|
40
35
|
interface FlattenOptions {
|
|
41
36
|
/** Joins the keys of a path. Default: `'.'`. */
|
|
@@ -127,8 +122,6 @@ type Flatten<T, O extends FlattenOptions = {}> = IsAny<T> extends true ? Record<
|
|
|
127
122
|
escape: Option<O, "escape", true>;
|
|
128
123
|
}> : Record<string, unknown>;
|
|
129
124
|
type FlattenWith<T, C extends Context> = IsWide<C> extends true ? Record<string, unknown> : T extends unknown ? Prettify<FlatContainer<T, "", [], C>> : never;
|
|
130
|
-
//#endregion
|
|
131
|
-
//#region src/shared/path-types.d.ts
|
|
132
125
|
/** The options that decide how a path is written. */
|
|
133
126
|
interface PathContext {
|
|
134
127
|
delimiter: string;
|
|
@@ -145,5 +138,4 @@ type SplitBracket<K extends string, D extends string, E extends boolean, Acc ext
|
|
|
145
138
|
type SplitBracketNext<K extends string, D extends string, E extends boolean, Acc extends string> = K extends `${D}${infer Rest}` ? [Acc, Rest] : K extends `${infer Char}${infer Rest}` ? SplitBracket<Rest, D, E, `${Acc}${Char}`> : [`${Acc}${K}`, never];
|
|
146
139
|
/** Every key of a path, in order: `Segments<'a.b[0]', bracket>` is `['a', 'b', '0']`. */
|
|
147
140
|
type Segments<P extends string, C extends PathContext> = Split<P, C> extends [infer Head extends string, infer Rest] ? ([Rest] extends [never] ? [Head] : Rest extends string ? [Head, ...Segments<Rest, C>] : [Head]) : string[];
|
|
148
|
-
//#endregion
|
|
149
141
|
export { Notation as _, ContainersOf as a, FlattenOptions as c, TupleEntries as d, TypeDepthLimit as f, Prettify as g, Option as h, Below as i, Join as l, IsUnion as m, Segments as n, Context as o, IsAny as p, Split as r, Flatten as s, PathContext as t, Kind as u };
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/shared/notation.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* How paths are written:
|
|
4
3
|
* - `'dot'`: `items.0.id`
|
|
@@ -6,8 +5,6 @@
|
|
|
6
5
|
* - `'pointer'`: `/items/0/id`, a JSON Pointer (RFC 6901); `delimiter` and `escape` do not apply
|
|
7
6
|
*/
|
|
8
7
|
type Notation = "dot" | "bracket" | "pointer";
|
|
9
|
-
//#endregion
|
|
10
|
-
//#region src/shared/types.d.ts
|
|
11
8
|
/** Flattens intersections so editors show the resulting keys instead of the type expression. */
|
|
12
9
|
type Prettify<T> = { [K in keyof T]: T[K]; } & {};
|
|
13
10
|
type UnionToIntersection<U> = (U extends unknown ? (x: U) => void : never) extends ((x: infer I) => void) ? I : never;
|
|
@@ -34,8 +31,6 @@ type KeysOf<U> = U extends unknown ? keyof U : never;
|
|
|
34
31
|
type ValueIn<U, K extends PropertyKey> = U extends unknown ? (K extends keyof U ? U[K & keyof U] : never) : never;
|
|
35
32
|
type RequiredKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? never : K; }[keyof T];
|
|
36
33
|
type IsRequiredInAll<U, K extends PropertyKey> = [U extends unknown ? (K extends RequiredKeys<U> ? never : 1) : never] extends [never] ? true : false;
|
|
37
|
-
//#endregion
|
|
38
|
-
//#region src/flatten/types.d.ts
|
|
39
34
|
/** Options of `flatten`. Each one also changes the inferred keys of the result. */
|
|
40
35
|
interface FlattenOptions {
|
|
41
36
|
/** Joins the keys of a path. Default: `'.'`. */
|
|
@@ -127,8 +122,6 @@ type Flatten<T, O extends FlattenOptions = {}> = IsAny<T> extends true ? Record<
|
|
|
127
122
|
escape: Option<O, "escape", true>;
|
|
128
123
|
}> : Record<string, unknown>;
|
|
129
124
|
type FlattenWith<T, C extends Context> = IsWide<C> extends true ? Record<string, unknown> : T extends unknown ? Prettify<FlatContainer<T, "", [], C>> : never;
|
|
130
|
-
//#endregion
|
|
131
|
-
//#region src/shared/path-types.d.ts
|
|
132
125
|
/** The options that decide how a path is written. */
|
|
133
126
|
interface PathContext {
|
|
134
127
|
delimiter: string;
|
|
@@ -145,5 +138,4 @@ type SplitBracket<K extends string, D extends string, E extends boolean, Acc ext
|
|
|
145
138
|
type SplitBracketNext<K extends string, D extends string, E extends boolean, Acc extends string> = K extends `${D}${infer Rest}` ? [Acc, Rest] : K extends `${infer Char}${infer Rest}` ? SplitBracket<Rest, D, E, `${Acc}${Char}`> : [`${Acc}${K}`, never];
|
|
146
139
|
/** Every key of a path, in order: `Segments<'a.b[0]', bracket>` is `['a', 'b', '0']`. */
|
|
147
140
|
type Segments<P extends string, C extends PathContext> = Split<P, C> extends [infer Head extends string, infer Rest] ? ([Rest] extends [never] ? [Head] : Rest extends string ? [Head, ...Segments<Rest, C>] : [Head]) : string[];
|
|
148
|
-
//#endregion
|
|
149
141
|
export { Notation as _, ContainersOf as a, FlattenOptions as c, TupleEntries as d, TypeDepthLimit as f, Prettify as g, Option as h, Below as i, Join as l, IsUnion as m, Segments as n, Context as o, IsAny as p, Split as r, Flatten as s, PathContext as t, Kind as u };
|
package/dist/path.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_flatten = require("./flatten-
|
|
3
|
-
|
|
2
|
+
const require_flatten = require("./flatten-BzHEOWOi.cjs");
|
|
3
|
+
// src/path/path.ts
|
|
4
4
|
const MISSING = Symbol("missing");
|
|
5
5
|
const FORBIDDEN = /* @__PURE__ */ new Set([
|
|
6
6
|
"__proto__",
|
|
@@ -51,7 +51,7 @@ function has(obj, path, options = {}) {
|
|
|
51
51
|
function set(obj, path, value, options = {}) {
|
|
52
52
|
checkTarget(obj, "set");
|
|
53
53
|
const { object = false, arrayLimit = 1e3 } = options;
|
|
54
|
-
if (arrayLimit !==
|
|
54
|
+
if (arrayLimit !== 1e400 && (!Number.isInteger(arrayLimit) || arrayLimit < 0)) throw new RangeError("`arrayLimit` must be a non-negative integer or Infinity");
|
|
55
55
|
const segments = formatOf(options).split(path);
|
|
56
56
|
if (segments.length === 0) throw new TypeError("set() cannot replace the whole object: the JSON Pointer \"\" has no key");
|
|
57
57
|
if (segments.includes("__proto__")) return obj;
|
|
@@ -103,7 +103,7 @@ function stringifyPath(keys, options = {}) {
|
|
|
103
103
|
const format = formatOf(options);
|
|
104
104
|
const bracket = options.notation === "bracket";
|
|
105
105
|
let path;
|
|
106
|
-
for (const key of keys) path = format.join(path, String(key), bracket && require_flatten.isIndex(String(key),
|
|
106
|
+
for (const key of keys) path = format.join(path, String(key), bracket && require_flatten.isIndex(String(key), 1e400));
|
|
107
107
|
return (_path = path) !== null && _path !== void 0 ? _path : "";
|
|
108
108
|
}
|
|
109
109
|
/**
|
|
@@ -121,7 +121,6 @@ function escapeKey(key, options = {}) {
|
|
|
121
121
|
if (notation === "pointer") return require_flatten.escapePointer(key);
|
|
122
122
|
return require_flatten.escapeKey(key, delimiter, notation === "bracket" ? "[" : "");
|
|
123
123
|
}
|
|
124
|
-
//#endregion
|
|
125
124
|
exports.del = del;
|
|
126
125
|
exports.escapeKey = escapeKey;
|
|
127
126
|
exports.get = get;
|
package/dist/path.d.cts
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Read and write nested values by path, with autocompleted paths and typed values.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { get, set } from 'flattify/path';
|
|
7
|
+
*
|
|
8
|
+
* const config = { db: { host: 'localhost', port: 5432 } };
|
|
9
|
+
* get(config, 'db.port'); // 5432, typed number
|
|
10
|
+
* set(config, 'db.host', 'db.internal');
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* @module
|
|
14
|
+
*/
|
|
15
|
+
import { _ as Notation, a as ContainersOf, c as FlattenOptions, d as TupleEntries, f as TypeDepthLimit, h as Option, i as Below, l as Join, m as IsUnion, n as Segments, o as Context, p as IsAny, s as Flatten, t as PathContext, u as Kind } from "./path-types-CKfz-km1.cjs";
|
|
3
16
|
/** How the paths given to the `flattify/path` helpers are written. */
|
|
4
17
|
interface PathOptions {
|
|
5
18
|
/** Separates the keys of a path. Default: `'.'`. */
|
|
@@ -56,8 +69,6 @@ type Walk<T, S, Get extends boolean> = S extends [infer K extends string, ...inf
|
|
|
56
69
|
type Get<T, P extends string, O extends PathOptions = {}> = IsAny<T> extends true ? any : string extends P ? unknown : IsWide<ContextOf$1<O>> extends true ? unknown : [Segments<P, ContextOf$1<O>>] extends [infer S] ? Walk<T, S, true> : never;
|
|
57
70
|
/** The type `set` accepts at path `P` of `T`. */
|
|
58
71
|
type SetValue<T, P extends string, O extends PathOptions = {}> = IsAny<T> extends true ? any : string extends P ? unknown : IsWide<ContextOf$1<O>> extends true ? unknown : [Segments<P, ContextOf$1<O>>] extends [infer S] ? Walk<T, S, false> : never;
|
|
59
|
-
//#endregion
|
|
60
|
-
//#region src/path/path.d.ts
|
|
61
72
|
/**
|
|
62
73
|
* Reads the value at `path`, or `undefined` when a key is missing along the way. The JSON Pointer `''`
|
|
63
74
|
* is `obj` itself.
|
|
@@ -200,5 +211,4 @@ export declare function stringifyPath(keys: readonly (string | number)[], option
|
|
|
200
211
|
* ```
|
|
201
212
|
*/
|
|
202
213
|
export declare function escapeKey(key: string, options?: PathOptions): string;
|
|
203
|
-
//#endregion
|
|
204
214
|
export type { Get, Notation, Path, PathOptions, SetOptions, SetValue };
|
package/dist/path.d.ts
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Read and write nested values by path, with autocompleted paths and typed values.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { get, set } from 'flattify/path';
|
|
7
|
+
*
|
|
8
|
+
* const config = { db: { host: 'localhost', port: 5432 } };
|
|
9
|
+
* get(config, 'db.port'); // 5432, typed number
|
|
10
|
+
* set(config, 'db.host', 'db.internal');
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* @module
|
|
14
|
+
*/
|
|
15
|
+
import { _ as Notation, a as ContainersOf, c as FlattenOptions, d as TupleEntries, f as TypeDepthLimit, h as Option, i as Below, l as Join, m as IsUnion, n as Segments, o as Context, p as IsAny, s as Flatten, t as PathContext, u as Kind } from "./path-types-CKfz-km1.js";
|
|
3
16
|
/** How the paths given to the `flattify/path` helpers are written. */
|
|
4
17
|
interface PathOptions {
|
|
5
18
|
/** Separates the keys of a path. Default: `'.'`. */
|
|
@@ -56,8 +69,6 @@ type Walk<T, S, Get extends boolean> = S extends [infer K extends string, ...inf
|
|
|
56
69
|
type Get<T, P extends string, O extends PathOptions = {}> = IsAny<T> extends true ? any : string extends P ? unknown : IsWide<ContextOf$1<O>> extends true ? unknown : [Segments<P, ContextOf$1<O>>] extends [infer S] ? Walk<T, S, true> : never;
|
|
57
70
|
/** The type `set` accepts at path `P` of `T`. */
|
|
58
71
|
type SetValue<T, P extends string, O extends PathOptions = {}> = IsAny<T> extends true ? any : string extends P ? unknown : IsWide<ContextOf$1<O>> extends true ? unknown : [Segments<P, ContextOf$1<O>>] extends [infer S] ? Walk<T, S, false> : never;
|
|
59
|
-
//#endregion
|
|
60
|
-
//#region src/path/path.d.ts
|
|
61
72
|
/**
|
|
62
73
|
* Reads the value at `path`, or `undefined` when a key is missing along the way. The JSON Pointer `''`
|
|
63
74
|
* is `obj` itself.
|
|
@@ -200,5 +211,4 @@ export declare function stringifyPath(keys: readonly (string | number)[], option
|
|
|
200
211
|
* ```
|
|
201
212
|
*/
|
|
202
213
|
export declare function escapeKey(key: string, options?: PathOptions): string;
|
|
203
|
-
//#endregion
|
|
204
214
|
export type { Get, Notation, Path, PathOptions, SetOptions, SetValue };
|
package/dist/path.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as escapeKey$1, c as assign, i as validateNotation, n as validate, o as escapePointer, r as pathFormat, s as isIndex, t as flatten, u as isPlainObject } from "./flatten-
|
|
2
|
-
|
|
1
|
+
import { a as escapeKey$1, c as assign, i as validateNotation, n as validate, o as escapePointer, r as pathFormat, s as isIndex, t as flatten, u as isPlainObject } from "./flatten-DD3D_40K.js";
|
|
2
|
+
// src/path/path.ts
|
|
3
3
|
const MISSING = Symbol("missing");
|
|
4
4
|
const FORBIDDEN = /* @__PURE__ */ new Set([
|
|
5
5
|
"__proto__",
|
|
@@ -50,7 +50,7 @@ function has(obj, path, options = {}) {
|
|
|
50
50
|
function set(obj, path, value, options = {}) {
|
|
51
51
|
checkTarget(obj, "set");
|
|
52
52
|
const { object = false, arrayLimit = 1e3 } = options;
|
|
53
|
-
if (arrayLimit !==
|
|
53
|
+
if (arrayLimit !== 1e400 && (!Number.isInteger(arrayLimit) || arrayLimit < 0)) throw new RangeError("`arrayLimit` must be a non-negative integer or Infinity");
|
|
54
54
|
const segments = formatOf(options).split(path);
|
|
55
55
|
if (segments.length === 0) throw new TypeError("set() cannot replace the whole object: the JSON Pointer \"\" has no key");
|
|
56
56
|
if (segments.includes("__proto__")) return obj;
|
|
@@ -102,7 +102,7 @@ function stringifyPath(keys, options = {}) {
|
|
|
102
102
|
const format = formatOf(options);
|
|
103
103
|
const bracket = options.notation === "bracket";
|
|
104
104
|
let path;
|
|
105
|
-
for (const key of keys) path = format.join(path, String(key), bracket && isIndex(String(key),
|
|
105
|
+
for (const key of keys) path = format.join(path, String(key), bracket && isIndex(String(key), 1e400));
|
|
106
106
|
return (_path = path) !== null && _path !== void 0 ? _path : "";
|
|
107
107
|
}
|
|
108
108
|
/**
|
|
@@ -120,5 +120,4 @@ function escapeKey(key, options = {}) {
|
|
|
120
120
|
if (notation === "pointer") return escapePointer(key);
|
|
121
121
|
return escapeKey$1(key, delimiter, notation === "bracket" ? "[" : "");
|
|
122
122
|
}
|
|
123
|
-
//#endregion
|
|
124
123
|
export { del, escapeKey, get, has, parsePath, paths, set, stringifyPath };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "flattify",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.2",
|
|
4
4
|
"description": "Flatten and unflatten nested objects without losing data: dates, nulls, empty objects and dotted keys survive the round trip. Typed paths, safe on untrusted input, zero dependencies.",
|
|
5
5
|
"author": "Fernando Machado Bernardino <fernandombernardino@gmail.com>",
|
|
6
6
|
"homepage": "https://github.com/NandoMB/flattify#readme",
|
|
@@ -73,23 +73,23 @@
|
|
|
73
73
|
"devDependencies": {
|
|
74
74
|
"@arethetypeswrong/cli": "^0.18.5",
|
|
75
75
|
"@changesets/cli": "^3.0.3",
|
|
76
|
-
"@types/node": "^26.6.
|
|
77
|
-
"@vitest/browser-playwright": "
|
|
78
|
-
"@vitest/coverage-istanbul": "
|
|
79
|
-
"es-toolkit": "1.
|
|
76
|
+
"@types/node": "^26.6.6",
|
|
77
|
+
"@vitest/browser-playwright": "~5.1.0",
|
|
78
|
+
"@vitest/coverage-istanbul": "~5.1.0",
|
|
79
|
+
"es-toolkit": "1.53.2",
|
|
80
80
|
"esbuild": "^0.28.2",
|
|
81
|
-
"fast-check": "^4.10.
|
|
81
|
+
"fast-check": "^4.10.3",
|
|
82
82
|
"flat": "6.0.1",
|
|
83
83
|
"flattie": "1.1.1",
|
|
84
84
|
"miniflare": "^4.20260730.0",
|
|
85
85
|
"nestie": "1.0.3",
|
|
86
|
-
"playwright": "^1.
|
|
87
|
-
"publint": "^0.3.
|
|
88
|
-
"radashi": "
|
|
89
|
-
"tsdown": "^0.23.
|
|
86
|
+
"playwright": "^1.65.1",
|
|
87
|
+
"publint": "^0.3.25",
|
|
88
|
+
"radashi": "13.0.4",
|
|
89
|
+
"tsdown": "^0.23.7",
|
|
90
90
|
"typescript": "^7.0.2",
|
|
91
91
|
"typescript-5.0": "npm:typescript@5.0.4",
|
|
92
|
-
"vitest": "
|
|
92
|
+
"vitest": "~5.1.0"
|
|
93
93
|
},
|
|
94
94
|
"keywords": [
|
|
95
95
|
"flattify",
|