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/src/step.ts
CHANGED
|
@@ -1,122 +1,256 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import { colorize, formatDuration } from './formatting.js'
|
|
3
|
+
import type { JsonValue, MaybePromise } from './types.js'
|
|
2
4
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
5
|
+
/** Envelope written to `SeederCache.set` / `SeederCache.setMany` by plantr */
|
|
6
|
+
export type CacheEntry = {
|
|
7
|
+
readonly __plantr: 1
|
|
8
|
+
readonly version?: string
|
|
9
|
+
readonly value?: unknown
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Single entry passed to `SeederCache.setMany` */
|
|
13
|
+
export type CacheWrite = {
|
|
14
|
+
readonly key: string
|
|
15
|
+
readonly value: CacheEntry
|
|
12
16
|
}
|
|
13
17
|
|
|
18
|
+
export type StepOptions =
|
|
19
|
+
| {
|
|
20
|
+
/** Enable caching for this step */
|
|
21
|
+
useCache?: false | undefined
|
|
22
|
+
version?: never
|
|
23
|
+
key?: never
|
|
24
|
+
}
|
|
25
|
+
| {
|
|
26
|
+
/** Enable caching for this step */
|
|
27
|
+
useCache: true
|
|
28
|
+
/**
|
|
29
|
+
* Optional explicit cache key (scoped to the seeder name).
|
|
30
|
+
* Defaults to a slugified version of the step description.
|
|
31
|
+
* Use this when you want to reword a description without busting the cache,
|
|
32
|
+
* or when the description contains non-ASCII characters.
|
|
33
|
+
*/
|
|
34
|
+
key?: string | undefined
|
|
35
|
+
/**
|
|
36
|
+
* Any JSON value describing what the step's output depends on (a number you bump,
|
|
37
|
+
* the data the step writes). A cached entry stored with a different version is a
|
|
38
|
+
* miss: the step runs again and its entry is overwritten. Object keys are compared
|
|
39
|
+
* deterministically regardless of insertion order.
|
|
40
|
+
*/
|
|
41
|
+
version?: JsonValue | undefined
|
|
42
|
+
}
|
|
43
|
+
|
|
14
44
|
export type StepFn = <T>(
|
|
15
45
|
description: string,
|
|
16
|
-
fn: () =>
|
|
46
|
+
fn: () => MaybePromise<T>,
|
|
17
47
|
options?: StepOptions,
|
|
18
48
|
) => Promise<T>
|
|
19
49
|
|
|
20
50
|
/**
|
|
21
51
|
* Cache interface for step caching.
|
|
22
|
-
* Provide get/set functions to enable caching in the step runner.
|
|
52
|
+
* Provide `get` / `set` functions to enable caching in the step runner.
|
|
23
53
|
* plantr stores an envelope object (`{ __plantr: 1, version?, value }`), so `set`
|
|
24
|
-
* always receives
|
|
54
|
+
* always receives a `CacheEntry` and `get` should return it as stored (or `undefined`/`null` on miss).
|
|
55
|
+
*
|
|
56
|
+
* Optionally provide `getAll` to preload all entries in one query at the start of a run,
|
|
57
|
+
* and `setMany` to flush new/updated entries in one batch write at the end of a run.
|
|
25
58
|
*/
|
|
26
59
|
export type SeederCache = {
|
|
27
|
-
/** Get a cached value by key.
|
|
28
|
-
get:
|
|
60
|
+
/** Get a cached value by key. Return undefined or null if not found. */
|
|
61
|
+
get: (key: string) => MaybePromise<unknown>
|
|
29
62
|
/** Set a cached value by key. */
|
|
30
|
-
set:
|
|
63
|
+
set: (key: string, value: CacheEntry) => MaybePromise<void>
|
|
64
|
+
/**
|
|
65
|
+
* Optional: load all cached entries once at the start of a run to avoid N+1 `get` queries.
|
|
66
|
+
*/
|
|
67
|
+
getAll?: (() => MaybePromise<Map<string, unknown> | Record<string, unknown>>) | undefined
|
|
68
|
+
/**
|
|
69
|
+
* Optional: write all new/updated cache entries in a single batch at the end of a run
|
|
70
|
+
* (before `onAfterAll`), removing per-step write round-trips from the critical path.
|
|
71
|
+
*/
|
|
72
|
+
setMany?: ((entries: readonly CacheWrite[]) => MaybePromise<void>) | undefined
|
|
31
73
|
}
|
|
32
74
|
|
|
33
75
|
/** What the steps of the current seeder did, for error reporting */
|
|
34
76
|
export type StepRecord = {
|
|
35
77
|
/** Descriptions of the steps whose output came from the cache */
|
|
36
78
|
cachedSteps: string[]
|
|
37
|
-
/** Description and error of the
|
|
79
|
+
/** Description and error of the innermost step that threw */
|
|
38
80
|
failed?: { step: string; error: unknown }
|
|
39
81
|
}
|
|
40
82
|
|
|
41
|
-
|
|
42
|
-
|
|
83
|
+
/** Isolated execution scope for a single seeder's steps (concurrency-safe) */
|
|
84
|
+
export type StepScope = {
|
|
85
|
+
seederName: string
|
|
86
|
+
fresh: boolean
|
|
87
|
+
record: StepRecord
|
|
88
|
+
prefix?: string | undefined
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export type StepRunnerConfig = {
|
|
92
|
+
cache?: SeederCache | undefined
|
|
43
93
|
/** Seeder name for scoping cache keys */
|
|
44
|
-
seederName?: string
|
|
94
|
+
seederName?: string | undefined
|
|
45
95
|
/** Print a line per step (default: true) */
|
|
46
|
-
log?: boolean
|
|
96
|
+
log?: boolean | undefined
|
|
47
97
|
}
|
|
48
98
|
|
|
49
|
-
type
|
|
99
|
+
export type StepRunner = {
|
|
100
|
+
step: StepFn
|
|
101
|
+
/**
|
|
102
|
+
* Start a seeder in sequential mode: scopes cache keys to its name and returns the
|
|
103
|
+
* record its steps fill. With `fresh`, its cached steps ignore stored entries and overwrite them.
|
|
104
|
+
*/
|
|
105
|
+
setSeederName: (name: string, options?: { fresh?: boolean }) => StepRecord
|
|
106
|
+
/** Create an isolated scope for running one seeder concurrently */
|
|
107
|
+
createScope: (options: { seederName: string; fresh?: boolean; prefix?: string }) => StepScope
|
|
108
|
+
/** Run an async callback with `scope` bound via AsyncLocalStorage */
|
|
109
|
+
runWithScope: <T>(scope: StepScope, fn: () => Promise<T>) => Promise<T>
|
|
110
|
+
/** Preload cache entries via `cache.getAll()` if configured */
|
|
111
|
+
preload: () => Promise<void>
|
|
112
|
+
/** Flush buffered cache writes via `cache.setMany()` if configured */
|
|
113
|
+
flush: () => Promise<void>
|
|
114
|
+
}
|
|
50
115
|
|
|
51
116
|
const isCacheEntry = (stored: unknown): stored is CacheEntry =>
|
|
52
117
|
typeof stored === 'object' && stored !== null && (stored as CacheEntry).__plantr === 1
|
|
53
118
|
|
|
119
|
+
const slugify = (description: string): string =>
|
|
120
|
+
description
|
|
121
|
+
.toLowerCase()
|
|
122
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
123
|
+
.replace(/^-|-$/g, '')
|
|
124
|
+
|
|
125
|
+
/** Canonical JSON stringify with sorted object keys so version comparisons are order-independent */
|
|
126
|
+
function canonicalStringify(value: unknown): string {
|
|
127
|
+
if (value === null || typeof value !== 'object') {
|
|
128
|
+
return JSON.stringify(value)
|
|
129
|
+
}
|
|
130
|
+
if (Array.isArray(value)) {
|
|
131
|
+
return `[${value.map((item) => (item === undefined ? 'null' : canonicalStringify(item))).join(',')}]`
|
|
132
|
+
}
|
|
133
|
+
if (typeof (value as { toJSON?: unknown }).toJSON === 'function') {
|
|
134
|
+
return canonicalStringify((value as { toJSON: () => unknown }).toJSON())
|
|
135
|
+
}
|
|
136
|
+
const obj = value as Record<string, unknown>
|
|
137
|
+
const keys = Object.keys(obj).sort()
|
|
138
|
+
const parts: string[] = []
|
|
139
|
+
for (const key of keys) {
|
|
140
|
+
const entryValue = obj[key]
|
|
141
|
+
if (entryValue !== undefined) {
|
|
142
|
+
parts.push(`${JSON.stringify(key)}:${canonicalStringify(entryValue)}`)
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return `{${parts.join(',')}}`
|
|
146
|
+
}
|
|
147
|
+
|
|
54
148
|
/**
|
|
55
149
|
* Create a step runner for organizing seeder workflow.
|
|
56
150
|
* Optionally provide a cache for step caching support.
|
|
57
151
|
*/
|
|
58
|
-
export function createStepRunner(config?: StepRunnerConfig): {
|
|
59
|
-
step: StepFn
|
|
60
|
-
/**
|
|
61
|
-
* Start a seeder: scopes cache keys to its name and returns the record its steps fill.
|
|
62
|
-
* With `fresh`, its cached steps ignore stored entries and overwrite them.
|
|
63
|
-
*/
|
|
64
|
-
setSeederName: (name: string, options?: { fresh?: boolean }) => StepRecord
|
|
65
|
-
} {
|
|
152
|
+
export function createStepRunner(config?: StepRunnerConfig): StepRunner {
|
|
66
153
|
const { cache, log = true } = config ?? {}
|
|
67
|
-
|
|
68
|
-
let
|
|
69
|
-
|
|
154
|
+
const scopeStorage = new AsyncLocalStorage<StepScope>()
|
|
155
|
+
let fallbackScope: StepScope = {
|
|
156
|
+
seederName: config?.seederName ?? '',
|
|
157
|
+
fresh: false,
|
|
158
|
+
record: { cachedSteps: [] },
|
|
159
|
+
}
|
|
70
160
|
const usedKeys = new Set<string>()
|
|
161
|
+
const pendingWrites = new Map<string, CacheEntry>()
|
|
162
|
+
let preloaded: Map<string, unknown> | undefined
|
|
163
|
+
let warnedNoCache = false
|
|
71
164
|
|
|
72
165
|
const setSeederName = (name: string, options?: { fresh?: boolean }): StepRecord => {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
166
|
+
const record: StepRecord = { cachedSteps: [] }
|
|
167
|
+
fallbackScope = {
|
|
168
|
+
seederName: name,
|
|
169
|
+
fresh: options?.fresh ?? false,
|
|
170
|
+
record,
|
|
171
|
+
}
|
|
76
172
|
return record
|
|
77
173
|
}
|
|
78
174
|
|
|
175
|
+
const createScope = (options: {
|
|
176
|
+
seederName: string
|
|
177
|
+
fresh?: boolean
|
|
178
|
+
prefix?: string
|
|
179
|
+
}): StepScope => ({
|
|
180
|
+
seederName: options.seederName,
|
|
181
|
+
fresh: options.fresh ?? false,
|
|
182
|
+
record: { cachedSteps: [] },
|
|
183
|
+
prefix: options.prefix,
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
const runWithScope = <T>(scope: StepScope, fn: () => Promise<T>): Promise<T> =>
|
|
187
|
+
scopeStorage.run(scope, fn)
|
|
188
|
+
|
|
189
|
+
const preload = async (): Promise<void> => {
|
|
190
|
+
if (!cache?.getAll) return
|
|
191
|
+
const entries = await cache.getAll()
|
|
192
|
+
preloaded = entries instanceof Map ? new Map(entries) : new Map(Object.entries(entries))
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const flush = async (): Promise<void> => {
|
|
196
|
+
if (!cache?.setMany || pendingWrites.size === 0) return
|
|
197
|
+
const entries: CacheWrite[] = [...pendingWrites.entries()].map(([key, value]) => ({
|
|
198
|
+
key,
|
|
199
|
+
value,
|
|
200
|
+
}))
|
|
201
|
+
pendingWrites.clear()
|
|
202
|
+
await cache.setMany(entries)
|
|
203
|
+
}
|
|
204
|
+
|
|
79
205
|
const print = (line: string) => {
|
|
80
206
|
if (log) console.log(line)
|
|
81
207
|
}
|
|
82
208
|
|
|
209
|
+
const formatPrefix = (scope: StepScope): string =>
|
|
210
|
+
scope.prefix ? ` ${colorize(`[${scope.prefix}]`, 'cyan')} ` : ' '
|
|
211
|
+
|
|
83
212
|
const step: StepFn = async <T>(
|
|
84
213
|
description: string,
|
|
85
|
-
fn: () =>
|
|
214
|
+
fn: () => MaybePromise<T>,
|
|
86
215
|
options?: StepOptions,
|
|
87
216
|
): Promise<T> => {
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const
|
|
92
|
-
.toLowerCase()
|
|
93
|
-
.replace(/[^a-z0-9]+/g, '-')
|
|
94
|
-
.replace(/^-|-$/g, '')
|
|
95
|
-
const cacheKey = currentSeederName
|
|
96
|
-
? `${currentSeederName}:${slugifiedDescription}`
|
|
97
|
-
: slugifiedDescription
|
|
98
|
-
const startTime = Date.now()
|
|
217
|
+
const scope = scopeStorage.getStore() ?? fallbackScope
|
|
218
|
+
const useCache = options?.useCache === true
|
|
219
|
+
const startTime = performance.now()
|
|
220
|
+
const prefix = formatPrefix(scope)
|
|
99
221
|
|
|
100
222
|
try {
|
|
101
223
|
let result: T
|
|
102
224
|
let wasCached = false
|
|
103
225
|
|
|
104
226
|
if (useCache && cache) {
|
|
227
|
+
const rawKey = options.key !== undefined ? options.key : slugify(description)
|
|
228
|
+
const cacheKey = scope.seederName ? `${scope.seederName}:${rawKey}` : rawKey
|
|
229
|
+
|
|
105
230
|
if (usedKeys.has(cacheKey)) {
|
|
106
231
|
throw new Error(
|
|
107
|
-
`Step "${description}" uses cache key "${cacheKey}", which another cached step in this run already used. Give each cached step a unique description.`,
|
|
232
|
+
`Step "${description}" uses cache key "${cacheKey}", which another cached step in this run already used. Give each cached step a unique description or explicit key.`,
|
|
108
233
|
)
|
|
109
234
|
}
|
|
110
235
|
usedKeys.add(cacheKey)
|
|
111
|
-
}
|
|
112
236
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const stored = fresh
|
|
237
|
+
const version =
|
|
238
|
+
options.version === undefined ? undefined : canonicalStringify(options.version)
|
|
239
|
+
const stored = scope.fresh
|
|
240
|
+
? undefined
|
|
241
|
+
: preloaded !== undefined
|
|
242
|
+
? preloaded.get(cacheKey)
|
|
243
|
+
: await cache.get(cacheKey)
|
|
244
|
+
|
|
116
245
|
if (isCacheEntry(stored) && stored.version === version) {
|
|
117
246
|
result = stored.value as T
|
|
118
247
|
wasCached = true
|
|
119
|
-
} else if (
|
|
248
|
+
} else if (
|
|
249
|
+
stored !== undefined &&
|
|
250
|
+
stored !== null &&
|
|
251
|
+
!isCacheEntry(stored) &&
|
|
252
|
+
version === undefined
|
|
253
|
+
) {
|
|
120
254
|
// Written by plantr 1.x, which stored the value bare
|
|
121
255
|
result = stored as T
|
|
122
256
|
wasCached = true
|
|
@@ -126,31 +260,41 @@ export function createStepRunner(config?: StepRunnerConfig): {
|
|
|
126
260
|
version === undefined
|
|
127
261
|
? { __plantr: 1, value: result }
|
|
128
262
|
: { __plantr: 1, version, value: result }
|
|
129
|
-
|
|
263
|
+
preloaded?.set(cacheKey, entry)
|
|
264
|
+
if (cache.setMany) {
|
|
265
|
+
pendingWrites.set(cacheKey, entry)
|
|
266
|
+
} else {
|
|
267
|
+
await cache.set(cacheKey, entry)
|
|
268
|
+
}
|
|
130
269
|
}
|
|
131
270
|
} else if (useCache && !cache) {
|
|
132
|
-
|
|
133
|
-
|
|
271
|
+
if (!warnedNoCache) {
|
|
272
|
+
warnedNoCache = true
|
|
273
|
+
print(`${prefix}${colorize('⚠ Cache not configured, running without cache', 'yellow')}`)
|
|
274
|
+
}
|
|
134
275
|
result = await fn()
|
|
135
276
|
} else {
|
|
136
277
|
result = await fn()
|
|
137
278
|
}
|
|
138
279
|
|
|
139
|
-
if (wasCached) record.cachedSteps.push(description)
|
|
280
|
+
if (wasCached) scope.record.cachedSteps.push(description)
|
|
140
281
|
const suffix = wasCached
|
|
141
282
|
? ` ${colorize('(cached)', 'cyan')}`
|
|
142
|
-
: ` ${colorize(formatDuration(
|
|
143
|
-
print(
|
|
283
|
+
: ` ${colorize(formatDuration(performance.now() - startTime), 'dim')}`
|
|
284
|
+
print(`${prefix}${colorize('✓', 'green')} ${description}${suffix}`)
|
|
144
285
|
return result
|
|
145
286
|
} catch (error) {
|
|
146
|
-
|
|
147
|
-
|
|
287
|
+
// Preserve the innermost failing step if steps are nested
|
|
288
|
+
if (!scope.record.failed || scope.record.failed.error !== error) {
|
|
289
|
+
scope.record.failed = { step: description, error }
|
|
290
|
+
}
|
|
291
|
+
print(`${prefix}${colorize('✗', 'red')} ${description}`)
|
|
148
292
|
if (error instanceof Error) {
|
|
149
|
-
print(
|
|
293
|
+
print(`${prefix} ${colorize(error.message, 'dim')}`)
|
|
150
294
|
}
|
|
151
295
|
throw error
|
|
152
296
|
}
|
|
153
297
|
}
|
|
154
298
|
|
|
155
|
-
return { step, setSeederName }
|
|
299
|
+
return { step, setSeederName, createScope, runWithScope, preload, flush }
|
|
156
300
|
}
|
package/src/types.ts
CHANGED
|
@@ -5,36 +5,84 @@
|
|
|
5
5
|
* Consumers can extend this with their own context (e.g. prisma, custom helpers).
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import type {
|
|
9
|
-
import type {
|
|
10
|
-
import type { StepFn } from './step'
|
|
8
|
+
import type { Faker } from '@faker-js/faker'
|
|
9
|
+
import type { ExpectFn } from './expect.js'
|
|
10
|
+
import type { StepFn } from './step.js'
|
|
11
|
+
|
|
12
|
+
/** Flatten intersections and mapped types for cleaner IDE hover tooltips */
|
|
13
|
+
export type Prettify<T> = { [K in keyof T]: T[K] } & {}
|
|
14
|
+
|
|
15
|
+
/** A value or a Promise resolving to that value */
|
|
16
|
+
export type MaybePromise<T> = T | Promise<T>
|
|
17
|
+
|
|
18
|
+
/** JSON-serializable primitive */
|
|
19
|
+
export type JsonPrimitive = string | number | boolean | null
|
|
20
|
+
|
|
21
|
+
/** JSON-serializable value (used for step cache versions) */
|
|
22
|
+
export type JsonValue =
|
|
23
|
+
| JsonPrimitive
|
|
24
|
+
| readonly JsonValue[]
|
|
25
|
+
| { readonly [key: string]: JsonValue | undefined }
|
|
11
26
|
|
|
12
27
|
/**
|
|
13
28
|
* Base seeder context provided by the library.
|
|
14
29
|
* Contains faker for generating test data, step for workflow organization,
|
|
15
30
|
* and expect for assertions.
|
|
16
31
|
*/
|
|
17
|
-
export type BaseSeederContext = {
|
|
32
|
+
export type BaseSeederContext<TExpect = ExpectFn> = {
|
|
18
33
|
/** Faker instance for generating test data */
|
|
19
|
-
faker:
|
|
34
|
+
faker: Faker
|
|
20
35
|
/** Step function for organizing seeder workflow */
|
|
21
36
|
step: StepFn
|
|
22
|
-
/** Assertion function
|
|
23
|
-
expect:
|
|
37
|
+
/** Assertion function for verifying data (bun:test on Bun, built-in fallback on Node, or custom) */
|
|
38
|
+
expect: TExpect
|
|
24
39
|
}
|
|
25
40
|
|
|
26
41
|
/** Extract the output type from a Seeder */
|
|
27
42
|
// biome-ignore lint/suspicious/noExplicitAny: needs any to match any context type
|
|
28
|
-
export type SeederOutput<T> = T extends Seeder<any,
|
|
43
|
+
export type SeederOutput<T> = T extends Seeder<any, any, infer O, any> ? O : never
|
|
29
44
|
|
|
30
45
|
/** Extract the name from a Seeder */
|
|
31
46
|
// biome-ignore lint/suspicious/noExplicitAny: needs any to match any context type
|
|
32
|
-
export type SeederName<T> = T extends Seeder<any, infer N,
|
|
47
|
+
export type SeederName<T> = T extends Seeder<any, infer N, any, any> ? N : never
|
|
48
|
+
|
|
49
|
+
/** Extract the dependency names from a Seeder */
|
|
50
|
+
// biome-ignore lint/suspicious/noExplicitAny: needs any to match any context type
|
|
51
|
+
export type SeederDeps<T> = T extends Seeder<any, any, any, infer D> ? D : never
|
|
33
52
|
|
|
34
53
|
/** Build a typed deps object from an array of seeder dependencies */
|
|
35
|
-
export type DepsFromSeeders<T extends readonly SeederAny[]> = {
|
|
54
|
+
export type DepsFromSeeders<T extends readonly SeederAny[]> = Prettify<{
|
|
36
55
|
[K in T[number] as SeederName<K>]: SeederOutput<K>
|
|
37
|
-
}
|
|
56
|
+
}>
|
|
57
|
+
|
|
58
|
+
/** Map of seeder name -> output type for a collection of seeders */
|
|
59
|
+
export type SeederOutputs<TSeeders extends readonly SeederAny[]> = Prettify<{
|
|
60
|
+
[K in TSeeders[number] as SeederName<K>]: SeederOutput<K>
|
|
61
|
+
}>
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Dependency names required by seeders in `TSeeders` that are not present in `TSeeders`.
|
|
65
|
+
* Evaluates to `never` when all dependencies are present or when names are widened to `string`.
|
|
66
|
+
*/
|
|
67
|
+
export type MissingSeederDeps<TSeeders extends readonly SeederAny[]> = string extends SeederName<
|
|
68
|
+
TSeeders[number]
|
|
69
|
+
>
|
|
70
|
+
? never
|
|
71
|
+
: string extends SeederDeps<TSeeders[number]>
|
|
72
|
+
? never
|
|
73
|
+
: Exclude<SeederDeps<TSeeders[number]>, SeederName<TSeeders[number]>>
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Compile-time constraint verifying that every dependency declared by a seeder in `TSeeders`
|
|
77
|
+
* is also included in `TSeeders`.
|
|
78
|
+
*/
|
|
79
|
+
export type ValidateSeeders<TSeeders extends readonly SeederAny[]> = [
|
|
80
|
+
MissingSeederDeps<TSeeders>,
|
|
81
|
+
] extends [never]
|
|
82
|
+
? unknown
|
|
83
|
+
: {
|
|
84
|
+
readonly __missingDependencies__: `Missing required seeder(s) in list: ${MissingSeederDeps<TSeeders>}`
|
|
85
|
+
}
|
|
38
86
|
|
|
39
87
|
/** Configuration for creating a seeder */
|
|
40
88
|
export type SeederConfig<
|
|
@@ -46,74 +94,158 @@ export type SeederConfig<
|
|
|
46
94
|
/** Unique name for the seeder */
|
|
47
95
|
name: TName
|
|
48
96
|
/** Optional description of what the seeder does */
|
|
49
|
-
description?: string
|
|
97
|
+
description?: string | undefined
|
|
50
98
|
/** Seeder objects that must run before this one - provides typed outputs */
|
|
51
|
-
dependsOn?: TDeps
|
|
52
|
-
/** The seeding function that creates data */
|
|
99
|
+
dependsOn?: TDeps | undefined
|
|
100
|
+
/** The seeding function that creates data (sync or async) */
|
|
53
101
|
run: (
|
|
54
102
|
ctx: TContext,
|
|
55
103
|
deps: TDeps extends readonly never[] ? Record<string, never> : DepsFromSeeders<TDeps>,
|
|
56
|
-
) =>
|
|
104
|
+
) => MaybePromise<TOutput>
|
|
57
105
|
}
|
|
58
106
|
|
|
59
107
|
/** A seeder instance ready for execution */
|
|
60
|
-
export type Seeder<
|
|
108
|
+
export type Seeder<
|
|
109
|
+
TContext,
|
|
110
|
+
TName extends string = string,
|
|
111
|
+
TOutput = unknown,
|
|
112
|
+
TDepNames extends string = string,
|
|
113
|
+
> = {
|
|
61
114
|
/** Unique name for the seeder */
|
|
62
|
-
name: TName
|
|
115
|
+
readonly name: TName
|
|
63
116
|
/** Optional description of what the seeder does */
|
|
64
|
-
description?: string
|
|
117
|
+
readonly description?: string | undefined
|
|
65
118
|
/** Names of seeders that must run before this one (extracted from dependsOn) */
|
|
66
|
-
dependsOn: readonly
|
|
119
|
+
readonly dependsOn: readonly TDepNames[]
|
|
67
120
|
/** The seeding function that creates data */
|
|
68
|
-
run: (ctx: TContext, deps: Record<string, unknown>) =>
|
|
121
|
+
readonly run: (ctx: TContext, deps: Record<string, unknown>) => MaybePromise<TOutput>
|
|
69
122
|
}
|
|
70
123
|
|
|
71
124
|
/** Type-erased seeder for collections (can hold any seeder type) */
|
|
72
125
|
// biome-ignore lint/suspicious/noExplicitAny: SeederAny needs 'any' to work without explicit context type
|
|
73
|
-
export type SeederAny = Seeder<any, string, unknown>
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
export type
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
126
|
+
export type SeederAny = Seeder<any, string, unknown, string>
|
|
127
|
+
|
|
128
|
+
/** Result for a seeder that completed successfully */
|
|
129
|
+
export type CompletedSeederResult<TName extends string = string, TOutput = unknown> = {
|
|
130
|
+
name: TName
|
|
131
|
+
status: 'completed'
|
|
132
|
+
durationMs: number
|
|
133
|
+
output: TOutput
|
|
134
|
+
/** Descriptions of the steps whose output came from the cache */
|
|
135
|
+
cachedSteps: string[]
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Result for a seeder that threw an error */
|
|
139
|
+
export type FailedSeederResult<TName extends string = string> = {
|
|
140
|
+
name: TName
|
|
141
|
+
status: 'failed'
|
|
142
|
+
durationMs: number
|
|
143
|
+
error: Error
|
|
85
144
|
/** Description of the step that threw, when the seeder failed in a step */
|
|
86
|
-
failedStep?: string
|
|
145
|
+
failedStep?: string | undefined
|
|
87
146
|
/** Descriptions of the steps whose output came from the cache */
|
|
88
|
-
cachedSteps
|
|
147
|
+
cachedSteps: string[]
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Result for a seeder that was skipped because one or more dependencies failed */
|
|
151
|
+
export type SkippedSeederResult<TName extends string = string> = {
|
|
152
|
+
name: TName
|
|
153
|
+
status: 'skipped'
|
|
154
|
+
/** Names of direct dependencies that failed or were skipped */
|
|
155
|
+
failedDeps: string[]
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Result for a seeder that never started (e.g. an earlier seeder failed without continueOnFailure) */
|
|
159
|
+
export type PendingSeederResult<TName extends string = string> = {
|
|
160
|
+
name: TName
|
|
161
|
+
status: 'pending'
|
|
89
162
|
}
|
|
90
163
|
|
|
164
|
+
/** Discriminated union representing the outcome of a seeder */
|
|
165
|
+
export type SeederResult<TName extends string = string, TOutput = unknown> =
|
|
166
|
+
| CompletedSeederResult<TName, TOutput>
|
|
167
|
+
| FailedSeederResult<TName>
|
|
168
|
+
| SkippedSeederResult<TName>
|
|
169
|
+
| PendingSeederResult<TName>
|
|
170
|
+
|
|
171
|
+
/** Status of a seeder result */
|
|
172
|
+
export type SeederStatus = SeederResult['status']
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Union of typed `SeederResult` members pairing each seeder in `TSeeders`
|
|
176
|
+
* with its literal name and output type.
|
|
177
|
+
*/
|
|
178
|
+
export type SeederResultFor<TSeeders extends readonly SeederAny[]> =
|
|
179
|
+
TSeeders[number] extends infer S
|
|
180
|
+
? S extends SeederAny
|
|
181
|
+
? SeederResult<SeederName<S>, SeederOutput<S>>
|
|
182
|
+
: never
|
|
183
|
+
: never
|
|
184
|
+
|
|
91
185
|
/** Options for the seeder runner */
|
|
92
|
-
export type RunSeedersOptions = {
|
|
186
|
+
export type RunSeedersOptions<TName extends string = string> = {
|
|
93
187
|
/** Whether to print the results table (default: true) */
|
|
94
|
-
printResults?: boolean
|
|
188
|
+
printResults?: boolean | undefined
|
|
95
189
|
/** Whether to print verbose output (default: true) */
|
|
96
|
-
verbose?: boolean
|
|
190
|
+
verbose?: boolean | undefined
|
|
97
191
|
/**
|
|
98
192
|
* Whether to continue running seeders after a failure (default: false).
|
|
99
193
|
* When true, seeders that depend on a failed seeder will be skipped,
|
|
100
194
|
* but independent seeders will still run.
|
|
101
195
|
*/
|
|
102
|
-
continueOnFailure?: boolean
|
|
196
|
+
continueOnFailure?: boolean | undefined
|
|
103
197
|
/**
|
|
104
198
|
* Run only these seeders and everything they depend on, in dependency order.
|
|
105
199
|
* Throws `UnknownSeederError` for a name that is not registered.
|
|
106
200
|
*/
|
|
107
|
-
only?: readonly
|
|
201
|
+
only?: readonly TName[] | undefined
|
|
108
202
|
/**
|
|
109
203
|
* Ignore cached step entries and overwrite them: `true` for every seeder,
|
|
110
204
|
* or the names of the seeders to run fresh. Dependencies of those seeders still
|
|
111
205
|
* replay their cache unless they are named too.
|
|
112
206
|
*/
|
|
113
|
-
fresh?: boolean | readonly
|
|
207
|
+
fresh?: boolean | readonly TName[] | undefined
|
|
114
208
|
/**
|
|
115
209
|
* Seed a target that is not local (see `target` on the instance config).
|
|
116
210
|
* Without it, a non-local target throws `SeedTargetError` before anything runs.
|
|
117
211
|
*/
|
|
118
|
-
allowRemote?: boolean
|
|
212
|
+
allowRemote?: boolean | undefined
|
|
213
|
+
/**
|
|
214
|
+
* Maximum number of independent seeders to run concurrently (default: 1).
|
|
215
|
+
* Set to a positive integer (e.g. `4`) or `Infinity` to run independent DAG branches in parallel.
|
|
216
|
+
*/
|
|
217
|
+
concurrency?: number | undefined
|
|
119
218
|
}
|
|
219
|
+
|
|
220
|
+
type OutputsOnSuccess<TSeeders extends readonly SeederAny[], TOptions> = [TOptions] extends [
|
|
221
|
+
undefined,
|
|
222
|
+
]
|
|
223
|
+
? SeederOutputs<TSeeders>
|
|
224
|
+
: TOptions extends { readonly only: readonly (infer TOnly extends string)[] }
|
|
225
|
+
? string extends TOnly
|
|
226
|
+
? Partial<SeederOutputs<TSeeders>>
|
|
227
|
+
: Prettify<
|
|
228
|
+
Pick<SeederOutputs<TSeeders>, Extract<TOnly, keyof SeederOutputs<TSeeders>>> &
|
|
229
|
+
Partial<SeederOutputs<TSeeders>>
|
|
230
|
+
>
|
|
231
|
+
: TOptions extends { readonly only?: readonly string[] | undefined }
|
|
232
|
+
? 'only' extends keyof TOptions
|
|
233
|
+
? Partial<SeederOutputs<TSeeders>>
|
|
234
|
+
: SeederOutputs<TSeeders>
|
|
235
|
+
: SeederOutputs<TSeeders>
|
|
236
|
+
|
|
237
|
+
/** Return value of `runSeeders` with typed `results` and `outputs` */
|
|
238
|
+
export type RunSeedersResult<
|
|
239
|
+
TSeeders extends readonly SeederAny[] = readonly SeederAny[],
|
|
240
|
+
TOptions = undefined,
|
|
241
|
+
> =
|
|
242
|
+
| {
|
|
243
|
+
success: true
|
|
244
|
+
results: SeederResultFor<TSeeders>[]
|
|
245
|
+
outputs: OutputsOnSuccess<TSeeders, TOptions>
|
|
246
|
+
}
|
|
247
|
+
| {
|
|
248
|
+
success: false
|
|
249
|
+
results: SeederResultFor<TSeeders>[]
|
|
250
|
+
outputs: Partial<SeederOutputs<TSeeders>>
|
|
251
|
+
}
|
package/state.ts
CHANGED