plantr 2.1.0 → 2.3.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.
@@ -1,12 +1,12 @@
1
- import { expect } from 'bun:test'
2
1
  import { AsyncLocalStorage } from 'node:async_hooks'
3
2
  import type { Faker } from '@faker-js/faker'
4
3
  import { type RunSeedersCliOptions, runCli } from './cli.js'
5
4
  import { createDefineSeeder } from './define-seeder.js'
5
+ import { type AnyExpectFn, type ExpectFn, getDefaultExpect } from './expect.js'
6
6
  import { getDefaultFaker, lazyFaker } from './lazy-faker.js'
7
- import { runSeedersCore } from './run-seeders.js'
7
+ import { type FreshRun, runSeedersCore, type SetupHelpers } from './run-seeders.js'
8
8
  import { isSeedingActive } from './seeding-state.js'
9
- import { createStepRunner, type SeederCache } from './step.js'
9
+ import { createStepRunner, type SeederCache, type StepRunner } from './step.js'
10
10
  import type {
11
11
  BaseSeederContext,
12
12
  MaybePromise,
@@ -19,35 +19,91 @@ import type {
19
19
  ValidateSeeders,
20
20
  } from './types.js'
21
21
 
22
+ /** Resolve the effective `expect` type from an optional `config.expect` type parameter */
23
+ export type ResolvedExpect<TExpect> = [Exclude<TExpect, undefined>] extends [never]
24
+ ? ExpectFn
25
+ : [AnyExpectFn] extends [Exclude<TExpect, undefined>]
26
+ ? ExpectFn
27
+ : undefined extends TExpect
28
+ ? Exclude<TExpect, undefined> | ExpectFn
29
+ : TExpect
30
+
22
31
  /**
23
32
  * Full context type resolved from `BaseSeederContext` plus the extra properties
24
33
  * returned by `config.context`. Any base key returned by `context` overrides the default.
25
34
  */
26
- export type ResolvedContext<TExtra extends object = Record<never, never>> = Prettify<
27
- Omit<BaseSeederContext, keyof TExtra> & TExtra
28
- >
35
+ export type ResolvedContext<
36
+ TExtra extends object = Record<never, never>,
37
+ TExpect = ExpectFn,
38
+ > = Prettify<Omit<BaseSeederContext<ResolvedExpect<TExpect>>, keyof TExtra> & TExtra>
29
39
 
30
40
  /**
31
41
  * Configuration for creating a seeder instance.
32
42
  * `context` is optional and its returned properties are automatically merged onto `BaseSeederContext`.
33
43
  */
34
- export type SeederInstanceConfig<TExtra extends object = Record<never, never>> = {
44
+ export type SeederInstanceConfig<
45
+ TExtra extends object = Record<never, never>,
46
+ TExpect extends AnyExpectFn | undefined = ExpectFn,
47
+ TResources = undefined,
48
+ > = {
49
+ /**
50
+ * Optional: acquire what the run needs (a database connection, an authenticated client)
51
+ * and return it. Runs once per run, after the target guard, before the cache and the
52
+ * context factory, which both receive the returned resources. Throw to refuse the run.
53
+ *
54
+ * Register the cleanup for each resource with `defer` right after acquiring it when
55
+ * `setup` acquires several: if `setup` throws later, the deferred cleanups still run
56
+ * (last registered first), while `teardown` does not, as there are no resources to pass it.
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * setup: async () => {
61
+ * const db = await connect(process.env.DATABASE_URL)
62
+ * return { db }
63
+ * },
64
+ * teardown: ({ db }) => db.close(),
65
+ * ```
66
+ */
67
+ setup?: ((helpers: SetupHelpers) => MaybePromise<TResources>) | undefined
68
+
69
+ /**
70
+ * Optional: release what `setup` returned. Runs once whenever `setup` returned: after
71
+ * the seeders (also when one fails), when the cache or context factory throws, and on
72
+ * SIGINT or SIGTERM before the process exits. Deferred cleanups run after it.
73
+ */
74
+ teardown?: ((resources: NoInfer<TResources>) => MaybePromise<void>) | undefined
75
+
35
76
  /**
36
77
  * Optional factory function that extends the base context (`faker`, `step`, `expect`).
37
78
  * Returned properties are merged onto `base` automatically — no need to spread `...base`,
38
79
  * though spreading or overriding keys (such as `faker`) also works.
39
- * Called once per run, after `onBeforeAll`.
80
+ * Called once per run, after `setup`, with the resources it returned.
40
81
  *
41
82
  * @example
42
83
  * ```typescript
43
- * context: () => ({ prisma })
84
+ * context: (base, { db }) => ({ db })
44
85
  * ```
45
86
  */
46
- context?: ((base: BaseSeederContext) => MaybePromise<TExtra>) | undefined
87
+ context?:
88
+ | ((
89
+ base: NoInfer<BaseSeederContext<ResolvedExpect<TExpect>>>,
90
+ resources: NoInfer<TResources>,
91
+ ) => MaybePromise<TExtra>)
92
+ | undefined
93
+
94
+ /**
95
+ * Optional: custom `expect` assertion function (for example Vitest's `expect`).
96
+ * Defaults to `bun:test`'s `expect` on Bun and a zero-dependency `node:assert/strict`
97
+ * implementation on Node.js.
98
+ */
99
+ expect?: TExpect | undefined
47
100
 
48
101
  /**
49
102
  * Optional cache for step caching.
50
- * Provide `get` / `set` (and optionally `getAll` for single-query preloading).
103
+ * Provide `get` / `set` (and optionally `getAll` for single-query preloading), or a
104
+ * function that builds the cache from the resources `setup` returned. The function runs
105
+ * once per run, after `setup` and before the cache preload; return `undefined` to run
106
+ * without a cache.
51
107
  *
52
108
  * @example
53
109
  * ```typescript
@@ -58,9 +114,32 @@ export type SeederInstanceConfig<TExtra extends object = Record<never, never>> =
58
114
  * await prisma.seedCache.upsert({ where: { key }, create: { key, output }, update: { output } })
59
115
  * },
60
116
  * }
117
+ * // or, from setup's resources:
118
+ * cache: ({ db }) => db.seedCache,
119
+ * ```
120
+ */
121
+ cache?:
122
+ | SeederCache
123
+ | ((resources: NoInfer<TResources>) => MaybePromise<SeederCache | undefined>)
124
+ | undefined
125
+
126
+ /**
127
+ * Optional: reset the target before a fresh run (CLI `--fresh`, or the `fresh` option),
128
+ * for example wipe a local emulator, so steps that create records with ids the target
129
+ * chooses do not create them a second time. Runs after `setup` and the cache factory,
130
+ * before the cache preload and the context factory, and only when at least one seeder of
131
+ * the run is fresh. `all` is true only when every registered seeder runs fresh: with
132
+ * `--fresh` plus seeder names, the seeders they depend on still replay their cache, so
133
+ * wipe only when `all` is true (or throw to refuse a partial fresh run).
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * onFresh: async ({ resources: { db }, all }) => {
138
+ * if (all) await db.wipe()
139
+ * }
61
140
  * ```
62
141
  */
63
- cache?: SeederCache | undefined
142
+ onFresh?: ((run: FreshRun<NoInfer<TResources>>) => MaybePromise<void>) | undefined
64
143
 
65
144
  /**
66
145
  * Optional: default maximum number of independent seeders to run concurrently (default: 1).
@@ -91,8 +170,25 @@ export type SeederInstanceConfig<TExtra extends object = Record<never, never>> =
91
170
  fakerSeed?: number | undefined
92
171
 
93
172
  /**
94
- * Called before all seeders run, before the context factory.
95
- * Use for setup like connecting to databases, or to refuse a run.
173
+ * Optional, with `fakerSeed`: how finely faker is seeded (default: `'seeder'`).
174
+ *
175
+ * - `'seeder'`: one faker per seeder, seeded from `fakerSeed` and the seeder's name. A
176
+ * cached step skips its function, and with it the faker draws in it, so everything the
177
+ * seeder draws after that step shifts between a cached and an uncached run.
178
+ * - `'step'`: each step's function also gets its own faker, seeded from `fakerSeed`, the
179
+ * seeder's name and the step's `key` (or description), plus a counter when a key repeats.
180
+ * Draws inside a step and draws after it are the same whether earlier steps ran or came
181
+ * from the cache, and parallel steps no longer share one sequence.
182
+ *
183
+ * Switching to `'step'` changes the data steps generate once, which is why it is not the default.
184
+ */
185
+ fakerSeedScope?: 'seeder' | 'step' | undefined
186
+
187
+ /**
188
+ * Called before all seeders run, before `setup` and the context factory.
189
+ *
190
+ * @deprecated Use `setup`: throw from it to refuse a run, and return what it connects
191
+ * so `teardown`, `context` and a `cache` factory receive it. Still called, before `setup`.
96
192
  *
97
193
  * @example
98
194
  * ```typescript
@@ -106,7 +202,9 @@ export type SeederInstanceConfig<TExtra extends object = Record<never, never>> =
106
202
  /**
107
203
  * Called after all seeders complete (success or failure), also when the context
108
204
  * factory throws. Receives the created context (or `undefined` if the context factory threw).
109
- * Use for cleanup like disconnecting from databases.
205
+ *
206
+ * @deprecated Use `teardown`, which receives the resources `setup` returned even when
207
+ * no context exists. Still called, before `teardown`.
110
208
  *
111
209
  * @example
112
210
  * ```typescript
@@ -116,7 +214,7 @@ export type SeederInstanceConfig<TExtra extends object = Record<never, never>> =
116
214
  * ```
117
215
  */
118
216
  onAfterAll?:
119
- | ((ctx: NoInfer<ResolvedContext<TExtra>> | undefined) => MaybePromise<void>)
217
+ | ((ctx: NoInfer<ResolvedContext<TExtra, TExpect>> | undefined) => MaybePromise<void>)
120
218
  | undefined
121
219
  }
122
220
 
@@ -243,15 +341,21 @@ type FakerSlot = {
243
341
  instance?: Faker
244
342
  }
245
343
 
246
- export function createSeederInstance<TExtra extends object = Record<never, never>>(
247
- config?: SeederInstanceConfig<TExtra>,
248
- ): SeederInstance<ResolvedContext<TExtra>> {
249
- type TContext = ResolvedContext<TExtra>
344
+ export function createSeederInstance<
345
+ TExtra extends object = Record<never, never>,
346
+ TExpect extends AnyExpectFn | undefined = ExpectFn,
347
+ TResources = undefined,
348
+ >(
349
+ config?: SeederInstanceConfig<TExtra, TExpect, TResources>,
350
+ ): SeederInstance<ResolvedContext<TExtra, TExpect>> {
351
+ type TContext = ResolvedContext<TExtra, TExpect>
250
352
 
251
353
  const defineSeeder = createDefineSeeder<TContext>()
252
354
  const customFaker = config?.faker && config.faker !== lazyFaker ? config.faker : undefined
253
355
  const resolveBaseFaker = (): Faker => customFaker ?? getDefaultFaker()
356
+ const customExpect = config?.expect
254
357
  const fakerSeed = config?.fakerSeed
358
+ const seedPerStep = fakerSeed !== undefined && config?.fakerSeedScope === 'step'
255
359
  const defaultConcurrency = config?.concurrency
256
360
 
257
361
  const runInternal = async (
@@ -259,11 +363,13 @@ export function createSeederInstance<TExtra extends object = Record<never, never
259
363
  options?: RunSeedersOptions,
260
364
  bannerName?: string,
261
365
  ) => {
262
- // One step runner and faker storage per run, so cache keys, duplicate checks, and scopes are isolated
263
- const stepRunner = createStepRunner({
264
- cache: config?.cache,
265
- log: options?.verbose ?? true,
266
- })
366
+ // One step runner and faker storage per run, so cache keys, duplicate checks, and scopes are
367
+ // isolated. The runner is built after setup, since the cache may come from its resources.
368
+ let stepRunner: StepRunner | undefined
369
+ const requireStepRunner = (): StepRunner => {
370
+ if (!stepRunner) throw new Error('plantr: the step runner is used before setup finished')
371
+ return stepRunner
372
+ }
267
373
  const fakerStorage = new AsyncLocalStorage<FakerSlot>()
268
374
  const resolveActiveFaker = (): Faker => {
269
375
  const slot = fakerStorage.getStore()
@@ -316,21 +422,36 @@ export function createSeederInstance<TExtra extends object = Record<never, never
316
422
  return runSeedersCore(
317
423
  seeders,
318
424
  {
319
- context: async () => {
320
- const base: BaseSeederContext = {
425
+ prepare: async (resources) => {
426
+ const cache =
427
+ typeof config?.cache === 'function' ? await config.cache(resources) : config?.cache
428
+ stepRunner = createStepRunner({
429
+ cache,
430
+ log: options?.verbose ?? true,
431
+ aroundStep: seedPerStep
432
+ ? ({ seederName, key, occurrence }, run) => {
433
+ const name = `${seederName}:${key}${occurrence > 0 ? `#${occurrence}` : ''}`
434
+ return fakerStorage.run({ name, isolated: true }, run)
435
+ }
436
+ : undefined,
437
+ })
438
+ },
439
+ preloadCache: () => stepRunner?.preload(),
440
+ flushCache: () => stepRunner?.flush(),
441
+ context: async (resources) => {
442
+ const base: BaseSeederContext<ResolvedExpect<TExpect>> = {
321
443
  faker: scopedFaker,
322
- step: stepRunner.step,
323
- expect,
444
+ step: requireStepRunner().step,
445
+ expect: (customExpect ?? getDefaultExpect()) as ResolvedExpect<TExpect>,
324
446
  }
325
447
  if (!config?.context) return base as unknown as TContext
326
- const extra = await config.context(base)
448
+ const extra = await config.context(base, resources)
327
449
  return extra === base
328
450
  ? (base as unknown as TContext)
329
451
  : ({ ...base, ...extra } as unknown as TContext)
330
452
  },
331
- preloadCache: config?.cache?.getAll ? () => stepRunner.preload() : undefined,
332
- flushCache: config?.cache?.setMany ? () => stepRunner.flush() : undefined,
333
453
  createSeederScope: ({ name, fresh, concurrent }) => {
454
+ const stepRunner = requireStepRunner()
334
455
  const stepScope = stepRunner.createScope({
335
456
  seederName: name,
336
457
  fresh,
@@ -349,6 +470,9 @@ export function createSeederInstance<TExtra extends object = Record<never, never
349
470
  },
350
471
  bannerName,
351
472
  target: config?.target,
473
+ setup: config?.setup,
474
+ onFresh: config?.onFresh,
475
+ teardown: config?.teardown,
352
476
  onBeforeAll: config?.onBeforeAll,
353
477
  onAfterAll: config?.onAfterAll,
354
478
  },
@@ -1,9 +1,10 @@
1
+ import { SeedUsageError } from './errors.js'
1
2
  import type { SeederAny } from './types.js'
2
3
 
3
4
  /**
4
5
  * Error thrown when circular dependencies are detected in seeders
5
6
  */
6
- export class CircularDependencyError extends Error {
7
+ export class CircularDependencyError extends SeedUsageError {
7
8
  constructor(cycle: string[]) {
8
9
  super(`Circular dependency detected in seeders: ${cycle.join(' -> ')} -> ${cycle[0] ?? ''}`)
9
10
  this.name = 'CircularDependencyError'
@@ -13,7 +14,7 @@ export class CircularDependencyError extends Error {
13
14
  /**
14
15
  * Error thrown when a seeder depends on a non-existent seeder
15
16
  */
16
- export class MissingDependencyError extends Error {
17
+ export class MissingDependencyError extends SeedUsageError {
17
18
  constructor(seeder: string, missingDep: string) {
18
19
  super(`Seeder "${seeder}" depends on "${missingDep}" which does not exist`)
19
20
  this.name = 'MissingDependencyError'
@@ -23,7 +24,7 @@ export class MissingDependencyError extends Error {
23
24
  /**
24
25
  * Error thrown when two seeders share a name
25
26
  */
26
- export class DuplicateSeederError extends Error {
27
+ export class DuplicateSeederError extends SeedUsageError {
27
28
  constructor(name: string) {
28
29
  super(`Two seeders are named "${name}"; seeder names must be unique`)
29
30
  this.name = 'DuplicateSeederError'
@@ -33,7 +34,7 @@ export class DuplicateSeederError extends Error {
33
34
  /**
34
35
  * Error thrown when a seeder is selected by a name that is not registered
35
36
  */
36
- export class UnknownSeederError extends Error {
37
+ export class UnknownSeederError extends SeedUsageError {
37
38
  constructor(name: string, known: readonly string[]) {
38
39
  super(`Unknown seeder "${name}". Registered seeders: ${known.join(', ') || '(none)'}`)
39
40
  this.name = 'UnknownSeederError'
package/src/errors.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Marks an error as a usage or configuration problem. Set it to `true` on any error (or
3
+ * throw `SeedUsageError`) and `runSeedersCli` prints only the message and exits 1, and a
4
+ * seeder failing with it is reported without a stack trace. A registered symbol, so it also
5
+ * works across copies of plantr and on errors from your own classes.
6
+ */
7
+ export const usageErrorSymbol: unique symbol = Symbol.for('plantr.usageError')
8
+
9
+ /**
10
+ * A usage or configuration error: a refused target, a missing environment variable, a bad
11
+ * argument. The message should say what to do; the CLI prints only it, without a stack trace.
12
+ */
13
+ export class SeedUsageError extends Error {
14
+ readonly [usageErrorSymbol] = true
15
+
16
+ constructor(message: string, options?: ErrorOptions) {
17
+ super(message, options)
18
+ this.name = 'SeedUsageError'
19
+ }
20
+ }
21
+
22
+ /** Whether `error` is marked as a usage error (`SeedUsageError`, or `usageErrorSymbol` set to true) */
23
+ export function isSeedUsageError(error: unknown): error is Error {
24
+ return (
25
+ typeof error === 'object' &&
26
+ error !== null &&
27
+ (error as { [usageErrorSymbol]?: unknown })[usageErrorSymbol] === true
28
+ )
29
+ }