plantr 1.0.1 → 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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/dist/index.d.ts +23 -20
  3. package/dist/index.d.ts.map +1 -0
  4. package/dist/index.js +906 -235
  5. package/dist/src/cli.d.ts +23 -0
  6. package/dist/src/cli.d.ts.map +1 -0
  7. package/dist/src/create-seeder-instance.d.ts +73 -83
  8. package/dist/src/create-seeder-instance.d.ts.map +1 -0
  9. package/dist/src/define-seeder.d.ts +4 -3
  10. package/dist/src/define-seeder.d.ts.map +1 -0
  11. package/dist/src/dependency-resolver.d.ts +18 -2
  12. package/dist/src/dependency-resolver.d.ts.map +1 -0
  13. package/dist/src/formatting.d.ts +31 -12
  14. package/dist/src/formatting.d.ts.map +1 -0
  15. package/dist/src/lazy-faker.d.ts +12 -0
  16. package/dist/src/lazy-faker.d.ts.map +1 -0
  17. package/dist/src/run-seeders.d.ts +57 -17
  18. package/dist/src/run-seeders.d.ts.map +1 -0
  19. package/dist/src/seeding-state.d.ts +17 -2
  20. package/dist/src/seeding-state.d.ts.map +1 -0
  21. package/dist/src/step.d.ts +97 -15
  22. package/dist/src/step.d.ts.map +1 -0
  23. package/dist/src/types.d.ts +132 -29
  24. package/dist/src/types.d.ts.map +1 -0
  25. package/dist/state.d.ts +12 -0
  26. package/dist/state.d.ts.map +1 -0
  27. package/dist/state.js +20 -0
  28. package/index.ts +60 -24
  29. package/package.json +20 -10
  30. package/readme.md +169 -49
  31. package/src/cli.ts +251 -0
  32. package/src/create-seeder-instance.ts +254 -173
  33. package/src/define-seeder.ts +14 -7
  34. package/src/dependency-resolver.ts +59 -30
  35. package/src/formatting.ts +142 -39
  36. package/src/lazy-faker.ts +46 -0
  37. package/src/run-seeders.ts +413 -123
  38. package/src/seeding-state.ts +32 -5
  39. package/src/step.ts +247 -46
  40. package/src/types.ts +184 -32
  41. package/state.ts +11 -0
  42. package/dist/cli.d.ts +0 -17
  43. package/dist/cli.js +0 -59
  44. package/dist/index-a1s5r901.js +0 -4
package/readme.md CHANGED
@@ -1,17 +1,19 @@
1
1
  # plantr
2
2
 
3
- A Bun-first database seeder library with built-in faker, step workflow, and type-safe dependencies.
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
- - **Type-safe dependencies** - Seeder outputs are fully typed when used as dependencies
9
- - **Automatic ordering** - Seeders run in correct order based on dependencies
10
- - **Step workflow** - Organize seeders into steps with progress logging
11
- - **Step caching** - Cache expensive operations across runs
12
- - **Lifecycle hooks** - `onBeforeAll` / `onAfterAll` for setup and teardown
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
+ - **Run a subset** - Run named seeders plus what they depend on (`--only`, `only`)
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
+ - **Target guard** - Refuse to seed a database that is not local unless asked to
14
+ - **Lifecycle hooks** - `onBeforeAll` / `onAfterAll(ctx)` for setup and teardown
13
15
  - **Continue on failure** - Keep seeding independent data when one seeder fails
14
- - **Dry run mode** - Preview execution order without running
16
+ - **Dry run & list modes** - Preview execution order, target, and descriptions without running
15
17
 
16
18
  ## Installation
17
19
 
@@ -27,23 +29,18 @@ bun add plantr
27
29
 
28
30
  ```typescript
29
31
  // src/seed.ts
30
- import { createSeederInstance, type BaseSeederContext } from 'plantr'
32
+ import { createSeederInstance } from 'plantr'
31
33
  import { prisma } from './prisma'
32
34
 
33
- type MyContext = BaseSeederContext & {
34
- prisma: typeof prisma
35
- }
36
-
37
- export const { defineSeeder, runSeeders, runSeedersCli } = createSeederInstance<MyContext>({
38
- context: (base) => ({
39
- ...base,
40
- prisma,
41
- }),
35
+ export const { defineSeeder, runSeeders, runSeedersCli } = createSeederInstance({
36
+ // Optional: extra properties are merged onto { faker, step, expect } automatically
37
+ context: () => ({ prisma }),
38
+ target: () => process.env.DATABASE_URL,
42
39
  onBeforeAll: async () => {
43
40
  await prisma.$connect()
44
41
  },
45
- onAfterAll: async () => {
46
- await prisma.$disconnect()
42
+ onAfterAll: async (ctx) => {
43
+ await ctx?.prisma.$disconnect()
47
44
  },
48
45
  })
49
46
  ```
