plantr 1.0.1
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/cli.d.ts +17 -0
- package/dist/cli.js +59 -0
- package/dist/index-a1s5r901.js +4 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.js +517 -0
- package/dist/src/create-seeder-instance.d.ts +171 -0
- package/dist/src/define-seeder.d.ts +28 -0
- package/dist/src/dependency-resolver.d.ts +23 -0
- package/dist/src/formatting.d.ts +40 -0
- package/dist/src/run-seeders.d.ts +27 -0
- package/dist/src/seeding-state.d.ts +18 -0
- package/dist/src/step.d.ts +30 -0
- package/dist/src/types.d.ts +77 -0
- package/index.ts +76 -0
- package/package.json +66 -0
- package/readme.md +230 -0
- package/src/create-seeder-instance.ts +315 -0
- package/src/define-seeder.ts +46 -0
- package/src/dependency-resolver.ts +152 -0
- package/src/formatting.ts +202 -0
- package/src/run-seeders.ts +182 -0
- package/src/seeding-state.ts +26 -0
- package/src/step.ts +99 -0
- package/src/types.ts +99 -0
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* Seeder CLI
|
|
4
|
+
*
|
|
5
|
+
* This is a thin CLI wrapper. Consumers should create their own entry point
|
|
6
|
+
* that imports their seeders and calls runSeeders.
|
|
7
|
+
*
|
|
8
|
+
* Usage:
|
|
9
|
+
* bun run ./path/to/seed-config.ts [options]
|
|
10
|
+
*
|
|
11
|
+
* The config file should export:
|
|
12
|
+
* - default: { seeders, context, cache? }
|
|
13
|
+
*
|
|
14
|
+
* Or simply use the config file as the entry point:
|
|
15
|
+
* bun run apps/backend/src/registries/seed.ts
|
|
16
|
+
*/
|
|
17
|
+
export {};
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import {
|
|
3
|
+
__require
|
|
4
|
+
} from "./index-a1s5r901.js";
|
|
5
|
+
|
|
6
|
+
// cli.ts
|
|
7
|
+
var args = process.argv.slice(2);
|
|
8
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
9
|
+
console.log(`
|
|
10
|
+
plantr CLI
|
|
11
|
+
|
|
12
|
+
Usage:
|
|
13
|
+
bunx plantr --config <path> Run seeders from a config file
|
|
14
|
+
bunx plantr --help Show this help message
|
|
15
|
+
|
|
16
|
+
Config file should export:
|
|
17
|
+
export default {
|
|
18
|
+
seeders: [...],
|
|
19
|
+
context: (base) => ({ ...base, prisma }),
|
|
20
|
+
cache?: {
|
|
21
|
+
get: async (key) => { ... },
|
|
22
|
+
set: async (key, value) => { ... },
|
|
23
|
+
},
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
Alternatively, create your own entry point:
|
|
27
|
+
// seed.ts
|
|
28
|
+
import { createSeederInstance } from 'plantr'
|
|
29
|
+
|
|
30
|
+
const { runSeeders } = createSeederInstance({ ... })
|
|
31
|
+
|
|
32
|
+
if (import.meta.main) {
|
|
33
|
+
await runSeeders([...seeders])
|
|
34
|
+
}
|
|
35
|
+
`);
|
|
36
|
+
process.exit(0);
|
|
37
|
+
}
|
|
38
|
+
var configIndex = args.indexOf("--config");
|
|
39
|
+
if (configIndex === -1 || !args[configIndex + 1]) {
|
|
40
|
+
console.error("Error: --config <path> is required");
|
|
41
|
+
console.error("Run with --help for usage information");
|
|
42
|
+
process.exit(1);
|
|
43
|
+
}
|
|
44
|
+
var configPath = args[configIndex + 1];
|
|
45
|
+
try {
|
|
46
|
+
const config = await import(configPath);
|
|
47
|
+
const { seeders, context, cache } = config.default || config;
|
|
48
|
+
if (!seeders || !context) {
|
|
49
|
+
console.error("Error: Config must export { seeders, context }");
|
|
50
|
+
process.exit(1);
|
|
51
|
+
}
|
|
52
|
+
const { createSeederInstance } = await import("./index.js");
|
|
53
|
+
const { runSeeders } = createSeederInstance({ context, cache });
|
|
54
|
+
const { success } = await runSeeders(seeders);
|
|
55
|
+
process.exit(success ? 0 : 1);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
console.error("Error loading config:", error);
|
|
58
|
+
process.exit(1);
|
|
59
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* plantr - Generic seeder library with built-in faker, step, and expect
|
|
3
|
+
*
|
|
4
|
+
* A Bun-first library for creating type-safe database seeders with dependency resolution.
|
|
5
|
+
* The library provides a base context with faker, step, and expect. Consumers
|
|
6
|
+
* extend this with their own context (e.g. prisma, custom helpers).
|
|
7
|
+
*
|
|
8
|
+
* Note: This library requires Bun as it uses bun:test for the expect function.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* import { createSeederInstance, type BaseSeederContext } from 'plantr'
|
|
13
|
+
*
|
|
14
|
+
* type MyContext = BaseSeederContext & { prisma: typeof prisma }
|
|
15
|
+
*
|
|
16
|
+
* const { defineSeeder, runSeeders } = createSeederInstance<MyContext>({
|
|
17
|
+
* context: (base) => ({
|
|
18
|
+
* ...base,
|
|
19
|
+
* prisma,
|
|
20
|
+
* }),
|
|
21
|
+
* })
|
|
22
|
+
*
|
|
23
|
+
* const userSeeder = defineSeeder({
|
|
24
|
+
* name: 'userSeeder',
|
|
25
|
+
* run: async ({ faker, step, expect, prisma }) => {
|
|
26
|
+
* // faker, step, expect are always available from base context
|
|
27
|
+
* const user = await step('Create user', async () => {
|
|
28
|
+
* return prisma.user.create({ data: { name: faker.person.fullName() } })
|
|
29
|
+
* })
|
|
30
|
+
* expect(user).toBeDefined()
|
|
31
|
+
* return { userId: user.id }
|
|
32
|
+
* }
|
|
33
|
+
* })
|
|
34
|
+
*
|
|
35
|
+
* await runSeeders([userSeeder])
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export { expect } from 'bun:test';
|
|
39
|
+
export { faker } from '@faker-js/faker';
|
|
40
|
+
export type { SeederInstance, SeederInstanceConfig } from './src/create-seeder-instance';
|
|
41
|
+
export { createSeederInstance } from './src/create-seeder-instance';
|
|
42
|
+
export { createDefineSeeder } from './src/define-seeder';
|
|
43
|
+
export { CircularDependencyError, MissingDependencyError, resolveDependencyOrder, } from './src/dependency-resolver';
|
|
44
|
+
export { colorize, formatDuration } from './src/formatting';
|
|
45
|
+
export { runSeedersCore } from './src/run-seeders';
|
|
46
|
+
export { isSeedingActive } from './src/seeding-state';
|
|
47
|
+
export type { SeederCache, StepFn, StepOptions } from './src/step';
|
|
48
|
+
export { createStepRunner } from './src/step';
|
|
49
|
+
export type { BaseSeederContext, DepsFromSeeders, RunSeedersOptions, Seeder, SeederAny, SeederConfig, SeederName, SeederOutput, SeederResult, SeederStatus, } from './src/types';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
// index.ts
|
|
2
|
+
import { expect as expect2 } from "bun:test";
|
|
3
|
+
import { faker as faker2 } from "@faker-js/faker";
|
|
4
|
+
|
|
5
|
+
// src/create-seeder-instance.ts
|
|
6
|
+
import { expect } from "bun:test";
|
|
7
|
+
import { faker } from "@faker-js/faker";
|
|
8
|
+
|
|
9
|
+
// src/define-seeder.ts
|
|
10
|
+
function createDefineSeeder() {
|
|
11
|
+
return function defineSeeder(config) {
|
|
12
|
+
const dependsOnNames = (config.dependsOn ?? []).map((seeder) => seeder.name);
|
|
13
|
+
return {
|
|
14
|
+
name: config.name,
|
|
15
|
+
description: config.description,
|
|
16
|
+
dependsOn: dependsOnNames,
|
|
17
|
+
run: config.run
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// src/dependency-resolver.ts
|
|
23
|
+
class CircularDependencyError extends Error {
|
|
24
|
+
constructor(cycle) {
|
|
25
|
+
super(`Circular dependency detected in seeders: ${cycle.join(" -> ")} -> ${cycle[0]}`);
|
|
26
|
+
this.name = "CircularDependencyError";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
class MissingDependencyError extends Error {
|
|
31
|
+
constructor(seeder, missingDep) {
|
|
32
|
+
super(`Seeder "${seeder}" depends on "${missingDep}" which does not exist`);
|
|
33
|
+
this.name = "MissingDependencyError";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function resolveDependencyOrder(seeders) {
|
|
37
|
+
const seederMap = new Map;
|
|
38
|
+
for (const seeder of seeders) {
|
|
39
|
+
seederMap.set(seeder.name, seeder);
|
|
40
|
+
}
|
|
41
|
+
for (const seeder of seeders) {
|
|
42
|
+
for (const dep of seeder.dependsOn) {
|
|
43
|
+
if (!seederMap.has(dep)) {
|
|
44
|
+
throw new MissingDependencyError(seeder.name, dep);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const inDegree = new Map;
|
|
49
|
+
const dependents = new Map;
|
|
50
|
+
for (const seeder of seeders) {
|
|
51
|
+
inDegree.set(seeder.name, 0);
|
|
52
|
+
dependents.set(seeder.name, []);
|
|
53
|
+
}
|
|
54
|
+
for (const seeder of seeders) {
|
|
55
|
+
inDegree.set(seeder.name, seeder.dependsOn.length);
|
|
56
|
+
for (const dep of seeder.dependsOn) {
|
|
57
|
+
const deps = dependents.get(dep);
|
|
58
|
+
if (deps) {
|
|
59
|
+
deps.push(seeder.name);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const queue = [];
|
|
64
|
+
for (const [name, degree] of inDegree) {
|
|
65
|
+
if (degree === 0) {
|
|
66
|
+
queue.push(name);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const result = [];
|
|
70
|
+
while (queue.length > 0) {
|
|
71
|
+
const current = queue.shift();
|
|
72
|
+
result.push(current);
|
|
73
|
+
const deps = dependents.get(current) ?? [];
|
|
74
|
+
for (const dependent of deps) {
|
|
75
|
+
const newDegree = (inDegree.get(dependent) ?? 0) - 1;
|
|
76
|
+
inDegree.set(dependent, newDegree);
|
|
77
|
+
if (newDegree === 0) {
|
|
78
|
+
queue.push(dependent);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (result.length !== seeders.length) {
|
|
83
|
+
const remaining = seeders.filter((s) => !result.includes(s.name));
|
|
84
|
+
const cycle = findCycle(remaining, seederMap);
|
|
85
|
+
throw new CircularDependencyError(cycle);
|
|
86
|
+
}
|
|
87
|
+
return result;
|
|
88
|
+
}
|
|
89
|
+
function findCycle(remaining, seederMap) {
|
|
90
|
+
const visited = new Set;
|
|
91
|
+
const path = [];
|
|
92
|
+
let cycleStart = -1;
|
|
93
|
+
function dfs(name) {
|
|
94
|
+
const existingIndex = path.indexOf(name);
|
|
95
|
+
if (existingIndex !== -1) {
|
|
96
|
+
cycleStart = existingIndex;
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
if (visited.has(name)) {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
visited.add(name);
|
|
103
|
+
path.push(name);
|
|
104
|
+
const seeder = seederMap.get(name);
|
|
105
|
+
if (seeder) {
|
|
106
|
+
for (const dep of seeder.dependsOn) {
|
|
107
|
+
if (dfs(dep)) {
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
path.pop();
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
for (const seeder of remaining) {
|
|
116
|
+
path.length = 0;
|
|
117
|
+
cycleStart = -1;
|
|
118
|
+
if (dfs(seeder.name)) {
|
|
119
|
+
return cycleStart >= 0 ? path.slice(cycleStart) : path;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return remaining.map((s) => s.name);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// src/formatting.ts
|
|
126
|
+
var colors = {
|
|
127
|
+
reset: "\x1B[0m",
|
|
128
|
+
bold: "\x1B[1m",
|
|
129
|
+
dim: "\x1B[2m",
|
|
130
|
+
red: "\x1B[31m",
|
|
131
|
+
green: "\x1B[32m",
|
|
132
|
+
yellow: "\x1B[33m",
|
|
133
|
+
cyan: "\x1B[36m",
|
|
134
|
+
white: "\x1B[37m",
|
|
135
|
+
gray: "\x1B[90m"
|
|
136
|
+
};
|
|
137
|
+
function colorize(text, color, style) {
|
|
138
|
+
let result = "";
|
|
139
|
+
if (style === "bold")
|
|
140
|
+
result += colors.bold;
|
|
141
|
+
if (style === "dim")
|
|
142
|
+
result += colors.dim;
|
|
143
|
+
result += colors[color] + text + colors.reset;
|
|
144
|
+
return result;
|
|
145
|
+
}
|
|
146
|
+
function formatDuration(ms) {
|
|
147
|
+
if (ms < 1000)
|
|
148
|
+
return `${ms}ms`;
|
|
149
|
+
if (ms < 60000)
|
|
150
|
+
return `${(ms / 1000).toFixed(1)}s`;
|
|
151
|
+
return `${(ms / 60000).toFixed(1)}m`;
|
|
152
|
+
}
|
|
153
|
+
function printResultsTable(results) {
|
|
154
|
+
if (results.length === 0) {
|
|
155
|
+
console.log("No seeders registered");
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
const nameHeader = "Seeder";
|
|
159
|
+
const statusHeader = "Status";
|
|
160
|
+
const durationHeader = "Duration";
|
|
161
|
+
const maxNameLen = Math.max(nameHeader.length, ...results.map((r) => r.name.length));
|
|
162
|
+
const maxStatusLen = Math.max(statusHeader.length, 10);
|
|
163
|
+
const maxDurationLen = Math.max(durationHeader.length, ...results.map((r) => formatDuration(r.durationMs ?? 0).length));
|
|
164
|
+
const topBorder = `┌${"─".repeat(maxNameLen + 2)}┬${"─".repeat(maxStatusLen + 2)}┬${"─".repeat(maxDurationLen + 2)}┐`;
|
|
165
|
+
const divider = `├${"─".repeat(maxNameLen + 2)}┼${"─".repeat(maxStatusLen + 2)}┼${"─".repeat(maxDurationLen + 2)}┤`;
|
|
166
|
+
const bottomBorder = `└${"─".repeat(maxNameLen + 2)}┴${"─".repeat(maxStatusLen + 2)}┴${"─".repeat(maxDurationLen + 2)}┘`;
|
|
167
|
+
console.log("");
|
|
168
|
+
console.log(topBorder);
|
|
169
|
+
console.log(`│ ${colorize(nameHeader.padEnd(maxNameLen), "white", "bold")} │ ${colorize(statusHeader.padEnd(maxStatusLen), "white", "bold")} │ ${colorize(durationHeader.padEnd(maxDurationLen), "white", "bold")} │`);
|
|
170
|
+
console.log(divider);
|
|
171
|
+
for (const result of results) {
|
|
172
|
+
let statusDisplay;
|
|
173
|
+
let statusColor;
|
|
174
|
+
switch (result.status) {
|
|
175
|
+
case "completed":
|
|
176
|
+
statusDisplay = "✓ Done";
|
|
177
|
+
statusColor = "green";
|
|
178
|
+
break;
|
|
179
|
+
case "failed":
|
|
180
|
+
statusDisplay = "✗ Failed";
|
|
181
|
+
statusColor = "red";
|
|
182
|
+
break;
|
|
183
|
+
case "skipped":
|
|
184
|
+
statusDisplay = "⊘ Skipped";
|
|
185
|
+
statusColor = "yellow";
|
|
186
|
+
break;
|
|
187
|
+
case "running":
|
|
188
|
+
statusDisplay = "⟳ Running";
|
|
189
|
+
statusColor = "yellow";
|
|
190
|
+
break;
|
|
191
|
+
default:
|
|
192
|
+
statusDisplay = "○ Pending";
|
|
193
|
+
statusColor = "gray";
|
|
194
|
+
}
|
|
195
|
+
const duration = result.durationMs !== undefined ? formatDuration(result.durationMs) : "-";
|
|
196
|
+
console.log(`│ ${result.name.padEnd(maxNameLen)} │ ${colorize(statusDisplay.padEnd(maxStatusLen), statusColor)} │ ${colorize(duration.padEnd(maxDurationLen), "dim")} │`);
|
|
197
|
+
}
|
|
198
|
+
console.log(bottomBorder);
|
|
199
|
+
console.log("");
|
|
200
|
+
}
|
|
201
|
+
function printErrors(results) {
|
|
202
|
+
const failed = results.filter((r) => r.status === "failed");
|
|
203
|
+
for (const result of failed) {
|
|
204
|
+
console.log(colorize(`❌ Seeder "${result.name}" failed:`, "red"));
|
|
205
|
+
if (result.error) {
|
|
206
|
+
console.log(` ${colorize(result.error.message, "dim")}`);
|
|
207
|
+
if (result.error.stack) {
|
|
208
|
+
const stackLines = result.error.stack.split(`
|
|
209
|
+
`).slice(1, 4);
|
|
210
|
+
for (const line of stackLines) {
|
|
211
|
+
console.log(` ${colorize(line.trim(), "gray")}`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
console.log("");
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
function printSeederHeader(name, index, total, description) {
|
|
219
|
+
const seederIndex = `[${index + 1}/${total}]`;
|
|
220
|
+
const headerLine = `━━━ ${seederIndex} ${name} ${"━".repeat(Math.max(0, 50 - name.length - seederIndex.length))}`;
|
|
221
|
+
console.log(colorize(headerLine, "cyan", "bold"));
|
|
222
|
+
if (description) {
|
|
223
|
+
console.log(colorize(` ${description}`, "dim"));
|
|
224
|
+
}
|
|
225
|
+
console.log("");
|
|
226
|
+
}
|
|
227
|
+
function printSeederComplete(durationMs, success) {
|
|
228
|
+
console.log("");
|
|
229
|
+
if (success) {
|
|
230
|
+
console.log(colorize(` ✓ Completed in ${formatDuration(durationMs)}`, "green"));
|
|
231
|
+
} else {
|
|
232
|
+
console.log(colorize(` ✗ Failed after ${formatDuration(durationMs)}`, "red"));
|
|
233
|
+
}
|
|
234
|
+
console.log("");
|
|
235
|
+
}
|
|
236
|
+
function printStartBanner(label) {
|
|
237
|
+
const labelText = label ? ` ${colorize(`(${label})`, "dim")}` : "";
|
|
238
|
+
console.log(`
|
|
239
|
+
${colorize("\uD83C\uDF31 Running Seeders", "cyan", "bold")}${labelText}
|
|
240
|
+
`);
|
|
241
|
+
}
|
|
242
|
+
function printSeederSkipped(failedDeps) {
|
|
243
|
+
console.log("");
|
|
244
|
+
console.log(colorize(` ⊘ Skipped (depends on failed: ${failedDeps.join(", ")})`, "yellow"));
|
|
245
|
+
console.log("");
|
|
246
|
+
}
|
|
247
|
+
function printSummary(results) {
|
|
248
|
+
const completed = results.filter((r) => r.status === "completed").length;
|
|
249
|
+
const failed = results.filter((r) => r.status === "failed").length;
|
|
250
|
+
const skipped = results.filter((r) => r.status === "skipped").length;
|
|
251
|
+
const pending = results.filter((r) => r.status === "pending").length;
|
|
252
|
+
if (failed > 0 || skipped > 0) {
|
|
253
|
+
const parts = [`${completed} completed`];
|
|
254
|
+
if (failed > 0)
|
|
255
|
+
parts.push(`${failed} failed`);
|
|
256
|
+
if (skipped > 0)
|
|
257
|
+
parts.push(`${skipped} skipped`);
|
|
258
|
+
if (pending > 0)
|
|
259
|
+
parts.push(`${pending} pending`);
|
|
260
|
+
console.log(colorize(`Seeding failed: ${parts.join(", ")}`, "red"));
|
|
261
|
+
} else {
|
|
262
|
+
console.log(`${colorize("✓ Seeding complete:", "green")} ${completed} seeders executed successfully
|
|
263
|
+
`);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// src/run-seeders.ts
|
|
268
|
+
async function runSeedersCore(seeders, config, options = {}) {
|
|
269
|
+
const { printResults = true, verbose = true, continueOnFailure = false } = options;
|
|
270
|
+
if (config.onBeforeAll) {
|
|
271
|
+
await config.onBeforeAll();
|
|
272
|
+
}
|
|
273
|
+
if (verbose) {
|
|
274
|
+
printStartBanner();
|
|
275
|
+
}
|
|
276
|
+
let orderedNames;
|
|
277
|
+
try {
|
|
278
|
+
orderedNames = resolveDependencyOrder(seeders);
|
|
279
|
+
} catch (error) {
|
|
280
|
+
console.error("Failed to resolve seeder dependencies:");
|
|
281
|
+
console.error(` ${error instanceof Error ? error.message : String(error)}`);
|
|
282
|
+
if (config.onAfterAll) {
|
|
283
|
+
await config.onAfterAll();
|
|
284
|
+
}
|
|
285
|
+
return { results: [], success: false };
|
|
286
|
+
}
|
|
287
|
+
const seederMap = new Map;
|
|
288
|
+
for (const seeder of seeders) {
|
|
289
|
+
seederMap.set(seeder.name, seeder);
|
|
290
|
+
}
|
|
291
|
+
const results = orderedNames.map((name) => ({
|
|
292
|
+
name,
|
|
293
|
+
status: "pending"
|
|
294
|
+
}));
|
|
295
|
+
const outputs = {};
|
|
296
|
+
const failedSeeders = new Set;
|
|
297
|
+
const ctx = await config.context();
|
|
298
|
+
for (let i = 0;i < orderedNames.length; i++) {
|
|
299
|
+
const name = orderedNames[i];
|
|
300
|
+
const result = results[i];
|
|
301
|
+
if (!name || !result)
|
|
302
|
+
continue;
|
|
303
|
+
const seeder = seederMap.get(name);
|
|
304
|
+
if (!seeder)
|
|
305
|
+
continue;
|
|
306
|
+
if (continueOnFailure) {
|
|
307
|
+
const hasFailedDep = seeder.dependsOn.some((dep) => failedSeeders.has(dep));
|
|
308
|
+
if (hasFailedDep) {
|
|
309
|
+
result.status = "skipped";
|
|
310
|
+
failedSeeders.add(name);
|
|
311
|
+
if (verbose) {
|
|
312
|
+
printSeederHeader(name, i, orderedNames.length, seeder.description);
|
|
313
|
+
printSeederSkipped(seeder.dependsOn.filter((d) => failedSeeders.has(d)));
|
|
314
|
+
}
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
if (verbose) {
|
|
319
|
+
printSeederHeader(name, i, orderedNames.length, seeder.description);
|
|
320
|
+
}
|
|
321
|
+
result.status = "running";
|
|
322
|
+
if (config.setSeederName) {
|
|
323
|
+
config.setSeederName(name);
|
|
324
|
+
}
|
|
325
|
+
const deps = {};
|
|
326
|
+
for (const depName of seeder.dependsOn) {
|
|
327
|
+
deps[depName] = outputs[depName];
|
|
328
|
+
}
|
|
329
|
+
const startTime = Date.now();
|
|
330
|
+
try {
|
|
331
|
+
const output = await seeder.run(ctx, deps);
|
|
332
|
+
outputs[name] = output;
|
|
333
|
+
result.status = "completed";
|
|
334
|
+
result.durationMs = Date.now() - startTime;
|
|
335
|
+
result.output = output;
|
|
336
|
+
if (verbose) {
|
|
337
|
+
printSeederComplete(result.durationMs, true);
|
|
338
|
+
}
|
|
339
|
+
} catch (error) {
|
|
340
|
+
result.status = "failed";
|
|
341
|
+
result.durationMs = Date.now() - startTime;
|
|
342
|
+
result.error = error instanceof Error ? error : new Error(String(error));
|
|
343
|
+
failedSeeders.add(name);
|
|
344
|
+
if (verbose) {
|
|
345
|
+
printSeederComplete(result.durationMs, false);
|
|
346
|
+
}
|
|
347
|
+
if (!continueOnFailure) {
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
if (printResults) {
|
|
353
|
+
printResultsTable(results);
|
|
354
|
+
printErrors(results);
|
|
355
|
+
printSummary(results);
|
|
356
|
+
}
|
|
357
|
+
if (config.onAfterAll) {
|
|
358
|
+
await config.onAfterAll();
|
|
359
|
+
}
|
|
360
|
+
const failed = results.filter((r) => r.status === "failed").length;
|
|
361
|
+
return { results, success: failed === 0 };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// src/seeding-state.ts
|
|
365
|
+
var isSeeding = false;
|
|
366
|
+
function isSeedingActive() {
|
|
367
|
+
return isSeeding;
|
|
368
|
+
}
|
|
369
|
+
function setSeedingActive(active) {
|
|
370
|
+
isSeeding = active;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// src/step.ts
|
|
374
|
+
function createStepRunner(config) {
|
|
375
|
+
const { cache } = config ?? {};
|
|
376
|
+
let currentSeederName = config?.seederName ?? "";
|
|
377
|
+
const setSeederName = (name) => {
|
|
378
|
+
currentSeederName = name;
|
|
379
|
+
};
|
|
380
|
+
const step = async (description, fn, options) => {
|
|
381
|
+
const { useCache = false } = options ?? {};
|
|
382
|
+
const slugifiedDescription = description.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
383
|
+
const cacheKey = currentSeederName ? `${currentSeederName}:${slugifiedDescription}` : slugifiedDescription;
|
|
384
|
+
try {
|
|
385
|
+
let result;
|
|
386
|
+
let wasCached = false;
|
|
387
|
+
if (useCache && cache) {
|
|
388
|
+
const cached = await cache.get(cacheKey);
|
|
389
|
+
if (cached !== undefined) {
|
|
390
|
+
result = cached;
|
|
391
|
+
wasCached = true;
|
|
392
|
+
} else {
|
|
393
|
+
result = await fn();
|
|
394
|
+
await cache.set(cacheKey, result);
|
|
395
|
+
}
|
|
396
|
+
} else if (useCache && !cache) {
|
|
397
|
+
console.log(colorize(` ⚠ Cache not configured, running without cache`, "yellow"));
|
|
398
|
+
result = await fn();
|
|
399
|
+
} else {
|
|
400
|
+
result = await fn();
|
|
401
|
+
}
|
|
402
|
+
const cacheIndicator = wasCached ? ` ${colorize("(cached)", "cyan")}` : "";
|
|
403
|
+
console.log(` ${colorize("✓", "green")} ${description}${cacheIndicator}`);
|
|
404
|
+
return result;
|
|
405
|
+
} catch (error) {
|
|
406
|
+
console.log(` ${colorize("✗", "red")} ${description}`);
|
|
407
|
+
if (error instanceof Error) {
|
|
408
|
+
console.log(` ${colorize(error.message, "dim")}`);
|
|
409
|
+
}
|
|
410
|
+
throw error;
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
return { step, setSeederName };
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// src/create-seeder-instance.ts
|
|
417
|
+
function createSeederInstance(config) {
|
|
418
|
+
const defineSeeder = createDefineSeeder();
|
|
419
|
+
const runSeeders = async (seeders, options) => {
|
|
420
|
+
const { step, setSeederName } = createStepRunner({ cache: config.cache });
|
|
421
|
+
const baseContext = {
|
|
422
|
+
faker,
|
|
423
|
+
step,
|
|
424
|
+
expect
|
|
425
|
+
};
|
|
426
|
+
const ctx = await config.context(baseContext);
|
|
427
|
+
const internalConfig = {
|
|
428
|
+
context: () => ctx,
|
|
429
|
+
setSeederName,
|
|
430
|
+
onBeforeAll: async () => {
|
|
431
|
+
setSeedingActive(true);
|
|
432
|
+
if (config.onBeforeAll) {
|
|
433
|
+
await config.onBeforeAll();
|
|
434
|
+
}
|
|
435
|
+
},
|
|
436
|
+
onAfterAll: async () => {
|
|
437
|
+
setSeedingActive(false);
|
|
438
|
+
if (config.onAfterAll) {
|
|
439
|
+
await config.onAfterAll();
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
return runSeedersCore(seeders, internalConfig, options);
|
|
444
|
+
};
|
|
445
|
+
const runSeedersCli = async (seeders, options) => {
|
|
446
|
+
const args = process.argv.slice(2);
|
|
447
|
+
const name = options?.name ?? "Seeders";
|
|
448
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
449
|
+
console.log(`
|
|
450
|
+
${colorize("Usage:", "cyan", "bold")} bun run seed [options]
|
|
451
|
+
|
|
452
|
+
${colorize("Options:", "white", "bold")}
|
|
453
|
+
--help, -h Show this help message
|
|
454
|
+
--dry-run Show execution order without running seeders
|
|
455
|
+
|
|
456
|
+
Runs all ${seeders.length} seeders in dependency order.
|
|
457
|
+
`);
|
|
458
|
+
process.exit(0);
|
|
459
|
+
}
|
|
460
|
+
if (args.includes("--dry-run")) {
|
|
461
|
+
console.log(`
|
|
462
|
+
${colorize("\uD83C\uDF31 Dry Run", "cyan", "bold")} ${colorize(`(${seeders.length} seeders)`, "dim")}
|
|
463
|
+
`);
|
|
464
|
+
const seederMap = new Map;
|
|
465
|
+
for (const seeder of seeders) {
|
|
466
|
+
seederMap.set(seeder.name, seeder);
|
|
467
|
+
}
|
|
468
|
+
try {
|
|
469
|
+
const order = resolveDependencyOrder(seeders);
|
|
470
|
+
console.log(colorize("Execution order:", "white", "bold"));
|
|
471
|
+
for (let i = 0;i < order.length; i++) {
|
|
472
|
+
const seederName = order[i];
|
|
473
|
+
if (!seederName)
|
|
474
|
+
continue;
|
|
475
|
+
const seeder = seederMap.get(seederName);
|
|
476
|
+
const deps = seeder?.dependsOn ?? [];
|
|
477
|
+
const depsStr = deps.length > 0 ? ` ${colorize(`(depends on: ${deps.join(", ")})`, "dim")}` : "";
|
|
478
|
+
console.log(` ${i + 1}. ${seederName}${depsStr}`);
|
|
479
|
+
}
|
|
480
|
+
console.log("");
|
|
481
|
+
process.exit(0);
|
|
482
|
+
} catch (error) {
|
|
483
|
+
console.error(colorize("Failed to resolve dependencies:", "red"));
|
|
484
|
+
console.error(` ${error instanceof Error ? error.message : String(error)}`);
|
|
485
|
+
process.exit(1);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
console.log(`
|
|
489
|
+
${colorize(`\uD83C\uDF31 Running ${name}`, "cyan", "bold")} ${colorize(`(${seeders.length} seeders)`, "dim")}
|
|
490
|
+
`);
|
|
491
|
+
const { success } = await runSeeders(seeders, {
|
|
492
|
+
printResults: true,
|
|
493
|
+
verbose: true
|
|
494
|
+
});
|
|
495
|
+
process.exit(success ? 0 : 1);
|
|
496
|
+
};
|
|
497
|
+
return {
|
|
498
|
+
defineSeeder,
|
|
499
|
+
runSeeders,
|
|
500
|
+
runSeedersCli,
|
|
501
|
+
isSeedingActive
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
export {
|
|
505
|
+
runSeedersCore,
|
|
506
|
+
resolveDependencyOrder,
|
|
507
|
+
isSeedingActive,
|
|
508
|
+
formatDuration,
|
|
509
|
+
faker2 as faker,
|
|
510
|
+
expect2 as expect,
|
|
511
|
+
createStepRunner,
|
|
512
|
+
createSeederInstance,
|
|
513
|
+
createDefineSeeder,
|
|
514
|
+
colorize,
|
|
515
|
+
MissingDependencyError,
|
|
516
|
+
CircularDependencyError
|
|
517
|
+
};
|