@base44-preview/cli 0.0.1-pr.10.3124f70

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/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # Base44 CLI
2
+
3
+ A unified command-line interface for managing Base44 applications, entities, functions, deployments, and related services.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ # Using npm
9
+ npm install
10
+
11
+ # Build the project
12
+ npm run build
13
+
14
+ # Run the CLI
15
+ npm start # Using node directly
16
+ ./dist/cli/index.js # Run executable directly
17
+ ```
18
+
19
+ ## Development
20
+
21
+ ```bash
22
+ # Run in development mode
23
+ npm run dev
24
+
25
+ # Build the project
26
+ npm run build
27
+
28
+ # Run the built CLI
29
+ npm run start
30
+
31
+ # Clean build artifacts
32
+ npm run clean
33
+
34
+ # Lint the code
35
+ npm run lint
36
+
37
+ ```
38
+
39
+ ## Commands
40
+
41
+ ### Authentication
42
+
43
+ - `base44 login` - Authenticate with Base44 using device code flow
44
+ - `base44 whoami` - Display current authenticated user
45
+ - `base44 logout` - Logout from current device
46
+
47
+ ### Project
48
+
49
+ - `base44 show-project` - Display project configuration, entities, and functions
@@ -0,0 +1,631 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import { intro, log, spinner } from "@clack/prompts";
4
+ import pWaitFor from "p-wait-for";
5
+ import { z } from "zod";
6
+ import { dirname, join } from "node:path";
7
+ import { homedir } from "node:os";
8
+ import ky from "ky";
9
+ import { access, mkdir, readFile, unlink, writeFile } from "node:fs/promises";
10
+ import { parse, printParseErrorCode } from "jsonc-parser";
11
+ import chalk from "chalk";
12
+ import { globby } from "globby";
13
+
14
+ //#region src/core/auth/schema.ts
15
+ const AuthDataSchema = z.object({
16
+ accessToken: z.string().min(1, "Token cannot be empty"),
17
+ refreshToken: z.string().min(1, "Refresh token cannot be empty"),
18
+ expiresAt: z.number().int().positive("Expires at must be a positive integer"),
19
+ email: z.email(),
20
+ name: z.string().min(1, "Name cannot be empty")
21
+ });
22
+ const DeviceCodeResponseSchema = z.object({
23
+ device_code: z.string().min(1, "Device code cannot be empty"),
24
+ user_code: z.string().min(1, "User code cannot be empty"),
25
+ verification_uri: z.url("Invalid verification URL"),
26
+ verification_uri_complete: z.url("Invalid complete verification URL"),
27
+ expires_in: z.number().int().positive("Expires in must be a positive integer"),
28
+ interval: z.number().int().positive("Interval in must be a positive integer")
29
+ }).transform((data) => ({
30
+ deviceCode: data.device_code,
31
+ userCode: data.user_code,
32
+ verificationUri: data.verification_uri,
33
+ verificationUriComplete: data.verification_uri_complete,
34
+ expiresIn: data.expires_in,
35
+ interval: data.interval
36
+ }));
37
+ const TokenResponseSchema = z.object({
38
+ access_token: z.string().min(1, "Token cannot be empty"),
39
+ token_type: z.string().min(1, "Token type cannot be empty"),
40
+ expires_in: z.number().int().positive("Expires in must be a positive integer"),
41
+ refresh_token: z.string().min(1, "Refresh token cannot be empty"),
42
+ scope: z.string().optional()
43
+ }).transform((data) => ({
44
+ accessToken: data.access_token,
45
+ tokenType: data.token_type,
46
+ expiresIn: data.expires_in,
47
+ refreshToken: data.refresh_token,
48
+ scope: data.scope
49
+ }));
50
+ const OAuthErrorSchema = z.object({
51
+ error: z.string(),
52
+ error_description: z.string().optional()
53
+ });
54
+ const UserInfoSchema = z.object({
55
+ email: z.email(),
56
+ name: z.string()
57
+ });
58
+
59
+ //#endregion
60
+ //#region src/core/errors.ts
61
+ var AuthApiError = class extends Error {
62
+ constructor(message, cause) {
63
+ super(message);
64
+ this.cause = cause;
65
+ this.name = "AuthApiError";
66
+ }
67
+ };
68
+ var AuthValidationError = class extends Error {
69
+ constructor(message) {
70
+ super(message);
71
+ this.name = "AuthValidationError";
72
+ }
73
+ };
74
+
75
+ //#endregion
76
+ //#region src/core/consts.ts
77
+ const PROJECT_SUBDIR = "base44";
78
+ const FUNCTION_CONFIG_FILE = "function.jsonc";
79
+ function getBase44Dir() {
80
+ return join(homedir(), ".base44");
81
+ }
82
+ function getAuthFilePath() {
83
+ return join(getBase44Dir(), "auth", "auth.json");
84
+ }
85
+ function getProjectConfigPatterns() {
86
+ return [
87
+ `${PROJECT_SUBDIR}/config.jsonc`,
88
+ `${PROJECT_SUBDIR}/config.json`,
89
+ "config.jsonc",
90
+ "config.json"
91
+ ];
92
+ }
93
+ const AUTH_CLIENT_ID = "base44_cli";
94
+ const DEFAULT_API_URL = "https://app.base44.com";
95
+ function getBase44ApiUrl() {
96
+ return process.env.BASE44_API_URL || DEFAULT_API_URL;
97
+ }
98
+
99
+ //#endregion
100
+ //#region src/core/auth/authClient.ts
101
+ /**
102
+ * Separate ky instance for OAuth endpoints.
103
+ * These don't need Authorization headers (they use client_id + tokens in body).
104
+ */
105
+ const authClient = ky.create({
106
+ prefixUrl: getBase44ApiUrl(),
107
+ headers: { "User-Agent": "Base44 CLI" }
108
+ });
109
+ var authClient_default = authClient;
110
+
111
+ //#endregion
112
+ //#region src/core/utils/fs.ts
113
+ function pathExists(path) {
114
+ return access(path).then(() => true).catch(() => false);
115
+ }
116
+ async function readJsonFile(filePath) {
117
+ if (!await pathExists(filePath)) throw new Error(`File not found: ${filePath}`);
118
+ try {
119
+ const fileContent = await readFile(filePath, "utf-8");
120
+ const errors = [];
121
+ const result = parse(fileContent, errors, { allowTrailingComma: true });
122
+ if (errors.length > 0) {
123
+ const errorMessages = errors.map((e) => `${printParseErrorCode(e.error)} at offset ${e.offset}`).join(", ");
124
+ throw new Error(`File contains invalid JSONC: ${filePath} (${errorMessages})`);
125
+ }
126
+ return result;
127
+ } catch (error) {
128
+ if (error instanceof Error && error.message.includes("invalid JSONC")) throw error;
129
+ throw new Error(`Failed to read file ${filePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
130
+ }
131
+ }
132
+ async function writeJsonFile(filePath, data) {
133
+ try {
134
+ const dir = dirname(filePath);
135
+ if (!await pathExists(dir)) await mkdir(dir, { recursive: true });
136
+ await writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
137
+ } catch (error) {
138
+ throw new Error(`Failed to write file ${filePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
139
+ }
140
+ }
141
+ async function deleteFile(filePath) {
142
+ if (!await pathExists(filePath)) return;
143
+ try {
144
+ await unlink(filePath);
145
+ } catch (error) {
146
+ throw new Error(`Failed to delete file ${filePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
147
+ }
148
+ }
149
+
150
+ //#endregion
151
+ //#region src/core/auth/config.ts
152
+ const TOKEN_REFRESH_BUFFER_MS = 60 * 1e3;
153
+ let refreshPromise = null;
154
+ async function readAuth() {
155
+ try {
156
+ const parsed = await readJsonFile(getAuthFilePath());
157
+ const result = AuthDataSchema.safeParse(parsed);
158
+ if (!result.success) throw new Error(`Invalid authentication data: ${result.error.issues.map((e) => e.message).join(", ")}`);
159
+ return result.data;
160
+ } catch (error) {
161
+ if (error instanceof Error && error.message.includes("Authentication")) throw error;
162
+ if (error instanceof Error && error.message.includes("File not found")) throw new Error("Authentication file not found. Please login first.");
163
+ throw new Error(`Failed to read authentication file: ${error instanceof Error ? error.message : "Unknown error"}`);
164
+ }
165
+ }
166
+ async function writeAuth(authData) {
167
+ const result = AuthDataSchema.safeParse(authData);
168
+ if (!result.success) throw new Error(`Invalid authentication data: ${result.error.issues.map((e) => e.message).join(", ")}`);
169
+ try {
170
+ await writeJsonFile(getAuthFilePath(), result.data);
171
+ } catch (error) {
172
+ throw new Error(`Failed to write authentication file: ${error instanceof Error ? error.message : "Unknown error"}`);
173
+ }
174
+ }
175
+ async function deleteAuth() {
176
+ try {
177
+ await deleteFile(getAuthFilePath());
178
+ } catch (error) {
179
+ throw new Error(`Failed to delete authentication file: ${error instanceof Error ? error.message : "Unknown error"}`);
180
+ }
181
+ }
182
+ /**
183
+ * Checks if the access token is expired or about to expire.
184
+ */
185
+ function isTokenExpired(auth) {
186
+ return Date.now() >= auth.expiresAt - TOKEN_REFRESH_BUFFER_MS;
187
+ }
188
+ /**
189
+ * Refreshes the access token and saves the new tokens.
190
+ * Returns the new access token, or null if refresh failed.
191
+ * Uses a lock to prevent concurrent refresh requests.
192
+ */
193
+ async function refreshAndSaveTokens() {
194
+ if (refreshPromise) return refreshPromise;
195
+ refreshPromise = (async () => {
196
+ try {
197
+ const auth = await readAuth();
198
+ const tokenResponse = await renewAccessToken(auth.refreshToken);
199
+ await writeAuth({
200
+ ...auth,
201
+ accessToken: tokenResponse.accessToken,
202
+ refreshToken: tokenResponse.refreshToken,
203
+ expiresAt: Date.now() + tokenResponse.expiresIn * 1e3
204
+ });
205
+ return tokenResponse.accessToken;
206
+ } catch {
207
+ await deleteAuth();
208
+ return null;
209
+ } finally {
210
+ refreshPromise = null;
211
+ }
212
+ })();
213
+ return refreshPromise;
214
+ }
215
+
216
+ //#endregion
217
+ //#region src/core/utils/httpClient.ts
218
+ const retriedRequests = /* @__PURE__ */ new WeakSet();
219
+ /**
220
+ * Handles 401 responses by refreshing the token and retrying the request.
221
+ * Only retries once per request to prevent infinite loops.
222
+ */
223
+ async function handleUnauthorized(request, _options, response) {
224
+ if (response.status !== 401) return;
225
+ if (retriedRequests.has(request)) return;
226
+ const newAccessToken = await refreshAndSaveTokens();
227
+ if (!newAccessToken) return;
228
+ retriedRequests.add(request);
229
+ request.headers.set("Authorization", `Bearer ${newAccessToken}`);
230
+ return ky(request);
231
+ }
232
+ const httpClient = ky.create({
233
+ prefixUrl: getBase44ApiUrl(),
234
+ headers: { "User-Agent": "Base44 CLI" },
235
+ hooks: {
236
+ beforeRequest: [async (request) => {
237
+ try {
238
+ const auth = await readAuth();
239
+ if (isTokenExpired(auth)) {
240
+ const newAccessToken = await refreshAndSaveTokens();
241
+ if (newAccessToken) {
242
+ request.headers.set("Authorization", `Bearer ${newAccessToken}`);
243
+ return;
244
+ }
245
+ }
246
+ request.headers.set("Authorization", `Bearer ${auth.accessToken}`);
247
+ } catch {}
248
+ }],
249
+ afterResponse: [handleUnauthorized]
250
+ }
251
+ });
252
+
253
+ //#endregion
254
+ //#region src/core/auth/api.ts
255
+ async function generateDeviceCode() {
256
+ const response = await authClient_default.post("oauth/device/code", {
257
+ json: {
258
+ client_id: AUTH_CLIENT_ID,
259
+ scope: "apps:read apps:write"
260
+ },
261
+ throwHttpErrors: false
262
+ });
263
+ if (!response.ok) throw new AuthApiError(`Failed to generate device code: ${response.status} ${response.statusText}`);
264
+ const result = DeviceCodeResponseSchema.safeParse(await response.json());
265
+ if (!result.success) throw new AuthValidationError(`Invalid device code response from server: ${result.error.message}`);
266
+ return result.data;
267
+ }
268
+ async function getTokenFromDeviceCode(deviceCode) {
269
+ const searchParams = new URLSearchParams();
270
+ searchParams.set("grant_type", "urn:ietf:params:oauth:grant-type:device_code");
271
+ searchParams.set("device_code", deviceCode);
272
+ searchParams.set("client_id", AUTH_CLIENT_ID);
273
+ const response = await authClient_default.post("oauth/token", {
274
+ body: searchParams.toString(),
275
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
276
+ throwHttpErrors: false
277
+ });
278
+ const json = await response.json();
279
+ if (!response.ok) {
280
+ const errorResult = OAuthErrorSchema.safeParse(json);
281
+ if (!errorResult.success) throw new AuthValidationError(`Token request failed: ${errorResult.error.message}`);
282
+ const { error, error_description } = errorResult.data;
283
+ if (error === "authorization_pending" || error === "slow_down") return null;
284
+ throw new AuthApiError(error_description ?? `OAuth error: ${error}`);
285
+ }
286
+ const result = TokenResponseSchema.safeParse(json);
287
+ if (!result.success) throw new AuthValidationError(`Invalid token response from server: ${result.error.message}`);
288
+ return result.data;
289
+ }
290
+ async function renewAccessToken(refreshToken) {
291
+ const searchParams = new URLSearchParams();
292
+ searchParams.set("grant_type", "refresh_token");
293
+ searchParams.set("refresh_token", refreshToken);
294
+ searchParams.set("client_id", AUTH_CLIENT_ID);
295
+ const response = await authClient_default.post("oauth/token", {
296
+ body: searchParams.toString(),
297
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
298
+ throwHttpErrors: false
299
+ });
300
+ const json = await response.json();
301
+ if (!response.ok) {
302
+ const errorResult = OAuthErrorSchema.safeParse(json);
303
+ if (!errorResult.success) throw new AuthApiError(`Token refresh failed: ${response.statusText}`);
304
+ const { error, error_description } = errorResult.data;
305
+ throw new AuthApiError(error_description ?? `OAuth error: ${error}`);
306
+ }
307
+ const result = TokenResponseSchema.safeParse(json);
308
+ if (!result.success) throw new AuthValidationError(`Invalid token response from server: ${result.error.message}`);
309
+ return result.data;
310
+ }
311
+
312
+ //#endregion
313
+ //#region src/cli/utils/runCommand.ts
314
+ const base44Color = chalk.bgHex("#E86B3C");
315
+ /**
316
+ * Wraps a command function with the Base44 intro banner.
317
+ * All CLI commands should use this utility to ensure consistent branding.
318
+ *
319
+ * @param commandFn - The async function to execute as the command
320
+ */
321
+ async function runCommand(commandFn) {
322
+ intro(base44Color(" Base 44 "));
323
+ try {
324
+ await commandFn();
325
+ } catch (e) {
326
+ if (e instanceof Error) log.error(e.stack ?? e.message);
327
+ else log.error(String(e));
328
+ process.exit(1);
329
+ }
330
+ }
331
+
332
+ //#endregion
333
+ //#region src/cli/utils/runTask.ts
334
+ /**
335
+ * Wraps an async operation with automatic spinner management.
336
+ * The spinner is automatically started, and stopped on both success and error.
337
+ *
338
+ * @param startMessage - Message to show when spinner starts
339
+ * @param operation - The async operation to execute
340
+ * @param options - Optional configuration
341
+ * @returns The result of the operation
342
+ */
343
+ async function runTask(startMessage, operation, options) {
344
+ const s = spinner();
345
+ s.start(startMessage);
346
+ try {
347
+ const result = await operation();
348
+ s.stop(options?.successMessage || startMessage);
349
+ return result;
350
+ } catch (error) {
351
+ s.stop(options?.errorMessage || "Failed");
352
+ throw error;
353
+ }
354
+ }
355
+
356
+ //#endregion
357
+ //#region src/cli/commands/auth/login.ts
358
+ async function generateAndDisplayDeviceCode() {
359
+ const deviceCodeResponse = await runTask("Generating device code...", async () => {
360
+ return await generateDeviceCode();
361
+ }, {
362
+ successMessage: "Device code generated",
363
+ errorMessage: "Failed to generate device code"
364
+ });
365
+ log.info(`Please visit: ${deviceCodeResponse.verificationUriComplete}`);
366
+ return deviceCodeResponse;
367
+ }
368
+ async function waitForAuthentication(deviceCode, expiresIn, interval) {
369
+ let tokenResponse;
370
+ try {
371
+ await runTask("Waiting for you to complete authentication...", async () => {
372
+ await pWaitFor(async () => {
373
+ const result = await getTokenFromDeviceCode(deviceCode);
374
+ if (result !== null) {
375
+ tokenResponse = result;
376
+ return true;
377
+ }
378
+ return false;
379
+ }, {
380
+ interval: interval * 1e3,
381
+ timeout: expiresIn * 1e3
382
+ });
383
+ }, {
384
+ successMessage: "Authentication completed!",
385
+ errorMessage: "Authentication failed"
386
+ });
387
+ } catch (error) {
388
+ if (error instanceof Error && error.message.includes("timed out")) throw new Error("Authentication timed out. Please try again.");
389
+ throw error;
390
+ }
391
+ if (tokenResponse === void 0) throw new Error("Failed to retrieve authentication token.");
392
+ return tokenResponse;
393
+ }
394
+ async function saveAuthData(response) {
395
+ const expiresAt = Date.now() + response.expiresIn * 1e3;
396
+ await writeAuth({
397
+ accessToken: response.accessToken,
398
+ refreshToken: response.refreshToken,
399
+ expiresAt,
400
+ email: "user@base44.com",
401
+ name: "Base44 User"
402
+ });
403
+ }
404
+ async function login() {
405
+ const deviceCodeResponse = await generateAndDisplayDeviceCode();
406
+ await saveAuthData(await waitForAuthentication(deviceCodeResponse.deviceCode, deviceCodeResponse.expiresIn, deviceCodeResponse.interval));
407
+ log.success("Successfully logged in!");
408
+ }
409
+ const loginCommand = new Command("login").description("Authenticate with Base44").action(async () => {
410
+ await runCommand(login);
411
+ });
412
+
413
+ //#endregion
414
+ //#region src/cli/commands/auth/whoami.ts
415
+ async function whoami() {
416
+ const auth = await readAuth();
417
+ log.info(`Logged in as: ${auth.name} (${auth.email})`);
418
+ }
419
+ const whoamiCommand = new Command("whoami").description("Display current authenticated user").action(async () => {
420
+ await runCommand(whoami);
421
+ });
422
+
423
+ //#endregion
424
+ //#region src/cli/commands/auth/logout.ts
425
+ async function logout() {
426
+ await deleteAuth();
427
+ log.info("Logged out successfully");
428
+ }
429
+ const logoutCommand = new Command("logout").description("Logout from current device").action(async () => {
430
+ await runCommand(logout);
431
+ });
432
+
433
+ //#endregion
434
+ //#region src/core/resources/entity/schema.ts
435
+ const EntityPropertySchema = z.object({
436
+ type: z.string(),
437
+ description: z.string().optional(),
438
+ enum: z.array(z.string()).optional(),
439
+ default: z.union([
440
+ z.string(),
441
+ z.number(),
442
+ z.boolean()
443
+ ]).optional(),
444
+ format: z.string().optional(),
445
+ items: z.any().optional(),
446
+ relation: z.object({
447
+ entity: z.string(),
448
+ type: z.string()
449
+ }).optional()
450
+ });
451
+ const EntityPoliciesSchema = z.object({
452
+ read: z.string().optional(),
453
+ create: z.string().optional(),
454
+ update: z.string().optional(),
455
+ delete: z.string().optional()
456
+ });
457
+ const EntitySchema = z.object({
458
+ name: z.string().min(1, "Entity name cannot be empty"),
459
+ type: z.literal("object"),
460
+ properties: z.record(z.string(), EntityPropertySchema),
461
+ required: z.array(z.string()).optional(),
462
+ policies: EntityPoliciesSchema.optional()
463
+ });
464
+
465
+ //#endregion
466
+ //#region src/core/resources/entity/config.ts
467
+ async function readEntityFile(entityPath) {
468
+ const parsed = await readJsonFile(entityPath);
469
+ const result = EntitySchema.safeParse(parsed);
470
+ if (!result.success) throw new Error(`Invalid entity configuration in ${entityPath}: ${result.error.issues.map((e) => e.message).join(", ")}`);
471
+ return result.data;
472
+ }
473
+ async function readAllEntities(entitiesDir) {
474
+ if (!await pathExists(entitiesDir)) return [];
475
+ const files = await globby("*.{json,jsonc}", {
476
+ cwd: entitiesDir,
477
+ absolute: true
478
+ });
479
+ return await Promise.all(files.map((filePath) => readEntityFile(filePath)));
480
+ }
481
+
482
+ //#endregion
483
+ //#region src/core/resources/entity/resource.ts
484
+ const entityResource = { readAll: readAllEntities };
485
+
486
+ //#endregion
487
+ //#region src/core/resources/function/schema.ts
488
+ const HttpTriggerSchema = z.object({
489
+ id: z.string().optional(),
490
+ name: z.string().optional(),
491
+ description: z.string().optional(),
492
+ type: z.literal("http"),
493
+ path: z.string().min(1, "Path cannot be empty")
494
+ });
495
+ const ScheduleTriggerSchema = z.object({
496
+ id: z.string().optional(),
497
+ name: z.string().optional(),
498
+ description: z.string().optional(),
499
+ type: z.literal("schedule"),
500
+ scheduleMode: z.enum(["recurring", "once"]).optional(),
501
+ cron: z.string().min(1, "Cron expression cannot be empty"),
502
+ isActive: z.boolean().optional(),
503
+ timezone: z.string().optional()
504
+ });
505
+ const EventTriggerSchema = z.object({
506
+ id: z.string().optional(),
507
+ name: z.string().optional(),
508
+ description: z.string().optional(),
509
+ type: z.literal("event"),
510
+ entity: z.string().min(1, "Entity name cannot be empty"),
511
+ event: z.string().min(1, "Event type cannot be empty")
512
+ });
513
+ const TriggerSchema = z.discriminatedUnion("type", [
514
+ HttpTriggerSchema,
515
+ ScheduleTriggerSchema,
516
+ EventTriggerSchema
517
+ ]);
518
+ const FunctionConfigSchema = z.object({
519
+ entry: z.string().min(1, "Entry point cannot be empty"),
520
+ triggers: z.array(TriggerSchema).optional()
521
+ });
522
+
523
+ //#endregion
524
+ //#region src/core/resources/function/config.ts
525
+ async function readFunctionConfig(configPath) {
526
+ const parsed = await readJsonFile(configPath);
527
+ const result = FunctionConfigSchema.safeParse(parsed);
528
+ if (!result.success) throw new Error(`Invalid function configuration in ${configPath}: ${result.error.issues.map((e) => e.message).join(", ")}`);
529
+ return result.data;
530
+ }
531
+ async function readAllFunctions(functionsDir) {
532
+ if (!await pathExists(functionsDir)) return [];
533
+ const configFiles = await globby(`*/${FUNCTION_CONFIG_FILE}`, {
534
+ cwd: functionsDir,
535
+ absolute: true
536
+ });
537
+ return await Promise.all(configFiles.map((configPath) => readFunctionConfig(configPath)));
538
+ }
539
+
540
+ //#endregion
541
+ //#region src/core/resources/function/resource.ts
542
+ const functionResource = { readAll: readAllFunctions };
543
+
544
+ //#endregion
545
+ //#region src/core/config/project.ts
546
+ const ProjectConfigSchema = z.looseObject({
547
+ name: z.string().min(1, "Project name cannot be empty"),
548
+ entitySrc: z.string().default("./entities"),
549
+ functionSrc: z.string().default("./functions")
550
+ });
551
+ async function findConfigInDir(dir) {
552
+ return (await globby(getProjectConfigPatterns(), {
553
+ cwd: dir,
554
+ absolute: true
555
+ }))[0] ?? null;
556
+ }
557
+ async function findProjectRoot(startPath) {
558
+ let current = startPath || process.cwd();
559
+ while (current !== dirname(current)) {
560
+ const configPath = await findConfigInDir(current);
561
+ if (configPath) return {
562
+ root: current,
563
+ configPath
564
+ };
565
+ current = dirname(current);
566
+ }
567
+ return null;
568
+ }
569
+ async function readProjectConfig(projectRoot) {
570
+ let found;
571
+ if (projectRoot) {
572
+ const configPath$1 = await findConfigInDir(projectRoot);
573
+ found = configPath$1 ? {
574
+ root: projectRoot,
575
+ configPath: configPath$1
576
+ } : null;
577
+ } else found = await findProjectRoot();
578
+ if (!found) throw new Error(`Project root not found. Please ensure config.jsonc or config.json exists in the project directory or ${PROJECT_SUBDIR}/ subdirectory.`);
579
+ const { root, configPath } = found;
580
+ const parsed = await readJsonFile(configPath);
581
+ const result = ProjectConfigSchema.safeParse(parsed);
582
+ if (!result.success) {
583
+ const errors = result.error.issues.map((e) => e.message).join(", ");
584
+ throw new Error(`Invalid project configuration: ${errors}`);
585
+ }
586
+ const project = result.data;
587
+ const configDir = dirname(configPath);
588
+ const [entities, functions] = await Promise.all([entityResource.readAll(join(configDir, project.entitySrc)), functionResource.readAll(join(configDir, project.functionSrc))]);
589
+ return {
590
+ project: {
591
+ ...project,
592
+ root,
593
+ configPath
594
+ },
595
+ entities,
596
+ functions
597
+ };
598
+ }
599
+
600
+ //#endregion
601
+ //#region src/cli/commands/project/show-project.ts
602
+ async function showProject() {
603
+ const projectData = await runTask("Reading project configuration", async () => {
604
+ return await readProjectConfig();
605
+ }, {
606
+ successMessage: "Project configuration loaded",
607
+ errorMessage: "Failed to load project configuration"
608
+ });
609
+ const jsonOutput = JSON.stringify(projectData, null, 2);
610
+ log.info(jsonOutput);
611
+ }
612
+ const showProjectCommand = new Command("show-project").description("Display project configuration, entities, and functions").action(async () => {
613
+ await runCommand(showProject);
614
+ });
615
+
616
+ //#endregion
617
+ //#region package.json
618
+ var version = "0.0.1";
619
+
620
+ //#endregion
621
+ //#region src/cli/index.ts
622
+ const program = new Command();
623
+ program.name("base44").description("Base44 CLI - Unified interface for managing Base44 applications").version(version);
624
+ program.addCommand(loginCommand);
625
+ program.addCommand(whoamiCommand);
626
+ program.addCommand(logoutCommand);
627
+ program.addCommand(showProjectCommand);
628
+ program.parse();
629
+
630
+ //#endregion
631
+ export { };
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@base44-preview/cli",
3
+ "version": "0.0.1-pr.10.3124f70",
4
+ "description": "Base44 CLI - Unified interface for managing Base44 applications",
5
+ "type": "module",
6
+ "main": "./dist/cli/index.js",
7
+ "bin": "./dist/cli/index.js",
8
+ "exports": {
9
+ ".": "./dist/cli/index.js"
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "scripts": {
15
+ "build": "tsdown",
16
+ "typecheck": "tsc --noEmit",
17
+ "dev": "tsx src/cli/index.ts",
18
+ "start": "node dist/cli/index.js",
19
+ "clean": "rm -rf dist",
20
+ "lint": "eslint src",
21
+ "test": "vitest run",
22
+ "test:watch": "vitest"
23
+ },
24
+ "keywords": [
25
+ "base44",
26
+ "cli",
27
+ "command-line"
28
+ ],
29
+ "author": "",
30
+ "license": "ISC",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/base44/cli"
34
+ },
35
+ "dependencies": {
36
+ "@clack/prompts": "^0.11.0",
37
+ "chalk": "^5.6.2",
38
+ "commander": "^12.1.0",
39
+ "globby": "^16.1.0",
40
+ "jsonc-parser": "^3.3.1",
41
+ "ky": "^1.14.2",
42
+ "p-wait-for": "^6.0.0",
43
+ "zod": "^4.3.5"
44
+ },
45
+ "devDependencies": {
46
+ "@stylistic/eslint-plugin": "^5.6.1",
47
+ "@types/node": "^22.10.5",
48
+ "@typescript-eslint/eslint-plugin": "^8.51.0",
49
+ "@typescript-eslint/parser": "^8.51.0",
50
+ "eslint": "^9.39.2",
51
+ "eslint-plugin-import": "^2.32.0",
52
+ "eslint-plugin-unicorn": "^62.0.0",
53
+ "tsdown": "^0.12.4",
54
+ "tsx": "^4.19.2",
55
+ "typescript": "^5.7.2",
56
+ "typescript-eslint": "^8.52.0",
57
+ "vitest": "^4.0.16"
58
+ },
59
+ "engines": {
60
+ "node": ">=20.19.0"
61
+ }
62
+ }