@anil-labs/factory 0.1.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/CHANGELOG.md +54 -0
- package/LICENSE +21 -0
- package/README.md +371 -0
- package/dist/builders/index.d.cts +40 -0
- package/dist/builders/index.d.ts +40 -0
- package/dist/chunks/faker-BOtDMmjd.cjs +1430 -0
- package/dist/chunks/faker-BOtDMmjd.cjs.map +1 -0
- package/dist/chunks/faker-BlEhpR26.mjs +1287 -0
- package/dist/chunks/faker-BlEhpR26.mjs.map +1 -0
- package/dist/chunks/persist-DcARfeC-.cjs +134 -0
- package/dist/chunks/persist-DcARfeC-.cjs.map +1 -0
- package/dist/chunks/persist-ZGX3NWMF.mjs +117 -0
- package/dist/chunks/persist-ZGX3NWMF.mjs.map +1 -0
- package/dist/core/collection.d.cts +41 -0
- package/dist/core/collection.d.ts +41 -0
- package/dist/core/factory.d.cts +115 -0
- package/dist/core/factory.d.ts +115 -0
- package/dist/core/index.d.cts +6 -0
- package/dist/core/index.d.ts +6 -0
- package/dist/core/registry.d.cts +20 -0
- package/dist/core/registry.d.ts +20 -0
- package/dist/core/sequence.d.cts +36 -0
- package/dist/core/sequence.d.ts +36 -0
- package/dist/core/types.d.cts +47 -0
- package/dist/core/types.d.ts +47 -0
- package/dist/faker/color.d.cts +22 -0
- package/dist/faker/color.d.ts +22 -0
- package/dist/faker/commerce.d.cts +21 -0
- package/dist/faker/commerce.d.ts +21 -0
- package/dist/faker/company.d.cts +20 -0
- package/dist/faker/company.d.ts +20 -0
- package/dist/faker/datatype.d.cts +16 -0
- package/dist/faker/datatype.d.ts +16 -0
- package/dist/faker/date.d.cts +29 -0
- package/dist/faker/date.d.ts +29 -0
- package/dist/faker/faker.d.cts +82 -0
- package/dist/faker/faker.d.ts +82 -0
- package/dist/faker/finance.d.cts +25 -0
- package/dist/faker/finance.d.ts +25 -0
- package/dist/faker/helpers.d.cts +52 -0
- package/dist/faker/helpers.d.ts +52 -0
- package/dist/faker/image.d.cts +22 -0
- package/dist/faker/image.d.ts +22 -0
- package/dist/faker/index.d.cts +21 -0
- package/dist/faker/index.d.ts +21 -0
- package/dist/faker/internet.d.cts +33 -0
- package/dist/faker/internet.d.ts +33 -0
- package/dist/faker/locale.d.cts +26 -0
- package/dist/faker/locale.d.ts +26 -0
- package/dist/faker/location.d.cts +30 -0
- package/dist/faker/location.d.ts +30 -0
- package/dist/faker/lorem.d.cts +26 -0
- package/dist/faker/lorem.d.ts +26 -0
- package/dist/faker/number.d.cts +31 -0
- package/dist/faker/number.d.ts +31 -0
- package/dist/faker/person.d.cts +29 -0
- package/dist/faker/person.d.ts +29 -0
- package/dist/faker/regex.d.cts +19 -0
- package/dist/faker/regex.d.ts +19 -0
- package/dist/faker/string.d.cts +33 -0
- package/dist/faker/string.d.ts +33 -0
- package/dist/faker/system.d.cts +29 -0
- package/dist/faker/system.d.ts +29 -0
- package/dist/faker.cjs +26 -0
- package/dist/faker.mjs +3 -0
- package/dist/index.cjs +635 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +37 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.mjs +596 -0
- package/dist/index.mjs.map +1 -0
- package/dist/locales/en.cjs +351 -0
- package/dist/locales/en.cjs.map +1 -0
- package/dist/locales/en.d.cts +11 -0
- package/dist/locales/en.d.ts +11 -0
- package/dist/locales/en.mjs +350 -0
- package/dist/locales/en.mjs.map +1 -0
- package/dist/locales/types.d.cts +30 -0
- package/dist/locales/types.d.ts +30 -0
- package/dist/persist/console.d.cts +15 -0
- package/dist/persist/console.d.ts +15 -0
- package/dist/persist/http.d.cts +42 -0
- package/dist/persist/http.d.ts +42 -0
- package/dist/persist/index.d.cts +5 -0
- package/dist/persist/index.d.ts +5 -0
- package/dist/persist/memory.d.cts +26 -0
- package/dist/persist/memory.d.ts +26 -0
- package/dist/persist.cjs +5 -0
- package/dist/persist.mjs +2 -0
- package/dist/prng/index.d.cts +5 -0
- package/dist/prng/index.d.ts +5 -0
- package/dist/prng/mulberry32.d.cts +19 -0
- package/dist/prng/mulberry32.d.ts +19 -0
- package/dist/prng/types.d.cts +23 -0
- package/dist/prng/types.d.ts +23 -0
- package/dist/snapshot/index.d.cts +16 -0
- package/dist/snapshot/index.d.ts +16 -0
- package/package.json +136 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [0.1.0] — Initial release
|
|
11
|
+
|
|
12
|
+
### Factory
|
|
13
|
+
|
|
14
|
+
- Immutable fluent builder: `defineFactory<T>(definition)` → chainable `Factory<T>`.
|
|
15
|
+
- States: `.state(name, value)` to register, `.state(name)` to activate, `.state(sequence)` to attach a sequence as state.
|
|
16
|
+
- Sequences: standalone `Sequence<T>` class + `.sequence(entries)` + `.fieldSequence(field, values)` for per-field cycling.
|
|
17
|
+
- Relations: `.has(childFactory, key)` (one-to-many), `.for(parent, foreignKey, resolver?)` (foreign key), `.hasAttached(child, key, pivot)` (many-to-many with pivot).
|
|
18
|
+
- Recycle pool: `.recycle(models, key)` + `.getRecycled(key)`.
|
|
19
|
+
- Hooks: `.afterMaking(fn)`, `.afterCreating(fn)` (sync or async).
|
|
20
|
+
- Persistence: `.persist(fn)` + terminal `.create()` / `.createMany()`.
|
|
21
|
+
- Per-factory determinism: `.seed(n)` / `.locale(name)` fork into an isolated `Faker`.
|
|
22
|
+
- Terminal methods: `.makeOne()`, `.makeMany()`, `.make()`, `.raw()`, `.collect()`.
|
|
23
|
+
|
|
24
|
+
### Faker
|
|
25
|
+
|
|
26
|
+
- Seedable PRNG (Mulberry32, deterministic).
|
|
27
|
+
- Faceted namespaces: `person`, `internet`, `location`, `lorem`, `date`, `number`, `string`, `color`, `company`, `commerce`, `finance`, `image`, `system`, `datatype`, `helpers`.
|
|
28
|
+
- Regex-based string generation: `faker.helpers.fromRegExp(/[A-Z]{3}\d{4}/)`.
|
|
29
|
+
- Weighted picking, unique-collection, enum-value, shuffle, slug, nanoid, UUID, IBAN, Luhn-valid card numbers.
|
|
30
|
+
- Locale system with pluggable registry: `registerLocale`, `getLocale`, `listLocales`. English (`en`) ships by default.
|
|
31
|
+
|
|
32
|
+
### Persistence adapters
|
|
33
|
+
|
|
34
|
+
- `memoryPersist<T>()` — in-memory store with `all()` / `find(id)` / `reset()`.
|
|
35
|
+
- `httpPersist<T>(url, options?)` — fetch-shaped POST adapter with response unwrapping.
|
|
36
|
+
- `consolePersist<T>(label?)` — logging adapter for inspection.
|
|
37
|
+
|
|
38
|
+
### Builders
|
|
39
|
+
|
|
40
|
+
- `oneOf(items)`, `maybe(value, chance?)`, `array(item, count)`, `lazy(fn)`.
|
|
41
|
+
|
|
42
|
+
### Snapshot
|
|
43
|
+
|
|
44
|
+
- `snapshot(value)` — normalises Dates / key order so test runners (vitest, jest) can snapshot stably.
|
|
45
|
+
|
|
46
|
+
### Packaging
|
|
47
|
+
|
|
48
|
+
- ESM + CJS dual build via Vite + `vite-plugin-dts`.
|
|
49
|
+
- Subpath exports: `@anil-labs/factory`, `/faker`, `/persist`, `/locales/en`.
|
|
50
|
+
- `.d.ts` + `.d.cts` for strict `node16` / `nodenext` type resolution.
|
|
51
|
+
- Zero runtime dependencies. Node 20+.
|
|
52
|
+
|
|
53
|
+
[Unreleased]: https://github.com/anilkumarthakur60/factory/compare/v0.1.0...HEAD
|
|
54
|
+
[0.1.0]: https://github.com/anilkumarthakur60/factory/releases/tag/v0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026-present Anil Kumar Thakur
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
# @anil-labs/factory
|
|
2
|
+
|
|
3
|
+
Laravel-inspired model factories + a seedable, locale-aware faceted faker for TypeScript. **Zero runtime dependencies.** ESM + CJS. Browser, Node 20+, Bun, Deno.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm i @anil-labs/factory
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { defineFactory, oneOf, faker } from '@anil-labs/factory'
|
|
11
|
+
|
|
12
|
+
interface User {
|
|
13
|
+
id: number
|
|
14
|
+
name: string
|
|
15
|
+
email: string
|
|
16
|
+
role: 'admin' | 'editor' | 'viewer'
|
|
17
|
+
active: boolean
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const UserFactory = defineFactory<User>(({ seq, faker }) => ({
|
|
21
|
+
id: seq,
|
|
22
|
+
name: faker.person.fullName(),
|
|
23
|
+
email: faker.internet.email(),
|
|
24
|
+
role: oneOf(['admin', 'editor', 'viewer']),
|
|
25
|
+
active: true,
|
|
26
|
+
}))
|
|
27
|
+
.state('admin', { role: 'admin' })
|
|
28
|
+
.state('inactive', { active: false })
|
|
29
|
+
|
|
30
|
+
UserFactory.make() // → User
|
|
31
|
+
UserFactory.count(5).make() // → User[]
|
|
32
|
+
UserFactory.state('admin').make() // → User with role: 'admin'
|
|
33
|
+
UserFactory.seed(42).make() // → deterministic User
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## Why one more factory library
|
|
39
|
+
|
|
40
|
+
Most JS data-generation libraries pick one job and stop:
|
|
41
|
+
|
|
42
|
+
- **`@faker-js/faker`** gives you faker, no model factories.
|
|
43
|
+
- **`fishery`**, **`rosie`** give you factories, no faker.
|
|
44
|
+
- **ORM-specific seeders** are tied to one DB layer.
|
|
45
|
+
|
|
46
|
+
`@anil-labs/factory` combines **Laravel-quality model factories** with a **seedable, locale-aware faker**, in one zero-dep package with first-class TypeScript types and pluggable persistence adapters. It's the package I wanted to find when I went looking.
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## Quick tour
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import {
|
|
54
|
+
defineFactory,
|
|
55
|
+
faker,
|
|
56
|
+
oneOf,
|
|
57
|
+
maybe,
|
|
58
|
+
array,
|
|
59
|
+
memoryPersist,
|
|
60
|
+
httpPersist,
|
|
61
|
+
sequence,
|
|
62
|
+
Collection,
|
|
63
|
+
FactoryRegistry,
|
|
64
|
+
} from '@anil-labs/factory'
|
|
65
|
+
|
|
66
|
+
// 1. A faker with namespaces
|
|
67
|
+
faker.seed(123)
|
|
68
|
+
faker.person.fullName() // "Olivia Patel"
|
|
69
|
+
faker.internet.email()
|
|
70
|
+
faker.location.streetAddress()
|
|
71
|
+
faker.string.uuid()
|
|
72
|
+
faker.lorem.paragraph()
|
|
73
|
+
faker.number.int({ min: 1, max: 100 })
|
|
74
|
+
faker.color.hex()
|
|
75
|
+
faker.finance.creditCardNumber() // Luhn-valid
|
|
76
|
+
faker.helpers.fromRegExp(/[A-Z]{3}-\d{4}/)
|
|
77
|
+
faker.helpers.weightedArrayElement([
|
|
78
|
+
{ value: 'rare', weight: 1 },
|
|
79
|
+
{ value: 'common', weight: 9 },
|
|
80
|
+
])
|
|
81
|
+
|
|
82
|
+
// 2. A factory
|
|
83
|
+
interface User {
|
|
84
|
+
id: number
|
|
85
|
+
name: string
|
|
86
|
+
email: string
|
|
87
|
+
active: boolean
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const UserFactory = defineFactory<User>(({ seq, faker }) => ({
|
|
91
|
+
id: seq,
|
|
92
|
+
name: faker.person.fullName(),
|
|
93
|
+
email: faker.internet.email(),
|
|
94
|
+
active: true,
|
|
95
|
+
}))
|
|
96
|
+
|
|
97
|
+
// 3. Build (sync) — Laravel parity
|
|
98
|
+
UserFactory.make() // single
|
|
99
|
+
UserFactory.count(10).make() // array
|
|
100
|
+
UserFactory.with({ active: false }).make() // overrides
|
|
101
|
+
UserFactory.state('inactive').make() // named states
|
|
102
|
+
UserFactory.fieldSequence('active', [true, false]).count(4).make()
|
|
103
|
+
UserFactory.sequence([{ active: true }, { active: false }])
|
|
104
|
+
.count(4)
|
|
105
|
+
.make()
|
|
106
|
+
|
|
107
|
+
// 4. Persist (async) — works with any backend
|
|
108
|
+
const memory = memoryPersist<User>()
|
|
109
|
+
await UserFactory.persist(memory).count(3).create()
|
|
110
|
+
memory.all() // [User, User, User]
|
|
111
|
+
|
|
112
|
+
await UserFactory.persist(httpPersist<User>('/api/users')).create()
|
|
113
|
+
|
|
114
|
+
// 5. Relationships
|
|
115
|
+
interface Post {
|
|
116
|
+
id: number
|
|
117
|
+
title: string
|
|
118
|
+
userId: number
|
|
119
|
+
}
|
|
120
|
+
const PostFactory = defineFactory<Post>(({ seq, faker }) => ({
|
|
121
|
+
id: seq,
|
|
122
|
+
title: faker.lorem.sentence(4),
|
|
123
|
+
userId: 0,
|
|
124
|
+
}))
|
|
125
|
+
|
|
126
|
+
UserFactory.has(PostFactory.count(3), 'posts').make() // attach children
|
|
127
|
+
PostFactory.for(UserFactory, 'userId').make() // set foreign key
|
|
128
|
+
|
|
129
|
+
interface Role {
|
|
130
|
+
id: number
|
|
131
|
+
name: string
|
|
132
|
+
}
|
|
133
|
+
const RoleFactory = defineFactory<Role>(({ seq }) => ({ id: seq, name: `Role ${seq}` }))
|
|
134
|
+
UserFactory.hasAttached(RoleFactory.count(2), 'roles', { active: true })
|
|
135
|
+
|
|
136
|
+
// 6. Collection helpers (Laravel-style)
|
|
137
|
+
const users = UserFactory.count(20).collect()
|
|
138
|
+
users.where((u) => u.active).count()
|
|
139
|
+
users.pluck('email').toArray()
|
|
140
|
+
|
|
141
|
+
// 7. Registry — look up by name
|
|
142
|
+
FactoryRegistry.register('User', UserFactory)
|
|
143
|
+
FactoryRegistry.resolve<User>('User').count(5).make()
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
## API
|
|
149
|
+
|
|
150
|
+
### `defineFactory<T>(definition, persist?)`
|
|
151
|
+
|
|
152
|
+
Create a new factory. `definition` receives a build context `{ seq, faker }` and returns the base attributes for one item.
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
const f = defineFactory<User>(({ seq, faker }) => ({
|
|
156
|
+
id: seq,
|
|
157
|
+
name: faker.person.fullName(),
|
|
158
|
+
}))
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
You can also use the static form: `Factory.define<T>(definition, persist?)`.
|
|
162
|
+
|
|
163
|
+
### Building methods
|
|
164
|
+
|
|
165
|
+
| Method | Returns | Notes |
|
|
166
|
+
| ----------------------------------------- | ------------ | --------------------------------------------------------------------------------------- |
|
|
167
|
+
| `.count(n)` | `Factory<T>` | Set how many items to build. Alias: `.times(n)`. |
|
|
168
|
+
| `.with(overrides)` | `Factory<T>` | Merge overrides into every built item. |
|
|
169
|
+
| `.state(name, value)` | `Factory<T>` | Register a named state — `value` may be a partial OR `(item, ctx) => partial`. |
|
|
170
|
+
| `.state(name)` | `Factory<T>` | Activate a registered state. |
|
|
171
|
+
| `.state(sequenceInstance)` | `Factory<T>` | Attach a sequence as state. |
|
|
172
|
+
| `.states({ a: …, b: … })` | `Factory<T>` | Bulk-register states. |
|
|
173
|
+
| `.sequence([…])` | `Factory<T>` | Cycle attribute patches across items. |
|
|
174
|
+
| `.fieldSequence(key, [v1, v2])` | `Factory<T>` | Cycle one field's values. |
|
|
175
|
+
| `.has(childFactory, key)` | `Factory<T>` | Attach `count` child records under `key`. |
|
|
176
|
+
| `.for(parent, foreignKey, resolver?)` | `Factory<T>` | Set the foreign-key on each child from a parent (factory, instance, or `() => parent`). |
|
|
177
|
+
| `.hasAttached(childFactory, key, pivot)` | `Factory<T>` | Many-to-many; `pivot` may be an object or `(parent, child) => object`. |
|
|
178
|
+
| `.recycle(model, key)` | `Factory<T>` | Add reusable model instances; `.getRecycled(key)` returns one. |
|
|
179
|
+
| `.afterMaking(fn)` / `.afterCreating(fn)` | `Factory<T>` | Lifecycle hooks; async hooks awaited only by `create()`. |
|
|
180
|
+
| `.persist(fn)` | `Factory<T>` | Register the persistence callback for `create()`. |
|
|
181
|
+
| `.seed(n)` | `Factory<T>` | Bind to a private deterministic Faker. |
|
|
182
|
+
| `.locale(name)` | `Factory<T>` | Bind to a private Faker on the named locale. |
|
|
183
|
+
|
|
184
|
+
### Terminal methods
|
|
185
|
+
|
|
186
|
+
| Method | Returns | Notes |
|
|
187
|
+
| --------------- | ------------------- | ------------------------------------------- |
|
|
188
|
+
| `.makeOne()` | `T` | Single item regardless of `count`. |
|
|
189
|
+
| `.makeMany()` | `T[]` | Array of `count` items. |
|
|
190
|
+
| `.make()` | `T \| T[]` | Single when `count === 1`, array otherwise. |
|
|
191
|
+
| `.raw()` | `T \| T[]` | Same shape as `make()`. |
|
|
192
|
+
| `.collect()` | `Collection<T>` | Always a `Collection`. |
|
|
193
|
+
| `.create()` | `Promise<T \| T[]>` | Persists via `.persist(fn)`. |
|
|
194
|
+
| `.createMany()` | `Promise<T[]>` | Always an array; persistence required. |
|
|
195
|
+
|
|
196
|
+
### `Sequence` / `sequence([...])`
|
|
197
|
+
|
|
198
|
+
Cycle attribute patches across items. Entries may be literal patches or `({ index, count }) => patch` closures.
|
|
199
|
+
|
|
200
|
+
```ts
|
|
201
|
+
const seq = sequence<{ name: string }>([
|
|
202
|
+
({ index }) => ({ name: `User ${index}` }),
|
|
203
|
+
{ name: 'Pinned' },
|
|
204
|
+
])
|
|
205
|
+
factory.state(seq).count(4).make() // → User 0, Pinned, User 2, Pinned
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
### `Collection<T>`
|
|
209
|
+
|
|
210
|
+
Immutable iterable wrapper. Methods: `count`, `isEmpty`, `each`, `map`, `pluck`, `where`, `first`, `last`, `sortBy`, `groupBy`, `reduce`, `toArray`, `[Symbol.iterator]`. The underlying `items` array is `Object.freeze`d.
|
|
211
|
+
|
|
212
|
+
### `FactoryRegistry`
|
|
213
|
+
|
|
214
|
+
Process-global lookup table.
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
FactoryRegistry.register('User', UserFactory)
|
|
218
|
+
FactoryRegistry.has('User') // true
|
|
219
|
+
FactoryRegistry.resolve<User>('User') // → Factory<User>
|
|
220
|
+
FactoryRegistry.names() // ['User']
|
|
221
|
+
FactoryRegistry.unregister('User')
|
|
222
|
+
FactoryRegistry.clear()
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### `Faker` (the data generator)
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
import { Faker, faker } from '@anil-labs/factory'
|
|
229
|
+
|
|
230
|
+
const f = new Faker({ seed: 7, locale: 'en' })
|
|
231
|
+
f.seed(7)
|
|
232
|
+
f.locale('en')
|
|
233
|
+
f.currentSeed()
|
|
234
|
+
f.currentLocale()
|
|
235
|
+
f.fork() // independent Faker with derived seed
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
Namespaces (all read from the shared PRNG + locale):
|
|
239
|
+
|
|
240
|
+
| Namespace | Examples |
|
|
241
|
+
| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
242
|
+
| `person` | `firstName({sex})`, `lastName`, `fullName({withPrefix})`, `prefix`, `suffix`, `sex` |
|
|
243
|
+
| `internet` | `email({firstName, lastName})`, `userName`, `url`, `domainName`, `ipv4`, `ipv6`, `mac`, `password(length)` |
|
|
244
|
+
| `location` | `streetAddress`, `city`, `state`, `zipCode`, `country`, `countryName`, `fullAddress`, `latitude`, `longitude` |
|
|
245
|
+
| `lorem` | `word`, `words(n)`, `sentence(n?)`, `paragraph(n?)`, `paragraphs(n)`, `text` |
|
|
246
|
+
| `date` | `past(days)`, `recent(days)`, `future(days)`, `soon(days)`, `between(a, b)`, `iso(days)`, `birthdate({min, max})` |
|
|
247
|
+
| `number` | `int({min, max})`, `float({min, max, decimals})`, `bigInt({min, max})`, `between(a, b)` |
|
|
248
|
+
| `string` | `uuid`, `nanoid(length)`, `alpha`, `numeric`, `alphanumeric`, `hexadecimal(length, {prefix})`, `sample`, `slug(words)` |
|
|
249
|
+
| `color` | `name`, `hex`, `rgb`, `hsl` |
|
|
250
|
+
| `company` | `name`, `jobTitle`, `buzzPhrase` |
|
|
251
|
+
| `commerce` | `productName`, `department`, `price(min, max, dec)`, `productDescription` |
|
|
252
|
+
| `finance` | `amount(min, max, dec, symbol)`, `accountNumber(digits)`, `creditCardNumber` (Luhn-valid), `currencyCode`, `iban(cc, len)`, `bitcoinAddress` |
|
|
253
|
+
| `image` | `url(w, h)`, `avatar(name)`, `dataUri(w, h)` |
|
|
254
|
+
| `system` | `fileName({withExt})`, `commonFileExt`, `fileExt`, `mimeType`, `directoryPath`, `filePath`, `semver` |
|
|
255
|
+
| `datatype` | `boolean(chance)` |
|
|
256
|
+
| `helpers` | `arrayElement`, `arrayElements(arr, count)`, `shuffle`, `weightedArrayElement`, `multiple(n, fn)`, `repeat`, `fromRegExp`, `unique(fn, n, opts)`, `enumValue`, `maybe(v, chance)` |
|
|
257
|
+
|
|
258
|
+
### Locales
|
|
259
|
+
|
|
260
|
+
The package ships with an English (`en`) corpus. Register your own:
|
|
261
|
+
|
|
262
|
+
```ts
|
|
263
|
+
import { registerLocale, faker } from '@anil-labs/factory'
|
|
264
|
+
|
|
265
|
+
registerLocale('np', {
|
|
266
|
+
title: 'नेपाली',
|
|
267
|
+
firstNames: ['Aakash', 'Bina', 'Chetana', 'Dipesh'],
|
|
268
|
+
lastNames: ['Adhikari', 'Bhandari', 'Chhetri', 'Dhakal'],
|
|
269
|
+
// ...etc — see the `LocaleData` interface
|
|
270
|
+
})
|
|
271
|
+
faker.locale('np')
|
|
272
|
+
faker.person.fullName() // "Dipesh Bhandari"
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
### Builder helpers
|
|
276
|
+
|
|
277
|
+
```ts
|
|
278
|
+
import { oneOf, maybe, array, lazy } from '@anil-labs/factory'
|
|
279
|
+
|
|
280
|
+
defineFactory<Profile>(({ faker }) => ({
|
|
281
|
+
role: oneOf(['admin', 'editor', 'viewer']),
|
|
282
|
+
bio: maybe(faker.lorem.paragraph(), 0.7),
|
|
283
|
+
tags: array(2, 5, () => faker.lorem.word()),
|
|
284
|
+
}))
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
### Persistence adapters
|
|
288
|
+
|
|
289
|
+
```ts
|
|
290
|
+
import { memoryPersist, httpPersist, consolePersist } from '@anil-labs/factory'
|
|
291
|
+
|
|
292
|
+
const store = memoryPersist<User>()
|
|
293
|
+
UserFactory.persist(store).create()
|
|
294
|
+
|
|
295
|
+
UserFactory.persist(
|
|
296
|
+
httpPersist<User>('/api/users', {
|
|
297
|
+
headers: {
|
|
298
|
+
/* … */
|
|
299
|
+
},
|
|
300
|
+
}),
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
UserFactory.persist(consolePersist<User>()).create() // just logs each item
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
Write your own:
|
|
307
|
+
|
|
308
|
+
```ts
|
|
309
|
+
const drizzlePersist =
|
|
310
|
+
(db): Persist<User> =>
|
|
311
|
+
async (user) => {
|
|
312
|
+
const [row] = await db.insert(users).values(user).returning()
|
|
313
|
+
return row
|
|
314
|
+
}
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
### Snapshot helper
|
|
318
|
+
|
|
319
|
+
Normalises `Date` instances and sorts object keys so snapshots are stable across machines.
|
|
320
|
+
|
|
321
|
+
```ts
|
|
322
|
+
import { snapshot } from '@anil-labs/factory'
|
|
323
|
+
|
|
324
|
+
expect(snapshot(UserFactory.seed(42).count(3).make())).toMatchSnapshot()
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
---
|
|
328
|
+
|
|
329
|
+
## Reproducibility
|
|
330
|
+
|
|
331
|
+
```ts
|
|
332
|
+
faker.seed(2026)
|
|
333
|
+
const a = faker.person.fullName()
|
|
334
|
+
faker.seed(2026)
|
|
335
|
+
const b = faker.person.fullName()
|
|
336
|
+
// a === b
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
Factory-scoped seeds don't pollute the default singleton:
|
|
340
|
+
|
|
341
|
+
```ts
|
|
342
|
+
defineFactory(...).seed(7) // private Faker; the global `faker` is untouched
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
---
|
|
346
|
+
|
|
347
|
+
## Laravel parity
|
|
348
|
+
|
|
349
|
+
| Laravel Eloquent Factory | `@anil-labs/factory` |
|
|
350
|
+
| -------------------------------------------------------------- | --------------------------------------------------------------- |
|
|
351
|
+
| `Factory::new()` | `defineFactory(...)` / `Factory.define(...)` |
|
|
352
|
+
| `->count(5)` | `.count(5)` |
|
|
353
|
+
| `->state(['admin' => true])` | `.with({ admin: true })` |
|
|
354
|
+
| `->state('admin')` (named) | `.state('admin', { … })` + `.state('admin')` |
|
|
355
|
+
| `->sequence(['a' => 1], ['a' => 2])` | `.sequence([{ a: 1 }, { a: 2 }])` |
|
|
356
|
+
| `->has(Post::factory()->count(3))` | `.has(PostFactory.count(3), 'posts')` |
|
|
357
|
+
| `->for(User::factory())` | `.for(UserFactory, 'userId')` |
|
|
358
|
+
| `->hasAttached(Role::factory()->count(2), ['active' => true])` | `.hasAttached(RoleFactory.count(2), 'roles', { active: true })` |
|
|
359
|
+
| `->recycle($airline)` | `.recycle(airline, 'Airline')` |
|
|
360
|
+
| `->afterMaking(fn ($u) => ...)` | `.afterMaking(u => ...)` |
|
|
361
|
+
| `->afterCreating(fn ($u) => ...)` | `.afterCreating(u => ...)` |
|
|
362
|
+
| `Factory::configure()` | chain methods on the factory directly |
|
|
363
|
+
| `->make()` | `.make()` |
|
|
364
|
+
| `->create()` | `.persist(fn).create()` |
|
|
365
|
+
| `->raw()` | `.raw()` |
|
|
366
|
+
|
|
367
|
+
---
|
|
368
|
+
|
|
369
|
+
## License
|
|
370
|
+
|
|
371
|
+
MIT.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pick one value from `choices` at call time. Reads from the default faker.
|
|
3
|
+
* Use inside factory definitions to express "any of these".
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* defineFactory<User>(({ faker }) => ({
|
|
8
|
+
* role: oneOf(['admin', 'editor', 'viewer']),
|
|
9
|
+
* }))
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export declare function oneOf<T>(choices: readonly T[]): T;
|
|
13
|
+
/**
|
|
14
|
+
* Return `value` with probability `chance`, else `undefined`. Useful for
|
|
15
|
+
* optional fields.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* { bio: maybe(faker.lorem.sentence(), 0.6) }
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export declare function maybe<T>(value: T, chance?: number): T | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Build an array of length `[min, max]` (inclusive) by calling `fn(index)`.
|
|
25
|
+
* If only `min` is given, the length is exactly `min`.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```ts
|
|
29
|
+
* { tags: array(2, 5, () => faker.lorem.word()) }
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export declare function array<T>(min: number, maxOrFn: number | ((i: number) => T), fn?: (i: number) => T): T[];
|
|
33
|
+
/**
|
|
34
|
+
* Defer evaluation until the value is actually read. Inside factory
|
|
35
|
+
* definitions you rarely need this (the definition is a function already),
|
|
36
|
+
* but it's useful for sequence entries and state values.
|
|
37
|
+
*/
|
|
38
|
+
export declare function lazy<T>(fn: () => T): {
|
|
39
|
+
resolve(): T;
|
|
40
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pick one value from `choices` at call time. Reads from the default faker.
|
|
3
|
+
* Use inside factory definitions to express "any of these".
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* defineFactory<User>(({ faker }) => ({
|
|
8
|
+
* role: oneOf(['admin', 'editor', 'viewer']),
|
|
9
|
+
* }))
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export declare function oneOf<T>(choices: readonly T[]): T;
|
|
13
|
+
/**
|
|
14
|
+
* Return `value` with probability `chance`, else `undefined`. Useful for
|
|
15
|
+
* optional fields.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* { bio: maybe(faker.lorem.sentence(), 0.6) }
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export declare function maybe<T>(value: T, chance?: number): T | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Build an array of length `[min, max]` (inclusive) by calling `fn(index)`.
|
|
25
|
+
* If only `min` is given, the length is exactly `min`.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```ts
|
|
29
|
+
* { tags: array(2, 5, () => faker.lorem.word()) }
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export declare function array<T>(min: number, maxOrFn: number | ((i: number) => T), fn?: (i: number) => T): T[];
|
|
33
|
+
/**
|
|
34
|
+
* Defer evaluation until the value is actually read. Inside factory
|
|
35
|
+
* definitions you rarely need this (the definition is a function already),
|
|
36
|
+
* but it's useful for sequence entries and state values.
|
|
37
|
+
*/
|
|
38
|
+
export declare function lazy<T>(fn: () => T): {
|
|
39
|
+
resolve(): T;
|
|
40
|
+
};
|