@@ -123,31 +120,69 @@ Run with:
123
120
  bun run src/seed.ts
124
121
  ```
125
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
+
126
132
  ## CLI Options
127
133
 
128
134
  ```bash
129
- bun run src/seed.ts --help # Show help
130
- bun run src/seed.ts --dry-run # Show execution order without running
135
+ bun run src/seed.ts # Run every seeder
136
+ bun run src/seed.ts postSeeder # Run postSeeder and the seeders it depends on
137
+ bun run src/seed.ts --only a,b # Same as naming them
138
+ bun run src/seed.ts postSeeder --fresh # Ignore and overwrite postSeeder's cached steps
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)
141
+ bun run src/seed.ts --continue-on-failure # Keep running seeders that do not depend on a failed one
142
+ bun run src/seed.ts --allow-remote # Seed a target that is not local (see Target guard)
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)
131
147
  ```
132
148
 
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.
150
+
133
151
  ## API
134
152
 
135
- ### `createSeederInstance(config)`
153
+ ### `createSeederInstance(config?)`
136
154
 
137
155
  ```typescript
138
156
  createSeederInstance({
139
- // Required: factory that receives base context and returns your context
140
- context: (base) => ({ ...base, prisma }),
141
-
142
- // Optional: cache for step caching
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 }),
161
+
162
+ // Optional: cache for step caching (see Step Caching)
143
163
  cache: {
144
- get: async (key) => { /* return cached value */ },
145
- set: async (key, value) => { /* store value */ },
164
+ get: async (key) => { /* return the stored value, or undefined / null */ },
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 */ },
146
168
  },
147
-
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
+
176
+ // Optional: the database URL the run writes to (see Target guard)
177
+ target: () => process.env.DATABASE_URL,
178
+
179
+ // Optional: seed faker per seeder (fakerSeed + hash of the seeder name),
180
+ // so every run generates the same data even when running concurrently
181
+ fakerSeed: 1,
182
+
148
183
  // Optional: lifecycle hooks
149
- onBeforeAll: async () => { /* setup */ },
150
- onAfterAll: async () => { /* teardown */ },
184
+ onBeforeAll: async () => { /* setup; throw to refuse the run */ },
185
+ onAfterAll: async (ctx) => { /* teardown; receives ctx (or undefined if context() threw) */ },
151
186
  })
152
187
  ```
153
188
 
@@ -159,11 +194,11 @@ Returns `{ defineSeeder, runSeeders, runSeedersCli, isSeedingActive }`.
159
194
  defineSeeder({
160
195
  name: 'seederName', // Unique name
161
196
  description: 'What it does', // Optional
162
- dependsOn: [otherSeeder], // Optional dependencies
163
- run: async (ctx, deps) => {
197
+ dependsOn: [otherSeeder], // Optional dependencies (must have a compatible context)
198
+ run: async (ctx, deps) => { // Sync or async
164
199
  // ctx has faker, step, expect, and your custom context
165
200
  // deps has typed outputs from dependsOn seeders
166
- return { /* output available to dependents */ }
201
+ return { /* output available to dependents and run.outputs */ }
167
202
  },
168
203
  })
169
204
  ```
