plantr 1.0.1 → 2.0.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/LICENSE +21 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +365 -193
- package/dist/src/cli.d.ts +13 -0
- package/dist/src/create-seeder-instance.d.ts +29 -16
- package/dist/src/dependency-resolver.d.ts +16 -1
- package/dist/src/formatting.d.ts +7 -2
- package/dist/src/run-seeders.d.ts +28 -5
- package/dist/src/seeding-state.d.ts +5 -1
- package/dist/src/step.d.ts +27 -2
- package/dist/src/types.d.ts +20 -0
- package/dist/state.d.ts +11 -0
- package/dist/state.js +12 -0
- package/index.ts +6 -3
- package/package.json +19 -10
- package/readme.md +105 -26
- package/src/cli.ts +118 -0
- package/src/create-seeder-instance.ts +77 -111
- package/src/dependency-resolver.ts +42 -2
- package/src/formatting.ts +30 -12
- package/src/run-seeders.ts +172 -103
- package/src/seeding-state.ts +9 -4
- package/src/step.ts +73 -16
- package/src/types.ts +20 -0
- package/state.ts +11 -0
- package/dist/cli.d.ts +0 -17
- package/dist/cli.js +0 -59
- package/dist/index-a1s5r901.js +0 -4
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { RunSeedersOptions, SeederAny } from './types';
|
|
2
|
+
type RunSeeders = (seeders: readonly SeederAny[], options?: RunSeedersOptions) => Promise<{
|
|
3
|
+
success: boolean;
|
|
4
|
+
}>;
|
|
5
|
+
/**
|
|
6
|
+
* Parse CLI arguments, run the seeders and return the exit code.
|
|
7
|
+
* Unknown flags and unknown seeder names return 1.
|
|
8
|
+
*/
|
|
9
|
+
export declare function runCli(seeders: readonly SeederAny[], runSeeders: RunSeeders, { name, argv }: {
|
|
10
|
+
name: string;
|
|
11
|
+
argv: readonly string[];
|
|
12
|
+
}): Promise<number>;
|
|
13
|
+
export {};
|
|
@@ -31,15 +31,29 @@ export type SeederInstanceConfig<TContext extends BaseSeederContext> = {
|
|
|
31
31
|
* return cached?.output as T | undefined
|
|
32
32
|
* },
|
|
33
33
|
* set: async (key, value) => {
|
|
34
|
-
*
|
|
34
|
+
* const output = value as Prisma.InputJsonValue
|
|
35
|
+
* await prisma.seedCache.upsert({ where: { key }, create: { key, output }, update: { output } })
|
|
35
36
|
* }
|
|
36
37
|
* }
|
|
37
38
|
* ```
|
|
38
39
|
*/
|
|
39
40
|
cache?: SeederCache;
|
|
40
41
|
/**
|
|
41
|
-
*
|
|
42
|
-
*
|
|
42
|
+
* Optional: the database URL this instance writes to, e.g. `() => process.env.DATABASE_URL`.
|
|
43
|
+
* The banner prints its host and database (never credentials), and a run refuses a
|
|
44
|
+
* host that is not local unless it passes `allowRemote` (CLI: `--allow-remote`).
|
|
45
|
+
* Return undefined to skip the check.
|
|
46
|
+
*/
|
|
47
|
+
target?: () => string | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* Optional: seed faker before each seeder with this number plus a hash of the
|
|
50
|
+
* seeder's name, so every run generates the same data and adding a seeder does
|
|
51
|
+
* not shift the others'.
|
|
52
|
+
*/
|
|
53
|
+
fakerSeed?: number;
|
|
54
|
+
/**
|
|
55
|
+
* Called before all seeders run, before the context factory.
|
|
56
|
+
* Use for setup like connecting to databases, or to refuse a run.
|
|
43
57
|
*
|
|
44
58
|
* @example
|
|
45
59
|
* ```typescript
|
|
@@ -50,7 +64,8 @@ export type SeederInstanceConfig<TContext extends BaseSeederContext> = {
|
|
|
50
64
|
*/
|
|
51
65
|
onBeforeAll?: () => void | Promise<void>;
|
|
52
66
|
/**
|
|
53
|
-
* Called after all seeders complete (success or failure)
|
|
67
|
+
* Called after all seeders complete (success or failure), also when the context
|
|
68
|
+
* factory throws.
|
|
54
69
|
* Use for cleanup like disconnecting from databases.
|
|
55
70
|
*
|
|
56
71
|
* @example
|
|
@@ -89,15 +104,19 @@ export type SeederInstance<TContext extends BaseSeederContext> = {
|
|
|
89
104
|
*
|
|
90
105
|
* @param seeders - Array of seeders to run
|
|
91
106
|
* @param options - Optional runner options
|
|
92
|
-
* @returns Object containing results and success status
|
|
107
|
+
* @returns Object containing results and success status; `success` is false when a seeder failed
|
|
108
|
+
* @throws Before anything runs, on an invalid registry (duplicate name, missing
|
|
109
|
+
* dependency, cycle), an unknown name in `only`/`fresh`, or a refused `target`
|
|
93
110
|
*/
|
|
94
111
|
runSeeders: (seeders: readonly SeederAny[], options?: RunSeedersOptions) => Promise<{
|
|
95
112
|
results: SeederResult[];
|
|
96
113
|
success: boolean;
|
|
97
114
|
}>;
|
|
98
115
|
/**
|
|
99
|
-
* Run seeders as a CLI command.
|
|
100
|
-
*
|
|
116
|
+
* Run seeders as a CLI command: parses the arguments, runs, and exits with 0 or 1.
|
|
117
|
+
* Seeder names (positional or `--only a,b`) select seeders plus their dependencies;
|
|
118
|
+
* `--fresh`, `--continue-on-failure`, `--allow-remote`, `--dry-run` and `--help` map
|
|
119
|
+
* to the runner options. Unknown flags and names exit 1.
|
|
101
120
|
*
|
|
102
121
|
* @example
|
|
103
122
|
* ```typescript
|
|
@@ -109,6 +128,8 @@ export type SeederInstance<TContext extends BaseSeederContext> = {
|
|
|
109
128
|
*/
|
|
110
129
|
runSeedersCli: (seeders: readonly SeederAny[], options?: {
|
|
111
130
|
name?: string;
|
|
131
|
+
/** Arguments to parse (default: `process.argv.slice(2)`) */
|
|
132
|
+
argv?: readonly string[];
|
|
112
133
|
}) => Promise<void>;
|
|
113
134
|
/**
|
|
114
135
|
* Check if seeding is currently active.
|
|
@@ -145,15 +166,7 @@ export type SeederInstance<TContext extends BaseSeederContext> = {
|
|
|
145
166
|
* ...base,
|
|
146
167
|
* prisma,
|
|
147
168
|
* }),
|
|
148
|
-
*
|
|
149
|
-
* get: async (key) => {
|
|
150
|
-
* const cached = await prisma.seedCache.findUnique({ where: { key } })
|
|
151
|
-
* return cached?.output
|
|
152
|
-
* },
|
|
153
|
-
* set: async (key, value) => {
|
|
154
|
-
* await prisma.seedCache.create({ data: { key, output: value } })
|
|
155
|
-
* }
|
|
156
|
-
* },
|
|
169
|
+
* target: () => process.env.DATABASE_URL,
|
|
157
170
|
* })
|
|
158
171
|
*
|
|
159
172
|
* export { defineSeeder, isSeedingActive }
|
|
@@ -11,13 +11,28 @@ export declare class CircularDependencyError extends Error {
|
|
|
11
11
|
export declare class MissingDependencyError extends Error {
|
|
12
12
|
constructor(seeder: string, missingDep: string);
|
|
13
13
|
}
|
|
14
|
+
/**
|
|
15
|
+
* Error thrown when two seeders share a name
|
|
16
|
+
*/
|
|
17
|
+
export declare class DuplicateSeederError extends Error {
|
|
18
|
+
constructor(name: string);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Error thrown when a seeder is selected by a name that is not registered
|
|
22
|
+
*/
|
|
23
|
+
export declare class UnknownSeederError extends Error {
|
|
24
|
+
constructor(name: string, known: readonly string[]);
|
|
25
|
+
}
|
|
14
26
|
/**
|
|
15
27
|
* Resolves the execution order of seeders based on their dependencies
|
|
16
28
|
* using Kahn's algorithm (topological sort)
|
|
17
29
|
*
|
|
18
30
|
* @param seeders - Array of seeders to sort
|
|
31
|
+
* @param only - Optional names to select: returns them and everything they depend on
|
|
19
32
|
* @returns Array of seeder names in execution order
|
|
33
|
+
* @throws {DuplicateSeederError} If two seeders share a name
|
|
34
|
+
* @throws {UnknownSeederError} If a name in `only` is not registered
|
|
20
35
|
* @throws {CircularDependencyError} If circular dependencies are detected
|
|
21
36
|
* @throws {MissingDependencyError} If a seeder depends on a non-existent seeder
|
|
22
37
|
*/
|
|
23
|
-
export declare function resolveDependencyOrder(seeders: readonly SeederAny[]): string[];
|
|
38
|
+
export declare function resolveDependencyOrder(seeders: readonly SeederAny[], only?: readonly string[]): string[];
|
package/dist/src/formatting.d.ts
CHANGED
|
@@ -14,7 +14,9 @@ export declare function formatDuration(ms: number): string;
|
|
|
14
14
|
*/
|
|
15
15
|
export declare function printResultsTable(results: SeederResult[]): void;
|
|
16
16
|
/**
|
|
17
|
-
* Print error details for failed seeders
|
|
17
|
+
* Print error details for failed seeders: the failing step, the full error (message,
|
|
18
|
+
* stack, cause and own fields via Bun.inspect) and a hint when cached steps ran first.
|
|
19
|
+
* Under GitHub Actions, also prints one `::error` annotation per failed seeder.
|
|
18
20
|
*/
|
|
19
21
|
export declare function printErrors(results: SeederResult[]): void;
|
|
20
22
|
/**
|
|
@@ -28,7 +30,10 @@ export declare function printSeederComplete(durationMs: number, success: boolean
|
|
|
28
30
|
/**
|
|
29
31
|
* Print the initial banner when seeding starts
|
|
30
32
|
*/
|
|
31
|
-
export declare function printStartBanner(
|
|
33
|
+
export declare function printStartBanner(target?: {
|
|
34
|
+
label: string;
|
|
35
|
+
local: boolean;
|
|
36
|
+
}): void;
|
|
32
37
|
/**
|
|
33
38
|
* Print message when a seeder is skipped due to failed dependencies
|
|
34
39
|
*/
|
|
@@ -1,18 +1,40 @@
|
|
|
1
|
+
import type { StepRecord } from './step';
|
|
1
2
|
import type { RunSeedersOptions, SeederAny, SeederResult } from './types';
|
|
2
3
|
/**
|
|
3
4
|
* Internal configuration used by the runner.
|
|
4
5
|
* This is created by createSeederInstance and includes the wrapped context factory.
|
|
5
6
|
*/
|
|
6
7
|
export type InternalSeederConfig<TContext> = {
|
|
7
|
-
/** Factory function that creates the full context
|
|
8
|
+
/** Factory function that creates the full context; called once, after onBeforeAll */
|
|
8
9
|
context: () => TContext | Promise<TContext>;
|
|
9
|
-
/** Called before each seeder
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
/** Called before each seeder runs (cache scoping); may return the record its steps fill */
|
|
11
|
+
beforeSeeder?: (name: string, options: {
|
|
12
|
+
fresh: boolean;
|
|
13
|
+
}) => StepRecord | undefined;
|
|
14
|
+
/** Database URL the run writes to; non-local hosts are refused unless allowRemote */
|
|
15
|
+
target?: () => string | undefined;
|
|
16
|
+
/** Called before the context is created */
|
|
12
17
|
onBeforeAll?: () => void | Promise<void>;
|
|
13
|
-
/** Called after all seeders complete */
|
|
18
|
+
/** Called after all seeders complete, also when a seeder or the context factory throws */
|
|
14
19
|
onAfterAll?: () => void | Promise<void>;
|
|
15
20
|
};
|
|
21
|
+
/**
|
|
22
|
+
* Error thrown when a run would write to a database that is not local
|
|
23
|
+
*/
|
|
24
|
+
export declare class SeedTargetError extends Error {
|
|
25
|
+
constructor(label: string);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Describe a database URL without its credentials and say whether every host it names
|
|
29
|
+
* is local: loopback, `*.localhost`, `host.docker.internal`, a socket or `file:` path,
|
|
30
|
+
* or a name without a dot (a compose service). A `host=` parameter overrides the
|
|
31
|
+
* URL's host, as libpq does. Hand-parsed so driver formats `URL` rejects still work
|
|
32
|
+
* (several hosts, `sqlserver://host;key=value`, sockets with credentials).
|
|
33
|
+
*/
|
|
34
|
+
export declare function describeTarget(target: string): {
|
|
35
|
+
label: string;
|
|
36
|
+
local: boolean;
|
|
37
|
+
};
|
|
16
38
|
/**
|
|
17
39
|
* Core seeder runner - executes seeders in dependency order
|
|
18
40
|
*
|
|
@@ -20,6 +42,7 @@ export type InternalSeederConfig<TContext> = {
|
|
|
20
42
|
* @param config - Instance configuration (context factory, lifecycle hooks)
|
|
21
43
|
* @param options - Runner options (verbose output, etc.)
|
|
22
44
|
* @returns Object containing results and success status
|
|
45
|
+
* @throws Dependency errors, `UnknownSeederError` and `SeedTargetError`, before any hook runs
|
|
23
46
|
*/
|
|
24
47
|
export declare function runSeedersCore<TContext>(seeders: readonly SeederAny[], config: InternalSeederConfig<TContext>, options?: RunSeedersOptions): Promise<{
|
|
25
48
|
results: SeederResult[];
|
|
@@ -6,6 +6,10 @@
|
|
|
6
6
|
* - Sending notifications (email, Slack, push)
|
|
7
7
|
* - Creating background jobs
|
|
8
8
|
* - Syncing to external services
|
|
9
|
+
*
|
|
10
|
+
* The flag lives on `globalThis`, so `plantr` and `plantr/state` share it even when
|
|
11
|
+
* they are loaded as separate bundles. It is one flag per process, shared by every
|
|
12
|
+
* seeder instance.
|
|
9
13
|
*/
|
|
10
14
|
/**
|
|
11
15
|
* Check if seeding is currently active
|
|
@@ -13,6 +17,6 @@
|
|
|
13
17
|
export declare function isSeedingActive(): boolean;
|
|
14
18
|
/**
|
|
15
19
|
* Set the seeding state.
|
|
16
|
-
* Called automatically by
|
|
20
|
+
* Called automatically by `runSeeders` around a run.
|
|
17
21
|
*/
|
|
18
22
|
export declare function setSeedingActive(active: boolean): void;
|
package/dist/src/step.d.ts
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
export type StepOptions = {
|
|
2
2
|
/** Enable caching for this step */
|
|
3
3
|
useCache?: boolean;
|
|
4
|
+
/**
|
|
5
|
+
* Any JSON value describing what the step's output depends on (a number you bump,
|
|
6
|
+
* the data the step writes). A cached entry stored with a different version is a
|
|
7
|
+
* miss: the step runs again and its entry is overwritten.
|
|
8
|
+
*/
|
|
9
|
+
version?: unknown;
|
|
4
10
|
};
|
|
5
11
|
export type StepFn = <T>(description: string, fn: () => T | Promise<T>, options?: StepOptions) => Promise<T>;
|
|
6
12
|
/**
|
|
7
13
|
* Cache interface for step caching.
|
|
8
14
|
* Provide get/set functions to enable caching in the step runner.
|
|
15
|
+
* plantr stores an envelope object (`{ __plantr: 1, version?, value }`), so `set`
|
|
16
|
+
* always receives an object and `get` should return it as stored.
|
|
9
17
|
*/
|
|
10
18
|
export type SeederCache = {
|
|
11
19
|
/** Get a cached value by key. Returns undefined if not found. */
|
|
@@ -13,10 +21,22 @@ export type SeederCache = {
|
|
|
13
21
|
/** Set a cached value by key. */
|
|
14
22
|
set: <T>(key: string, value: T) => Promise<void>;
|
|
15
23
|
};
|
|
24
|
+
/** What the steps of the current seeder did, for error reporting */
|
|
25
|
+
export type StepRecord = {
|
|
26
|
+
/** Descriptions of the steps whose output came from the cache */
|
|
27
|
+
cachedSteps: string[];
|
|
28
|
+
/** Description and error of the last step that threw */
|
|
29
|
+
failed?: {
|
|
30
|
+
step: string;
|
|
31
|
+
error: unknown;
|
|
32
|
+
};
|
|
33
|
+
};
|
|
16
34
|
type StepRunnerConfig = {
|
|
17
35
|
cache?: SeederCache;
|
|
18
36
|
/** Seeder name for scoping cache keys */
|
|
19
37
|
seederName?: string;
|
|
38
|
+
/** Print a line per step (default: true) */
|
|
39
|
+
log?: boolean;
|
|
20
40
|
};
|
|
21
41
|
/**
|
|
22
42
|
* Create a step runner for organizing seeder workflow.
|
|
@@ -24,7 +44,12 @@ type StepRunnerConfig = {
|
|
|
24
44
|
*/
|
|
25
45
|
export declare function createStepRunner(config?: StepRunnerConfig): {
|
|
26
46
|
step: StepFn;
|
|
27
|
-
/**
|
|
28
|
-
|
|
47
|
+
/**
|
|
48
|
+
* Start a seeder: scopes cache keys to its name and returns the record its steps fill.
|
|
49
|
+
* With `fresh`, its cached steps ignore stored entries and overwrite them.
|
|
50
|
+
*/
|
|
51
|
+
setSeederName: (name: string, options?: {
|
|
52
|
+
fresh?: boolean;
|
|
53
|
+
}) => StepRecord;
|
|
29
54
|
};
|
|
30
55
|
export {};
|
package/dist/src/types.d.ts
CHANGED
|
@@ -61,6 +61,10 @@ export type SeederResult = {
|
|
|
61
61
|
durationMs?: number;
|
|
62
62
|
output?: unknown;
|
|
63
63
|
error?: Error;
|
|
64
|
+
/** Description of the step that threw, when the seeder failed in a step */
|
|
65
|
+
failedStep?: string;
|
|
66
|
+
/** Descriptions of the steps whose output came from the cache */
|
|
67
|
+
cachedSteps?: string[];
|
|
64
68
|
};
|
|
65
69
|
/** Options for the seeder runner */
|
|
66
70
|
export type RunSeedersOptions = {
|
|
@@ -74,4 +78,20 @@ export type RunSeedersOptions = {
|
|
|
74
78
|
* but independent seeders will still run.
|
|
75
79
|
*/
|
|
76
80
|
continueOnFailure?: boolean;
|
|
81
|
+
/**
|
|
82
|
+
* Run only these seeders and everything they depend on, in dependency order.
|
|
83
|
+
* Throws `UnknownSeederError` for a name that is not registered.
|
|
84
|
+
*/
|
|
85
|
+
only?: readonly string[];
|
|
86
|
+
/**
|
|
87
|
+
* Ignore cached step entries and overwrite them: `true` for every seeder,
|
|
88
|
+
* or the names of the seeders to run fresh. Dependencies of those seeders still
|
|
89
|
+
* replay their cache unless they are named too.
|
|
90
|
+
*/
|
|
91
|
+
fresh?: boolean | readonly string[];
|
|
92
|
+
/**
|
|
93
|
+
* Seed a target that is not local (see `target` on the instance config).
|
|
94
|
+
* Without it, a non-local target throws `SeedTargetError` before anything runs.
|
|
95
|
+
*/
|
|
96
|
+
allowRemote?: boolean;
|
|
77
97
|
};
|
package/dist/state.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime entry point: reads the seeding flag without loading faker or bun:test.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* ```typescript
|
|
6
|
+
* import { isSeedingActive } from 'plantr/state'
|
|
7
|
+
*
|
|
8
|
+
* if (isSeedingActive()) return // skip jobs and mail while seeding
|
|
9
|
+
* ```
|
|
10
|
+
*/
|
|
11
|
+
export { isSeedingActive } from './src/seeding-state';
|
package/dist/state.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// src/seeding-state.ts
|
|
2
|
+
var key = Symbol.for("plantr.seedingActive");
|
|
3
|
+
var state = globalThis;
|
|
4
|
+
function isSeedingActive() {
|
|
5
|
+
return state[key] === true;
|
|
6
|
+
}
|
|
7
|
+
function setSeedingActive(active) {
|
|
8
|
+
state[key] = active;
|
|
9
|
+
}
|
|
10
|
+
export {
|
|
11
|
+
isSeedingActive
|
|
12
|
+
};
|
package/index.ts
CHANGED
|
@@ -48,17 +48,20 @@ export { createSeederInstance } from './src/create-seeder-instance'
|
|
|
48
48
|
export { createDefineSeeder } from './src/define-seeder'
|
|
49
49
|
export {
|
|
50
50
|
CircularDependencyError,
|
|
51
|
+
DuplicateSeederError,
|
|
51
52
|
MissingDependencyError,
|
|
52
53
|
resolveDependencyOrder,
|
|
54
|
+
UnknownSeederError,
|
|
53
55
|
} from './src/dependency-resolver'
|
|
54
56
|
export { colorize, formatDuration } from './src/formatting'
|
|
55
|
-
export { runSeedersCore } from './src/run-seeders'
|
|
57
|
+
export { describeTarget, runSeedersCore, SeedTargetError } from './src/run-seeders'
|
|
56
58
|
|
|
57
|
-
// Seeding state
|
|
59
|
+
// Seeding state. Runtime code (job queues, mailers) should import it from 'plantr/state',
|
|
60
|
+
// which does not load faker or bun:test.
|
|
58
61
|
export { isSeedingActive } from './src/seeding-state'
|
|
59
62
|
|
|
60
63
|
// Step types and cache
|
|
61
|
-
export type { SeederCache, StepFn, StepOptions } from './src/step'
|
|
64
|
+
export type { SeederCache, StepFn, StepOptions, StepRecord } from './src/step'
|
|
62
65
|
export { createStepRunner } from './src/step'
|
|
63
66
|
|
|
64
67
|
// Types
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "plantr",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "A generic seeder library with built-in faker, step, and expect support for type-safe database seeding",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -27,10 +27,10 @@
|
|
|
27
27
|
"bun": ">=1.0.0"
|
|
28
28
|
},
|
|
29
29
|
"files": [
|
|
30
|
-
"
|
|
30
|
+
"index.ts",
|
|
31
|
+
"state.ts",
|
|
31
32
|
"src/*.ts",
|
|
32
33
|
"dist",
|
|
33
|
-
"!*.test.ts",
|
|
34
34
|
"!src/*.test.ts"
|
|
35
35
|
],
|
|
36
36
|
"exports": {
|
|
@@ -39,20 +39,24 @@
|
|
|
39
39
|
"bun": "./index.ts",
|
|
40
40
|
"import": "./dist/index.js",
|
|
41
41
|
"default": "./dist/index.js"
|
|
42
|
+
},
|
|
43
|
+
"./state": {
|
|
44
|
+
"types": "./dist/state.d.ts",
|
|
45
|
+
"bun": "./state.ts",
|
|
46
|
+
"import": "./dist/state.js",
|
|
47
|
+
"default": "./dist/state.js"
|
|
42
48
|
}
|
|
43
49
|
},
|
|
44
50
|
"scripts": {
|
|
45
51
|
"build": "bun run build:js && bun run build:types",
|
|
46
|
-
"build:js": "bun build ./index.ts --outdir ./dist --target node --packages external",
|
|
52
|
+
"build:js": "bun build ./index.ts ./state.ts --outdir ./dist --target node --packages external",
|
|
47
53
|
"build:types": "tsc -p tsconfig.build.json",
|
|
48
54
|
"test": "bun test",
|
|
49
55
|
"prepublishOnly": "bun run build",
|
|
50
|
-
"publish:patch": "npm version patch && npm publish",
|
|
51
|
-
"publish:minor": "npm version minor && npm publish",
|
|
52
|
-
"publish:major": "npm version major && npm publish",
|
|
53
56
|
"lint": "bun run typecheck && biome check",
|
|
54
|
-
"lint:write": "bun run typecheck && biome check --
|
|
55
|
-
"typecheck": "tsgo --incremental"
|
|
57
|
+
"lint:write": "bun run typecheck && biome check --write",
|
|
58
|
+
"typecheck": "tsgo --incremental",
|
|
59
|
+
"verify:package": "node scripts/verify-package.mjs"
|
|
56
60
|
},
|
|
57
61
|
"dependencies": {
|
|
58
62
|
"@faker-js/faker": "^9.0.0"
|
|
@@ -62,5 +66,10 @@
|
|
|
62
66
|
"@biomejs/biome": "2.3.4",
|
|
63
67
|
"@typescript/native-preview": "7.0.0-dev.20260127.1",
|
|
64
68
|
"typescript": "^5.7.0"
|
|
65
|
-
}
|
|
69
|
+
},
|
|
70
|
+
"homepage": "https://github.com/HansKristoffer/plantr#readme",
|
|
71
|
+
"bugs": {
|
|
72
|
+
"url": "https://github.com/HansKristoffer/plantr/issues"
|
|
73
|
+
},
|
|
74
|
+
"packageManager": "bun@1.4.2"
|
|
66
75
|
}
|
package/readme.md
CHANGED
|
@@ -7,8 +7,10 @@ A Bun-first database seeder library with built-in faker, step workflow, and type
|
|
|
7
7
|
- **Built-in utilities** - `faker`, `step`, and `expect` available in every seeder
|
|
8
8
|
- **Type-safe dependencies** - Seeder outputs are fully typed when used as dependencies
|
|
9
9
|
- **Automatic ordering** - Seeders run in correct order based on dependencies
|
|
10
|
+
- **Run a subset** - Run named seeders plus what they depend on (`--only`, `only`)
|
|
10
11
|
- **Step workflow** - Organize seeders into steps with progress logging
|
|
11
|
-
- **Step caching** -
|
|
12
|
+
- **Step caching** - Skip steps that already ran, with versions and a `--fresh` override
|
|
13
|
+
- **Target guard** - Refuse to seed a database that is not local unless asked to
|
|
12
14
|
- **Lifecycle hooks** - `onBeforeAll` / `onAfterAll` for setup and teardown
|
|
13
15
|
- **Continue on failure** - Keep seeding independent data when one seeder fails
|
|
14
16
|
- **Dry run mode** - Preview execution order without running
|
|
@@ -36,9 +38,10 @@ type MyContext = BaseSeederContext & {
|
|
|
36
38
|
|
|
37
39
|
export const { defineSeeder, runSeeders, runSeedersCli } = createSeederInstance<MyContext>({
|
|
38
40
|
context: (base) => ({
|
|
39
|
-
...base,
|
|
41
|
+
...base, // faker, step, expect
|
|
40
42
|
prisma,
|
|
41
43
|
}),
|
|
44
|
+
target: () => process.env.DATABASE_URL,
|
|
42
45
|
onBeforeAll: async () => {
|
|
43
46
|
await prisma.$connect()
|
|
44
47
|
},
|
|
@@ -126,28 +129,45 @@ bun run src/seed.ts
|
|
|
126
129
|
## CLI Options
|
|
127
130
|
|
|
128
131
|
```bash
|
|
129
|
-
bun run src/seed.ts
|
|
130
|
-
bun run src/seed.ts
|
|
132
|
+
bun run src/seed.ts # Run every seeder
|
|
133
|
+
bun run src/seed.ts postSeeder # Run postSeeder and the seeders it depends on
|
|
134
|
+
bun run src/seed.ts --only a,b # Same as naming them
|
|
135
|
+
bun run src/seed.ts postSeeder --fresh # Ignore and overwrite postSeeder's cached steps
|
|
136
|
+
bun run src/seed.ts --fresh # Ignore and overwrite every cached step
|
|
137
|
+
bun run src/seed.ts --continue-on-failure # Keep running seeders that do not depend on a failed one
|
|
138
|
+
bun run src/seed.ts --allow-remote # Seed a target that is not local (see Target guard)
|
|
139
|
+
bun run src/seed.ts --dry-run postSeeder # Show execution order without running
|
|
140
|
+
bun run src/seed.ts --help # Show help
|
|
131
141
|
```
|
|
132
142
|
|
|
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.
|
|
144
|
+
|
|
133
145
|
## API
|
|
134
146
|
|
|
135
147
|
### `createSeederInstance(config)`
|
|
136
148
|
|
|
137
149
|
```typescript
|
|
138
150
|
createSeederInstance({
|
|
139
|
-
// Required: factory that receives base context and returns your context
|
|
151
|
+
// Required: factory that receives base context and returns your context.
|
|
152
|
+
// Called once per run, after onBeforeAll.
|
|
140
153
|
context: (base) => ({ ...base, prisma }),
|
|
141
|
-
|
|
142
|
-
// Optional: cache for step caching
|
|
154
|
+
|
|
155
|
+
// Optional: cache for step caching (see Step Caching)
|
|
143
156
|
cache: {
|
|
144
|
-
get: async (key) => { /* return
|
|
145
|
-
set: async (key, value) => { /* store value */ },
|
|
157
|
+
get: async (key) => { /* return the stored value, or undefined */ },
|
|
158
|
+
set: async (key, value) => { /* store value, overwriting */ },
|
|
146
159
|
},
|
|
147
|
-
|
|
160
|
+
|
|
161
|
+
// Optional: the database URL the run writes to (see Target guard)
|
|
162
|
+
target: () => process.env.DATABASE_URL,
|
|
163
|
+
|
|
164
|
+
// Optional: seed faker per seeder (fakerSeed + hash of the seeder name),
|
|
165
|
+
// so every run generates the same data
|
|
166
|
+
fakerSeed: 1,
|
|
167
|
+
|
|
148
168
|
// Optional: lifecycle hooks
|
|
149
|
-
onBeforeAll: async () => { /* setup */ },
|
|
150
|
-
onAfterAll: async () => { /* teardown */ },
|
|
169
|
+
onBeforeAll: async () => { /* setup; throw to refuse the run */ },
|
|
170
|
+
onAfterAll: async () => { /* teardown; also runs when a seeder or the context factory throws */ },
|
|
151
171
|
})
|
|
152
172
|
```
|
|
153
173
|
|
|
@@ -171,13 +191,20 @@ defineSeeder({
|
|
|
171
191
|
### `runSeeders(seeders, options?)`
|
|
172
192
|
|
|
173
193
|
```typescript
|
|
174
|
-
await runSeeders(seeders, {
|
|
175
|
-
printResults: true,
|
|
176
|
-
verbose: true,
|
|
177
|
-
continueOnFailure: false // Continue after failures (default: false)
|
|
194
|
+
const { results, success } = await runSeeders(seeders, {
|
|
195
|
+
printResults: true, // Print results table and errors (default: true)
|
|
196
|
+
verbose: true, // Print progress and step lines (default: true)
|
|
197
|
+
continueOnFailure: false, // Continue after failures (default: false)
|
|
198
|
+
only: ['postSeeder'], // Run these and what they depend on (default: all)
|
|
199
|
+
fresh: ['postSeeder'], // Ignore cached steps: true for all, or seeder names
|
|
200
|
+
allowRemote: false, // Seed a non-local target (default: false)
|
|
178
201
|
})
|
|
179
202
|
```
|
|
180
203
|
|
|
204
|
+
`success` is false when a seeder failed; each failed result carries `error`, `failedStep` (the step that threw) and `cachedSteps` (steps that replayed from the cache before it).
|
|
205
|
+
|
|
206
|
+
`runSeeders` **throws**, before any hook or seeder runs, when the input is invalid: `DuplicateSeederError`, `MissingDependencyError`, `CircularDependencyError`, `UnknownSeederError` (a name in `only` or `fresh`), or `SeedTargetError`.
|
|
207
|
+
|
|
181
208
|
### Step Function
|
|
182
209
|
|
|
183
210
|
```typescript
|
|
@@ -191,15 +218,52 @@ run: async ({ step }) => {
|
|
|
191
218
|
const cached = await step('Expensive operation', async () => {
|
|
192
219
|
return computeExpensiveValue()
|
|
193
220
|
}, { useCache: true })
|
|
221
|
+
|
|
222
|
+
// Versioned cached step: a different version reruns it and overwrites the entry
|
|
223
|
+
await step('Apply widget settings', () => applySettings(SETTINGS), {
|
|
224
|
+
useCache: true,
|
|
225
|
+
version: SETTINGS, // any JSON value, e.g. 2 or the data the step writes
|
|
226
|
+
})
|
|
194
227
|
}
|
|
195
228
|
```
|
|
196
229
|
|
|
230
|
+
## Step Caching
|
|
231
|
+
|
|
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.
|
|
233
|
+
|
|
234
|
+
- **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 description within its seeder.** Two cached steps with the same key in one run throw.
|
|
236
|
+
- **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
|
+
- **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. Values written bare by plantr 1.x are still read as hits (when the step has no `version`).
|
|
239
|
+
|
|
240
|
+
A Prisma store:
|
|
241
|
+
|
|
242
|
+
```typescript
|
|
243
|
+
cache: {
|
|
244
|
+
get: async (key) => {
|
|
245
|
+
const row = await prisma.seedCache.findUnique({ where: { key } })
|
|
246
|
+
return row?.output as never
|
|
247
|
+
},
|
|
248
|
+
set: async (key, value) => {
|
|
249
|
+
const output = value as Prisma.InputJsonValue
|
|
250
|
+
await prisma.seedCache.upsert({ where: { key }, create: { key, output }, update: { output } })
|
|
251
|
+
},
|
|
252
|
+
}
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
## Target guard
|
|
256
|
+
|
|
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.
|
|
258
|
+
|
|
259
|
+
Without `target` there is no check. For other rules (an environment variable, a list of allowed hosts), throw from `onBeforeAll`.
|
|
260
|
+
|
|
197
261
|
## Seeding State
|
|
198
262
|
|
|
199
|
-
Check if seeding is active to skip side effects:
|
|
263
|
+
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
264
|
|
|
201
265
|
```typescript
|
|
202
|
-
import { isSeedingActive } from '
|
|
266
|
+
import { isSeedingActive } from 'plantr/state'
|
|
203
267
|
|
|
204
268
|
// In your event handlers, webhooks, etc.
|
|
205
269
|
if (isSeedingActive()) {
|
|
@@ -208,23 +272,38 @@ if (isSeedingActive()) {
|
|
|
208
272
|
}
|
|
209
273
|
```
|
|
210
274
|
|
|
275
|
+
The flag is set for the duration of `runSeeders` and cleared afterwards, also when a hook throws. It is one flag per process, shared by every seeder instance, so it only reports seeding that runs in the same process.
|
|
276
|
+
|
|
211
277
|
## Error Handling
|
|
212
278
|
|
|
213
279
|
```typescript
|
|
214
|
-
import {
|
|
280
|
+
import {
|
|
281
|
+
CircularDependencyError,
|
|
282
|
+
DuplicateSeederError,
|
|
283
|
+
MissingDependencyError,
|
|
284
|
+
SeedTargetError,
|
|
285
|
+
UnknownSeederError,
|
|
286
|
+
} from 'plantr'
|
|
215
287
|
|
|
216
288
|
try {
|
|
217
|
-
await runSeeders(seeders)
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
console.error(
|
|
221
|
-
}
|
|
222
|
-
if (error instanceof MissingDependencyError) {
|
|
223
|
-
console.error('Missing dependency')
|
|
289
|
+
const { success, results } = await runSeeders(seeders)
|
|
290
|
+
if (!success) {
|
|
291
|
+
const failed = results.find((r) => r.status === 'failed')
|
|
292
|
+
console.error(`${failed?.name} failed in step ${failed?.failedStep}`, failed?.error)
|
|
224
293
|
}
|
|
294
|
+
} catch (error) {
|
|
295
|
+
// The registry or options are invalid, or the target was refused; nothing ran
|
|
296
|
+
if (error instanceof CircularDependencyError) console.error('Circular dependency')
|
|
297
|
+
if (error instanceof SeedTargetError) console.error(error.message)
|
|
225
298
|
}
|
|
226
299
|
```
|
|
227
300
|
|
|
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.
|
|
302
|
+
|
|
228
303
|
## License
|
|
229
304
|
|
|
230
305
|
MIT
|
|
306
|
+
|
|
307
|
+
## Releasing
|
|
308
|
+
|
|
309
|
+
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).
|