@donkeylabs/cli 2.0.22 → 2.1.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/package.json +1 -1
- package/src/commands/generate-client.ts +104 -0
- package/src/commands/generate-utils.ts +121 -0
- package/src/commands/generate.ts +115 -184
- package/src/index.ts +15 -0
package/package.json
CHANGED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { writeFile, mkdir } from "node:fs/promises";
|
|
2
|
+
import { join, dirname } from "node:path";
|
|
3
|
+
import pc from "picocolors";
|
|
4
|
+
import { loadConfig, extractRoutesFromServer, type DonkeylabsConfig, type RouteInfo } from "./generate-utils";
|
|
5
|
+
|
|
6
|
+
export async function generateClientCommand(
|
|
7
|
+
_args: string[],
|
|
8
|
+
options: { output?: string; adapter?: string }
|
|
9
|
+
): Promise<void> {
|
|
10
|
+
const config = await loadConfig();
|
|
11
|
+
|
|
12
|
+
// Resolve adapter: flag > config > default "typescript"
|
|
13
|
+
const adapter = options.adapter || config.adapter || "typescript";
|
|
14
|
+
|
|
15
|
+
// Resolve output: flag > config.client.output > "./client"
|
|
16
|
+
const output = options.output || config.client?.output || "./client";
|
|
17
|
+
|
|
18
|
+
// Extract routes from server
|
|
19
|
+
const entryPath = config.entry || "./src/index.ts";
|
|
20
|
+
console.log(pc.dim(`Extracting routes from ${entryPath}...`));
|
|
21
|
+
const routes = await extractRoutesFromServer(entryPath);
|
|
22
|
+
|
|
23
|
+
if (routes.length === 0) {
|
|
24
|
+
console.warn(pc.yellow("No routes found - generating empty client"));
|
|
25
|
+
} else {
|
|
26
|
+
console.log(pc.green(`Found ${routes.length} routes`));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Dispatch to adapter
|
|
30
|
+
if (adapter === "typescript") {
|
|
31
|
+
await generateTypescriptClient(routes, output);
|
|
32
|
+
} else {
|
|
33
|
+
await generateAdapterClient(adapter, config, routes, output);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Built-in TypeScript client generation using @donkeylabs/server/generator
|
|
39
|
+
*/
|
|
40
|
+
async function generateTypescriptClient(routes: RouteInfo[], output: string): Promise<void> {
|
|
41
|
+
try {
|
|
42
|
+
const { generateClientCode } = await import("@donkeylabs/server/generator");
|
|
43
|
+
|
|
44
|
+
const code = generateClientCode({ routes });
|
|
45
|
+
|
|
46
|
+
// Write single .ts file
|
|
47
|
+
const outputPath = output.endsWith(".ts") ? output : join(output, "index.ts");
|
|
48
|
+
await mkdir(dirname(outputPath), { recursive: true });
|
|
49
|
+
await writeFile(outputPath, code);
|
|
50
|
+
|
|
51
|
+
console.log(pc.green(`Generated TypeScript client:`), pc.dim(outputPath));
|
|
52
|
+
} catch (e: any) {
|
|
53
|
+
if (e.code === "ERR_MODULE_NOT_FOUND" || e.message?.includes("Cannot find")) {
|
|
54
|
+
console.error(pc.red("@donkeylabs/server not found"));
|
|
55
|
+
console.error(pc.dim("Make sure @donkeylabs/server is installed"));
|
|
56
|
+
} else {
|
|
57
|
+
console.error(pc.red("Failed to generate TypeScript client"));
|
|
58
|
+
console.error(pc.dim(e.message));
|
|
59
|
+
}
|
|
60
|
+
process.exit(1);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Adapter-based client generation (sveltekit, swift, or custom package)
|
|
66
|
+
*/
|
|
67
|
+
async function generateAdapterClient(
|
|
68
|
+
adapter: string,
|
|
69
|
+
config: DonkeylabsConfig,
|
|
70
|
+
routes: RouteInfo[],
|
|
71
|
+
output: string
|
|
72
|
+
): Promise<void> {
|
|
73
|
+
// Resolve adapter to package path
|
|
74
|
+
let adapterPackage: string;
|
|
75
|
+
if (adapter === "sveltekit") {
|
|
76
|
+
adapterPackage = "@donkeylabs/adapter-sveltekit";
|
|
77
|
+
} else if (adapter === "swift") {
|
|
78
|
+
adapterPackage = "@donkeylabs/adapter-swift";
|
|
79
|
+
} else {
|
|
80
|
+
// Treat as full package name (e.g., "@myorg/custom-adapter")
|
|
81
|
+
adapterPackage = adapter;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const generatorPath = `${adapterPackage}/generator`;
|
|
85
|
+
|
|
86
|
+
try {
|
|
87
|
+
const adapterModule = await import(generatorPath);
|
|
88
|
+
if (!adapterModule.generateClient) {
|
|
89
|
+
console.error(pc.red(`Adapter ${adapterPackage} does not export generateClient`));
|
|
90
|
+
process.exit(1);
|
|
91
|
+
}
|
|
92
|
+
await adapterModule.generateClient(config, routes, output);
|
|
93
|
+
console.log(pc.green(`Generated client (${adapter}):`), pc.dim(output));
|
|
94
|
+
} catch (e: any) {
|
|
95
|
+
if (e.code === "ERR_MODULE_NOT_FOUND" || e.message?.includes("Cannot find")) {
|
|
96
|
+
console.error(pc.red(`Adapter not found: ${adapterPackage}`));
|
|
97
|
+
console.error(pc.dim(`Install it with: bun add ${adapterPackage}`));
|
|
98
|
+
} else {
|
|
99
|
+
console.error(pc.red(`Failed to generate client with adapter: ${adapterPackage}`));
|
|
100
|
+
console.error(pc.dim(e.message));
|
|
101
|
+
}
|
|
102
|
+
process.exit(1);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import pc from "picocolors";
|
|
5
|
+
|
|
6
|
+
export interface DonkeylabsConfig {
|
|
7
|
+
plugins: string[];
|
|
8
|
+
outDir?: string;
|
|
9
|
+
client?: {
|
|
10
|
+
output: string;
|
|
11
|
+
};
|
|
12
|
+
routes?: string;
|
|
13
|
+
entry?: string;
|
|
14
|
+
adapter?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function loadConfig(): Promise<DonkeylabsConfig> {
|
|
18
|
+
const configPath = join(process.cwd(), "donkeylabs.config.ts");
|
|
19
|
+
|
|
20
|
+
if (!existsSync(configPath)) {
|
|
21
|
+
throw new Error("donkeylabs.config.ts not found. Run 'donkeylabs init' first.");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const config = await import(configPath);
|
|
25
|
+
return config.default;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface RouteInfo {
|
|
29
|
+
name: string;
|
|
30
|
+
prefix: string;
|
|
31
|
+
routeName: string;
|
|
32
|
+
handler: "typed" | "raw" | string;
|
|
33
|
+
inputSource?: string;
|
|
34
|
+
outputSource?: string;
|
|
35
|
+
/** SSE event schemas (for sse handler) */
|
|
36
|
+
eventsSource?: Record<string, string>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Run the server entry file with DONKEYLABS_GENERATE=1 to get typed route metadata
|
|
41
|
+
*/
|
|
42
|
+
export async function extractRoutesFromServer(entryPath: string): Promise<RouteInfo[]> {
|
|
43
|
+
const fullPath = join(process.cwd(), entryPath);
|
|
44
|
+
|
|
45
|
+
if (!existsSync(fullPath)) {
|
|
46
|
+
console.warn(pc.yellow(`Entry file not found: ${entryPath}`));
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const TIMEOUT_MS = 10000; // 10 second timeout
|
|
51
|
+
|
|
52
|
+
return new Promise((resolve) => {
|
|
53
|
+
const child = spawn("bun", [fullPath], {
|
|
54
|
+
env: { ...process.env, DONKEYLABS_GENERATE: "1" },
|
|
55
|
+
stdio: ["inherit", "pipe", "pipe"],
|
|
56
|
+
cwd: process.cwd(),
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
let stdout = "";
|
|
60
|
+
let stderr = "";
|
|
61
|
+
let timedOut = false;
|
|
62
|
+
|
|
63
|
+
// Timeout handler
|
|
64
|
+
const timeout = setTimeout(() => {
|
|
65
|
+
timedOut = true;
|
|
66
|
+
child.kill("SIGTERM");
|
|
67
|
+
console.warn(pc.yellow(`Route extraction timed out after ${TIMEOUT_MS / 1000}s`));
|
|
68
|
+
console.warn(pc.dim("Make sure routes are registered with server.use() before any blocking operations"));
|
|
69
|
+
resolve([]);
|
|
70
|
+
}, TIMEOUT_MS);
|
|
71
|
+
|
|
72
|
+
child.stdout?.on("data", (data) => {
|
|
73
|
+
stdout += data.toString();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
child.stderr?.on("data", (data) => {
|
|
77
|
+
stderr += data.toString();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
child.on("close", (code) => {
|
|
81
|
+
clearTimeout(timeout);
|
|
82
|
+
if (timedOut) return; // Already resolved
|
|
83
|
+
|
|
84
|
+
if (code !== 0) {
|
|
85
|
+
console.warn(pc.yellow(`Failed to extract routes from server (exit code ${code})`));
|
|
86
|
+
if (stderr) console.warn(pc.dim(stderr));
|
|
87
|
+
resolve([]);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
try {
|
|
92
|
+
const result = JSON.parse(stdout.trim());
|
|
93
|
+
// Convert server output to RouteInfo format
|
|
94
|
+
const routes: RouteInfo[] = (result.routes || []).map((r: any) => {
|
|
95
|
+
const parts = r.name.split(".");
|
|
96
|
+
return {
|
|
97
|
+
name: r.name,
|
|
98
|
+
prefix: parts.slice(0, -1).join("."),
|
|
99
|
+
routeName: parts[parts.length - 1] || r.name,
|
|
100
|
+
handler: r.handler || "typed",
|
|
101
|
+
// Server outputs TypeScript strings directly now
|
|
102
|
+
inputSource: r.inputType,
|
|
103
|
+
outputSource: r.outputType,
|
|
104
|
+
// SSE event schemas
|
|
105
|
+
eventsSource: r.eventsType,
|
|
106
|
+
};
|
|
107
|
+
});
|
|
108
|
+
resolve(routes);
|
|
109
|
+
} catch (e) {
|
|
110
|
+
console.warn(pc.yellow("Failed to parse route data from server"));
|
|
111
|
+
resolve([]);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
child.on("error", (err) => {
|
|
116
|
+
clearTimeout(timeout);
|
|
117
|
+
console.warn(pc.yellow(`Failed to run entry file: ${err.message}`));
|
|
118
|
+
resolve([]);
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
}
|
package/src/commands/generate.ts
CHANGED
|
@@ -1,35 +1,13 @@
|
|
|
1
1
|
import { readdir, writeFile, readFile, mkdir, unlink } from "node:fs/promises";
|
|
2
2
|
import { join, relative, dirname, basename } from "node:path";
|
|
3
3
|
import { existsSync } from "node:fs";
|
|
4
|
-
import { spawn } from "node:child_process";
|
|
5
4
|
import pc from "picocolors";
|
|
6
5
|
import { Kysely, Migrator, FileMigrationProvider } from "kysely";
|
|
7
6
|
import { BunSqliteDialect } from "kysely-bun-sqlite";
|
|
8
7
|
import { Database } from "bun:sqlite";
|
|
9
8
|
import { generate, KyselyBunSqliteDialect } from "kysely-codegen";
|
|
10
9
|
import * as ts from "typescript";
|
|
11
|
-
|
|
12
|
-
interface DonkeylabsConfig {
|
|
13
|
-
plugins: string[];
|
|
14
|
-
outDir?: string;
|
|
15
|
-
client?: {
|
|
16
|
-
output: string;
|
|
17
|
-
};
|
|
18
|
-
routes?: string; // Route files pattern, default: "./src/routes/**/handler.ts"
|
|
19
|
-
entry?: string; // Server entry file for extracting routes, default: "./src/index.ts"
|
|
20
|
-
adapter?: string; // Adapter package for framework-specific generation, e.g., "@donkeylabs/adapter-sveltekit"
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
async function loadConfig(): Promise<DonkeylabsConfig> {
|
|
24
|
-
const configPath = join(process.cwd(), "donkeylabs.config.ts");
|
|
25
|
-
|
|
26
|
-
if (!existsSync(configPath)) {
|
|
27
|
-
throw new Error("donkeylabs.config.ts not found. Run 'donkeylabs init' first.");
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
const config = await import(configPath);
|
|
31
|
-
return config.default;
|
|
32
|
-
}
|
|
10
|
+
import { loadConfig, extractRoutesFromServer, type DonkeylabsConfig, type RouteInfo } from "./generate-utils";
|
|
33
11
|
|
|
34
12
|
async function getPluginExportName(pluginPath: string): Promise<string | null> {
|
|
35
13
|
try {
|
|
@@ -55,18 +33,95 @@ async function getPluginDefinedName(pluginPath: string): Promise<string | null>
|
|
|
55
33
|
async function extractHandlerNames(pluginPath: string): Promise<string[]> {
|
|
56
34
|
try {
|
|
57
35
|
const content = await readFile(pluginPath, "utf-8");
|
|
58
|
-
const
|
|
59
|
-
if (
|
|
36
|
+
const astNames = extractHandlerNamesFromAst(content, pluginPath);
|
|
37
|
+
if (astNames.length > 0) {
|
|
38
|
+
return astNames;
|
|
39
|
+
}
|
|
60
40
|
|
|
61
|
-
|
|
62
|
-
return [...handlersBlock.matchAll(/(\w+)\s*:/g)]
|
|
63
|
-
.map((m) => m[1])
|
|
64
|
-
.filter((name): name is string => !!name);
|
|
41
|
+
return extractHandlerNamesRegexFallback(content);
|
|
65
42
|
} catch {
|
|
66
43
|
return [];
|
|
67
44
|
}
|
|
68
45
|
}
|
|
69
46
|
|
|
47
|
+
function extractHandlerNamesFromAst(content: string, fileName: string): string[] {
|
|
48
|
+
const sourceFile = ts.createSourceFile(fileName, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
49
|
+
const names = new Set<string>();
|
|
50
|
+
|
|
51
|
+
const addFromObjectLiteral = (obj: ts.ObjectLiteralExpression) => {
|
|
52
|
+
for (const prop of obj.properties) {
|
|
53
|
+
if (!ts.isPropertyAssignment(prop) && !ts.isMethodDeclaration(prop)) continue;
|
|
54
|
+
const propName = getStaticPropertyName(prop.name);
|
|
55
|
+
if (propName && isSafeIdentifier(propName)) {
|
|
56
|
+
names.add(propName);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const collectFromHandlersInitializer = (initializer: ts.Expression) => {
|
|
62
|
+
if (ts.isObjectLiteralExpression(initializer)) {
|
|
63
|
+
addFromObjectLiteral(initializer);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)) {
|
|
68
|
+
const body = initializer.body;
|
|
69
|
+
|
|
70
|
+
if (ts.isObjectLiteralExpression(body)) {
|
|
71
|
+
addFromObjectLiteral(body);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (ts.isParenthesizedExpression(body) && ts.isObjectLiteralExpression(body.expression)) {
|
|
76
|
+
addFromObjectLiteral(body.expression);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (ts.isBlock(body)) {
|
|
81
|
+
for (const stmt of body.statements) {
|
|
82
|
+
if (!ts.isReturnStatement(stmt) || !stmt.expression) continue;
|
|
83
|
+
|
|
84
|
+
if (ts.isObjectLiteralExpression(stmt.expression)) {
|
|
85
|
+
addFromObjectLiteral(stmt.expression);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (
|
|
90
|
+
ts.isParenthesizedExpression(stmt.expression) &&
|
|
91
|
+
ts.isObjectLiteralExpression(stmt.expression.expression)
|
|
92
|
+
) {
|
|
93
|
+
addFromObjectLiteral(stmt.expression.expression);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const visit = (node: ts.Node) => {
|
|
102
|
+
if (ts.isPropertyAssignment(node)) {
|
|
103
|
+
const propName = getStaticPropertyName(node.name);
|
|
104
|
+
if (propName === "handlers") {
|
|
105
|
+
collectFromHandlersInitializer(node.initializer);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
ts.forEachChild(node, visit);
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
visit(sourceFile);
|
|
112
|
+
return [...names];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function extractHandlerNamesRegexFallback(content: string): string[] {
|
|
116
|
+
const handlersMatch = content.match(/handlers:\s*\{([^}]+)\}/);
|
|
117
|
+
if (!handlersMatch?.[1]) return [];
|
|
118
|
+
|
|
119
|
+
const handlersBlock = handlersMatch[1];
|
|
120
|
+
return [...handlersBlock.matchAll(/(\w+)\s*:/g)]
|
|
121
|
+
.map((m) => m[1])
|
|
122
|
+
.filter((name): name is string => !!name);
|
|
123
|
+
}
|
|
124
|
+
|
|
70
125
|
async function extractMiddlewareNames(pluginPath: string): Promise<string[]> {
|
|
71
126
|
try {
|
|
72
127
|
const content = await readFile(pluginPath, "utf-8");
|
|
@@ -358,82 +413,49 @@ interface EventDefinitionInfo {
|
|
|
358
413
|
async function extractEventsFromFile(filePath: string): Promise<EventDefinitionInfo[]> {
|
|
359
414
|
try {
|
|
360
415
|
const content = await readFile(filePath, "utf-8");
|
|
416
|
+
const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
361
417
|
const events: EventDefinitionInfo[] = [];
|
|
362
418
|
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
// Extract the object block
|
|
370
|
-
const blockStart = defineEventsMatch.index + defineEventsMatch[0].length - 1;
|
|
371
|
-
const block = extractBalancedBlock(content, blockStart, "{", "}");
|
|
372
|
-
if (!block) return events;
|
|
373
|
-
|
|
374
|
-
// Parse event entries: "event.name": z.object({...})
|
|
375
|
-
// Match quoted keys followed by Zod schemas
|
|
376
|
-
const eventPattern = /["']([^"']+)["']\s*:\s*(z\.[^,}]+(?:\([^)]*\))?)/g;
|
|
377
|
-
|
|
378
|
-
let match;
|
|
379
|
-
const innerBlock = block.slice(1, -1); // Remove outer braces
|
|
419
|
+
const addFromObjectLiteral = (obj: ts.ObjectLiteralExpression) => {
|
|
420
|
+
for (const prop of obj.properties) {
|
|
421
|
+
if (!ts.isPropertyAssignment(prop)) continue;
|
|
422
|
+
const eventName = getEventNameFromPropertyName(prop.name);
|
|
423
|
+
if (!eventName) continue;
|
|
380
424
|
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
let keyMatch;
|
|
384
|
-
const keyPositions: { name: string; pos: number }[] = [];
|
|
425
|
+
const schemaSource = prop.initializer.getText(sourceFile).trim();
|
|
426
|
+
if (!schemaSource) continue;
|
|
385
427
|
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
// For each key, extract the Zod schema that follows
|
|
391
|
-
for (let i = 0; i < keyPositions.length; i++) {
|
|
392
|
-
const { name, pos } = keyPositions[i]!;
|
|
393
|
-
const nextPos = keyPositions[i + 1]?.pos ?? innerBlock.length;
|
|
394
|
-
|
|
395
|
-
// Get the slice between this key and the next
|
|
396
|
-
let schemaSlice = innerBlock.slice(pos, nextPos).trim();
|
|
397
|
-
|
|
398
|
-
// Find where the Zod expression ends
|
|
399
|
-
if (schemaSlice.startsWith("z.")) {
|
|
400
|
-
// Extract balanced parentheses for the schema
|
|
401
|
-
let depth = 0;
|
|
402
|
-
let endIdx = 0;
|
|
403
|
-
let foundParen = false;
|
|
404
|
-
|
|
405
|
-
for (let j = 0; j < schemaSlice.length; j++) {
|
|
406
|
-
if (schemaSlice[j] === "(") {
|
|
407
|
-
depth++;
|
|
408
|
-
foundParen = true;
|
|
409
|
-
} else if (schemaSlice[j] === ")") {
|
|
410
|
-
depth--;
|
|
411
|
-
if (depth === 0 && foundParen) {
|
|
412
|
-
endIdx = j + 1;
|
|
413
|
-
// Check for chained methods
|
|
414
|
-
const rest = schemaSlice.slice(endIdx);
|
|
415
|
-
const chainMatch = rest.match(/^(\s*\.\w+\([^)]*\))+/);
|
|
416
|
-
if (chainMatch) {
|
|
417
|
-
endIdx += chainMatch[0].length;
|
|
418
|
-
}
|
|
419
|
-
break;
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
}
|
|
428
|
+
events.push({ name: eventName, schemaSource });
|
|
429
|
+
}
|
|
430
|
+
};
|
|
423
431
|
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
432
|
+
const visit = (node: ts.Node) => {
|
|
433
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "defineEvents") {
|
|
434
|
+
const firstArg = node.arguments[0];
|
|
435
|
+
if (firstArg && ts.isObjectLiteralExpression(firstArg)) {
|
|
436
|
+
addFromObjectLiteral(firstArg);
|
|
427
437
|
}
|
|
428
438
|
}
|
|
429
|
-
|
|
439
|
+
ts.forEachChild(node, visit);
|
|
440
|
+
};
|
|
430
441
|
|
|
442
|
+
visit(sourceFile);
|
|
431
443
|
return events;
|
|
432
444
|
} catch {
|
|
433
445
|
return [];
|
|
434
446
|
}
|
|
435
447
|
}
|
|
436
448
|
|
|
449
|
+
function getEventNameFromPropertyName(name: ts.PropertyName): string | null {
|
|
450
|
+
if (ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name)) {
|
|
451
|
+
return name.text;
|
|
452
|
+
}
|
|
453
|
+
if (ts.isIdentifier(name)) {
|
|
454
|
+
return name.text;
|
|
455
|
+
}
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
|
|
437
459
|
/**
|
|
438
460
|
* Find and extract server-level events from common locations.
|
|
439
461
|
*/
|
|
@@ -560,16 +582,7 @@ interface ExtractedRoute {
|
|
|
560
582
|
handler: string;
|
|
561
583
|
}
|
|
562
584
|
|
|
563
|
-
|
|
564
|
-
name: string;
|
|
565
|
-
prefix: string;
|
|
566
|
-
routeName: string;
|
|
567
|
-
handler: "typed" | "raw" | string;
|
|
568
|
-
inputSource?: string;
|
|
569
|
-
outputSource?: string;
|
|
570
|
-
/** SSE event schemas (for sse handler) */
|
|
571
|
-
eventsSource?: Record<string, string>;
|
|
572
|
-
}
|
|
585
|
+
// RouteInfo is imported from ./generate-utils
|
|
573
586
|
|
|
574
587
|
/**
|
|
575
588
|
* Extract a balanced block from source code starting at a given position
|
|
@@ -792,89 +805,7 @@ async function findRouteFiles(pattern: string): Promise<string[]> {
|
|
|
792
805
|
return files;
|
|
793
806
|
}
|
|
794
807
|
|
|
795
|
-
|
|
796
|
-
* Run the server entry file with DONKEYLABS_GENERATE=1 to get typed route metadata
|
|
797
|
-
*/
|
|
798
|
-
async function extractRoutesFromServer(entryPath: string): Promise<RouteInfo[]> {
|
|
799
|
-
const fullPath = join(process.cwd(), entryPath);
|
|
800
|
-
|
|
801
|
-
if (!existsSync(fullPath)) {
|
|
802
|
-
console.warn(pc.yellow(`Entry file not found: ${entryPath}`));
|
|
803
|
-
return [];
|
|
804
|
-
}
|
|
805
|
-
|
|
806
|
-
const TIMEOUT_MS = 10000; // 10 second timeout
|
|
807
|
-
|
|
808
|
-
return new Promise((resolve) => {
|
|
809
|
-
const child = spawn("bun", [fullPath], {
|
|
810
|
-
env: { ...process.env, DONKEYLABS_GENERATE: "1" },
|
|
811
|
-
stdio: ["inherit", "pipe", "pipe"],
|
|
812
|
-
cwd: process.cwd(),
|
|
813
|
-
});
|
|
814
|
-
|
|
815
|
-
let stdout = "";
|
|
816
|
-
let stderr = "";
|
|
817
|
-
let timedOut = false;
|
|
818
|
-
|
|
819
|
-
// Timeout handler
|
|
820
|
-
const timeout = setTimeout(() => {
|
|
821
|
-
timedOut = true;
|
|
822
|
-
child.kill("SIGTERM");
|
|
823
|
-
console.warn(pc.yellow(`Route extraction timed out after ${TIMEOUT_MS / 1000}s`));
|
|
824
|
-
console.warn(pc.dim("Make sure routes are registered with server.use() before any blocking operations"));
|
|
825
|
-
resolve([]);
|
|
826
|
-
}, TIMEOUT_MS);
|
|
827
|
-
|
|
828
|
-
child.stdout?.on("data", (data) => {
|
|
829
|
-
stdout += data.toString();
|
|
830
|
-
});
|
|
831
|
-
|
|
832
|
-
child.stderr?.on("data", (data) => {
|
|
833
|
-
stderr += data.toString();
|
|
834
|
-
});
|
|
835
|
-
|
|
836
|
-
child.on("close", (code) => {
|
|
837
|
-
clearTimeout(timeout);
|
|
838
|
-
if (timedOut) return; // Already resolved
|
|
839
|
-
|
|
840
|
-
if (code !== 0) {
|
|
841
|
-
console.warn(pc.yellow(`Failed to extract routes from server (exit code ${code})`));
|
|
842
|
-
if (stderr) console.warn(pc.dim(stderr));
|
|
843
|
-
resolve([]);
|
|
844
|
-
return;
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
try {
|
|
848
|
-
const result = JSON.parse(stdout.trim());
|
|
849
|
-
// Convert server output to RouteInfo format
|
|
850
|
-
const routes: RouteInfo[] = (result.routes || []).map((r: any) => {
|
|
851
|
-
const parts = r.name.split(".");
|
|
852
|
-
return {
|
|
853
|
-
name: r.name,
|
|
854
|
-
prefix: parts.slice(0, -1).join("."),
|
|
855
|
-
routeName: parts[parts.length - 1] || r.name,
|
|
856
|
-
handler: r.handler || "typed",
|
|
857
|
-
// Server outputs TypeScript strings directly now
|
|
858
|
-
inputSource: r.inputType,
|
|
859
|
-
outputSource: r.outputType,
|
|
860
|
-
// SSE event schemas
|
|
861
|
-
eventsSource: r.eventsType,
|
|
862
|
-
};
|
|
863
|
-
});
|
|
864
|
-
resolve(routes);
|
|
865
|
-
} catch (e) {
|
|
866
|
-
console.warn(pc.yellow("Failed to parse route data from server"));
|
|
867
|
-
resolve([]);
|
|
868
|
-
}
|
|
869
|
-
});
|
|
870
|
-
|
|
871
|
-
child.on("error", (err) => {
|
|
872
|
-
clearTimeout(timeout);
|
|
873
|
-
console.warn(pc.yellow(`Failed to run entry file: ${err.message}`));
|
|
874
|
-
resolve([]);
|
|
875
|
-
});
|
|
876
|
-
});
|
|
877
|
-
}
|
|
808
|
+
// extractRoutesFromServer is imported from ./generate-utils
|
|
878
809
|
|
|
879
810
|
/**
|
|
880
811
|
* Generate schema.ts from plugin migrations using kysely-codegen
|
package/src/index.ts
CHANGED
|
@@ -20,6 +20,7 @@ const { positionals, values } = parseArgs({
|
|
|
20
20
|
local: { type: "boolean", short: "l" },
|
|
21
21
|
list: { type: "boolean" },
|
|
22
22
|
output: { type: "string", short: "o" },
|
|
23
|
+
adapter: { type: "string" },
|
|
23
24
|
all: { type: "boolean", short: "a" },
|
|
24
25
|
check: { type: "boolean", short: "c" },
|
|
25
26
|
"skip-docs": { type: "boolean" },
|
|
@@ -41,6 +42,7 @@ ${pc.bold("Commands:")}
|
|
|
41
42
|
${pc.cyan("init")} Initialize a new project
|
|
42
43
|
${pc.cyan("add")} Add optional plugins (images, auth, etc.)
|
|
43
44
|
${pc.cyan("generate")} Generate types (registry, context, client)
|
|
45
|
+
${pc.cyan("generate-client")} Generate API client only (TypeScript, Swift, SvelteKit)
|
|
44
46
|
${pc.cyan("plugin")} Plugin management
|
|
45
47
|
${pc.cyan("update")} Check and install package updates
|
|
46
48
|
${pc.cyan("docs")} Sync documentation from installed package
|
|
@@ -56,6 +58,7 @@ ${pc.bold("Options:")}
|
|
|
56
58
|
-v, --version Show version number
|
|
57
59
|
-t, --type <type> Project type for init (server, sveltekit)
|
|
58
60
|
-l, --local Use local workspace packages (for monorepo dev)
|
|
61
|
+
--adapter <adapter> Client adapter (typescript, sveltekit, swift, or package name)
|
|
59
62
|
|
|
60
63
|
${pc.bold("Examples:")}
|
|
61
64
|
donkeylabs # Interactive menu
|
|
@@ -63,6 +66,9 @@ ${pc.bold("Options:")}
|
|
|
63
66
|
donkeylabs init --type server # Server-only project
|
|
64
67
|
donkeylabs init --type sveltekit # SvelteKit + adapter project
|
|
65
68
|
donkeylabs generate
|
|
69
|
+
donkeylabs generate-client -o ./clients/typescript
|
|
70
|
+
donkeylabs generate-client -o ./ios/ApiClient --adapter swift
|
|
71
|
+
donkeylabs generate-client --adapter sveltekit
|
|
66
72
|
donkeylabs plugin create myPlugin
|
|
67
73
|
donkeylabs update # Interactive package update
|
|
68
74
|
donkeylabs update --check # Check for updates only
|
|
@@ -115,6 +121,15 @@ async function main() {
|
|
|
115
121
|
await generateCommand(positionals.slice(1));
|
|
116
122
|
break;
|
|
117
123
|
|
|
124
|
+
case "generate-client":
|
|
125
|
+
case "gen-client":
|
|
126
|
+
const { generateClientCommand } = await import("./commands/generate-client");
|
|
127
|
+
await generateClientCommand(positionals.slice(1), {
|
|
128
|
+
output: values.output,
|
|
129
|
+
adapter: values.adapter,
|
|
130
|
+
});
|
|
131
|
+
break;
|
|
132
|
+
|
|
118
133
|
case "plugin":
|
|
119
134
|
const { pluginCommand } = await import("./commands/plugin");
|
|
120
135
|
await pluginCommand(positionals.slice(1));
|