@@ -171,13 +206,30 @@ defineSeeder({
171
206
  ### `runSeeders(seeders, options?)`
172
207
 
173
208
  ```typescript
174
- await runSeeders(seeders, {
175
- printResults: true, // Print results table (default: true)
176
- verbose: true, // Print progress (default: true)
177
- continueOnFailure: false // Continue after failures (default: false)
209
+ const run = await runSeeders(seeders, {
210
+ printResults: true, // Print results table and errors (default: true)
211
+ verbose: true, // Print progress and step lines (default: true)
212
+ continueOnFailure: false, // Continue after failures (default: false)
213
+ only: ['postSeeder'], // Autocompleted & checked against seeders (default: all)
214
+ fresh: ['postSeeder'], // Ignore cached steps: true for all, or checked seeder names
215
+ allowRemote: false, // Seed a non-local target (default: false)
216
+ concurrency: 1, // Max independent seeders running in parallel (default: 1; supports Infinity)
178
217
  })
179
218
  ```
180
219
 
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.
224
+
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`.
232
+
181
233
  ### Step Function
182
234
 
183
235
  ```typescript
@@ -191,15 +243,66 @@ run: async ({ step }) => {
191
243
  const cached = await step('Expensive operation', async () => {
192
244
  return computeExpensiveValue()
193
245
  }, { useCache: true })
246
+
247
+ // Versioned cached step with an explicit stable key
248
+ await step('Apply widget settings', () => applySettings(SETTINGS), {
249
+ useCache: true,
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
252
+ })
194
253
  }
195
254
  ```
196
255
 
256
+ ## Step Caching
257
+
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.
259
+
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.
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.
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.
263
+ - **Every step must be safe to run again**: a version change, `fresh`, or a cleared cache reruns it against existing data.
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).
266
+
267
+ A Prisma store:
268
+
269
+ ```typescript
270
+ cache: {
271
+ get: async (key) => {
272
+ const row = await prisma.seedCache.findUnique({ where: { key } })
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]))
278
+ },
279
+ set: async (key, value) => {
280
+ const output = value as Prisma.InputJsonValue
281
+ await prisma.seedCache.upsert({ where: { key }, create: { key, output }, update: { output } })
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
+ },
291
+ }
292
+ ```
293
+
294
+ ## Target guard
295
+
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.
297
+
298
+ Without `target` there is no check. For other rules (an environment variable, a list of allowed hosts), throw from `onBeforeAll`.
299
+
197
300
  ## Seeding State
198
301
 
199
- Check if seeding is active to skip side effects:
302
+ 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 or `bun:test`:
200
303
 
201
304
  ```typescript
202
- import { isSeedingActive } from './seed'
305
+ import { isSeedingActive } from 'plantr/state'
203
306
 
204
307
  // In your event handlers, webhooks, etc.
