@nemmtor/ts-databuilders 0.0.1-alpha.0 → 0.0.1-alpha.10
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 +454 -10
- package/package.json +26 -12
- package/dist/main.js +0 -21
package/README.md
CHANGED
|
@@ -1,14 +1,458 @@
|
|
|
1
1
|
# 🧱 TS DataBuilders
|
|
2
|
-
|
|
3
|
-
Just add a @DataBuilder JSDoc tag, run one command, and get a fully-typed builder ready to use in your tests or factories.
|
|
2
|
+
Automatically generate type-safe builder classes from your TypeScript types to write cleaner, more focused tests.
|
|
4
3
|
|
|
5
|
-
|
|
4
|
+
## Installation
|
|
5
|
+
Install the package:
|
|
6
|
+
```bash
|
|
7
|
+
# npm
|
|
8
|
+
npm install -D @nemmtor/ts-databuilders
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
# pnpm
|
|
11
|
+
pnpm add -D @nemmtor/ts-databuilders
|
|
8
12
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
# yarn
|
|
14
|
+
yarn add -D @nemmtor/ts-databuilders
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Configuration
|
|
18
|
+
All configuration is optional with sensible defaults.
|
|
19
|
+
|
|
20
|
+
### Initialize Config File (optional)
|
|
21
|
+
Generate a default `ts-databuilders.json` configuration file:
|
|
22
|
+
```bash
|
|
23
|
+
pnpm ts-databuilders init
|
|
24
|
+
```
|
|
25
|
+
You can also generate configuration file by providing values step by step in an interactive wizard:
|
|
26
|
+
```bash
|
|
27
|
+
pnpm ts-databuilders init --wizard
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Configure via CLI flags (optional):
|
|
31
|
+
```bash
|
|
32
|
+
pnpm ts-databuilders --output-dir="src/__generated__" --jsdoc-tag=MyBuilder
|
|
33
|
+
```
|
|
34
|
+
You can also provide configuration by going through interactive wizard:
|
|
35
|
+
```bash
|
|
36
|
+
pnpm ts-databuilders --wizard
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Options Reference
|
|
40
|
+
|
|
41
|
+
| Name | Flag | Description | Default |
|
|
42
|
+
|---------------|-------------------------------------------------------|-----------------------------------------|----------------------|
|
|
43
|
+
| jsdocTag | `--jsdoc-tag` | JSDoc tag to mark types for generation | `DataBuilder` |
|
|
44
|
+
| inlineDefaultJsdocTag | `--inline-default-jsdoc-tag` | JSDoc tag used to set default value of given field. | `DataBuilderDefault` |
|
|
45
|
+
| outputDir | `--output-dir -o` | Output directory for generated builders | `generated/builders` |
|
|
46
|
+
| include | `--include -i` | Glob pattern for source files | `src/**/*.ts{,x}` |
|
|
47
|
+
| fileSuffix | `--file-suffix` | File suffix for builder files | `.builder` |
|
|
48
|
+
| builderSuffix | `--builder-suffix` | Class name suffix | `Builder` |
|
|
49
|
+
| defaults | `--default-string --default-number --default-boolean` | Default values for primitives | See example above |
|
|
50
|
+
|
|
51
|
+
**Priority:** CLI flags > Config file > Built-in defaults
|
|
52
|
+
|
|
53
|
+
#### Debugging
|
|
54
|
+
In order to turn on debug logs pass a flag: `--log-level debug`.
|
|
55
|
+
|
|
56
|
+
## Quick Start
|
|
57
|
+
**1. Annotate your types with JSDoc:**
|
|
58
|
+
```ts
|
|
59
|
+
/**
|
|
60
|
+
* @DataBuilder
|
|
61
|
+
*/
|
|
62
|
+
type User = {
|
|
63
|
+
id: string;
|
|
64
|
+
email: string;
|
|
65
|
+
name: string;
|
|
66
|
+
isActive: boolean;
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
**2. Generate builders:**
|
|
70
|
+
```bash
|
|
71
|
+
pnpm ts-databuilders
|
|
72
|
+
```
|
|
73
|
+
For the `User` type above, you'll get:
|
|
74
|
+
```ts
|
|
75
|
+
import type { User } from "...";
|
|
76
|
+
import { DataBuilder } from "./data-builder";
|
|
77
|
+
|
|
78
|
+
export class UserBuilder extends DataBuilder<User> {
|
|
79
|
+
constructor() {
|
|
80
|
+
super({
|
|
81
|
+
id: "",
|
|
82
|
+
email: "",
|
|
83
|
+
name: "",
|
|
84
|
+
isActive: false
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
withId(id: User['id']) {
|
|
89
|
+
return this.with({ id });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
withEmail(email: User['email']) {
|
|
93
|
+
return this.with({ email });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
withName(name: User['name']) {
|
|
97
|
+
return this.with({ name });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
withIsActive(isActive: User['isActive']) {
|
|
101
|
+
return this.with({ isActive });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
**3. Use in your tests:**
|
|
107
|
+
```ts
|
|
108
|
+
import { UserBuilder } from '...';
|
|
109
|
+
|
|
110
|
+
const testUser = new UserBuilder()
|
|
111
|
+
.withEmail('test@example.com')
|
|
112
|
+
.withIsActive(false)
|
|
113
|
+
.build();
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Why?
|
|
117
|
+
Tests often become cluttered with boilerplate when you need to create complex objects just to test one specific field. DataBuilders let you focus on what matters:
|
|
118
|
+
Imagine testing a case where document aggregate should emit an event when it successfully update it's content:
|
|
119
|
+
```ts
|
|
120
|
+
it('should emit a ContentUpdatedEvent', () => {
|
|
121
|
+
const aggregate = DocumentAggregate.create({
|
|
122
|
+
id: '1',
|
|
123
|
+
createdAt: new Date(),
|
|
124
|
+
updatedAt: new Date(),
|
|
125
|
+
content: 'old-content'
|
|
126
|
+
});
|
|
127
|
+
const userId = '1';
|
|
128
|
+
|
|
129
|
+
aggregate.updateContent({ updatedBy: userId, content: 'new-content' });
|
|
130
|
+
|
|
131
|
+
expect(...);
|
|
132
|
+
})
|
|
133
|
+
```
|
|
134
|
+
Above code is obfuscated with all of the default values you need to provide in order to satisfy typescript.
|
|
135
|
+
Where in reality the only thing specific to this single test is the fact that some new content was provided to `updateContent` method.
|
|
136
|
+
|
|
137
|
+
Imagine even more complex scenario:
|
|
138
|
+
```tsx
|
|
139
|
+
it('should show validation error when email is invalid', async () => {
|
|
140
|
+
render(<ProfileForm defaultValues={{
|
|
141
|
+
firstName: '',
|
|
142
|
+
lastName: '',
|
|
143
|
+
age: 0,
|
|
144
|
+
socials: {
|
|
145
|
+
linkedin: '',
|
|
146
|
+
github: '',
|
|
147
|
+
website: '',
|
|
148
|
+
twitter: '',
|
|
149
|
+
},
|
|
150
|
+
address: {
|
|
151
|
+
street: '',
|
|
152
|
+
city: '',
|
|
153
|
+
state: '',
|
|
154
|
+
zip: '',
|
|
155
|
+
},
|
|
156
|
+
skills: [],
|
|
157
|
+
bio: '',
|
|
158
|
+
email: 'invalid-email'
|
|
159
|
+
}}
|
|
160
|
+
/>)
|
|
161
|
+
|
|
162
|
+
await submitForm();
|
|
163
|
+
|
|
164
|
+
expect(...);
|
|
165
|
+
})
|
|
166
|
+
```
|
|
167
|
+
Again - in reality you should only be worried about email, not about whole form data.
|
|
168
|
+
|
|
169
|
+
Here's how above tests could be written with databuilders:
|
|
170
|
+
```ts
|
|
171
|
+
it('should emit a ContentUpdatedEvent', () => {
|
|
172
|
+
const aggregate = DocumentAggregate.create(
|
|
173
|
+
new CreateDocumentAggregatedPayloadBuilder().build()
|
|
174
|
+
);
|
|
175
|
+
|
|
176
|
+
aggregate.updateContent(
|
|
177
|
+
new UpdateDocumentContentPayloadBuilder().withContent('new-content').build()
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
expect(...);
|
|
181
|
+
})
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
```tsx
|
|
185
|
+
it('should show validation error when email is invalid', async () => {
|
|
186
|
+
render(<ProfileForm defaultValues={
|
|
187
|
+
new ProfileFormInputBuilder.withEmail('invalid-email').build()} />
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
await submitForm();
|
|
191
|
+
|
|
192
|
+
expect(...);
|
|
193
|
+
})
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
This not only makes the test code less verbose but also highlights what is really being tested.
|
|
197
|
+
|
|
198
|
+
**Why not use AI for that?** While AI can generate test data, ts-databuilders is fast, free and deterministic.
|
|
199
|
+
|
|
200
|
+
[Read more about data builders.](http://www.natpryce.com/articles/000714.html)
|
|
201
|
+
|
|
202
|
+
## Nested Builders
|
|
203
|
+
When your types contain complex nested objects, you can annotate their type definitions and TS DataBuilders will automatically generate nested builders, allowing you to compose them fluently.
|
|
204
|
+
### Example
|
|
205
|
+
|
|
206
|
+
**Input types:**
|
|
207
|
+
```ts
|
|
208
|
+
/**
|
|
209
|
+
* @DataBuilder
|
|
210
|
+
*/
|
|
211
|
+
export type User = {
|
|
212
|
+
name: string;
|
|
213
|
+
address: Address;
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* @DataBuilder
|
|
218
|
+
*/
|
|
219
|
+
export type Address = {
|
|
220
|
+
street: string;
|
|
221
|
+
city: string;
|
|
222
|
+
country: string;
|
|
223
|
+
};
|
|
224
|
+
```
|
|
225
|
+
**Generated builders:**
|
|
226
|
+
```ts
|
|
227
|
+
export class UserBuilder extends DataBuilder<User> {
|
|
228
|
+
constructor() {
|
|
229
|
+
super({
|
|
230
|
+
name: "",
|
|
231
|
+
address: new AddressBuilder().build();
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
withName(name: User['name']) {
|
|
236
|
+
return this.with({ name });
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
withAddress(address: DataBuilder<User['address']>) {
|
|
240
|
+
return this.with({ address: address.build() });
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export class AddressBuilder extends DataBuilder<Address> {
|
|
245
|
+
constructor() {
|
|
246
|
+
super({
|
|
247
|
+
street: "",
|
|
248
|
+
city: "",
|
|
249
|
+
country: ""
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
withStreet(street: Address['street']) {
|
|
254
|
+
return this.with({ street });
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
withCity(city: Address['city']) {
|
|
258
|
+
return this.with({ city });
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
withCountry(country: Address['country']) {
|
|
262
|
+
return this.with({ country });
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
**Usage:**
|
|
267
|
+
```ts
|
|
268
|
+
// ✅ Compose builders fluently
|
|
269
|
+
const user = new UserBuilder()
|
|
270
|
+
.withName('John Doe')
|
|
271
|
+
.withAddress(
|
|
272
|
+
new AddressBuilder()
|
|
273
|
+
.withStreet('123 Main St')
|
|
274
|
+
.withCity('New York')
|
|
275
|
+
)
|
|
276
|
+
.build();
|
|
277
|
+
// {..., address: { street: "123 Main st", city: "New York", country: "" } }
|
|
278
|
+
|
|
279
|
+
// ✅ Use default values
|
|
280
|
+
const userWithDefaultAddress = new UserBuilder().build();
|
|
281
|
+
// {..., address: { street: "", city: "", country: "" } }
|
|
282
|
+
|
|
283
|
+
// ✅ Override just one nested field
|
|
284
|
+
const userWithCity = new UserBuilder()
|
|
285
|
+
.withAddress(
|
|
286
|
+
new AddressBuilder()
|
|
287
|
+
.withCity('San Francisco')
|
|
288
|
+
)
|
|
289
|
+
.build();
|
|
290
|
+
// {..., address: { street: "", city: "San Francisco", country: "" } }
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
## Inline Default Values
|
|
294
|
+
|
|
295
|
+
While global defaults work well for most cases, sometimes you need field-specific default values. This is especially important for specialized string types like ISO dates, UUIDs etc.
|
|
296
|
+
|
|
297
|
+
```typescript
|
|
298
|
+
/** @DataBuilder */
|
|
299
|
+
type Order = {
|
|
300
|
+
id: string; // Empty string - won't work as UUID
|
|
301
|
+
createdAt: string; // Empty string - Invalid Date!
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Generated:
|
|
305
|
+
constructor() {
|
|
306
|
+
super({
|
|
307
|
+
id: "",
|
|
308
|
+
createdAt: "", // new Date("") = Invalid Date
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
Use `@DataBuilderDefault` JSDoc tag to override defaults per field:
|
|
314
|
+
```typescript
|
|
315
|
+
/** @DataBuilder */
|
|
316
|
+
type Order = {
|
|
317
|
+
/** @DataBuilderDefault '550e8400-e29b-41d4-a716-446655440000' */
|
|
318
|
+
id: string;
|
|
319
|
+
|
|
320
|
+
/** @DataBuilderDefault '2025-11-05T15:32:58.727Z' */
|
|
321
|
+
createdAt: string;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// Generated:
|
|
325
|
+
constructor() {
|
|
326
|
+
super({
|
|
327
|
+
id: '550e8400-e29b-41d4-a716-446655440000',
|
|
328
|
+
createdAt: '2025-11-05T15:32:58.727Z',
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
## Supported Types
|
|
334
|
+
|
|
335
|
+
The library supports a wide range of TypeScript type features:
|
|
336
|
+
|
|
337
|
+
✅ **Primitives & Built-ins**
|
|
338
|
+
- `string`, `number`, `boolean`, `Date`
|
|
339
|
+
- Literal types: `'active' | 'inactive'`, `1 | 2 | 3`
|
|
340
|
+
|
|
341
|
+
✅ **Complex Structures**
|
|
342
|
+
- Objects and nested objects
|
|
343
|
+
- Arrays: `string[]`, `Array<number>`
|
|
344
|
+
- Tuples: `[string, number]`
|
|
345
|
+
- Records: `Record<string, string>` `Record<'foo' | 'bar', string>`
|
|
346
|
+
|
|
347
|
+
✅ **Type Operations**
|
|
348
|
+
- Unions: `string | number | true | false`
|
|
349
|
+
- Intersections: `A & B`
|
|
350
|
+
- Utility types: `Pick<T, K>`, `Omit<T, K>`, `Partial<T>`, `Required<T>`, `Readonly<T>`, `Extract<T, U>`, `NonNullable<T>`
|
|
351
|
+
- Branded types: `type UserId = string & { __brand: 'UserId' }`
|
|
352
|
+
|
|
353
|
+
✅ **References**
|
|
354
|
+
- Type references from the same file
|
|
355
|
+
- Type references from other files
|
|
356
|
+
- External library types (e.g., `z.infer<typeof schema>`)
|
|
357
|
+
|
|
358
|
+
**For a comprehensive example** of supported types, check out the [example-data/bar.ts](https://github.com/nemmtor/ts-databuilders/blob/main/example-data/bar.ts) file in the repository. This file is used during development and demonstrates complex real-world type scenarios.
|
|
359
|
+
|
|
360
|
+
## Important Rules & Limitations
|
|
361
|
+
|
|
362
|
+
### Unique Builder Names
|
|
363
|
+
Each type annotated with the JSDoc tag must have a **unique name** across your codebase:
|
|
364
|
+
```ts
|
|
365
|
+
// ❌ Error: Duplicate builder names
|
|
366
|
+
// In file-a.ts
|
|
367
|
+
/** @DataBuilder */
|
|
368
|
+
export type User = { name: string };
|
|
369
|
+
|
|
370
|
+
// In file-b.ts
|
|
371
|
+
/** @DataBuilder */
|
|
372
|
+
export type User = { email: string }; // 💥 Duplicate!
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
### Exported Types Only
|
|
376
|
+
Types must be **exported** to generate builders:
|
|
377
|
+
```ts
|
|
378
|
+
// ❌ Won't work
|
|
379
|
+
/** @DataBuilder */
|
|
380
|
+
type User = { name: string };
|
|
381
|
+
|
|
382
|
+
// ✅ Works
|
|
383
|
+
/** @DataBuilder */
|
|
384
|
+
export type User = { name: string };
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
### Type Aliases Only
|
|
388
|
+
Currently, only **type aliases** are supported as root builder types. Interfaces, classes etc. are not supported:
|
|
389
|
+
```ts
|
|
390
|
+
// ❌ Not supported
|
|
391
|
+
/** @DataBuilder */
|
|
392
|
+
export interface User {
|
|
393
|
+
name: string;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// ❌ Not supported
|
|
397
|
+
/** @DataBuilder */
|
|
398
|
+
export class User {
|
|
399
|
+
name: string;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// ✅ Supported
|
|
403
|
+
/** @DataBuilder */
|
|
404
|
+
export type User = {
|
|
405
|
+
name: string;
|
|
406
|
+
};
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
### Unsupported TypeScript Features
|
|
410
|
+
|
|
411
|
+
Some TypeScript features are not yet supported and will cause generation errors:
|
|
412
|
+
|
|
413
|
+
- **Recursive types**: Types that reference themselves
|
|
414
|
+
```ts
|
|
415
|
+
// ❌ Not supported
|
|
416
|
+
type TreeNode = {
|
|
417
|
+
value: string;
|
|
418
|
+
children: TreeNode[]; // Self-reference
|
|
419
|
+
};
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
- **Function types**: Properties that are functions
|
|
423
|
+
```ts
|
|
424
|
+
// ❌ Not supported
|
|
425
|
+
type WithCallback = {
|
|
426
|
+
onSave: (data: string) => void;
|
|
427
|
+
};
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
- typeof, keyof, any, unknown, bigint, symbol
|
|
431
|
+
|
|
432
|
+
### Alpha Stage
|
|
433
|
+
⚠️ **This library is in active development**
|
|
434
|
+
|
|
435
|
+
- Breaking changes may occur
|
|
436
|
+
- Not all edge cases are covered yet
|
|
437
|
+
- Test thoroughly before using in production
|
|
438
|
+
|
|
439
|
+
**Found an issue?** Please [report it on GitHub](https://github.com/nemmtor/ts-databuilders/issues) with:
|
|
440
|
+
- A minimal reproducible example (if possible)
|
|
441
|
+
- The type definition causing the issue
|
|
442
|
+
- The error message received
|
|
443
|
+
- Your `ts-databuilders.json` config and any provided CLI flags (if applicable)
|
|
444
|
+
|
|
445
|
+
You can also turn on debug logs by passing `--log-level debug` flag.
|
|
446
|
+
|
|
447
|
+
Your feedback helps improve the library for everyone! 🙏
|
|
448
|
+
|
|
449
|
+
## Similar Projects
|
|
450
|
+
- [effect-builder](https://github.com/slashlifeai/effect-builder) - a runtime library for building objects with Effect Schema validation.
|
|
451
|
+
|
|
452
|
+
## Contributing
|
|
453
|
+
|
|
454
|
+
Contributions welcome! Please open an issue or PR on [GitHub](https://github.com/nemmtor/ts-databuilders).
|
|
455
|
+
|
|
456
|
+
## License
|
|
457
|
+
|
|
458
|
+
MIT © [nemmtor](https://github.com/nemmtor)
|
package/package.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
3
|
"name": "@nemmtor/ts-databuilders",
|
|
4
|
+
"version": "0.0.1-alpha.10",
|
|
4
5
|
"type": "module",
|
|
5
6
|
"private": false,
|
|
6
7
|
"description": "CLI tool that automatically generates builder classes from annotated TypeScript types.",
|
|
@@ -26,8 +27,11 @@
|
|
|
26
27
|
"dist"
|
|
27
28
|
],
|
|
28
29
|
"scripts": {
|
|
29
|
-
"build
|
|
30
|
-
"
|
|
30
|
+
"build": "tsup",
|
|
31
|
+
"test": "vitest run",
|
|
32
|
+
"test:watch": "vitest",
|
|
33
|
+
"test:coverage": "vitest run --coverage",
|
|
34
|
+
"start": "tsx src/main.ts",
|
|
31
35
|
"format": "biome format",
|
|
32
36
|
"format:fix": "biome format --write",
|
|
33
37
|
"lint": "biome lint",
|
|
@@ -36,26 +40,36 @@
|
|
|
36
40
|
"check-actions:fix": "pnpm exec biome check --formatter-enabled=false --linter-enabled=false --write",
|
|
37
41
|
"check-types": "tsc -b tsconfig.json",
|
|
38
42
|
"check-knip": "knip",
|
|
39
|
-
"check-dep": "depcruise --output-type err-long src"
|
|
43
|
+
"check-dep": "depcruise --output-type err-long src",
|
|
44
|
+
"gen:schema": "tsx scripts/generate-schema.ts"
|
|
40
45
|
},
|
|
41
46
|
"devDependencies": {
|
|
42
|
-
"@biomejs/biome": "^2.2
|
|
43
|
-
"@effect/language-service": "^0.
|
|
47
|
+
"@biomejs/biome": "^2.3.2",
|
|
48
|
+
"@effect/language-service": "^0.55.0",
|
|
49
|
+
"@effect/vitest": "^0.27.0",
|
|
44
50
|
"@total-typescript/ts-reset": "^0.6.1",
|
|
45
|
-
"@types/
|
|
46
|
-
"
|
|
47
|
-
"
|
|
51
|
+
"@types/node": "^24.0.0",
|
|
52
|
+
"@vitest/coverage-v8": "4.0.7",
|
|
53
|
+
"dependency-cruiser": "^17.2.0",
|
|
54
|
+
"knip": "^5.66.4",
|
|
55
|
+
"lefthook": "^2.0.2",
|
|
56
|
+
"tsup": "^8.5.0",
|
|
57
|
+
"tsx": "^4.20.6",
|
|
58
|
+
"vitest": "^4.0.6"
|
|
48
59
|
},
|
|
49
60
|
"peerDependencies": {
|
|
50
61
|
"typescript": "^5.9.3"
|
|
51
62
|
},
|
|
52
63
|
"dependencies": {
|
|
53
|
-
"@effect/cli": "^0.
|
|
54
|
-
"@effect/platform": "^0.
|
|
55
|
-
"@effect/platform-node": "^0.
|
|
64
|
+
"@effect/cli": "^0.72.0",
|
|
65
|
+
"@effect/platform": "^0.93.0",
|
|
66
|
+
"@effect/platform-node": "^0.100.0",
|
|
56
67
|
"effect": "^3.18.4",
|
|
57
68
|
"glob": "^11.0.3",
|
|
58
69
|
"ts-morph": "^27.0.2"
|
|
59
70
|
},
|
|
60
|
-
"
|
|
71
|
+
"packageManager": "pnpm@10.20.0+sha512.cf9998222162dd85864d0a8102e7892e7ba4ceadebbf5a31f9c2fce48dfce317a9c53b9f6464d1ef9042cba2e02ae02a9f7c143a2b438cd93c91840f0192b9dd",
|
|
72
|
+
"engines": {
|
|
73
|
+
"node": ">=20.0.0"
|
|
74
|
+
}
|
|
61
75
|
}
|
package/dist/main.js
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import*as Se from"@effect/platform-node/NodeContext";import*as Re from"@effect/platform-node/NodeRuntime";import{Effect as Ve}from"effect";import*as R from"@effect/cli/Command";import*as G from"effect/Layer";import*as le from"@effect/platform/FileSystem";import*as L from"effect/Effect";import*as oe from"effect/Context";import*as I from"effect/Schema";var ae={string:"",number:0,boolean:!1},ie=I.Struct({string:I.String,number:I.NumberFromString,boolean:I.BooleanFromString});class k extends oe.Tag("Configuration")(){}import Z from"node:path";import*as me from"@effect/platform/FileSystem";import*as w from"effect/Effect";import*as T from"effect/Match";import{Project as Pe}from"ts-morph";var q=(r)=>r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").replace(/_/g,"-").toLowerCase(),te=(r)=>{return r.split(/[-_\s]+/).flatMap((n)=>n.split(/(?=[A-Z])/)).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join("")},re=(r)=>{return r.split(/[-_\s]+/).flatMap((m)=>m.split(/(?=[A-Z])/)).filter(Boolean).map((m,e)=>{let o=m.toLowerCase();return e===0?o:o.charAt(0).toUpperCase()+o.slice(1)}).join("")};var se=(r)=>{let{fieldName:n,optional:m,typeName:e,isNestedBuilder:o}=r,l=n.replaceAll("'","").replaceAll('"',""),h=re(l),i=`with${te(l)}`,t=[`return this.with({ ${n}: ${h} });`],a=[`return this.with({ ${n}: ${h}.build() });`],f=o?a:t,u=[`if (!${h}) {`,` const { "${l}": _unused, ...rest } = this.build();`," return this.with(rest);","}"],C=m?[...u,...f]:f,B=`${e}['${l}']`;return{name:i,isPublic:!0,parameters:[{name:h,type:o?`DataBuilder<${B}>`:B}],statements:C}};class H extends w.Service()("@TSDataBuilders/BuilderGenerator",{effect:w.gen(function*(){let r=yield*me.FileSystem,{outputDir:n,fileSuffix:m,builderSuffix:e,defaults:o}=yield*k,l=(h)=>T.value(h).pipe(T.when({kind:"STRING"},()=>`"${o.string}"`),T.when({kind:"NUMBER"},()=>o.number),T.when({kind:"BOOLEAN"},()=>o.boolean),T.when({kind:"UNDEFINED"},()=>"undefined"),T.when({kind:"DATE"},()=>"new Date()"),T.when({kind:"ARRAY"},()=>"[]"),T.when({kind:"LITERAL"},(i)=>i.literalValue),T.when({kind:"TYPE_CAST"},(i)=>l(i.baseTypeMetadata)),T.when({kind:"TUPLE"},(i)=>{return`[${i.members.map((a)=>l(a)).map((a)=>`${a}`).join(", ")}]`}),T.when({kind:"TYPE_LITERAL"},(i)=>{return`{${Object.entries(i.metadata).filter(([a,{optional:f}])=>!f).map(([a,f])=>`${a}: ${l(f)}`).join(", ")}}`}),T.when({kind:"RECORD"},(i)=>{if(i.keyType.kind==="STRING"||i.keyType.kind==="NUMBER")return"{}";let t=l(i.keyType),a=l(i.valueType);return`{${t}: ${a}}`}),T.when({kind:"UNION"},(i)=>{let a=i.members.slice().sort((f,u)=>{let C=ce.indexOf(f.kind),B=ce.indexOf(u.kind);return(C===-1?1/0:C)-(B===-1?1/0:B)})[0];if(!a)return"never";return l(a)}),T.when({kind:"BUILDER"},(i)=>{return`new ${i.name}${e}().build()`}),T.exhaustive);return{generateBaseBuilder:w.fnUntraced(function*(){let h=Z.resolve(n,"data-builder.ts");yield*r.writeFileString(h,xe)}),generateBuilder:w.fnUntraced(function*(h){let i=new Pe,t=h.name,a=Z.resolve(n,`${q(t)}${m}.ts`),f=i.createSourceFile(a,"",{overwrite:!0}),u=Z.resolve(h.path),C=Z.relative(Z.dirname(a),u).replace(/\.ts$/,"");if(f.addImportDeclaration({namedImports:[t],isTypeOnly:!0,moduleSpecifier:C}),f.addImportDeclaration({namedImports:["DataBuilder"],moduleSpecifier:"./data-builder"}),h.shape.kind!=="TYPE_LITERAL")return yield*w.dieMessage("[BuilderGenerator]: Expected root type to be type literal");[...new Set(Me(h.shape.metadata))].forEach((g)=>{f.addImportDeclaration({namedImports:[`${g}${e}`],moduleSpecifier:`./${q(g)}${m}`})});let M=Object.entries(h.shape.metadata).filter(([g,{optional:b}])=>!b).map(([g,b])=>`${g}: ${b.kind==="TYPE_CAST"?`${l(b)} as ${t}['${g}']`:l(b)}`),P=Object.entries(h.shape.metadata).map(([g,{optional:b,kind:ee}])=>se({fieldName:g,optional:b,typeName:t,isNestedBuilder:ee==="BUILDER"})),F=`{
|
|
3
|
-
${M.join(`,
|
|
4
|
-
`)}
|
|
5
|
-
}`;f.addClass({name:`${t}${e}`,isExported:!0,extends:`DataBuilder<${t}>`,methods:[{name:"constructor",statements:[`super(${F});`]},...P]}),f.saveSync()})}})}){}var ce=["UNDEFINED","BOOLEAN","NUMBER","STRING","DATE","LITERAL","TYPE_LITERAL","ARRAY","TUPLE","RECORD"],xe=`export abstract class DataBuilder<T> {
|
|
6
|
-
private data: T;
|
|
7
|
-
|
|
8
|
-
constructor(initialData: T) {
|
|
9
|
-
this.data = initialData;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
public build(): Readonly<T> {
|
|
13
|
-
return structuredClone(this.data);
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
protected with(partial: Partial<T>): this {
|
|
17
|
-
this.data = { ...this.data, ...partial };
|
|
18
|
-
return this;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
`;function Me(r){let n=[];function m(e){switch(e.kind){case"BUILDER":n.push(e.name);break;case"TYPE_LITERAL":Object.values(e.metadata).forEach(m);break;case"UNION":case"TUPLE":e.members.forEach(m);break;case"RECORD":m(e.keyType),m(e.valueType);break}}return Object.values(r).forEach(m),n}class O extends L.Service()("@TSDataBuilders/Builders",{effect:L.gen(function*(){let r=yield*le.FileSystem,n=yield*H,{outputDir:m}=yield*k;return{create:L.fnUntraced(function*(e){if(yield*r.exists(m))yield*r.remove(m,{recursive:!0});yield*r.makeDirectory(m,{recursive:!0}),yield*n.generateBaseBuilder(),yield*L.all(e.map((l)=>n.generateBuilder(l)),{concurrency:"unbounded"})})}}),dependencies:[H.Default]}){}import*as s from"@effect/cli/Options";import*as N from"effect/HashMap";import*as J from"effect/Option";import*as $ from"effect/Schema";var Oe=s.text("jsdocTag").pipe(s.withDescription("JSDoc tag used to mark types for data building generation."),s.withSchema($.NonEmptyTrimmedString),s.withDefault("DataBuilder")),Ne=s.text("output-dir").pipe(s.withAlias("o"),s.withDescription("Output directory for generated builders."),s.withSchema($.NonEmptyTrimmedString),s.withDefault("generated/builders")),_e=s.text("include").pipe(s.withAlias("i"),s.withDescription("Glob pattern for files included while searching for jsdoc tag."),s.withSchema($.NonEmptyTrimmedString),s.withDefault("src/**/*.ts{,x}")),Ae=s.text("file-suffix").pipe(s.withDescription("File suffix for created builder files."),s.withSchema($.NonEmptyTrimmedString),s.withDefault(".builder")),Ue=s.text("builder-suffix").pipe(s.withDescription("Suffix for generated classes."),s.withSchema($.NonEmptyTrimmedString),s.withDefault("Builder")),je=s.keyValueMap("defaults").pipe(s.withDescription("Default values to be used in data builder constructor."),s.withSchema($.HashMapFromSelf({key:$.Literal("string","number","boolean"),value:$.String}).pipe($.transform(ie,{decode:(r)=>{return{string:r.pipe(N.get("string"),J.getOrElse(()=>"")),number:r.pipe(N.get("number"),J.getOrElse(()=>"0")),boolean:r.pipe(N.get("boolean"),J.getOrElse(()=>"false"))}},encode:(r)=>{return N.make(["string",r.string],["number",r.number],["boolean",r.boolean])},strict:!1}))),s.withDefault(ae)),fe={jsdocTag:Oe,outputDir:Ne,include:_e,fileSuffix:Ae,builderSuffix:Ue,defaults:je};import*as x from"effect/Chunk";import*as D from"effect/Effect";import*as he from"effect/Function";import*as U from"effect/Option";import*as X from"effect/Stream";import*as ue from"effect/Data";import*as de from"effect/Effect";import*as pe from"effect/Stream";import{glob as We}from"glob";class _ extends de.Service()("@TSDataBuilders/TreeWalker",{succeed:{walk:(r)=>{return pe.fromAsyncIterable(We.stream(r,{cwd:".",nodir:!0}),(n)=>new ne({cause:n}))}}}){}class ne extends ue.TaggedError("TreeWalkerError"){}import{FileSystem as Ye}from"@effect/platform";import*as A from"effect/Effect";import*as S from"effect/Stream";class Q extends A.Service()("@TSDataBuilders/FileContentChecker",{effect:A.gen(function*(){let r=yield*Ye.FileSystem,n=new TextDecoder;return{check:A.fnUntraced(function*(m){let{content:e,filePath:o}=m;return yield*r.stream(o,{chunkSize:16384}).pipe(S.map((i)=>n.decode(i,{stream:!0})),S.mapAccum("",(i,t)=>{let a=i+t;return[a.slice(-e.length+1),a.includes(e)]}),S.find(Boolean),S.runCollect)})}})}){}class j extends D.Service()("@TSDataBuilders/Finder",{effect:D.gen(function*(){let r=yield*Q,{include:n,jsdocTag:m}=yield*k,e=`@${m}`;return{find:D.fnUntraced(function*(){return yield*(yield*_).walk(n).pipe(X.mapEffect((i)=>r.check({filePath:i,content:e}).pipe(D.map(x.map((t)=>t?U.some(i):U.none()))),{concurrency:"unbounded"}),X.runCollect,D.map(x.flatMap(he.identity)),D.map(x.filter((i)=>U.isSome(i))),D.map(x.map((i)=>i.value)))})}}),dependencies:[Q.Default]}){}import*as ke from"@effect/platform/FileSystem";import*as V from"effect/Data";import*as p from"effect/Effect";import*as z from"effect/Either";import{Project as Ze,SyntaxKind as ve}from"ts-morph";import*as v from"effect/Data";import*as c from"effect/Effect";import*as d from"effect/Match";import*as Ce from"effect/Option";import{Node as Ge,SyntaxKind as E}from"ts-morph";class K extends c.Service()("@TSDataBuilders/TypeNodeParser",{effect:c.gen(function*(){let{jsdocTag:r}=yield*k,n=(m)=>c.gen(function*(){let{typeNode:e,optional:o}=m,l=e.getKind(),h=d.value(l).pipe(d.when(d.is(E.StringKeyword),()=>c.succeed({kind:"STRING",optional:o})),d.when(d.is(E.NumberKeyword),()=>c.succeed({kind:"NUMBER",optional:o})),d.when(d.is(E.BooleanKeyword),()=>c.succeed({kind:"BOOLEAN",optional:o})),d.when((t)=>t===E.TypeReference&&e.getText()==="Date",()=>c.succeed({kind:"DATE",optional:o})),d.when((t)=>t===E.UndefinedKeyword,()=>c.succeed({kind:"UNDEFINED",optional:o})),d.when((t)=>t===E.ArrayType,()=>c.succeed({kind:"ARRAY",optional:o})),d.when((t)=>t===E.LiteralType,()=>c.succeed({kind:"LITERAL",literalValue:e.asKindOrThrow(E.LiteralType).getLiteral().getText(),optional:o})),d.when((t)=>t===E.TypeLiteral,()=>c.gen(function*(){let a=e.asKindOrThrow(E.TypeLiteral).getMembers();return{kind:"TYPE_LITERAL",metadata:yield*c.reduce(a,{},(u,C)=>c.gen(function*(){if(!C.isKind(E.PropertySignature))return u;let B=C.getTypeNode();if(!B)return u;let M=C.getNameNode().getText(),P=C.hasQuestionToken(),F=yield*c.suspend(()=>n({typeNode:B,optional:P}));return{...u,[M]:F}})),optional:o}})),d.when(d.is(E.TupleType),()=>c.gen(function*(){let a=e.asKindOrThrow(E.TupleType).getElements(),f=yield*c.all(a.map((u)=>c.suspend(()=>n({typeNode:u,optional:!1}))));return{kind:"TUPLE",optional:o,members:f}})),d.when(d.is(E.TypeReference),()=>c.gen(function*(){let t=e.asKindOrThrow(E.TypeReference),a=t.getTypeName().getText(),f=t.getTypeArguments();if(a==="Record"){let[F,g]=f;if(!F||!g)return yield*new y({kind:l,raw:e.getText()});let b=yield*c.suspend(()=>n({typeNode:F,optional:!1})),ee=yield*c.suspend(()=>n({typeNode:g,optional:!1}));return{kind:"RECORD",keyType:b,valueType:ee,optional:o}}if(a==="Array")return{kind:"ARRAY",optional:o};let u=t.getType().getAliasSymbol();if(!u)return yield*new Te;let C=u.getDeclarations();if(C&&C.length>1)return yield*new Ee;let[B]=C;if(!B)return yield*new Be;let M=u?.getJsDocTags().map((F)=>F.getName()).includes(r);if(!Ge.isTypeAliasDeclaration(B))throw Error("TODO: for non-type-alias declarations (interfaces, etc.)");let P=B.getTypeNode();if(!P)return yield*new y({kind:l,raw:e.getText()});if(!M)return yield*c.suspend(()=>n({typeNode:P,optional:o}));return{kind:"BUILDER",name:B.getName(),optional:o}})),d.when(d.is(E.UnionType),()=>c.gen(function*(){let t=yield*c.all(e.asKindOrThrow(E.UnionType).getTypeNodes().map((a)=>c.suspend(()=>n({typeNode:a,optional:!1}))));return{kind:"UNION",optional:o,members:t}})),d.when(d.is(E.IntersectionType),()=>c.gen(function*(){let a=e.asKindOrThrow(E.IntersectionType).getTypeNodes(),f=[E.StringKeyword,E.NumberKeyword,E.BooleanKeyword],u=a.find((C)=>f.includes(C.getKind()));if(u&&a.length>1)return{kind:"TYPE_CAST",baseTypeMetadata:yield*c.suspend(()=>n({typeNode:u,optional:!1})),optional:o};throw Error("TODO: handle it")})),d.option);if(Ce.isNone(h))return yield*new y({kind:l,raw:e.getText()});return yield*h.value});return{generateMetadata:n}})}){}class y extends v.TaggedError("UnsupportedSyntaxKindError"){}class Ee extends v.TaggedError("MultipleSymbolDeclarationsError"){}class Be extends v.TaggedError("MissingSymbolDeclarationError"){}class Te extends v.TaggedError("MissingSymbolError"){}class W extends p.Service()("@TSDataBuilders/Parser",{effect:p.gen(function*(){let r=yield*ke.FileSystem,n=yield*K,{jsdocTag:m}=yield*k;return{generateBuildersMetadata:p.fnUntraced(function*(e){let o=yield*r.readFileString(e),l=yield*p.try({try:()=>{return new Ze().createSourceFile(e,o,{overwrite:!0}).getTypeAliases().filter((u)=>u.getJsDocs().flatMap((C)=>C.getTags().flatMap((B)=>B.getTagName())).includes(m)).map((u)=>{let C=u.getName();if(!u.isExported())return z.left(new ge({path:e,typeName:C}));let B=u.getTypeNode();if(!B||!B.isKind(ve.TypeLiteral))return z.left(new De({path:e,typeName:u.getName()}));return z.right({name:u.getName(),node:B})}).filter(Boolean)},catch:(t)=>new $e({cause:t})}),h=yield*p.all(l.map((t)=>t));return yield*p.all(h.map(({name:t,node:a})=>n.generateMetadata({typeNode:a,optional:!1}).pipe(p.map((f)=>({name:t,shape:f,path:e})),p.catchTag("UnsupportedSyntaxKindError",(f)=>p.fail(new be({kind:f.kind,raw:f.raw,path:e,typeName:t}))))))},p.catchTags({ParserError:(e)=>p.die(e),UnexportedDatabuilderError:(e)=>p.dieMessage(`[Parser]: Unexported databuilder ${e.typeName} at ${e.path}`),RichUnsupportedSyntaxKindError:(e)=>p.dieMessage(`[Parser]: Unsupported syntax kind of id: ${e.kind} with raw type: ${e.raw} found in type ${e.typeName} in file ${e.path}`),UnsupportedBuilderTypeError:(e)=>p.dieMessage(`[Parser]: Unsupported builder type ${e.typeName} in file ${e.path}.`)}))}}),dependencies:[K.Default]}){}class $e extends V.TaggedError("ParserError"){}class ge extends V.TaggedError("UnexportedDatabuilderError"){}class De extends V.TaggedError("UnsupportedBuilderTypeError"){}class be extends V.TaggedError("RichUnsupportedSyntaxKindError"){}import*as we from"effect/Chunk";import*as Y from"effect/Effect";import*as Fe from"effect/Function";var Ie=Y.gen(function*(){let r=yield*j,n=yield*W,m=yield*O,e=yield*r.find(),o=yield*Y.all(we.map(e,(l)=>n.generateBuildersMetadata(l)),{concurrency:"unbounded"}).pipe(Y.map((l)=>l.flatMap(Fe.identity)));if(o.length===0)return;yield*m.create(o)});var ze=R.make("ts-databuilders",fe),Le=ze.pipe(R.withHandler(()=>Ie),R.provide((r)=>G.mergeAll(j.Default,W.Default,O.Default,_.Default).pipe(G.provide(G.succeed(k,k.of(r))))),R.run({name:"Typescript Databuilders generator",version:"v0.0.1"}));Le(process.argv).pipe(Ve.provide(Se.layer),Re.runMain);
|