plantr 2.0.0 → 2.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/dist/index.d.ts +23 -20
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +761 -262
- 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 +55 -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/formatting.d.ts +27 -13
- 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 +39 -22
- 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 +117 -34
- 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 +56 -23
- package/package.json +2 -1
- package/readme.md +89 -48
- package/src/cli.ts +154 -21
- package/src/create-seeder-instance.ts +225 -110
- package/src/define-seeder.ts +14 -7
- package/src/dependency-resolver.ts +17 -28
- package/src/formatting.ts +121 -36
- package/src/lazy-faker.ts +46 -0
- package/src/run-seeders.ts +336 -115
- package/src/seeding-state.ts +27 -5
- package/src/step.ts +208 -64
- package/src/types.ts +169 -37
- package/state.ts +1 -1
package/readme.md
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
# plantr
|
|
2
2
|
|
|
3
|
-
A Bun-first database seeder library with built-in faker, step workflow, and
|
|
3
|
+
A Bun-first database seeder library with built-in faker, step workflow, parallel DAG execution, and end-to-end TypeScript inference.
|
|
4
4
|
|
|
5
5
|
## Features
|
|
6
6
|
|
|
7
|
-
- **Built-in utilities** - `faker`, `step`, and `expect` available in every seeder
|
|
8
|
-
- **
|
|
9
|
-
- **Automatic ordering** -
|
|
7
|
+
- **Built-in utilities** - `faker`, `step`, and `expect` available in every seeder (`faker` is lazy-loaded on first access, English locale only by default)
|
|
8
|
+
- **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`
|
|
9
|
+
- **Automatic ordering & parallel DAG execution** - Runs in dependency order with critical-path scheduling across independent branches via `concurrency` / `--concurrency`
|
|
10
10
|
- **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
|
|
11
|
+
- **Step workflow** - Organize seeders into sequential or `Promise.all` parallel steps with progress logging
|
|
12
|
+
- **Step caching** - Skip steps that already ran, with explicit keys, canonical JSON versions, single-query `getAll` preloading, batched `setMany` writes, and a `--fresh` override
|
|
13
13
|
- **Target guard** - Refuse to seed a database that is not local unless asked to
|
|
14
|
-
- **Lifecycle hooks** - `onBeforeAll` / `onAfterAll` for setup and teardown
|
|
14
|
+
- **Lifecycle hooks** - `onBeforeAll` / `onAfterAll(ctx)` for setup and teardown
|
|
15
15
|
- **Continue on failure** - Keep seeding independent data when one seeder fails
|
|
16
|
-
- **Dry run
|
|
16
|
+
- **Dry run & list modes** - Preview execution order, target, and descriptions without running
|
|
17
17
|
|
|
18
18
|
## Installation
|
|
19
19
|
|
|
@@ -29,24 +29,18 @@ bun add plantr
|
|
|
29
29
|
|
|
30
30
|
```typescript
|
|
31
31
|
// src/seed.ts
|
|
32
|
-
import { createSeederInstance
|
|
32
|
+
import { createSeederInstance } from 'plantr'
|
|
33
33
|
import { prisma } from './prisma'
|
|
34
34
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export const { defineSeeder, runSeeders, runSeedersCli } = createSeederInstance<MyContext>({
|
|
40
|
-
context: (base) => ({
|
|
41
|
-
...base, // faker, step, expect
|
|
42
|
-
prisma,
|
|
43
|
-
}),
|
|
35
|
+
export const { defineSeeder, runSeeders, runSeedersCli } = createSeederInstance({
|
|
36
|
+
// Optional: extra properties are merged onto { faker, step, expect } automatically
|
|
37
|
+
context: () => ({ prisma }),
|
|
44
38
|
target: () => process.env.DATABASE_URL,
|
|
45
39
|
onBeforeAll: async () => {
|
|
46
40
|
await prisma.$connect()
|
|
47
41
|
},
|
|
48
|
-
onAfterAll: async () => {
|
|
49
|
-
await prisma.$disconnect()
|
|
42
|
+
onAfterAll: async (ctx) => {
|
|
43
|
+
await ctx?.prisma.$disconnect()
|
|
50
44
|
},
|
|
51
45
|
})
|
|
52
46
|
```
|
|
@@ -126,6 +120,15 @@ Run with:
|
|
|
126
120
|
bun run src/seed.ts
|
|
127
121
|
```
|
|
128
122
|
|
|
123
|
+
Or programmatically (e.g. in tests) with fully typed `outputs`:
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
const run = await runSeeders([userSeeder, postSeeder])
|
|
127
|
+
if (run.success) {
|
|
128
|
+
console.log(run.outputs.userSeeder.userId, run.outputs.postSeeder.postId)
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
129
132
|
## CLI Options
|
|
130
133
|
|
|
131
134
|
```bash
|
|
@@ -134,40 +137,52 @@ bun run src/seed.ts postSeeder # Run postSeeder and the seeders it de
|
|
|
134
137
|
bun run src/seed.ts --only a,b # Same as naming them
|
|
135
138
|
bun run src/seed.ts postSeeder --fresh # Ignore and overwrite postSeeder's cached steps
|
|
136
139
|
bun run src/seed.ts --fresh # Ignore and overwrite every cached step
|
|
140
|
+
bun run src/seed.ts --concurrency 4 # Run up to 4 independent seeders in parallel (-c 4)
|
|
137
141
|
bun run src/seed.ts --continue-on-failure # Keep running seeders that do not depend on a failed one
|
|
138
142
|
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 --
|
|
143
|
+
bun run src/seed.ts --quiet # Suppress progress/step lines, keep results table (-q)
|
|
144
|
+
bun run src/seed.ts --dry-run postSeeder # Show execution order, target, and descriptions without running
|
|
145
|
+
bun run src/seed.ts --list # List registered seeders in dependency order (-l)
|
|
146
|
+
bun run src/seed.ts --help # Show help and registered seeders (-h)
|
|
141
147
|
```
|
|
142
148
|
|
|
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.
|
|
149
|
+
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
150
|
|
|
145
151
|
## API
|
|
146
152
|
|
|
147
|
-
### `createSeederInstance(config)`
|
|
153
|
+
### `createSeederInstance(config?)`
|
|
148
154
|
|
|
149
155
|
```typescript
|
|
150
156
|
createSeederInstance({
|
|
151
|
-
//
|
|
152
|
-
//
|
|
153
|
-
|
|
157
|
+
// Optional: factory returning extra properties to merge onto { faker, step, expect }.
|
|
158
|
+
// Receives `base` if you want to build helpers around faker/step/expect or override a base key.
|
|
159
|
+
// Called once per run, after onBeforeAll. Omit to use BaseSeederContext directly.
|
|
160
|
+
context: (base) => ({ prisma }),
|
|
154
161
|
|
|
155
162
|
// Optional: cache for step caching (see Step Caching)
|
|
156
163
|
cache: {
|
|
157
|
-
get: async (key) => { /* return the stored value, or undefined */ },
|
|
164
|
+
get: async (key) => { /* return the stored value, or undefined / null */ },
|
|
158
165
|
set: async (key, value) => { /* store value, overwriting */ },
|
|
166
|
+
getAll: async () => { /* optional: preload all entries in one query */ },
|
|
167
|
+
setMany: async (entries) => { /* optional: flush all writes in one batch at end of run */ },
|
|
159
168
|
},
|
|
160
169
|
|
|
170
|
+
// Optional: default parallel concurrency for independent seeders (default: 1; e.g. 4 or Infinity)
|
|
171
|
+
concurrency: 4,
|
|
172
|
+
|
|
173
|
+
// Optional: custom Faker locale instance (default: lazy-loaded @faker-js/faker/locale/en)
|
|
174
|
+
faker: fakerDE,
|
|
175
|
+
|
|
161
176
|
// Optional: the database URL the run writes to (see Target guard)
|
|
162
177
|
target: () => process.env.DATABASE_URL,
|
|
163
178
|
|
|
164
179
|
// Optional: seed faker per seeder (fakerSeed + hash of the seeder name),
|
|
165
|
-
// so every run generates the same data
|
|
180
|
+
// so every run generates the same data even when running concurrently
|
|
166
181
|
fakerSeed: 1,
|
|
167
182
|
|
|
168
183
|
// Optional: lifecycle hooks
|
|
169
184
|
onBeforeAll: async () => { /* setup; throw to refuse the run */ },
|
|
170
|
-
onAfterAll: async () => { /* teardown;
|
|
185
|
+
onAfterAll: async (ctx) => { /* teardown; receives ctx (or undefined if context() threw) */ },
|
|
171
186
|
})
|
|
172
187
|
```
|
|
173
188
|
|
|
@@ -179,11 +194,11 @@ Returns `{ defineSeeder, runSeeders, runSeedersCli, isSeedingActive }`.
|
|
|
179
194
|
defineSeeder({
|
|
180
195
|
name: 'seederName', // Unique name
|
|
181
196
|
description: 'What it does', // Optional
|
|
182
|
-
dependsOn: [otherSeeder], // Optional dependencies
|
|
183
|
-
run: async (ctx, deps) => {
|
|
197
|
+
dependsOn: [otherSeeder], // Optional dependencies (must have a compatible context)
|
|
198
|
+
run: async (ctx, deps) => { // Sync or async
|
|
184
199
|
// ctx has faker, step, expect, and your custom context
|
|
185
200
|
// deps has typed outputs from dependsOn seeders
|
|
186
|
-
return { /* output available to dependents */ }
|
|
201
|
+
return { /* output available to dependents and run.outputs */ }
|
|
187
202
|
},
|
|
188
203
|
})
|
|
189
204
|
```
|
|
@@ -191,19 +206,29 @@ defineSeeder({
|
|
|
191
206
|
### `runSeeders(seeders, options?)`
|
|
192
207
|
|
|
193
208
|
```typescript
|
|
194
|
-
const
|
|
209
|
+
const run = await runSeeders(seeders, {
|
|
195
210
|
printResults: true, // Print results table and errors (default: true)
|
|
196
211
|
verbose: true, // Print progress and step lines (default: true)
|
|
197
212
|
continueOnFailure: false, // Continue after failures (default: false)
|
|
198
|
-
only: ['postSeeder'], //
|
|
199
|
-
fresh: ['postSeeder'], // Ignore cached steps: true for all, or seeder names
|
|
213
|
+
only: ['postSeeder'], // Autocompleted & checked against seeders (default: all)
|
|
214
|
+
fresh: ['postSeeder'], // Ignore cached steps: true for all, or checked seeder names
|
|
200
215
|
allowRemote: false, // Seed a non-local target (default: false)
|
|
216
|
+
concurrency: 1, // Max independent seeders running in parallel (default: 1; supports Infinity)
|
|
201
217
|
})
|
|
202
218
|
```
|
|
203
219
|
|
|
204
|
-
`
|
|
220
|
+
`run` is a discriminated union on `success`:
|
|
221
|
+
- 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).
|
|
222
|
+
- `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`.
|
|
223
|
+
- Passing a seeder list that omits a declared dependency is caught at compile time by TypeScript as well as at runtime.
|
|
205
224
|
|
|
206
|
-
`
|
|
225
|
+
When `concurrency > 1` (configured on `createSeederInstance`, per `runSeeders` call, or via `--concurrency` / `-c`):
|
|
226
|
+
- 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).
|
|
227
|
+
- 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).
|
|
228
|
+
- Running `--dry-run` with `concurrency > 1` displays the execution plan grouped into parallel waves so you can inspect your DAG structure.
|
|
229
|
+
- Inside a single seeder, independent steps can also run concurrently with `await Promise.all([step(...), step(...)])`.
|
|
230
|
+
|
|
231
|
+
`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
232
|
|
|
208
233
|
### Step Function
|
|
209
234
|
|
|
@@ -219,23 +244,25 @@ run: async ({ step }) => {
|
|
|
219
244
|
return computeExpensiveValue()
|
|
220
245
|
}, { useCache: true })
|
|
221
246
|
|
|
222
|
-
// Versioned cached step
|
|
247
|
+
// Versioned cached step with an explicit stable key
|
|
223
248
|
await step('Apply widget settings', () => applySettings(SETTINGS), {
|
|
224
249
|
useCache: true,
|
|
225
|
-
|
|
250
|
+
key: 'widget-settings', // optional: keeps the key stable if the description changes
|
|
251
|
+
version: SETTINGS, // any JSON value; object keys are compared order-independently
|
|
226
252
|
})
|
|
227
253
|
}
|
|
228
254
|
```
|
|
229
255
|
|
|
230
256
|
## Step Caching
|
|
231
257
|
|
|
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.
|
|
258
|
+
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
259
|
|
|
234
260
|
- **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
|
|
261
|
+
- **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
262
|
- **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
263
|
- **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.
|
|
264
|
+
- 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`).
|
|
265
|
+
- 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
266
|
|
|
240
267
|
A Prisma store:
|
|
241
268
|
|
|
@@ -243,18 +270,30 @@ A Prisma store:
|
|
|
243
270
|
cache: {
|
|
244
271
|
get: async (key) => {
|
|
245
272
|
const row = await prisma.seedCache.findUnique({ where: { key } })
|
|
246
|
-
return row?.output
|
|
273
|
+
return row?.output
|
|
274
|
+
},
|
|
275
|
+
getAll: async () => {
|
|
276
|
+
const rows = await prisma.seedCache.findMany()
|
|
277
|
+
return new Map(rows.map((r) => [r.key, r.output]))
|
|
247
278
|
},
|
|
248
279
|
set: async (key, value) => {
|
|
249
280
|
const output = value as Prisma.InputJsonValue
|
|
250
281
|
await prisma.seedCache.upsert({ where: { key }, create: { key, output }, update: { output } })
|
|
251
282
|
},
|
|
283
|
+
setMany: async (entries) => {
|
|
284
|
+
await prisma.$transaction(
|
|
285
|
+
entries.map(({ key, value }) => {
|
|
286
|
+
const output = value as Prisma.InputJsonValue
|
|
287
|
+
return prisma.seedCache.upsert({ where: { key }, create: { key, output }, update: { output } })
|
|
288
|
+
}),
|
|
289
|
+
)
|
|
290
|
+
},
|
|
252
291
|
}
|
|
253
292
|
```
|
|
254
293
|
|
|
255
294
|
## Target guard
|
|
256
295
|
|
|
257
|
-
Set `target` to the database URL the instance writes to. The banner then shows its host and database, never credentials (`🌱 Running Seeders → localhost:5432/app`), and a run refuses with `SeedTargetError` before `onBeforeAll` when the host 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`), `*.localhost`, `host.docker.internal`, a socket directory or `file:` path, or a name without a dot such as a compose service. 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.
|
|
296
|
+
Set `target` to the database URL the instance writes to. The banner then shows its host and database, never credentials (`🌱 Running Seeders (2 seeders) → localhost:5432/app`), and a run refuses with `SeedTargetError` before `onBeforeAll` when the host 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`), `*.localhost`, `host.docker.internal`, a socket directory or `file:` path, or a name without a dot such as a compose service. 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
297
|
|
|
259
298
|
Without `target` there is no check. For other rules (an environment variable, a list of allowed hosts), throw from `onBeforeAll`.
|
|
260
299
|
|
|
@@ -272,7 +311,7 @@ if (isSeedingActive()) {
|
|
|
272
311
|
}
|
|
273
312
|
```
|
|
274
313
|
|
|
275
|
-
The flag is set
|
|
314
|
+
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
315
|
|
|
277
316
|
## Error Handling
|
|
278
317
|
|
|
@@ -289,7 +328,9 @@ try {
|
|
|
289
328
|
const { success, results } = await runSeeders(seeders)
|
|
290
329
|
if (!success) {
|
|
291
330
|
const failed = results.find((r) => r.status === 'failed')
|
|
292
|
-
|
|
331
|
+
if (failed) {
|
|
332
|
+
console.error(`${failed.name} failed in step ${failed.failedStep}`, failed.error)
|
|
333
|
+
}
|
|
293
334
|
}
|
|
294
335
|
} catch (error) {
|
|
295
336
|
// The registry or options are invalid, or the target was refused; nothing ran
|
|
@@ -298,7 +339,7 @@ try {
|
|
|
298
339
|
}
|
|
299
340
|
```
|
|
300
341
|
|
|
301
|
-
When a seeder fails, the summary names the failing step and prints the whole error with `Bun.inspect` (message, stack, `cause` and extra fields). Under GitHub Actions it also prints an `::error` annotation.
|
|
342
|
+
When a seeder fails, the summary names the failing step and prints the whole error with `Bun.inspect` (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
343
|
|
|
303
344
|
## License
|
|
304
345
|
|
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 } 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,57 +63,165 @@ ${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) {
|
|
@@ -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' },
|