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.
package/src/signals.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { colorize } from './formatting.js'
2
+
3
+ type TerminationSignal = 'SIGINT' | 'SIGTERM'
4
+ type Cleanup = () => Promise<void>
5
+
6
+ /** Exit codes a shell reports for a process ended by the signal (128 + signal number) */
7
+ const EXIT_CODES: Record<TerminationSignal, number> = { SIGINT: 130, SIGTERM: 143 }
8
+
9
+ // One listener per signal for the whole process, shared by overlapping runs, so the
10
+ // first run to finish its cleanup cannot exit while another is still tearing down.
11
+ const cleanups = new Set<Cleanup>()
12
+ let received: TerminationSignal | undefined
13
+
14
+ const onSignal = (signal: TerminationSignal) => {
15
+ if (received) {
16
+ // A second signal while cleaning up: give up on cleanup and exit now
17
+ process.exit(EXIT_CODES[signal])
18
+ }
19
+ received = signal
20
+ console.error(
21
+ colorize(
22
+ `\nReceived ${signal}: tearing down before exiting (send it again to exit now)`,
23
+ 'yellow',
24
+ ),
25
+ )
26
+ void Promise.allSettled([...cleanups].map((cleanup) => cleanup())).then(() =>
27
+ process.exit(EXIT_CODES[signal]),
28
+ )
29
+ }
30
+
31
+ const listeners: Record<TerminationSignal, () => void> = {
32
+ SIGINT: () => onSignal('SIGINT'),
33
+ SIGTERM: () => onSignal('SIGTERM'),
34
+ }
35
+
36
+ /**
37
+ * Run `cleanup` when the process receives SIGINT or SIGTERM, then exit with 130 or 143.
38
+ * Returns a function that unregisters it. The listeners are installed while at least one
39
+ * cleanup is registered, so outside a run the process keeps its default signal behavior.
40
+ */
41
+ export function onTerminationSignal(cleanup: Cleanup): () => void {
42
+ if (cleanups.size === 0 && !received) {
43
+ process.on('SIGINT', listeners.SIGINT)
44
+ process.on('SIGTERM', listeners.SIGTERM)
45
+ }
46
+ cleanups.add(cleanup)
47
+ return () => {
48
+ cleanups.delete(cleanup)
49
+ if (cleanups.size === 0 && !received) {
50
+ process.off('SIGINT', listeners.SIGINT)
51
+ process.off('SIGTERM', listeners.SIGTERM)
52
+ }
53
+ }
54
+ }
package/src/step.ts CHANGED
@@ -86,6 +86,17 @@ export type StepScope = {
86
86
  fresh: boolean
87
87
  record: StepRecord
88
88
  prefix?: string | undefined
89
+ /** How many steps per key this seeder started, so a repeated key gets its own identity */
90
+ keyCounts?: Map<string, number> | undefined
91
+ }
92
+
93
+ /** Identifies one step run, for `StepRunnerConfig.aroundStep` */
94
+ export type StepIdentity = {
95
+ seederName: string
96
+ /** The step's explicit `key`, or else its description */
97
+ key: string
98
+ /** How many earlier steps of this seeder used the same key in this run (0 for the first) */
99
+ occurrence: number
89
100
  }
90
101
 
