plantr 2.0.0 → 2.2.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/dist/index.d.ts +31 -25
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1050 -251
- package/dist/src/cli.d.ts +13 -3
- package/dist/src/cli.d.ts.map +1 -0
- package/dist/src/create-seeder-instance.d.ts +64 -78
- package/dist/src/create-seeder-instance.d.ts.map +1 -0
- package/dist/src/define-seeder.d.ts +4 -3
- package/dist/src/define-seeder.d.ts.map +1 -0
- package/dist/src/dependency-resolver.d.ts +2 -1
- package/dist/src/dependency-resolver.d.ts.map +1 -0
- package/dist/src/expect.d.ts +41 -0
- package/dist/src/expect.d.ts.map +1 -0
- package/dist/src/formatting.d.ts +36 -14
- package/dist/src/formatting.d.ts.map +1 -0
- package/dist/src/lazy-faker.d.ts +12 -0
- package/dist/src/lazy-faker.d.ts.map +1 -0
- package/dist/src/run-seeders.d.ts +46 -26
- package/dist/src/run-seeders.d.ts.map +1 -0
- package/dist/src/seeding-state.d.ts +15 -4
- package/dist/src/seeding-state.d.ts.map +1 -0
- package/dist/src/step.d.ts +79 -22
- package/dist/src/step.d.ts.map +1 -0
- package/dist/src/types.d.ts +121 -38
- package/dist/src/types.d.ts.map +1 -0
- package/dist/state.d.ts +2 -1
- package/dist/state.d.ts.map +1 -0
- package/dist/state.js +10 -2
- package/index.ts +70 -28
- package/package.json +5 -2
- package/readme.md +102 -52
- package/src/cli.ts +155 -22
- package/src/create-seeder-instance.ts +252 -111
- package/src/define-seeder.ts +14 -7
- package/src/dependency-resolver.ts +17 -28
- package/src/expect.ts +502 -0
- package/src/formatting.ts +142 -37
- package/src/lazy-faker.ts +46 -0
- package/src/run-seeders.ts +352 -122
- package/src/seeding-state.ts +27 -5
- package/src/step.ts +208 -64
- package/src/types.ts +173 -41
- package/state.ts +1 -1
package/readme.md
CHANGED
|
@@ -1,27 +1,30 @@
|
|
|
1
1
|
# plantr
|
|
2
2
|
|
|
3
|
-
A
|
|
3
|
+
A TypeScript database seeder library for **Bun and Node.js (>= 22)** with built-in faker, step workflow, parallel DAG execution, and end-to-end TypeScript inference.
|
|
4
4
|
|
|
5
5
|
## Features
|
|
6
6
|
|
|
7
|
-
- **
|
|
8
|
-
- **
|
|
9
|
-
- **
|
|
7
|
+
- **Bun & Node.js (>= 22)** - Runs natively on both Bun and Node.js (`node`, `tsx`, `ts-node`, `vitest`) with zero extra dependencies
|
|
8
|
+
- **Built-in utilities** - `faker`, `step`, and `expect` available in every seeder (`faker` is lazy-loaded on first access, English locale only by default; `expect` uses `bun:test` on Bun, a built-in `node:assert/strict` implementation on Node.js, or your own `expect` such as Vitest's)
|
|
9
|
+
- **End-to-end TypeScript** - Zero-boilerplate context inference, context-safe seeder registries, typed dependencies, typed `outputs`, discriminated-union `results`, compile-time missing dependency checks, and autocompleted `only`/`fresh`
|
|
10
|
+
- **Automatic ordering & parallel DAG execution** - Runs in dependency order with critical-path scheduling across independent branches via `concurrency` / `--concurrency`
|
|
10
11
|
- **Run a subset** - Run named seeders plus what they depend on (`--only`, `only`)
|
|
11
|
-
- **Step workflow** - Organize seeders into steps with progress logging
|
|
12
|
-
- **Step caching** - Skip steps that already ran, with versions and a `--fresh` override
|
|
13
|
-
- **Target guard** - Refuse to seed a database that is not local unless asked to
|
|
14
|
-
- **Lifecycle hooks** - `onBeforeAll` / `onAfterAll` for setup and teardown
|
|
12
|
+
- **Step workflow** - Organize seeders into sequential or `Promise.all` parallel steps with progress logging
|
|
13
|
+
- **Step caching** - Skip steps that already ran, with explicit keys, canonical JSON versions, single-query `getAll` preloading, batched `setMany` writes, and a `--fresh` override
|
|
14
|
+
- **Target guard** - Refuse to seed a database or emulator target that is not local unless asked to
|
|
15
|
+
- **Lifecycle hooks** - `onBeforeAll` / `onAfterAll(ctx)` for setup and teardown
|
|
15
16
|
- **Continue on failure** - Keep seeding independent data when one seeder fails
|
|
16
|
-
- **Dry run
|
|
17
|
+
- **Dry run & list modes** - Preview execution order, target, and descriptions without running
|
|
17
18
|
|
|
18
19
|
## Installation
|
|
19
20
|
|
|
20
21
|
```bash
|
|
21
22
|
bun add plantr
|
|
23
|
+
# or with pnpm / npm on Node.js >= 22
|
|
24
|
+
pnpm add plantr
|
|
22
25
|
```
|
|
23
26
|
|
|
24
|
-
> **
|
|
27
|
+
> **Runtime support:** Works on **Bun >= 1.0** and **Node.js >= 22**. On Bun, `expect` delegates to `bun:test`. On Node.js, `expect` uses a zero-dependency fallback backed by `node:assert/strict` (covering `toBe`, `toEqual`, `toStrictEqual`, `toBeDefined`, `toBeUndefined`, `toBeNull`, `toBeTruthy`, `toBeFalsy`, `toContain`, `toHaveLength`, `toMatch`, `toBeGreaterThan`, `toBeGreaterThanOrEqual`, `toBeLessThan`, `toBeLessThanOrEqual`, `toThrow`, and `.not.*`), or pass your own `expect` (for example Vitest's `expect`) via `createSeederInstance({ expect })`.
|
|
25
28
|
|
|
26
29
|
## Quick Start
|
|
27
30
|
|
|
@@ -29,24 +32,18 @@ bun add plantr
|
|
|
29
32
|
|
|
30
33
|
```typescript
|
|
31
34
|
// src/seed.ts
|
|
32
|
-
import { createSeederInstance
|
|
35
|
+
import { createSeederInstance } from 'plantr'
|
|
33
36
|
import { prisma } from './prisma'
|
|
34
37
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export const { defineSeeder, runSeeders, runSeedersCli } = createSeederInstance<MyContext>({
|
|
40
|
-
context: (base) => ({
|
|
41
|
-
...base, // faker, step, expect
|
|
42
|
-
prisma,
|
|
43
|
-
}),
|
|
38
|
+
export const { defineSeeder, runSeeders, runSeedersCli } = createSeederInstance({
|
|
39
|
+
// Optional: extra properties are merged onto { faker, step, expect } automatically
|
|
40
|
+
context: () => ({ prisma }),
|
|
44
41
|
target: () => process.env.DATABASE_URL,
|
|
45
42
|
onBeforeAll: async () => {
|
|
46
43
|
await prisma.$connect()
|
|
47
44
|
},
|
|
48
|
-
onAfterAll: async () => {
|
|
49
|
-
await prisma.$disconnect()
|
|
45
|
+
onAfterAll: async (ctx) => {
|
|
46
|
+
await ctx?.prisma.$disconnect()
|
|
50
47
|
},
|
|
51
48
|
})
|
|
52
49
|
```
|
|
@@ -124,6 +121,17 @@ if (import.meta.main) {
|
|
|
124
121
|
Run with:
|
|
125
122
|
```bash
|
|
126
123
|
bun run src/seed.ts
|
|
124
|
+
# or on Node.js:
|
|
125
|
+
npx tsx src/seed.ts
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Or programmatically (e.g. in tests) with fully typed `outputs`:
|
|
129
|
+
|
|
130
|
+
```typescript
|
|
131
|
+
const run = await runSeeders([userSeeder, postSeeder])
|
|
132
|
+
if (run.success) {
|
|
133
|
+
console.log(run.outputs.userSeeder.userId, run.outputs.postSeeder.postId)
|
|
134
|
+
}
|
|
127
135
|
```
|
|
128
136
|
|
|
129
137
|
## CLI Options
|
|
@@ -134,40 +142,56 @@ bun run src/seed.ts postSeeder # Run postSeeder and the seeders it de
|
|
|
134
142
|
bun run src/seed.ts --only a,b # Same as naming them
|
|
135
143
|
bun run src/seed.ts postSeeder --fresh # Ignore and overwrite postSeeder's cached steps
|
|
136
144
|
bun run src/seed.ts --fresh # Ignore and overwrite every cached step
|
|
145
|
+
bun run src/seed.ts --concurrency 4 # Run up to 4 independent seeders in parallel (-c 4)
|
|
137
146
|
bun run src/seed.ts --continue-on-failure # Keep running seeders that do not depend on a failed one
|
|
138
147
|
bun run src/seed.ts --allow-remote # Seed a target that is not local (see Target guard)
|
|
139
|
-
bun run src/seed.ts --
|
|
140
|
-
bun run src/seed.ts --
|
|
148
|
+
bun run src/seed.ts --quiet # Suppress progress/step lines, keep results table (-q)
|
|
149
|
+
bun run src/seed.ts --dry-run postSeeder # Show execution order, target, and descriptions without running
|
|
150
|
+
bun run src/seed.ts --list # List registered seeders in dependency order (-l)
|
|
151
|
+
bun run src/seed.ts --help # Show help and registered seeders (-h)
|
|
141
152
|
```
|
|
142
153
|
|
|
143
|
-
An unknown flag or seeder name prints the problem and exits 1 without seeding. `runSeedersCli` calls `process.exit`; pass `argv` to parse something other than `process.argv.slice(2)`. To embed seeding in your own CLI, call `runSeeders` with the options below instead.
|
|
154
|
+
An unknown flag, invalid `--concurrency`, or unknown seeder name prints the problem and exits 1 without seeding. `runSeedersCli` calls `process.exit`; pass `argv` to parse something other than `process.argv.slice(2)`. To embed seeding in your own CLI, call `runSeeders` with the options below instead.
|
|
144
155
|
|
|
145
156
|
## API
|
|
146
157
|
|
|
147
|
-
### `createSeederInstance(config)`
|
|
158
|
+
### `createSeederInstance(config?)`
|
|
148
159
|
|
|
149
160
|
```typescript
|
|
150
161
|
createSeederInstance({
|
|
151
|
-
//
|
|
152
|
-
//
|
|
153
|
-
|
|
162
|
+
// Optional: factory returning extra properties to merge onto { faker, step, expect }.
|
|
163
|
+
// Receives `base` if you want to build helpers around faker/step/expect or override a base key.
|
|
164
|
+
// Called once per run, after onBeforeAll. Omit to use BaseSeederContext directly.
|
|
165
|
+
context: (base) => ({ prisma }),
|
|
154
166
|
|
|
155
167
|
// Optional: cache for step caching (see Step Caching)
|
|
156
168
|
cache: {
|
|
157
|
-
get: async (key) => { /* return the stored value, or undefined */ },
|
|
169
|
+
get: async (key) => { /* return the stored value, or undefined / null */ },
|
|
158
170
|
set: async (key, value) => { /* store value, overwriting */ },
|
|
171
|
+
getAll: async () => { /* optional: preload all entries in one query */ },
|
|
172
|
+
setMany: async (entries) => { /* optional: flush all writes in one batch at end of run */ },
|
|
159
173
|
},
|
|
160
174
|
|
|
161
|
-
// Optional:
|
|
175
|
+
// Optional: default parallel concurrency for independent seeders (default: 1; e.g. 4 or Infinity)
|
|
176
|
+
concurrency: 4,
|
|
177
|
+
|
|
178
|
+
// Optional: custom Faker locale instance (default: lazy-loaded @faker-js/faker/locale/en)
|
|
179
|
+
faker: fakerDE,
|
|
180
|
+
|
|
181
|
+
// Optional: custom `expect` implementation (e.g. Vitest's `expect`).
|
|
182
|
+
// Defaults to `bun:test` on Bun and a built-in `node:assert/strict` fallback on Node.js.
|
|
183
|
+
expect: vitestExpect,
|
|
184
|
+
|
|
185
|
+
// Optional: the database or emulator URL the run writes to (see Target guard)
|
|
162
186
|
target: () => process.env.DATABASE_URL,
|
|
163
187
|
|
|
164
188
|
// Optional: seed faker per seeder (fakerSeed + hash of the seeder name),
|
|
165
|
-
// so every run generates the same data
|
|
189
|
+
// so every run generates the same data even when running concurrently
|
|
166
190
|
fakerSeed: 1,
|
|
167
191
|
|
|
168
192
|
// Optional: lifecycle hooks
|
|
169
193
|
onBeforeAll: async () => { /* setup; throw to refuse the run */ },
|
|
170
|
-
onAfterAll: async () => { /* teardown;
|
|
194
|
+
onAfterAll: async (ctx) => { /* teardown; receives ctx (or undefined if context() threw) */ },
|
|
171
195
|
})
|
|
172
196
|
```
|
|
173
197
|
|
|
@@ -179,11 +203,11 @@ Returns `{ defineSeeder, runSeeders, runSeedersCli, isSeedingActive }`.
|
|
|
179
203
|
defineSeeder({
|
|
180
204
|
name: 'seederName', // Unique name
|
|
181
205
|
description: 'What it does', // Optional
|
|
182
|
-
dependsOn: [otherSeeder], // Optional dependencies
|
|
183
|
-
run: async (ctx, deps) => {
|
|
206
|
+
dependsOn: [otherSeeder], // Optional dependencies (must have a compatible context)
|
|
207
|
+
run: async (ctx, deps) => { // Sync or async
|
|
184
208
|
// ctx has faker, step, expect, and your custom context
|
|
185
209
|
// deps has typed outputs from dependsOn seeders
|
|
186
|
-
return { /* output available to dependents */ }
|
|
210
|
+
return { /* output available to dependents and run.outputs */ }
|
|
187
211
|
},
|
|
188
212
|
})
|
|
189
213
|
```
|
|
@@ -191,19 +215,29 @@ defineSeeder({
|
|
|
191
215
|
### `runSeeders(seeders, options?)`
|
|
192
216
|
|
|
193
217
|
```typescript
|
|
194
|
-
const
|
|
218
|
+
const run = await runSeeders(seeders, {
|
|
195
219
|
printResults: true, // Print results table and errors (default: true)
|
|
196
220
|
verbose: true, // Print progress and step lines (default: true)
|
|
197
221
|
continueOnFailure: false, // Continue after failures (default: false)
|
|
198
|
-
only: ['postSeeder'], //
|
|
199
|
-
fresh: ['postSeeder'], // Ignore cached steps: true for all, or seeder names
|
|
222
|
+
only: ['postSeeder'], // Autocompleted & checked against seeders (default: all)
|
|
223
|
+
fresh: ['postSeeder'], // Ignore cached steps: true for all, or checked seeder names
|
|
200
224
|
allowRemote: false, // Seed a non-local target (default: false)
|
|
225
|
+
concurrency: 1, // Max independent seeders running in parallel (default: 1; supports Infinity)
|
|
201
226
|
})
|
|
202
227
|
```
|
|
203
228
|
|
|
204
|
-
`
|
|
229
|
+
`run` is a discriminated union on `success`:
|
|
230
|
+
- When `run.success` is `true`, `run.outputs` carries every completed seeder's typed output (non-optional for all seeders when `only` is omitted, or for the named seeders when `only` is set).
|
|
231
|
+
- `run.results` is a discriminated union by `status` (`'completed' | 'failed' | 'skipped' | 'pending'`). Narrowing on `r.status === 'failed'` gives non-optional `r.error`, `r.durationMs`, `r.failedStep`, and `r.cachedSteps`; narrowing on `r.status === 'skipped'` gives `r.failedDeps`.
|
|
232
|
+
- Passing a seeder list that omits a declared dependency is caught at compile time by TypeScript as well as at runtime.
|
|
205
233
|
|
|
206
|
-
`
|
|
234
|
+
When `concurrency > 1` (configured on `createSeederInstance`, per `runSeeders` call, or via `--concurrency` / `-c`):
|
|
235
|
+
- Independent branches of the dependency graph run in parallel, prioritized by **critical-path depth** (longest downstream dependency chains start first so leaf seeders backfill idle slots).
|
|
236
|
+
- Each seeder receives lazily-initialized, `AsyncLocalStorage`-isolated `step` and `faker` scopes (so `fakerSeed`, step cache keys, and helpers built around `base.step`/`base.faker` remain deterministic and race-free, and cached seeders that never touch `faker` pay zero setup cost).
|
|
237
|
+
- Running `--dry-run` with `concurrency > 1` displays the execution plan grouped into parallel waves so you can inspect your DAG structure.
|
|
238
|
+
- Inside a single seeder, independent steps can also run concurrently with `await Promise.all([step(...), step(...)])`.
|
|
239
|
+
|
|
240
|
+
`runSeeders` **throws**, before any hook or seeder runs (and before setting the seeding flag), when the input is invalid: `DuplicateSeederError`, `MissingDependencyError`, `CircularDependencyError`, `UnknownSeederError` (a name in `only` or `fresh`), `RangeError` (invalid `concurrency`), or `SeedTargetError`.
|
|
207
241
|
|
|
208
242
|
### Step Function
|
|
209
243
|
|
|
@@ -219,23 +253,25 @@ run: async ({ step }) => {
|
|
|
219
253
|
return computeExpensiveValue()
|
|
220
254
|
}, { useCache: true })
|
|
221
255
|
|
|
222
|
-
// Versioned cached step
|
|
256
|
+
// Versioned cached step with an explicit stable key
|
|
223
257
|
await step('Apply widget settings', () => applySettings(SETTINGS), {
|
|
224
258
|
useCache: true,
|
|
225
|
-
|
|
259
|
+
key: 'widget-settings', // optional: keeps the key stable if the description changes
|
|
260
|
+
version: SETTINGS, // any JSON value; object keys are compared order-independently
|
|
226
261
|
})
|
|
227
262
|
}
|
|
228
263
|
```
|
|
229
264
|
|
|
230
265
|
## Step Caching
|
|
231
266
|
|
|
232
|
-
A cached step stores its output under the key `<seederName>:<slugified description>` and returns the stored output on later runs instead of running again.
|
|
267
|
+
A cached step stores its output under the key `<seederName>:<key or slugified description>` and returns the stored output on later runs instead of running again.
|
|
233
268
|
|
|
234
269
|
- **Nothing else invalidates an entry.** Editing the step's code or the data it uses does not; bump `version` when the output should change, or run the seeder `fresh` (`--only x --fresh`). Rows deleted from the database leave their ids in the cache, so run fresh after a reset that keeps the cache.
|
|
235
|
-
- **Each cached step needs a unique
|
|
270
|
+
- **Each cached step needs a unique key within its seeder.** Two cached steps with the same key in one run throw. Pass `key` if you want to reword descriptions freely or use non-ASCII descriptions.
|
|
236
271
|
- **The value passes through your store.** With a JSON column, a `Date` comes back as a string and a `Map` as `{}` on the next run, so return plain JSON (ids) from cached steps.
|
|
237
272
|
- **Every step must be safe to run again**: a version change, `fresh`, or a cleared cache reruns it against existing data.
|
|
238
|
-
- plantr stores an envelope, `{ __plantr: 1, version?, value }`, so a step that returns `undefined` is cached too.
|
|
273
|
+
- plantr stores an envelope, `{ __plantr: 1, version?, value }`, so a step that returns `undefined` or `null` is cached too, while `undefined` or `null` returned bare from `cache.get` is treated as a cache miss. Non-null values written bare by plantr 1.x are still read as hits (when the step has no `version`).
|
|
274
|
+
- Provide `getAll` on `cache` to preload the entire table in a single query at the start of each run instead of issuing one `get` query per cached step, and `setMany` to flush new/updated entries in one batch write before `onAfterAll` (even if a later seeder fails).
|
|
239
275
|
|
|
240
276
|
A Prisma store:
|
|
241
277
|
|
|
@@ -243,24 +279,36 @@ A Prisma store:
|
|
|
243
279
|
cache: {
|
|
244
280
|
get: async (key) => {
|
|
245
281
|
const row = await prisma.seedCache.findUnique({ where: { key } })
|
|
246
|
-
return row?.output
|
|
282
|
+
return row?.output
|
|
283
|
+
},
|
|
284
|
+
getAll: async () => {
|
|
285
|
+
const rows = await prisma.seedCache.findMany()
|
|
286
|
+
return new Map(rows.map((r) => [r.key, r.output]))
|
|
247
287
|
},
|
|
248
288
|
set: async (key, value) => {
|
|
249
289
|
const output = value as Prisma.InputJsonValue
|
|
250
290
|
await prisma.seedCache.upsert({ where: { key }, create: { key, output }, update: { output } })
|
|
251
291
|
},
|
|
292
|
+
setMany: async (entries) => {
|
|
293
|
+
await prisma.$transaction(
|
|
294
|
+
entries.map(({ key, value }) => {
|
|
295
|
+
const output = value as Prisma.InputJsonValue
|
|
296
|
+
return prisma.seedCache.upsert({ where: { key }, create: { key, output }, update: { output } })
|
|
297
|
+
}),
|
|
298
|
+
)
|
|
299
|
+
},
|
|
252
300
|
}
|
|
253
301
|
```
|
|
254
302
|
|
|
255
303
|
## Target guard
|
|
256
304
|
|
|
257
|
-
Set `target` to the database URL the instance writes to. The banner then shows its host and
|
|
305
|
+
Set `target` to the database or emulator URL the instance writes to (for example `process.env.DATABASE_URL`, `http://127.0.0.1:8080`, or `firestore://127.0.0.1:8080/demo-app`). The banner then shows its host and path, never credentials (`🌱 Running Seeders (2 seeders) → localhost:5432/app`), and a run refuses with `SeedTargetError` before `onBeforeAll` when the target is not local. Local means every host the URL names (several hosts, or a `host=` parameter, which overrides the URL's host) is loopback (`localhost`, `127.*`, `::1`, `0.0.0.0`), `*.localhost`, `host.docker.internal`, a socket directory or `file:` path, or a single-label hostname with an explicit port such as a compose service (`postgres:5432`). A bare name without a port (such as a cloud project URL like `firestore://my-prod-project`) or a target without a `scheme://` is refused. Seed anything else on purpose with `allowRemote: true` or `--allow-remote`, for example in a staging pre-deploy command.
|
|
258
306
|
|
|
259
307
|
Without `target` there is no check. For other rules (an environment variable, a list of allowed hosts), throw from `onBeforeAll`.
|
|
260
308
|
|
|
261
309
|
## Seeding State
|
|
262
310
|
|
|
263
|
-
Check if seeding is active to skip side effects. Runtime code (job queues, mailers, the API) should import it from `plantr/state`, which does not load faker
|
|
311
|
+
Check if seeding is active to skip side effects. Runtime code (job queues, mailers, the API) should import it from `plantr/state`, which does not load faker, `bun:test`, or assertion helpers:
|
|
264
312
|
|
|
265
313
|
```typescript
|
|
266
314
|
import { isSeedingActive } from 'plantr/state'
|
|
@@ -272,7 +320,7 @@ if (isSeedingActive()) {
|
|
|
272
320
|
}
|
|
273
321
|
```
|
|
274
322
|
|
|
275
|
-
The flag is set
|
|
323
|
+
The flag is set after validation succeeds and cleared when the run finishes, also when a hook throws. Overlapping runs in the same process are reference-counted so one finishing run does not clear the flag while another is still active.
|
|
276
324
|
|
|
277
325
|
## Error Handling
|
|
278
326
|
|
|
@@ -289,7 +337,9 @@ try {
|
|
|
289
337
|
const { success, results } = await runSeeders(seeders)
|
|
290
338
|
if (!success) {
|
|
291
339
|
const failed = results.find((r) => r.status === 'failed')
|
|
292
|
-
|
|
340
|
+
if (failed) {
|
|
341
|
+
console.error(`${failed.name} failed in step ${failed.failedStep}`, failed.error)
|
|
342
|
+
}
|
|
293
343
|
}
|
|
294
344
|
} catch (error) {
|
|
295
345
|
// The registry or options are invalid, or the target was refused; nothing ran
|
|
@@ -298,7 +348,7 @@ try {
|
|
|
298
348
|
}
|
|
299
349
|
```
|
|
300
350
|
|
|
301
|
-
When a seeder fails, the summary names the failing step and prints the whole error
|
|
351
|
+
When a seeder fails, the summary names the failing step and prints the whole error (`Bun.inspect` on Bun or `util.inspect` on Node.js: message, stack, `cause` and extra fields). Under GitHub Actions it also prints an `::error` annotation. Terminal colors respect `NO_COLOR`, `FORCE_COLOR`, and stdout TTY state.
|
|
302
352
|
|
|
303
353
|
## License
|
|
304
354
|
|
package/src/cli.ts
CHANGED
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
import { parseArgs } from 'node:util'
|
|
2
|
-
import { resolveDependencyOrder } from './dependency-resolver'
|
|
3
|
-
import { colorize } from './formatting'
|
|
4
|
-
import
|
|
2
|
+
import { resolveDependencyOrder } from './dependency-resolver.js'
|
|
3
|
+
import { colorize, inspectValue } from './formatting.js'
|
|
4
|
+
import { describeTarget } from './run-seeders.js'
|
|
5
|
+
import type { RunSeedersOptions, SeederAny } from './types.js'
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
/** Options for `runSeedersCli` */
|
|
8
|
+
export type RunSeedersCliOptions = {
|
|
9
|
+
/** Display name shown in the banner (default: `'Seeders'`) */
|
|
10
|
+
name?: string | undefined
|
|
11
|
+
/** Arguments to parse (default: `process.argv.slice(2)`) */
|
|
12
|
+
argv?: readonly string[] | undefined
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
type CliRunner = (
|
|
7
16
|
seeders: readonly SeederAny[],
|
|
8
17
|
options?: RunSeedersOptions,
|
|
9
18
|
) => Promise<{ success: boolean }>
|
|
@@ -17,7 +26,17 @@ const USAGE_ERRORS = new Set([
|
|
|
17
26
|
'SeedTargetError',
|
|
18
27
|
])
|
|
19
28
|
|
|
20
|
-
|
|
29
|
+
function formatSeedersList(seeders: readonly SeederAny[]): string {
|
|
30
|
+
if (seeders.length === 0) return 'No seeders registered.'
|
|
31
|
+
const maxLen = Math.max(...seeders.map((s) => s.name.length))
|
|
32
|
+
const lines = seeders.map((s) => {
|
|
33
|
+
const desc = s.description ? ` ${colorize(s.description, 'dim')}` : ''
|
|
34
|
+
return ` ${s.name.padEnd(maxLen)}${desc}`
|
|
35
|
+
})
|
|
36
|
+
return `${colorize(`Registered seeders (${seeders.length}):`, 'white', 'bold')}\n${lines.join('\n')}`
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const helpText = (seeders: readonly SeederAny[]) => `
|
|
21
40
|
${colorize('Usage:', 'cyan', 'bold')} bun run seed [seeder...] [options]
|
|
22
41
|
|
|
23
42
|
${colorize('Arguments:', 'white', 'bold')}
|
|
@@ -27,12 +46,15 @@ ${colorize('Options:', 'white', 'bold')}
|
|
|
27
46
|
--only a,b Same as naming the seeders
|
|
28
47
|
--fresh Ignore and overwrite cached steps of the named seeders
|
|
29
48
|
(of every seeder when none are named)
|
|
49
|
+
--concurrency, -c <n> Run up to <n> independent seeders in parallel (default: 1)
|
|
30
50
|
--continue-on-failure Keep running seeders that do not depend on a failed one
|
|
31
51
|
--allow-remote Seed a database that is not local
|
|
52
|
+
--quiet, -q Suppress progress and step output (keep results table)
|
|
32
53
|
--dry-run Show execution order without running seeders
|
|
54
|
+
--list, -l List registered seeders in dependency order and exit
|
|
33
55
|
--help, -h Show this help message
|
|
34
56
|
|
|
35
|
-
${
|
|
57
|
+
${formatSeedersList(seeders)}
|
|
36
58
|
`
|
|
37
59
|
|
|
38
60
|
/**
|
|
@@ -41,62 +63,170 @@ ${count} seeders registered.
|
|
|
41
63
|
*/
|
|
42
64
|
export async function runCli(
|
|
43
65
|
seeders: readonly SeederAny[],
|
|
44
|
-
runSeeders:
|
|
45
|
-
{
|
|
66
|
+
runSeeders: CliRunner,
|
|
67
|
+
{
|
|
68
|
+
argv,
|
|
69
|
+
target,
|
|
70
|
+
defaultConcurrency,
|
|
71
|
+
}: {
|
|
72
|
+
name: string
|
|
73
|
+
argv: readonly string[]
|
|
74
|
+
target?: (() => string | undefined) | undefined
|
|
75
|
+
defaultConcurrency?: number | undefined
|
|
76
|
+
},
|
|
46
77
|
): Promise<number> {
|
|
47
78
|
let parsed: ReturnType<typeof parse>
|
|
48
79
|
try {
|
|
49
80
|
parsed = parse(argv)
|
|
50
81
|
} catch (error) {
|
|
51
82
|
console.error(colorize(error instanceof Error ? error.message : String(error), 'red'))
|
|
52
|
-
console.log(helpText(seeders
|
|
83
|
+
console.log(helpText(seeders))
|
|
53
84
|
return 1
|
|
54
85
|
}
|
|
55
86
|
const { values, positionals } = parsed
|
|
56
87
|
|
|
57
88
|
if (values.help) {
|
|
58
|
-
console.log(helpText(seeders
|
|
89
|
+
console.log(helpText(seeders))
|
|
59
90
|
return 0
|
|
60
91
|
}
|
|
61
92
|
|
|
93
|
+
let concurrency: number | undefined
|
|
94
|
+
if (values.concurrency !== undefined) {
|
|
95
|
+
const parsedConcurrency =
|
|
96
|
+
values.concurrency.toLowerCase() === 'infinity'
|
|
97
|
+
? Number.POSITIVE_INFINITY
|
|
98
|
+
: Number(values.concurrency)
|
|
99
|
+
if (
|
|
100
|
+
Number.isNaN(parsedConcurrency) ||
|
|
101
|
+
parsedConcurrency < 1 ||
|
|
102
|
+
(Number.isFinite(parsedConcurrency) && !Number.isInteger(parsedConcurrency))
|
|
103
|
+
) {
|
|
104
|
+
console.error(
|
|
105
|
+
colorize(
|
|
106
|
+
`Invalid --concurrency value "${values.concurrency}": expected a positive integer`,
|
|
107
|
+
'red',
|
|
108
|
+
),
|
|
109
|
+
)
|
|
110
|
+
return 1
|
|
111
|
+
}
|
|
112
|
+
concurrency = parsedConcurrency
|
|
113
|
+
}
|
|
114
|
+
|
|
62
115
|
const names = [...positionals, ...(values.only ?? []).flatMap((value) => value.split(','))]
|
|
63
116
|
.map((value) => value.trim())
|
|
64
117
|
.filter(Boolean)
|
|
65
118
|
const only = names.length > 0 ? names : undefined
|
|
66
119
|
|
|
67
120
|
try {
|
|
68
|
-
|
|
121
|
+
if (values.list) {
|
|
122
|
+
const order = resolveDependencyOrder(seeders, only)
|
|
123
|
+
const seederMap = new Map(seeders.map((s) => [s.name, s]))
|
|
124
|
+
console.log(
|
|
125
|
+
`\n${colorize('🌱 Seeders', 'cyan', 'bold')} ${colorize(`(${order.length})`, 'dim')}\n`,
|
|
126
|
+
)
|
|
127
|
+
const maxLen = Math.max(0, ...order.map((n) => n.length))
|
|
128
|
+
for (const seederName of order) {
|
|
129
|
+
const seeder = seederMap.get(seederName)
|
|
130
|
+
const desc = seeder?.description ? ` ${colorize(seeder.description, 'dim')}` : ''
|
|
131
|
+
const deps = seeder?.dependsOn ?? []
|
|
132
|
+
const depsStr =
|
|
133
|
+
deps.length > 0 ? ` ${colorize(`[depends on: ${deps.join(', ')}]`, 'dim')}` : ''
|
|
134
|
+
console.log(` ${seederName.padEnd(maxLen)}${desc}${depsStr}`)
|
|
135
|
+
}
|
|
136
|
+
console.log('')
|
|
137
|
+
return 0
|
|
138
|
+
}
|
|
69
139
|
|
|
70
140
|
if (values['dry-run']) {
|
|
141
|
+
const order = resolveDependencyOrder(seeders, only)
|
|
142
|
+
const seederMap = new Map(seeders.map((s) => [s.name, s]))
|
|
143
|
+
const targetUrl = target?.()
|
|
144
|
+
const targetDesc = targetUrl ? describeTarget(targetUrl) : undefined
|
|
145
|
+
const targetText = targetDesc
|
|
146
|
+
? ` ${colorize(`→ ${targetDesc.label}`, 'dim')}${targetDesc.local ? '' : ` ${colorize('(remote)', 'yellow')}`}`
|
|
147
|
+
: ''
|
|
148
|
+
const freshSet = values.fresh ? (only ? new Set(only) : true) : false
|
|
149
|
+
const effectiveConcurrency = concurrency ?? defaultConcurrency ?? 1
|
|
150
|
+
const concurrencyText =
|
|
151
|
+
effectiveConcurrency > 1
|
|
152
|
+
? `, concurrency: ${effectiveConcurrency === Number.POSITIVE_INFINITY ? '∞' : effectiveConcurrency}`
|
|
153
|
+
: ''
|
|
154
|
+
|
|
71
155
|
console.log(
|
|
72
|
-
`\n${colorize('🌱 Dry Run', 'cyan', 'bold')} ${colorize(`(${order.length} seeders)`, 'dim')}\n`,
|
|
156
|
+
`\n${colorize('🌱 Dry Run', 'cyan', 'bold')} ${colorize(`(${order.length} ${order.length === 1 ? 'seeder' : 'seeders'}${concurrencyText})`, 'dim')}${targetText}\n`,
|
|
73
157
|
)
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
const
|
|
158
|
+
|
|
159
|
+
const printItem = (seederName: string, num: number, indent: string) => {
|
|
160
|
+
const seeder = seederMap.get(seederName)
|
|
161
|
+
const deps = seeder?.dependsOn ?? []
|
|
77
162
|
const depsStr =
|
|
78
163
|
deps.length > 0 ? ` ${colorize(`(depends on: ${deps.join(', ')})`, 'dim')}` : ''
|
|
79
|
-
|
|
80
|
-
|
|
164
|
+
const freshStr =
|
|
165
|
+
freshSet === true || (freshSet instanceof Set && freshSet.has(seederName))
|
|
166
|
+
? ` ${colorize('(fresh)', 'yellow')}`
|
|
167
|
+
: ''
|
|
168
|
+
console.log(`${indent}${num}. ${seederName}${depsStr}${freshStr}`)
|
|
169
|
+
if (seeder?.description) {
|
|
170
|
+
console.log(`${indent} ${colorize(seeder.description, 'dim')}`)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (effectiveConcurrency > 1 && order.length > 0) {
|
|
175
|
+
const waveOf = new Map<string, number>()
|
|
176
|
+
const waves: string[][] = []
|
|
177
|
+
for (const seederName of order) {
|
|
178
|
+
const deps = seederMap.get(seederName)?.dependsOn ?? []
|
|
179
|
+
let wave = 0
|
|
180
|
+
for (const dep of deps) {
|
|
181
|
+
wave = Math.max(wave, (waveOf.get(dep) ?? 0) + 1)
|
|
182
|
+
}
|
|
183
|
+
waveOf.set(seederName, wave)
|
|
184
|
+
let bucket = waves[wave]
|
|
185
|
+
if (!bucket) {
|
|
186
|
+
bucket = []
|
|
187
|
+
waves[wave] = bucket
|
|
188
|
+
}
|
|
189
|
+
bucket.push(seederName)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
console.log(
|
|
193
|
+
colorize(
|
|
194
|
+
`Execution plan (${waves.length} ${waves.length === 1 ? 'wave' : 'waves'}):`,
|
|
195
|
+
'white',
|
|
196
|
+
'bold',
|
|
197
|
+
),
|
|
198
|
+
)
|
|
199
|
+
let index = 1
|
|
200
|
+
waves.forEach((waveSeeders, waveIdx) => {
|
|
201
|
+
const parallelTag = waveSeeders.length > 1 ? ` ${colorize('(parallel)', 'cyan')}` : ''
|
|
202
|
+
console.log(` ${colorize(`Wave ${waveIdx + 1}`, 'white', 'bold')}${parallelTag}`)
|
|
203
|
+
for (const seederName of waveSeeders) {
|
|
204
|
+
printItem(seederName, index++, ' ')
|
|
205
|
+
}
|
|
206
|
+
})
|
|
207
|
+
} else {
|
|
208
|
+
console.log(colorize('Execution order:', 'white', 'bold'))
|
|
209
|
+
order.forEach((seederName, i) => {
|
|
210
|
+
printItem(seederName, i + 1, ' ')
|
|
211
|
+
})
|
|
212
|
+
}
|
|
81
213
|
console.log('')
|
|
82
214
|
return 0
|
|
83
215
|
}
|
|
84
216
|
|
|
85
|
-
console.log(
|
|
86
|
-
`\n${colorize(`🌱 Running ${name}`, 'cyan', 'bold')} ${colorize(`(${order.length} seeders)`, 'dim')}\n`,
|
|
87
|
-
)
|
|
88
217
|
const { success } = await runSeeders(seeders, {
|
|
89
218
|
printResults: true,
|
|
90
|
-
verbose:
|
|
219
|
+
verbose: !values.quiet,
|
|
91
220
|
only,
|
|
92
221
|
fresh: values.fresh ? (only ?? true) : false,
|
|
93
222
|
continueOnFailure: values['continue-on-failure'],
|
|
94
223
|
allowRemote: values['allow-remote'],
|
|
224
|
+
concurrency,
|
|
95
225
|
})
|
|
96
226
|
return success ? 0 : 1
|
|
97
227
|
} catch (error) {
|
|
98
228
|
const usage = error instanceof Error && USAGE_ERRORS.has(error.name)
|
|
99
|
-
console.error(colorize(usage ? (error as Error).message :
|
|
229
|
+
console.error(colorize(usage ? (error as Error).message : inspectValue(error), 'red'))
|
|
100
230
|
return 1
|
|
101
231
|
}
|
|
102
232
|
}
|
|
@@ -108,6 +238,9 @@ function parse(argv: readonly string[]) {
|
|
|
108
238
|
strict: true,
|
|
109
239
|
options: {
|
|
110
240
|
help: { type: 'boolean', short: 'h' },
|
|
241
|
+
list: { type: 'boolean', short: 'l' },
|
|
242
|
+
quiet: { type: 'boolean', short: 'q' },
|
|
243
|
+
concurrency: { type: 'string', short: 'c' },
|
|
111
244
|
'dry-run': { type: 'boolean' },
|
|
112
245
|
only: { type: 'string', multiple: true },
|
|
113
246
|
fresh: { type: 'boolean' },
|