205
308
  if (isSeedingActive()) {
@@ -208,23 +311,40 @@ if (isSeedingActive()) {
208
311
  }
209
312
  ```
210
313
 
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.
315
+
211
316
  ## Error Handling
212
317
 
213
318
  ```typescript
214
- import { CircularDependencyError, MissingDependencyError } from 'plantr'
319
+ import {
320
+ CircularDependencyError,
321
+ DuplicateSeederError,
322
+ MissingDependencyError,
323
+ SeedTargetError,
324
+ UnknownSeederError,
325
+ } from 'plantr'
215
326
 
216
327
  try {
217
- await runSeeders(seeders)
218
- } catch (error) {
219
- if (error instanceof CircularDependencyError) {
220
- console.error('Circular dependency detected')
221
- }
222
- if (error instanceof MissingDependencyError) {
223
- console.error('Missing dependency')
328
+ const { success, results } = await runSeeders(seeders)
329
+ if (!success) {
330
+ const failed = results.find((r) => r.status === 'failed')
331
+ if (failed) {
332
+ console.error(`${failed.name} failed in step ${failed.failedStep}`, failed.error)
333
+ }
224
334
  }
335
+ } catch (error) {
336
+ // The registry or options are invalid, or the target was refused; nothing ran
337
+ if (error instanceof CircularDependencyError) console.error('Circular dependency')
338
+ if (error instanceof SeedTargetError) console.error(error.message)
225
339
  }
226
340
  ```
227
341
 
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.
343
+
228
344
  ## License
229
345
 
230
346
  MIT
347
+
348
+ ## Releasing
349
+
350
+ Squash PRs with conventional titles (`fix:`, `feat:`, or `feat!:`). Release Please keeps the version and changelog in a release PR; merge that PR to publish with release notes and npm provenance. See [release and recovery instructions](docs/releasing.md).
package/src/cli.ts ADDED
@@ -0,0 +1,251 @@
1
+ import { parseArgs } from 'node:util'
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'
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 = (
16
+ seeders: readonly SeederAny[],
17
+ options?: RunSeedersOptions,
18
+ ) => Promise<{ success: boolean }>
19
+
20
+ /** Errors whose message says everything; others are printed with their stack */
21
+ const USAGE_ERRORS = new Set([
22
+ 'CircularDependencyError',
23
+ 'MissingDependencyError',
24
+ 'DuplicateSeederError',
25
+ 'UnknownSeederError',
26
+ 'SeedTargetError',
27
+ ])
28
+
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[]) => `
40
+ ${colorize('Usage:', 'cyan', 'bold')} bun run seed [seeder...] [options]
41
+
42
+ ${colorize('Arguments:', 'white', 'bold')}
43
+ seeder... Run only these seeders and the seeders they depend on
44
+
45
+ ${colorize('Options:', 'white', 'bold')}
46
+ --only a,b Same as naming the seeders
47
+ --fresh Ignore and overwrite cached steps of the named seeders
48
+ (of every seeder when none are named)
49
+ --concurrency, -c <n> Run up to <n> independent seeders in parallel (default: 1)
50
+ --continue-on-failure Keep running seeders that do not depend on a failed one
51
+ --allow-remote Seed a database that is not local
52
+ --quiet, -q Suppress progress and step output (keep results table)
53
+ --dry-run Show execution order without running seeders
54
+ --list, -l List registered seeders in dependency order and exit
55
+ --help, -h Show this help message
56
+
57
+ ${formatSeedersList(seeders)}
58
+ `
59
+
60
+ /**
61
+ * Parse CLI arguments, run the seeders and return the exit code.
62
+ * Unknown flags and unknown seeder names return 1.
63
+ */
64
+ export async function runCli(
65
+ seeders: readonly SeederAny[],
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
+ },
77
+ ): Promise<number> {
78
+ let parsed: ReturnType<typeof parse>
79
+ try {
80
+ parsed = parse(argv)
81
+ } catch (error) {
82
+ console.error(colorize(error instanceof Error ? error.message : String(error), 'red'))
83
+ console.log(helpText(seeders))
84
+ return 1
85
+ }
86
+ const { values, positionals } = parsed
87
+
88
+ if (values.help) {
89
+ console.log(helpText(seeders))
90
+ return 0
91
+ }
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
+
115
+ const names = [...positionals, ...(values.only ?? []).flatMap((value) => value.split(','))]
116
+ .map((value) => value.trim())
117
+ .filter(Boolean)
118
+ const only = names.length > 0 ? names : undefined
119
+
120
+ try {
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
+ }
139
+
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
+
155
+ console.log(
156
+ `\n${colorize('🌱 Dry Run', 'cyan', 'bold')} ${colorize(`(${order.length} ${order.length === 1 ? 'seeder' : 'seeders'}${concurrencyText})`, 'dim')}${targetText}\n`,
157
+ )
158
+
159
+ const printItem = (seederName: string, num: number, indent: string) => {
160
+ const seeder = seederMap.get(seederName)
161
+ const deps = seeder?.dependsOn ?? []
162
+ const depsStr =
163
+ deps.length > 0 ? ` ${colorize(`(depends on: ${deps.join(', ')})`, 'dim')}` : ''
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
+ }
213
+ console.log('')
214
+ return 0
215
+ }
216
+
217
+ const { success } = await runSeeders(seeders, {
218
+ printResults: true,
219
+ verbose: !values.quiet,
220
+ only,
221
+ fresh: values.fresh ? (only ?? true) : false,
222
+ continueOnFailure: values['continue-on-failure'],
223
+ allowRemote: values['allow-remote'],
224
+ concurrency,
225
+ })
226
+ return success ? 0 : 1
227
+ } catch (error) {
228
+ const usage = error instanceof Error && USAGE_ERRORS.has(error.name)
229
+ console.error(colorize(usage ? (error as Error).message : Bun.inspect(error), 'red'))
230
+ return 1
231
+ }
232
+ }
233
+
234
+ function parse(argv: readonly string[]) {
235
+ return parseArgs({
236
+ args: [...argv],
237
+ allowPositionals: true,
238
+ strict: true,
239
+ options: {
240
+ help: { type: 'boolean', short: 'h' },
241
+ list: { type: 'boolean', short: 'l' },
242
+ quiet: { type: 'boolean', short: 'q' },
243
+ concurrency: { type: 'string', short: 'c' },
244
+ 'dry-run': { type: 'boolean' },
245
+ only: { type: 'string', multiple: true },
246
+ fresh: { type: 'boolean' },
247
+ 'continue-on-failure': { type: 'boolean' },
248
+ 'allow-remote': { type: 'boolean' },
249
+ },
250
+ })
251
+ }