91
102
  export type StepRunnerConfig = {
@@ -94,6 +105,11 @@ export type StepRunnerConfig = {
94
105
  seederName?: string | undefined
95
106
  /** Print a line per step (default: true) */
96
107
  log?: boolean | undefined
108
+ /**
109
+ * Wraps each run of a step's function (not cache hits), for example to give the step
110
+ * its own seeded faker. Must call `run` once and return its result.
111
+ */
112
+ aroundStep?: (<T>(step: StepIdentity, run: () => MaybePromise<T>) => MaybePromise<T>) | undefined
97
113
  }
98
114
 
99
115
  export type StepRunner = {
@@ -150,7 +166,7 @@ function canonicalStringify(value: unknown): string {
150
166
  * Optionally provide a cache for step caching support.
151
167
  */
152
168
  export function createStepRunner(config?: StepRunnerConfig): StepRunner {
153
- const { cache, log = true } = config ?? {}
169
+ const { cache, log = true, aroundStep } = config ?? {}
154
170
  const scopeStorage = new AsyncLocalStorage<StepScope>()
155
171
  let fallbackScope: StepScope = {
156
172
  seederName: config?.seederName ?? '',
@@ -219,6 +235,16 @@ export function createStepRunner(config?: StepRunnerConfig): StepRunner {
219
235
  const startTime = performance.now()
220
236
  const prefix = formatPrefix(scope)
221
237
 
238
+ // Counted before any await, so steps started together (Promise.all) number in call order
239
+ const identityKey = options?.key ?? description
240
+ scope.keyCounts ??= new Map()
241
+ const occurrence = scope.keyCounts.get(identityKey) ?? 0
242
+ scope.keyCounts.set(identityKey, occurrence + 1)
243
+ const run = (): MaybePromise<T> =>
244
+ aroundStep
245
+ ? aroundStep({ seederName: scope.seederName, key: identityKey, occurrence }, fn)
246
+ : fn()
247
+
222
248
  try {
223
249
  let result: T
224
250
  let wasCached = false
@@ -255,7 +281,7 @@ export function createStepRunner(config?: StepRunnerConfig): StepRunner {
255
281
  result = stored as T
256
282
  wasCached = true
257
283
  } else {
258
- result = await fn()
284
+ result = await run()
259
285
  const entry: CacheEntry =
260
286
  version === undefined
261
287
  ? { __plantr: 1, value: result }
@@ -272,9 +298,9 @@ export function createStepRunner(config?: StepRunnerConfig): StepRunner {
272
298
  warnedNoCache = true
273
299
  print(`${prefix}${colorize('⚠ Cache not configured, running without cache', 'yellow')}`)
274
300
  }
275
- result = await fn()
301
+ result = await run()
276
302
  } else {
277
- result = await fn()
303
+ result = await run()
278
304
  }
279
305
 
280
306
  if (wasCached) scope.record.cachedSteps.push(description)
package/src/types.ts CHANGED
@@ -5,8 +5,8 @@
5
5
  * Consumers can extend this with their own context (e.g. prisma, custom helpers).
6
6
  */
7
7
 
8
- import type { expect } from 'bun:test'
9
8
  import type { Faker } from '@faker-js/faker'
9
+ import type { ExpectFn } from './expect.js'
10
10
  import type { StepFn } from './step.js'
11
11
 
12
12
  /** Flatten intersections and mapped types for cleaner IDE hover tooltips */
@@ -29,13 +29,13 @@ export type JsonValue =
29
29
  * Contains faker for generating test data, step for workflow organization,
30
30
  * and expect for assertions.
31
31
  */
32
- export type BaseSeederContext = {
32
+ export type BaseSeederContext<TExpect = ExpectFn> = {
33
33
  /** Faker instance for generating test data */
34
34
  faker: Faker
35
35
  /** Step function for organizing seeder workflow */
36
36
  step: StepFn
37
- /** Assertion function from bun:test for verifying data */
38
- expect: typeof expect
37
+ /** Assertion function for verifying data (bun:test on Bun, built-in fallback on Node, or custom) */
38
+ expect: TExpect
39
39
  }
40
40
 
41
41
  /** Extract the output type from a Seeder */
@@ -215,6 +215,13 @@ export type RunSeedersOptions<TName extends string = string> = {
215
215
  * Set to a positive integer (e.g. `4`) or `Infinity` to run independent DAG branches in parallel.
216
216
  */
217
217
  concurrency?: number | undefined
218
+ /**
219
+ * Handle SIGINT and SIGTERM while the run is active (default: true): start no more
220
+ * seeders, flush the cache, run `onAfterAll`, `teardown` and deferred cleanups, then
221
+ * exit with 130 (SIGINT) or 143 (SIGTERM). A second signal exits at once. Set to
222
+ * `false` when your own signal handlers should stay in charge.
223
+ */
224
+ handleSignals?: boolean | undefined
218
225
  }
219
226
 
220
227
  type OutputsOnSuccess<TSeeders extends readonly SeederAny[], TOptions> = [TOptions] extends [