caseparser 5.0.0 → 6.0.0

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 CHANGED
@@ -3,21 +3,33 @@
3
3
  [![npm version](https://img.shields.io/npm/v/caseparser.svg)](https://www.npmjs.com/package/caseparser)
4
4
  [![JSR](https://jsr.io/badges/@nandomb/caseparser)](https://jsr.io/@nandomb/caseparser)
5
5
  [![JSR Score](https://jsr.io/badges/@nandomb/caseparser/score)](https://jsr.io/@nandomb/caseparser)
6
+ [![Socket Badge](https://badge.socket.dev/npm/package/caseparser)](https://socket.dev/npm/package/caseparser)
6
7
  [![CI](https://github.com/NandoMB/caseparser/actions/workflows/main.yml/badge.svg)](https://github.com/NandoMB/caseparser/actions/workflows/main.yml)
7
8
  [![npm downloads](https://img.shields.io/npm/dm/caseparser.svg)](https://www.npmjs.com/package/caseparser)
8
9
  [![license](https://img.shields.io/npm/l/caseparser.svg)](./LICENSE)
9
10
 
10
- Convert **Strings** and **JSON (Object Keys)** from a **case type** to another one with **type inference** based on parameter's type.
11
-
12
- - Zero dependencies
13
- - Written in TypeScript, published as ESM and CommonJS with type declarations
14
- - Available on [npm](https://www.npmjs.com/package/caseparser) and [JSR](https://jsr.io/@nandomb/caseparser)
15
- - Tree-shakeable
11
+ Convert **strings** and **object keys** to any case, **whatever case they are in now**, with the resulting keys inferred by TypeScript.
16
12
 
13
+ - **Any case in:** no need to know or normalize the input first. Keys in different cases can even be mixed in the same object
14
+ - **Deep:** nested objects and objects inside arrays are converted too
15
+ - **Typed:** your editor autocompletes the converted keys
16
+ - Zero dependencies, tree-shakeable, ESM and CommonJS, on [npm](https://www.npmjs.com/package/caseparser) and [JSR](https://jsr.io/@nandomb/caseparser)
17
17
 
18
18
  ###### Note:
19
19
  > If you're looking for version 1.x.x, [click here](https://github.com/NandoMB/caseparser/tree/v1.x.x) to see the docs.
20
20
 
21
+ ## Contents
22
+
23
+ - [Installation](#installation)
24
+ - [Quick start](#quick-start)
25
+ - [Cases](#cases)
26
+ - [Options](#options): [`allowSymbols`](#allowsymbols), [`ignore`](#ignore), [`transform`](#transform), [`separator`](#separator)
27
+ - [Type inference](#type-inference)
28
+ - [How keys are split into words](#how-keys-are-split-into-words)
29
+ - [Behavior and limitations](#behavior-and-limitations)
30
+ - [Benchmarks](#benchmarks)
31
+ - [Compatibility](#compatibility)
32
+ - [Security](#security)
21
33
 
22
34
  ## Installation
23
35
 
@@ -29,7 +41,7 @@ npm add caseparser # or: pnpm add caseparser / yarn add caseparser
29
41
  deno add jsr:@nandomb/caseparser
30
42
  ```
31
43
  ```ts
32
- import { camelToSnake } from '@nandomb/caseparser';
44
+ import { toSnake } from '@nandomb/caseparser';
33
45
  ```
34
46
  ###### Bun / Node.js from JSR
35
47
  ```sh
@@ -37,65 +49,52 @@ bunx jsr add @nandomb/caseparser
37
49
  npx jsr add @nandomb/caseparser
38
50
  ```
39
51
 
40
- ## Compatibility
41
-
42
- | Environment | Supported |
43
- | --- | --- |
44
- | ESM (`import`) | Node.js 12.22+, Deno, Bun, bundlers |
45
- | CommonJS (`require`) | Node.js 8+, Bun |
46
- | TypeScript | 4.5+ for the `toX` functions, 4.1+ for the deprecated `<from>To<To>` functions (any `moduleResolution`: `node`, `node16`/`nodenext`, `bundler`) |
47
- | Browsers | Any ES2015 browser (via bundler) |
48
- | Edge | Cloudflare Workers |
49
-
50
- Every change is tested in CI on Node.js 22, 24 and 26, Bun, Deno, Cloudflare Workers, and in Chromium, Firefox and WebKit.
51
-
52
- Ready-to-run projects for each environment (Node.js ESM/CommonJS, TypeScript, TypeScript 4.1, Bun, Deno, the browser and Cloudflare Workers) are in [examples/](./examples).
53
-
54
- ## How to use
55
-
56
- ```ts
57
- import { toSnake } from 'caseparser'; // ESM
58
- // const { toSnake } = require('caseparser'); // CommonJS
59
-
60
- toSnake('helloWorld'); // 'hello_world'
61
-
62
- toSnake({ firstName: 'John', addresses: [{ postalCode: '61105' }] });
63
- // { first_name: 'John', addresses: [{ postal_code: '61105' }] }
64
- ```
52
+ ## Quick start
65
53
 
66
- Objects are converted deeply, including objects inside arrays. The input is never mutated: a new object is returned.
67
-
68
- There is one function per target case, and the input can be in any case (see [From any case](#from-any-case)). Converting `'helloWorld'`:
69
-
70
- | Function | Result | Also known as |
71
- | --- | --- | --- |
72
- | `toCamel` | `helloWorld` | lowerCamelCase |
73
- | `toPascal` | `HelloWorld` | UpperCamelCase |
74
- | `toSnake` | `hello_world` | |
75
- | `toKebab` | `hello-world` | dash-case, param-case |
76
- | `toUpperSnake` | `HELLO_WORLD` | CONSTANT_CASE, SCREAMING_SNAKE_CASE |
77
- | `toUpperKebab` | `HELLO-WORLD` | COBOL-CASE, SCREAMING-KEBAB-CASE |
78
- | `toTrain` | `Hello-World` | Header-Case |
79
- | `toDot` | `hello.World` | dot.notation |
80
- | `toTitle` | `Hello World` | Capital Case |
81
- | `toSentence` | `Hello world` | |
82
- | `toPascalSnake` | `Hello_World` | Ada_Case, Title_Snake_Case |
83
- | `toPath` | `hello/World` | |
84
- | `toSpace` | `hello World` | |
85
- | `toLower` | `hello world` | no case |
86
- | `toUpper` | `HELLO WORLD` | |
87
-
88
- `toSpace`, `toPath` and `toDot` keep the original case of each word (`toPath('UserProfile')` → `'User/Profile'`); all the others lowercase the words first. To change the case of a whole string, use `toLowerCase()` or `toUpperCase()` on the result:
54
+ The input doesn't need a specific or consistent shape. Every key below is in a different case, and one call converts all of them, deeply:
89
55
 
90
56
  ```ts
91
- toPath('helloWorld'); // 'hello/World'
92
- toPath('helloWorld').toLowerCase(); // 'hello/world'
93
- toPath('helloWorld').toUpperCase(); // 'HELLO/WORLD'
57
+ import { toCamel } from 'caseparser'; // ESM
58
+ // const { toCamel } = require('caseparser'); // CommonJS
59
+
60
+ const response = {
61
+ userId: 42, // camelCase
62
+ FirstName: 'Ada', // PascalCase
63
+ last_name: 'Lovelace', // snake_case
64
+ 'birth-date': '1815-12-10', // kebab-case
65
+ ACCOUNT_STATUS: 'active', // UPPER_SNAKE_CASE
66
+ 'Content-Type': 'application/json', // Train-Case
67
+ 'Display Name': 'Countess', // Title Case
68
+ XMLHttpRequest: false, // acronym + word
69
+ $ref: '#/users/42', // symbol
70
+ 'billing address': { // nested objects...
71
+ 'Postal Code': '61105',
72
+ countryISO: 'US'
73
+ },
74
+ 'recent.orders': [{ order_id: 1, TotalAmount: 99.9 }], // ...and objects inside arrays
75
+ tags: ['someTag', 'another_tag'] // values are never converted
76
+ };
77
+
78
+ toCamel(response);
79
+ // {
80
+ // userId: 42,
81
+ // firstName: 'Ada',
82
+ // lastName: 'Lovelace',
83
+ // birthDate: '1815-12-10',
84
+ // accountStatus: 'active',
85
+ // contentType: 'application/json',
86
+ // displayName: 'Countess',
87
+ // xmlHttpRequest: false,
88
+ // ref: '#/users/42',
89
+ // billingAddress: { postalCode: '61105', countryIso: 'US' },
90
+ // recentOrders: [{ orderId: 1, totalAmount: 99.9 }],
91
+ // tags: ['someTag', 'another_tag']
92
+ // }
94
93
  ```
95
94
 
96
- Don't chain `toX` functions for this (`toUpper(toPath(...))`): each one splits its input into words again, so `/` and `.` would be treated as separators or symbols.
95
+ Strings work the same way: `toSnake('helloWorld')`, `toSnake('Hello World')` and `toSnake('HELLO-WORLD')` all return `'hello_world'`.
97
96
 
98
- ### Typical use: API responses
97
+ The input is never mutated: a new object is returned. A typical use is converting API payloads on the way in and out:
99
98
 
100
99
  ```ts
101
100
  import { toCamel, toSnake } from 'caseparser';
@@ -105,53 +104,123 @@ const user = toCamel(await res.json()); // { firstName, lastName, ... }
105
104
 
106
105
  await fetch('/api/users/1', {
107
106
  method: 'PUT',
108
- body: JSON.stringify(toSnake(user)), // back to { first_name, ... }
107
+ body: JSON.stringify(toSnake(user)), // back to { first_name, ... }
109
108
  });
110
109
  ```
111
110
 
112
- ### Type inference
111
+ ## Cases
113
112
 
114
- The resulting keys are inferred at the type level, so your editor autocompletes the converted names:
113
+ There is one function per target case, and each one accepts input in any case:
114
+
115
+ | Function | `'helloWorld'` → | `'LAST_login_AT'` → | Also known as |
116
+ | --- | --- | --- | --- |
117
+ | `toCamel` | `helloWorld` | `lastLoginAt` | lowerCamelCase |
118
+ | `toPascal` | `HelloWorld` | `LastLoginAt` | UpperCamelCase |
119
+ | `toSnake` | `hello_world` | `last_login_at` | |
120
+ | `toKebab` | `hello-world` | `last-login-at` | dash-case, param-case |
121
+ | `toUpperSnake` | `HELLO_WORLD` | `LAST_LOGIN_AT` | CONSTANT_CASE, SCREAMING_SNAKE_CASE |
122
+ | `toUpperKebab` | `HELLO-WORLD` | `LAST-LOGIN-AT` | COBOL-CASE, SCREAMING-KEBAB-CASE |
123
+ | `toTrain` | `Hello-World` | `Last-Login-At` | Header-Case |
124
+ | `toTitle` | `Hello World` | `Last Login At` | Capital Case |
125
+ | `toSentence` | `Hello world` | `Last login at` | |
126
+ | `toPascalSnake` | `Hello_World` | `Last_Login_At` | Ada_Case, Title_Snake_Case |
127
+ | `toLower` | `hello world` | `last login at` | no case |
128
+ | `toUpper` | `HELLO WORLD` | `LAST LOGIN AT` | |
129
+ | `toDot` | `hello.World` | `LAST.login.AT` | dot.notation |
130
+ | `toPath` | `hello/World` | `LAST/login/AT` | |
131
+ | `toSpace` | `hello World` | `LAST login AT` | |
132
+
133
+ `toDot`, `toPath` and `toSpace` only change the separator: they keep the original case of each word (upper, lower or mixed). To change it, see [`transform`](#transform).
134
+
135
+ ## Options
136
+
137
+ Every function takes an optional second argument.
138
+
139
+ ### `allowSymbols`
140
+
141
+ Symbols (ASCII punctuation such as `$`, `@`, `#` or `%`) are removed by default. `allowSymbols: true` keeps all of them, and an array keeps only the listed ones. It can be passed inside the options object, or directly as the second argument:
115
142
 
116
143
  ```ts
117
- const user = toCamel({ first_name: 'John', addresses: [{ postal_code: '61105' }] });
118
- // ^? { firstName: string; addresses: { postalCode: string }[] }
144
+ const data = { $ref: 1, '@type': 'User', 'discount%': 10 };
119
145
 
120
- user.firstName; // ✅
121
- user.first_name; // ❌ Property 'first_name' does not exist
146
+ toCamel(data); // { ref: 1, type: 'User', discount: 10 }
147
+ toCamel(data, { allowSymbols: true }); // { $ref: 1, '@type': 'User', 'discount%': 10 }
148
+ toCamel(data, { allowSymbols: ['$'] }); // { $ref: 1, type: 'User', discount: 10 }
149
+
150
+ // shorthand
151
+ toCamel(data, true); // same as { allowSymbols: true }
152
+ toCamel(data, ['$']); // same as { allowSymbols: ['$'] }
122
153
  ```
123
154
 
124
- ### From any case
155
+ A kept symbol sticks to the start of the next word: `toPascal('$id', true)` → `'$Id'`. See [How keys are split into words](#how-keys-are-split-into-words) for the details.
156
+
157
+ ### `ignore`
125
158
 
126
- You don't need to know the input's case: the input is split into words whatever its case, so keys in different cases can even be mixed in the same object:
159
+ Object keys that are kept as they are, at any depth. Their values are still converted:
127
160
 
128
161
  ```ts
129
- import { toCamel, toSnake } from 'caseparser';
162
+ toCamel({ _id: 1, user_id: 2, extra_data: { inner_key: 3 } }, { ignore: ['_id', 'extra_data'] });
163
+ // { _id: 1, userId: 2, extra_data: { innerKey: 3 } }
164
+ ```
165
+
166
+ Keys are matched exactly as they are in the input. The inferred type keeps the ignored keys too. It only applies to object keys: `toSnake('userId', { ignore: ['userId'] })` still returns `'user_id'`.
167
+
168
+ ### `transform`
169
+
170
+ Only for `toDot` and `toPath`, which keep the original case of each word by default. `'lowercase'` or `'uppercase'` changes the case of the whole result, object keys included:
130
171
 
131
- toSnake('helloWorld'); // 'hello_world'
132
- toSnake('Hello World'); // 'hello_world'
133
- toSnake('HELLO-WORLD'); // 'hello_world'
172
+ ```ts
173
+ toDot('LAST_login_AT'); // 'LAST.login.AT'
174
+ toDot('LAST_login_AT', { transform: 'lowercase' }); // 'last.login.at'
175
+ toPath('LAST_login_AT', { transform: 'uppercase' }); // 'LAST/LOGIN/AT'
176
+
177
+ toDot({ user_ID: 1, LAST_name: 'Doe' }, { transform: 'lowercase' });
178
+ // { 'user.id': 1, 'last.name': 'Doe' }
179
+
180
+ toDot('$UserId', { allowSymbols: true, transform: 'lowercase' }); // '$user.id'
181
+ ```
134
182
 
135
- toCamel({ user_id: 1, 'Last-Name': 'Doe', XMLHttpRequest: true });
136
- // ^? { userId: number; lastName: string; xmlHttpRequest: boolean }
183
+ `toSpace` has no `transform`: use `toLower` or `toUpper` instead. Don't chain functions for this (`toUpper(toPath(...))`): each one splits its input into words again, so `/` and `.` would be treated as separators or symbols.
184
+
185
+ ### `separator`
186
+
187
+ Only for `toPath`. It joins the words with `'/'` by default, or with `'\\'`:
188
+
189
+ ```ts
190
+ toPath('users/profilePicture'); // 'users/profile/Picture'
191
+ toPath('users/profilePicture', { separator: '\\' }); // 'users\\profile\\Picture'
192
+ toPath('users\\profilePicture', { separator: '/' }); // 'users/profile/Picture'
137
193
  ```
138
194
 
139
- Words are split on `_`, `-`, `.` and spaces, and before an uppercase letter that starts a new word.
195
+ In `toPath`, `/` and `\` in the input also separate words, so paths can be converted from one separator to the other. In the other functions they are symbols.
140
196
 
141
- ### Symbols
197
+ ## Type inference
142
198
 
143
- Symbols (ASCII punctuation such as `$`, `@`, `#` or `%`) are removed by default. Pass a second argument to keep them: `true` keeps all of them, and an array keeps only the listed ones:
199
+ The converted keys are inferred at the type level, so your editor autocompletes them and catches typos:
144
200
 
145
201
  ```ts
146
- toCamel({ $ref: 1, '@type': 'user' }); // { ref: 1, type: 'user' }
147
- toCamel({ $ref: 1, '@type': 'user' }, true); // { $ref: 1, '@type': 'user' }
148
- toCamel({ $ref: 1, '@type': 'user' }, ['$']); // { $ref: 1, type: 'user' }
202
+ const user = toCamel({ first_name: 'John', 'Home Addresses': [{ POSTAL_CODE: '61105' }] });
203
+ // ^? { firstName: string; homeAddresses: { postalCode: string }[] }
149
204
 
150
- toCamel('$Hello-world', true); // '$helloWorld'
151
- toPascal('$id', true); // '$Id'
205
+ user.firstName; // ✅
206
+ user.first_name; // ❌ Property 'first_name' does not exist
152
207
  ```
153
208
 
154
- A symbol always starts a new word, so the words are the same whether symbols are kept or not. A kept symbol sticks to the start of the next word, or to the end of the previous one when no word follows:
209
+ The options are part of the inference: `toCamel({ $ref: 1 }, ['$'])` is typed `{ $ref: number }`, and `toDot({ UserId: 1 }, { transform: 'lowercase' })` is typed `{ 'user.id': number }`. When the options are only known at runtime (e.g. a `boolean` variable), the keys are typed as `string`.
210
+
211
+ ## How keys are split into words
212
+
213
+ Every function first splits the input into words, then joins them in the target case. A new word starts:
214
+
215
+ - **at a separator:** `_`, `-`, `.` or a space, which are removed. Repeated or leading separators are ignored: `toSnake('__private_flag')` → `'private_flag'`
216
+ - **at an uppercase letter after a lowercase letter or a digit:** `helloWorld` → `hello`, `world`
217
+ - **at the last letter of an acronym:** `XMLHttpRequest` → `xml`, `http`, `request`, and `userID` → `user`, `id`
218
+ - **at a symbol**, whether it's kept or not
219
+ - **at `/` or `\`, only in `toPath`** (in the other functions they are symbols)
220
+
221
+ Digits stay attached to the previous word: `toSnake('html5Parser')` → `'html5_parser'`.
222
+
223
+ A kept symbol sticks to the start of the next word, or to the end of the previous one when no word follows:
155
224
 
156
225
  ```ts
157
226
  toSnake('$$hello$World$$hi'); // 'hello_world_hi'
@@ -160,69 +229,120 @@ toSnake('user@name', true); // 'user_@name'
160
229
  toSnake('total%_count', true); // 'total%_count'
161
230
  ```
162
231
 
163
- The inferred types follow the same rules. `_`, `-` and `.` are separators, not symbols, so `_links` always becomes `links`.
164
-
165
- ## Conversion Types
166
-
167
- > **Deprecated:** the `<from>To<To>` functions below are deprecated in favor of the `toX` functions ([How to use](#how-to-use)) and will be removed in the next major version, which will also require TypeScript 4.7+. They keep working until then. See [Migrating to `toX`](#migrating-to-tox).
168
-
169
- Every function is named `<from>To<To>`, e.g. `snakeToCamel`. The case names are:
170
-
171
- | Name | Example |
172
- | --- | --- |
173
- | `camel` | `helloWorld` |
174
- | `pascal` | `HelloWorld` |
175
- | `snake` | `hello_world` |
176
- | `dash` | `hello-world` |
177
- | `upperSnake` | `HELLO_WORLD` |
178
- | `upperDash` | `HELLO-WORLD` |
179
- | `train` | `Hello-World` |
180
- | `dot` | `hello.world` |
181
- | `title` | `Hello World` |
182
- | `sentence` | `Hello world` |
183
-
184
- All 90 functions:
185
-
186
- - **camelCase:** `camelToPascal`, `camelToSnake`, `camelToDash`, `camelToUpperSnake`, `camelToUpperDash`, `camelToTrain`, `camelToDot`, `camelToTitle`, `camelToSentence`
187
- - **PascalCase:** `pascalToCamel`, `pascalToSnake`, `pascalToDash`, `pascalToUpperSnake`, `pascalToUpperDash`, `pascalToTrain`, `pascalToDot`, `pascalToTitle`, `pascalToSentence`
188
- - **snake_case:** `snakeToCamel`, `snakeToPascal`, `snakeToDash`, `snakeToUpperSnake`, `snakeToUpperDash`, `snakeToTrain`, `snakeToDot`, `snakeToTitle`, `snakeToSentence`
189
- - **dash-case:** `dashToCamel`, `dashToPascal`, `dashToSnake`, `dashToUpperSnake`, `dashToUpperDash`, `dashToTrain`, `dashToDot`, `dashToTitle`, `dashToSentence`
190
- - **UPPER_SNAKE_CASE:** `upperSnakeToCamel`, `upperSnakeToPascal`, `upperSnakeToSnake`, `upperSnakeToDash`, `upperSnakeToUpperDash`, `upperSnakeToTrain`, `upperSnakeToDot`, `upperSnakeToTitle`, `upperSnakeToSentence`
191
- - **UPPER-DASH-CASE:** `upperDashToCamel`, `upperDashToPascal`, `upperDashToSnake`, `upperDashToDash`, `upperDashToUpperSnake`, `upperDashToTrain`, `upperDashToDot`, `upperDashToTitle`, `upperDashToSentence`
192
- - **Train-Case:** `trainToCamel`, `trainToPascal`, `trainToSnake`, `trainToDash`, `trainToUpperSnake`, `trainToUpperDash`, `trainToDot`, `trainToTitle`, `trainToSentence`
193
- - **dot.case:** `dotToCamel`, `dotToPascal`, `dotToSnake`, `dotToDash`, `dotToUpperSnake`, `dotToUpperDash`, `dotToTrain`, `dotToTitle`, `dotToSentence`
194
- - **Title Case:** `titleToCamel`, `titleToPascal`, `titleToSnake`, `titleToDash`, `titleToUpperSnake`, `titleToUpperDash`, `titleToTrain`, `titleToDot`, `titleToSentence`
195
- - **Sentence case:** `sentenceToCamel`, `sentenceToPascal`, `sentenceToSnake`, `sentenceToDash`, `sentenceToUpperSnake`, `sentenceToUpperDash`, `sentenceToTrain`, `sentenceToDot`, `sentenceToTitle`
196
-
197
- ## Migrating to `toX`
198
-
199
- Replace each `<from>To<To>` function with the `toX` function for its target case, whatever the source case: `camelToSnake`, `dashToSnake`, `titleToSnake`... all become `toSnake`. The dash cases were renamed: `<from>ToDash` becomes `toKebab`, and `<from>ToUpperDash` becomes `toUpperKebab`.
200
-
201
- For well-formed keys (`firstName`, `first_name`) the result is the same. It differs when a key has consecutive uppercase letters or doesn't match the source case, and `toDot` keeps the original case of each word:
202
-
203
- | Call | `<from>To<To>` result | `toX` result |
204
- | --- | --- | --- |
205
- | `camelToSnake('userID')` / `toSnake('userID')` | `'user_i_d'` | `'user_id'` |
206
- | `camelToSnake('XMLHttpRequest')` / `toSnake('XMLHttpRequest')` | `'_x_m_l_http_request'` | `'xml_http_request'` |
207
- | `camelToSnake('HelloWorld')` / `toSnake('HelloWorld')` | `'_hello_world'` | `'hello_world'` |
208
- | `snakeToCamel('user_ID')` / `toCamel('user_ID')` | `'userID'` | `'userId'` |
209
- | `camelToDot('helloWorld')` / `toDot('helloWorld')` | `'hello.world'` | `'hello.World'` |
210
-
211
- If your code reads keys like `user_i_d` produced by the old functions, update those reads when migrating. The inferred types follow the new results, so TypeScript points out every place to change.
232
+ The inferred types follow the same rules.
212
233
 
213
234
  ## Behavior and limitations
214
235
 
215
236
  - **Only keys are converted, never values.** In `{ userName: 'johnDoe' }`, `userName` becomes `user_name` but `'johnDoe'` is kept. Strings inside arrays are kept too.
216
- - **Only plain objects are traversed.** `Date`, `Map`, `Set` and class instances are returned as they are (same reference), without converting their contents.
237
+ - **Only plain objects are traversed.** `Date`, `Map`, `Set`, class instances and objects without a prototype (`Object.create(null)`) are returned as they are (same reference), without converting their contents.
217
238
  - **Acronyms are kept together, but not restored:** `toSnake('userID')` → `'user_id'`, and back `toCamel('user_id')` → `'userId'`.
218
- - **Words are lowercased** before converting (except by `toSpace`, `toPath` and `toDot`), so `toCamel('X-API-Key')` → `'xApiKey'` and `toCamel('First Name')` → `'firstName'`.
239
+ - **Words are lowercased** before converting (except by `toDot`, `toPath` and `toSpace`), so `toCamel('X-API-Key')` → `'xApiKey'` and `toCamel('First Name')` → `'firstName'`.
219
240
  - **Title Case capitalizes every word**, including short ones: `toTitle('termsOfUse')` → `'Terms Of Use'`.
220
- - **Digits stay attached to the previous word:** `toSnake('html5Parser')` → `'html5_parser'`, `toSnake('user1Name')` → `'user1_name'`.
221
- - **Type inference has a key length limit.** TypeScript limits how deeply a type can recurse, and keys are converted character by character at the type level. The `toX` functions infer keys up to ~120 characters; longer keys fail to compile with `Type instantiation is excessively deep and possibly infinite`. The runtime conversion has no limit.
241
+ - **Very deep or circular objects throw.** Objects are converted recursively, so an object nested thousands of levels deep (~5,000 with the default stack of Node.js), or one that contains itself, throws `RangeError: Maximum call stack size exceeded`. `JSON.parse` accepts that depth, so limit it if the input is untrusted and the error is not handled.
242
+ - **Type inference has a key length limit.** TypeScript limits how deeply a type can recurse, and keys are converted character by character at the type level. Keys are inferred up to ~120 characters; longer keys fail to compile with `Type instantiation is excessively deep and possibly infinite`. The runtime conversion has no limit.
243
+
244
+ ### Design trade-offs
245
+
246
+ - **Nothing is kept between calls.** Within a call, each distinct key is converted once, so the 100 items of an API response cost about as much as one. That work is dropped when the call returns. A library that keeps converted keys between calls (camelcase-keys keeps up to 2 × 100,000) is faster when the same small object is converted over and over, but it holds that memory for the life of the process. With untrusted input (keys chosen by whoever sends the request), that cache can also fill up with keys that never come back and push out the useful ones. caseparser keeps no memory and no state between calls (see [memory](./bench/results/memory.md)).
247
+ - **The cache is only created for arrays.** The objects in an array usually share their keys, while the keys of a single object don't repeat, so small objects and objects with unique keys don't pay for it. Keys repeated in nested objects outside arrays are converted again.
248
+ - **A few hundred bytes more for the same two functions.** Bundling only `toCamel` and `toSnake` takes 1.5 KB gzipped (0.8 KB in 5.1.0), for the character tables and the key cache that make them faster. The whole package is smaller than before (1.8 KB gzipped, 3.1 KB in 5.1.0), because 6.0 removed the deprecated functions.
249
+ - **Correct before fast.** Every `toX` function splits words the same way (acronyms, digits, symbols, non-ASCII letters), even when a simpler rule would be faster for plain `snake_case` → `camelCase` keys.
250
+
251
+ ## Benchmarks
252
+
253
+ Median time to convert the same data to each case on Node.js 24 (Apple M3 Pro); lower is faster. Each library was measured in 3 rounds, in a different order each time, and the time is the mean of the 3 medians. In **bold**: the fastest, and any library tied with it (its results in the 3 rounds overlap with the fastest's). ❌: the library doesn't convert keys to that case.
254
+
255
+ #### Repeated keys: an API response with 100 users (2,104 keys)
256
+
257
+ Every user has the same keys, like the items of a real API response.
258
+
259
+ | Case | caseparser | caseparser@5.1.0 | change-case | camelcase-keys | snakecase-keys | humps | es-toolkit |
260
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
261
+ | camelCase | **59 µs** | 979 µs | 969 µs | 271 µs | ❌ | 546 µs | 392 µs |
262
+ | PascalCase | **59 µs** | 1.06 ms | 1.03 ms | 364 µs | ❌ | 637 µs | 506 µs |
263
+ | snake_case | **57 µs** | 891 µs | 1.07 ms | ❌ | 1.38 ms | 400 µs | 380 µs |
264
+ | kebab-case | **58 µs** | 916 µs | 1.09 ms | ❌ | 1.41 ms | 404 µs | 385 µs |
265
+ | UPPER_SNAKE | **58 µs** | 950 µs | 1.13 ms | ❌ | ❌ | ❌ | 455 µs |
266
+ | UPPER-KEBAB | **58 µs** | 947 µs | 1.15 ms | ❌ | ❌ | ❌ | ❌ |
267
+ | Train-Case | **58 µs** | 1.10 ms | 1.19 ms | ❌ | ❌ | ❌ | ❌ |
268
+ | Title Case | **58 µs** | 1.11 ms | 1.16 ms | ❌ | ❌ | ❌ | ❌ |
269
+ | Sentence case | **58 µs** | 1.02 ms | 1.15 ms | ❌ | ❌ | ❌ | ❌ |
270
+ | Pascal_Snake | **58 µs** | 1.10 ms | 1.17 ms | ❌ | ❌ | ❌ | ❌ |
271
+ | lower case | **57 µs** | 893 µs | 1.08 ms | ❌ | 1.40 ms | 401 µs | ❌ |
272
+ | UPPER CASE | **58 µs** | 962 µs | 1.15 ms | ❌ | ❌ | ❌ | ❌ |
273
+ | dot.case | **57 µs** | 903 µs | 1.07 ms | ❌ | 1.40 ms | 404 µs | ❌ |
274
+ | path/case | **57 µs** | 971 µs | 1.08 ms | ❌ | 1.41 ms | 406 µs | ❌ |
275
+
276
+ #### Unique keys: an object with 1,000 keys
277
+
278
+ No key repeats, in the object or between calls, so this measures how fast each key is converted.
279
+
280
+ | Case | caseparser | caseparser@5.1.0 | change-case | camelcase-keys | snakecase-keys | humps | es-toolkit |
281
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
282
+ | camelCase | **379 µs** | 1.46 ms | 796 µs | 1.11 ms | ❌ | 576 µs | 464 µs |
283
+ | PascalCase | **415 µs** | 2.08 ms | 888 µs | 1.35 ms | ❌ | 648 µs | **516 µs** |
284
+ | snake_case | **390 µs** | 1.32 ms | 849 µs | ❌ | 921 µs | **444 µs** | **404 µs** |
285
+ | kebab-case | **381 µs** | 1.98 ms | 909 µs | ❌ | 1.00 ms | 519 µs | **475 µs** |
286
+ | UPPER_SNAKE | **439 µs** | 2.01 ms | 956 µs | ❌ | ❌ | ❌ | **497 µs** |
287
+ | UPPER-KEBAB | **502 µs** | 1.42 ms | 987 µs | ❌ | ❌ | ❌ | ❌ |
288
+ | Train-Case | **448 µs** | 1.54 ms | 1.00 ms | ❌ | ❌ | ❌ | ❌ |
289
+ | Title Case | **416 µs** | 1.53 ms | 995 µs | ❌ | ❌ | ❌ | ❌ |
290
+ | Sentence case | **429 µs** | 2.08 ms | 926 µs | ❌ | ❌ | ❌ | ❌ |
291
+ | Pascal_Snake | **438 µs** | 991 µs | 1.00 ms | ❌ | ❌ | ❌ | ❌ |
292
+ | lower case | **441 µs** | 1.47 ms | 949 µs | ❌ | 995 µs | **509 µs** | ❌ |
293
+ | UPPER CASE | **460 µs** | 1.49 ms | 987 µs | ❌ | ❌ | ❌ | ❌ |
294
+ | dot.case | **442 µs** | 854 µs | 961 µs | ❌ | 1.00 ms | **515 µs** | ❌ |
295
+ | path/case | **475 µs** | 1.42 ms | 973 µs | ❌ | 1.01 ms | **521 µs** | ❌ |
296
+
297
+ With repeated keys, caseparser is 5–25x faster than the others, because it converts each distinct key once per call. With unique keys every library converts every key, and caseparser is the fastest or tied: this scenario creates a lot of garbage, so the results change up to ~20% between rounds for every library. For a small object (8 keys) converted over and over, camelcase-keys is faster to camelCase (0.75 µs, against 0.96 µs), because it keeps converted keys between calls (see [Design trade-offs](#design-trade-offs)); to snake_case, caseparser is the fastest (0.92 µs). For strings, caseparser is the fastest too (1.1 µs for 10 strings, against 1.4 µs for es-toolkit).
298
+
299
+ #### Memory
300
+
301
+ Heap used on Node.js, measured in a new process for each library:
302
+
303
+ | Library | Loading the library | One call: API response | One call: 1,000 unique keys | Kept after converting 256,000 keys |
304
+ | --- | ---: | ---: | ---: | ---: |
305
+ | caseparser | 70 KB | **121 KB** | **516 KB** | 0 |
306
+ | caseparser@5.1.0 | 289 KB | 2,348 KB | 2,719 KB | 0 |
307
+ | change-case | 136 KB | 2,850 KB | 1,610 KB | 0 |
308
+ | camelcase-keys | 209 KB | 1,516 KB | 1,742 KB | 11,483 KB |
309
+ | humps | **62 KB** | 1,183 KB | 759 KB | 0 |
310
+ | es-toolkit | 622 KB | 1,745 KB | 1,062 KB | 0 |
311
+
312
+ Loading is the heap used by importing the library, as the benchmarks do. One call is the memory allocated to convert to camelCase, including the result (62 KB and 48 KB). "Kept" is the memory still used after the calls: camelcase-keys keeps the keys it converted between calls (up to 2 × 100,000). 0 means under 10 KB, which is the noise of the measurement.
313
+
314
+ #### Compared with the same libraries
315
+
316
+ - **Cases:** caseparser and change-case convert keys to all 14 cases; humps to 7, es-toolkit and snakecase-keys to 5, camelcase-keys to 2.
317
+ - **Mixed input:** keys in different cases in one object are converted by all of them except humps.
318
+ - **Values:** caseparser and es-toolkit keep `Date`, `Map` and class instances as they are. The others turn some of them into broken copies or plain objects.
319
+ - **Types:** the converted keys are typed by caseparser, camelcase-keys and snakecase-keys. es-toolkit types some keys differently from its result, humps types the result as `object`, and change-case as `unknown`.
320
+ - **Security:** with `__proto__` in untrusted JSON, `humps.decamelizeKeys` replaces the result's prototype, and with a `constructor` key, snakecase-keys throws. The others, caseparser included, convert both.
321
+ - **Skipping keys:** caseparser (`ignore`), camelcase-keys, snakecase-keys and humps have an option to keep some keys as they are; change-case and es-toolkit don't.
322
+ - **Edge cases:** the libraries return different results, for example `userID` → `user_id` or `user_i_d`, and `html5Parser` → `html5_parser` or `html_5_parser`. See [what each library returns](./bench/results/edge-cases.md).
323
+
324
+ The benchmarks check that every library returns the expected output before measuring it, and each library is called in [its own file](./bench/libraries), with its documented options. The method and every result, with the raw numbers of every round, the date and the versions, are in [`bench/`](./bench). To run them all:
325
+
326
+ ```sh
327
+ pnpm install
328
+ pnpm benchmark
329
+ ```
330
+
331
+ ## Compatibility
332
+
333
+ | Environment | Supported |
334
+ | --- | --- |
335
+ | ESM (`import`) | Node.js 22+, Deno, Bun, bundlers |
336
+ | CommonJS (`require`) | Node.js 22+, Bun |
337
+ | TypeScript | 4.7+ (any `moduleResolution`: `node`, `node16`/`nodenext`, `bundler`) |
338
+ | Browsers | Any ES2015 browser (via bundler) |
339
+ | Edge | Cloudflare Workers ([example](./examples/cloudflare-worker)) |
340
+
341
+ On every change, CI runs the test suite on Node.js 22, 24 and 26, Bun and Deno, and in Chromium, Firefox and WebKit, and runs [a Cloudflare Worker](./examples/cloudflare-worker) on workerd with the packed package. It also checks the packed package with [publint](https://publint.dev) and [Are the Types Wrong?](https://arethetypeswrong.github.io), for ESM, CommonJS and every `moduleResolution`, and compiles the type declarations with TypeScript 4.7.
222
342
 
223
343
  ## Security
224
344
 
225
- caseparser is safe to use with untrusted input (e.g. request bodies or `JSON.parse` output): keys such as `__proto__` are copied as regular keys and never change an object's prototype, and only the object's own properties are converted.
345
+ caseparser is safe to use with untrusted input (e.g. request bodies or `JSON.parse` output): keys such as `__proto__` are copied as regular keys and never change an object's prototype, a `constructor` key doesn't stop an object from being converted, only the object's own properties are converted, and nothing is kept between calls. Limit the depth of untrusted input if a `RangeError` for very deep objects is not handled (see [Behavior and limitations](#behavior-and-limitations)).
226
346
 
227
347
  Releases are built and published from GitHub Actions without long-lived tokens (OIDC), with [npm provenance](https://docs.npmjs.com/generating-provenance-statements), so every published version can be traced back to the exact commit and workflow that built it. On npm, new versions are [staged](https://docs.npmjs.com/staged-publishing/) and only go live after a maintainer approves them with 2FA.
228
348