@base44-preview/cli 0.0.1-pr.15.8b10ac1 → 0.0.1-pr.16.5e81288

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.
Files changed (22) hide show
  1. package/dist/cli/index.js +544 -363
  2. package/dist/cli/templates/backend-and-client/README.md +41 -0
  3. package/dist/cli/templates/backend-and-client/base44/config.jsonc.ejs +17 -0
  4. package/dist/cli/templates/backend-and-client/base44/entities/task.jsonc +16 -0
  5. package/dist/cli/templates/backend-and-client/components.json +16 -0
  6. package/dist/cli/templates/backend-and-client/index.html +13 -0
  7. package/dist/cli/templates/backend-and-client/jsconfig.json +13 -0
  8. package/dist/cli/templates/backend-and-client/package.json +24 -0
  9. package/dist/cli/templates/backend-and-client/postcss.config.js +6 -0
  10. package/dist/cli/templates/backend-and-client/src/App.jsx +135 -0
  11. package/dist/cli/templates/backend-and-client/src/api/base44Client.js.ejs +5 -0
  12. package/dist/cli/templates/backend-and-client/src/components/ui/button.jsx +23 -0
  13. package/dist/cli/templates/backend-and-client/src/components/ui/checkbox.jsx +20 -0
  14. package/dist/cli/templates/backend-and-client/src/components/ui/input.jsx +13 -0
  15. package/dist/cli/templates/backend-and-client/src/index.css +37 -0
  16. package/dist/cli/templates/backend-and-client/src/main.jsx +6 -0
  17. package/dist/cli/templates/backend-and-client/tailwind.config.js +41 -0
  18. package/dist/cli/templates/backend-and-client/vite.config.js +12 -0
  19. package/dist/cli/templates/backend-only/base44/.env.local.ejs +6 -0
  20. package/dist/cli/templates/backend-only/base44/config.jsonc.ejs +17 -0
  21. package/dist/cli/templates/templates.json +16 -0
  22. package/package.json +4 -1
package/dist/cli/index.js CHANGED
@@ -1,15 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from "commander";
3
3
  import chalk from "chalk";
4
- import { intro, log, spinner } from "@clack/prompts";
4
+ import { cancel, group, intro, log, select, spinner, text } from "@clack/prompts";
5
5
  import pWaitFor from "p-wait-for";
6
6
  import { z } from "zod";
7
- import { dirname, join } from "node:path";
7
+ import { dirname, join, resolve } from "node:path";
8
8
  import { homedir } from "node:os";
9
- import ky from "ky";
10
- import { access, mkdir, readFile, unlink, writeFile } from "node:fs/promises";
11
- import { parse, printParseErrorCode } from "jsonc-parser";
9
+ import { fileURLToPath } from "node:url";
10
+ import { config } from "dotenv";
12
11
  import { globby } from "globby";
12
+ import { access, copyFile, mkdir, readFile, unlink, writeFile } from "node:fs/promises";
13
+ import { parse, printParseErrorCode } from "jsonc-parser";
14
+ import ky from "ky";
15
+ import ejs from "ejs";
13
16
 
14
17
  //#region src/core/auth/schema.ts
15
18
  const AuthDataSchema = z.object({
@@ -73,116 +76,24 @@ var AuthValidationError = class extends Error {
73
76
  };
74
77
 
75
78
  //#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
- function getAppId() {
99
- const appId = process.env.BASE44_CLIENT_ID;
100
- if (!appId) throw new Error("BASE44_CLIENT_ID environment variable is not set");
101
- return appId;
102
- }
103
-
104
- //#endregion
105
- //#region src/core/auth/authClient.ts
106
- /**
107
- * Separate ky instance for OAuth endpoints.
108
- * These don't need Authorization headers (they use client_id + tokens in body).
109
- */
110
- const authClient = ky.create({
111
- prefixUrl: getBase44ApiUrl(),
112
- headers: { "User-Agent": "Base44 CLI" }
113
- });
114
- var authClient_default = authClient;
115
-
116
- //#endregion
117
- //#region src/core/auth/api.ts
118
- async function generateDeviceCode() {
119
- const response = await authClient_default.post("oauth/device/code", {
120
- json: {
121
- client_id: AUTH_CLIENT_ID,
122
- scope: "apps:read apps:write"
123
- },
124
- throwHttpErrors: false
125
- });
126
- if (!response.ok) throw new AuthApiError(`Failed to generate device code: ${response.status} ${response.statusText}`);
127
- const result = DeviceCodeResponseSchema.safeParse(await response.json());
128
- if (!result.success) throw new AuthValidationError(`Invalid device code response from server: ${result.error.message}`);
129
- return result.data;
130
- }
131
- async function getTokenFromDeviceCode(deviceCode) {
132
- const searchParams = new URLSearchParams();
133
- searchParams.set("grant_type", "urn:ietf:params:oauth:grant-type:device_code");
134
- searchParams.set("device_code", deviceCode);
135
- searchParams.set("client_id", AUTH_CLIENT_ID);
136
- const response = await authClient_default.post("oauth/token", {
137
- body: searchParams.toString(),
138
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
139
- throwHttpErrors: false
140
- });
141
- const json = await response.json();
142
- if (!response.ok) {
143
- const errorResult = OAuthErrorSchema.safeParse(json);
144
- if (!errorResult.success) throw new AuthValidationError(`Token request failed: ${errorResult.error.message}`);
145
- const { error, error_description } = errorResult.data;
146
- if (error === "authorization_pending" || error === "slow_down") return null;
147
- throw new AuthApiError(error_description ?? `OAuth error: ${error}`);
148
- }
149
- const result = TokenResponseSchema.safeParse(json);
150
- if (!result.success) throw new AuthValidationError(`Invalid token response from server: ${result.error.message}`);
151
- return result.data;
152
- }
153
- async function renewAccessToken(refreshToken) {
154
- const searchParams = new URLSearchParams();
155
- searchParams.set("grant_type", "refresh_token");
156
- searchParams.set("refresh_token", refreshToken);
157
- searchParams.set("client_id", AUTH_CLIENT_ID);
158
- const response = await authClient_default.post("oauth/token", {
159
- body: searchParams.toString(),
160
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
161
- throwHttpErrors: false
162
- });
163
- const json = await response.json();
164
- if (!response.ok) {
165
- const errorResult = OAuthErrorSchema.safeParse(json);
166
- if (!errorResult.success) throw new AuthApiError(`Token refresh failed: ${response.statusText}`);
167
- const { error, error_description } = errorResult.data;
168
- throw new AuthApiError(error_description ?? `OAuth error: ${error}`);
79
+ //#region src/core/utils/fs.ts
80
+ async function pathExists(path) {
81
+ try {
82
+ await access(path);
83
+ return true;
84
+ } catch {
85
+ return false;
169
86
  }
170
- const result = TokenResponseSchema.safeParse(json);
171
- if (!result.success) throw new AuthValidationError(`Invalid token response from server: ${result.error.message}`);
172
- return result.data;
173
87
  }
174
- async function getUserInfo(accessToken) {
175
- const response = await authClient_default.get("oauth/userinfo", { headers: { Authorization: `Bearer ${accessToken}` } });
176
- if (!response.ok) throw new AuthApiError(`Failed to fetch user info: ${response.status}`);
177
- const result = UserInfoSchema.safeParse(await response.json());
178
- if (!result.success) throw new AuthValidationError(`Invalid UserInfo response from server: ${result.error.message}`);
179
- return result.data;
88
+ async function writeFile$1(filePath, content) {
89
+ const dir = dirname(filePath);
90
+ if (!await pathExists(dir)) await mkdir(dir, { recursive: true });
91
+ await writeFile(filePath, content, "utf-8");
180
92
  }
181
-
182
- //#endregion
183
- //#region src/core/utils/fs.ts
184
- function pathExists(path) {
185
- return access(path).then(() => true).catch(() => false);
93
+ async function copyFile$1(src, dest) {
94
+ const dir = dirname(dest);
95
+ if (!await pathExists(dir)) await mkdir(dir, { recursive: true });
96
+ await copyFile(src, dest);
186
97
  }
187
98
  async function readJsonFile(filePath) {
188
99
  if (!await pathExists(filePath)) throw new Error(`File not found: ${filePath}`);
@@ -201,21 +112,67 @@ async function readJsonFile(filePath) {
201
112
  }
202
113
  }
203
114
  async function writeJsonFile(filePath, data) {
204
- try {
205
- const dir = dirname(filePath);
206
- if (!await pathExists(dir)) await mkdir(dir, { recursive: true });
207
- await writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
208
- } catch (error) {
209
- throw new Error(`Failed to write file ${filePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
210
- }
115
+ const dir = dirname(filePath);
116
+ if (!await pathExists(dir)) await mkdir(dir, { recursive: true });
117
+ await writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
211
118
  }
212
119
  async function deleteFile(filePath) {
213
120
  if (!await pathExists(filePath)) return;
214
- try {
215
- await unlink(filePath);
216
- } catch (error) {
217
- throw new Error(`Failed to delete file ${filePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
218
- }
121
+ await unlink(filePath);
122
+ }
123
+
124
+ //#endregion
125
+ //#region src/core/resources/entity/schema.ts
126
+ const EntityPropertySchema = z.object({
127
+ type: z.string(),
128
+ description: z.string().optional(),
129
+ enum: z.array(z.string()).optional(),
130
+ default: z.union([
131
+ z.string(),
132
+ z.number(),
133
+ z.boolean()
134
+ ]).optional(),
135
+ format: z.string().optional(),
136
+ items: z.any().optional(),
137
+ relation: z.object({
138
+ entity: z.string(),
139
+ type: z.string()
140
+ }).optional()
141
+ });
142
+ const EntityPoliciesSchema = z.object({
143
+ read: z.string().optional(),
144
+ create: z.string().optional(),
145
+ update: z.string().optional(),
146
+ delete: z.string().optional()
147
+ });
148
+ const EntitySchema = z.object({
149
+ name: z.string().min(1, "Entity name cannot be empty"),
150
+ type: z.literal("object"),
151
+ properties: z.record(z.string(), EntityPropertySchema),
152
+ required: z.array(z.string()).optional(),
153
+ policies: EntityPoliciesSchema.optional()
154
+ });
155
+ const SyncEntitiesResponseSchema = z.object({
156
+ created: z.array(z.string()),
157
+ updated: z.array(z.string()),
158
+ deleted: z.array(z.string())
159
+ });
160
+
161
+ //#endregion
162
+ //#region src/core/resources/entity/config.ts
163
+ async function readEntityFile(entityPath) {
164
+ const parsed = await readJsonFile(entityPath);
165
+ const result = EntitySchema.safeParse(parsed);
166
+ if (!result.success) throw new Error(`Invalid entity configuration in ${entityPath}: ${result.error.issues.map((e) => e.message).join(", ")}`);
167
+ return result.data;
168
+ }
169
+ async function readAllEntities(entitiesDir) {
170
+ if (!await pathExists(entitiesDir)) return [];
171
+ const files = await globby("*.{json,jsonc}", {
172
+ cwd: entitiesDir,
173
+ absolute: true
174
+ });
175
+ return await Promise.all(files.map((filePath) => readEntityFile(filePath)));
219
176
  }
220
177
 
221
178
  //#endregion
@@ -285,239 +242,62 @@ async function refreshAndSaveTokens() {
285
242
  }
286
243
 
287
244
  //#endregion
288
- //#region src/cli/utils/runCommand.ts
289
- const base44Color = chalk.bgHex("#E86B3C");
245
+ //#region src/core/utils/httpClient.ts
246
+ const retriedRequests = /* @__PURE__ */ new WeakSet();
290
247
  /**
291
- * Wraps a command function with the Base44 intro banner.
292
- * All CLI commands should use this utility to ensure consistent branding.
293
- *
294
- * @param commandFn - The async function to execute as the command
248
+ * Handles 401 responses by refreshing the token and retrying the request.
249
+ * Only retries once per request to prevent infinite loops.
295
250
  */
296
- async function runCommand(commandFn) {
297
- intro(base44Color(" Base 44 "));
298
- try {
299
- await commandFn();
300
- } catch (e) {
301
- if (e instanceof Error) log.error(e.stack ?? e.message);
302
- else log.error(String(e));
303
- process.exit(1);
304
- }
251
+ async function handleUnauthorized(request, _options, response) {
252
+ if (response.status !== 401) return;
253
+ if (retriedRequests.has(request)) return;
254
+ const newAccessToken = await refreshAndSaveTokens();
255
+ if (!newAccessToken) return;
256
+ retriedRequests.add(request);
257
+ return ky(request, { headers: { Authorization: `Bearer ${newAccessToken}` } });
305
258
  }
306
-
307
- //#endregion
308
- //#region src/cli/utils/runTask.ts
259
+ const base44Client = ky.create({
260
+ prefixUrl: getBase44ApiUrl(),
261
+ headers: { "User-Agent": "Base44 CLI" },
262
+ hooks: {
263
+ beforeRequest: [async (request) => {
264
+ try {
265
+ const auth = await readAuth();
266
+ if (isTokenExpired(auth)) {
267
+ const newAccessToken = await refreshAndSaveTokens();
268
+ if (newAccessToken) {
269
+ request.headers.set("Authorization", `Bearer ${newAccessToken}`);
270
+ return;
271
+ }
272
+ }
273
+ request.headers.set("Authorization", `Bearer ${auth.accessToken}`);
274
+ } catch {}
275
+ }],
276
+ afterResponse: [handleUnauthorized]
277
+ }
278
+ });
309
279
  /**
310
- * Wraps an async operation with automatic spinner management.
311
- * The spinner is automatically started, and stopped on both success and error.
312
- *
313
- * @param startMessage - Message to show when spinner starts
314
- * @param operation - The async operation to execute
315
- * @param options - Optional configuration
316
- * @returns The result of the operation
280
+ * Returns an HTTP client scoped to the current app.
317
281
  */
318
- async function runTask(startMessage, operation, options) {
319
- const s = spinner();
320
- s.start(startMessage);
321
- try {
322
- const result = await operation();
323
- s.stop(options?.successMessage || startMessage);
324
- return result;
325
- } catch (error) {
326
- s.stop(options?.errorMessage || "Failed");
327
- throw error;
328
- }
282
+ function getAppClient() {
283
+ return base44Client.extend({ prefixUrl: new URL(`/api/apps/${getBase44ClientId()}/`, getBase44ApiUrl()).href });
329
284
  }
330
285
 
331
286
  //#endregion
332
- //#region src/cli/commands/auth/login.ts
333
- async function generateAndDisplayDeviceCode() {
334
- const deviceCodeResponse = await runTask("Generating device code...", async () => {
335
- return await generateDeviceCode();
336
- }, {
337
- successMessage: "Device code generated",
338
- errorMessage: "Failed to generate device code"
287
+ //#region src/core/resources/entity/api.ts
288
+ async function pushEntities(entities) {
289
+ const appClient = getAppClient();
290
+ const schemaSyncPayload = Object.fromEntries(entities.map((entity) => [entity.name, entity]));
291
+ const response = await appClient.put("entities-schemas/sync-all", {
292
+ json: { entityNameToSchema: schemaSyncPayload },
293
+ throwHttpErrors: false
339
294
  });
340
- log.info(`Your code is: ${chalk.bold(deviceCodeResponse.userCode)}\nPlease visit: ${deviceCodeResponse.verificationUriComplete}`);
341
- return deviceCodeResponse;
342
- }
343
- async function waitForAuthentication(deviceCode, expiresIn, interval) {
344
- let tokenResponse;
345
- try {
346
- await runTask("Waiting for you to complete authentication...", async () => {
347
- await pWaitFor(async () => {
348
- const result = await getTokenFromDeviceCode(deviceCode);
349
- if (result !== null) {
350
- tokenResponse = result;
351
- return true;
352
- }
353
- return false;
354
- }, {
355
- interval: interval * 1e3,
356
- timeout: expiresIn * 1e3
357
- });
358
- }, {
359
- successMessage: "Authentication completed!",
360
- errorMessage: "Authentication failed"
361
- });
362
- } catch (error) {
363
- if (error instanceof Error && error.message.includes("timed out")) throw new Error("Authentication timed out. Please try again.");
364
- throw error;
365
- }
366
- if (tokenResponse === void 0) throw new Error("Failed to retrieve authentication token.");
367
- return tokenResponse;
368
- }
369
- async function saveAuthData(response, userInfo) {
370
- const expiresAt = Date.now() + response.expiresIn * 1e3;
371
- await writeAuth({
372
- accessToken: response.accessToken,
373
- refreshToken: response.refreshToken,
374
- expiresAt,
375
- email: userInfo.email,
376
- name: userInfo.name
377
- });
378
- }
379
- async function login() {
380
- const deviceCodeResponse = await generateAndDisplayDeviceCode();
381
- const token = await waitForAuthentication(deviceCodeResponse.deviceCode, deviceCodeResponse.expiresIn, deviceCodeResponse.interval);
382
- const userInfo = await getUserInfo(token.accessToken);
383
- await saveAuthData(token, userInfo);
384
- log.success(`Successfully logged in as ${chalk.bold(userInfo.email)}`);
385
- }
386
- const loginCommand = new Command("login").description("Authenticate with Base44").action(async () => {
387
- await runCommand(login);
388
- });
389
-
390
- //#endregion
391
- //#region src/cli/commands/auth/whoami.ts
392
- async function whoami() {
393
- const auth = await readAuth();
394
- log.info(`Logged in as: ${auth.name} (${auth.email})`);
395
- }
396
- const whoamiCommand = new Command("whoami").description("Display current authenticated user").action(async () => {
397
- await runCommand(whoami);
398
- });
399
-
400
- //#endregion
401
- //#region src/cli/commands/auth/logout.ts
402
- async function logout() {
403
- await deleteAuth();
404
- log.info("Logged out successfully");
405
- }
406
- const logoutCommand = new Command("logout").description("Logout from current device").action(async () => {
407
- await runCommand(logout);
408
- });
409
-
410
- //#endregion
411
- //#region src/core/resources/entity/schema.ts
412
- const EntityPropertySchema = z.object({
413
- type: z.string(),
414
- description: z.string().optional(),
415
- enum: z.array(z.string()).optional(),
416
- default: z.union([
417
- z.string(),
418
- z.number(),
419
- z.boolean()
420
- ]).optional(),
421
- format: z.string().optional(),
422
- items: z.any().optional(),
423
- relation: z.object({
424
- entity: z.string(),
425
- type: z.string()
426
- }).optional()
427
- });
428
- const EntityPoliciesSchema = z.object({
429
- read: z.string().optional(),
430
- create: z.string().optional(),
431
- update: z.string().optional(),
432
- delete: z.string().optional()
433
- });
434
- const EntitySchema = z.object({
435
- name: z.string().min(1, "Entity name cannot be empty"),
436
- type: z.literal("object"),
437
- properties: z.record(z.string(), EntityPropertySchema),
438
- required: z.array(z.string()).optional(),
439
- policies: EntityPoliciesSchema.optional()
440
- });
441
- const SyncEntitiesResponseSchema = z.object({
442
- created: z.array(z.string()),
443
- updated: z.array(z.string()),
444
- deleted: z.array(z.string())
445
- });
446
-
447
- //#endregion
448
- //#region src/core/resources/entity/config.ts
449
- async function readEntityFile(entityPath) {
450
- const parsed = await readJsonFile(entityPath);
451
- const result = EntitySchema.safeParse(parsed);
452
- if (!result.success) throw new Error(`Invalid entity configuration in ${entityPath}: ${result.error.issues.map((e) => e.message).join(", ")}`);
453
- return result.data;
454
- }
455
- async function readAllEntities(entitiesDir) {
456
- if (!await pathExists(entitiesDir)) return [];
457
- const files = await globby("*.{json,jsonc}", {
458
- cwd: entitiesDir,
459
- absolute: true
460
- });
461
- return await Promise.all(files.map((filePath) => readEntityFile(filePath)));
462
- }
463
-
464
- //#endregion
465
- //#region src/core/utils/httpClient.ts
466
- const retriedRequests = /* @__PURE__ */ new WeakSet();
467
- /**
468
- * Handles 401 responses by refreshing the token and retrying the request.
469
- * Only retries once per request to prevent infinite loops.
470
- */
471
- async function handleUnauthorized(request, _options, response) {
472
- if (response.status !== 401) return;
473
- if (retriedRequests.has(request)) return;
474
- const newAccessToken = await refreshAndSaveTokens();
475
- if (!newAccessToken) return;
476
- retriedRequests.add(request);
477
- return ky(request, { headers: { Authorization: `Bearer ${newAccessToken}` } });
478
- }
479
- const base44Client = ky.create({
480
- prefixUrl: getBase44ApiUrl(),
481
- headers: { "User-Agent": "Base44 CLI" },
482
- hooks: {
483
- beforeRequest: [async (request) => {
484
- try {
485
- const auth = await readAuth();
486
- if (isTokenExpired(auth)) {
487
- const newAccessToken = await refreshAndSaveTokens();
488
- if (newAccessToken) {
489
- request.headers.set("Authorization", `Bearer ${newAccessToken}`);
490
- return;
491
- }
492
- }
493
- request.headers.set("Authorization", `Bearer ${auth.accessToken}`);
494
- } catch {}
495
- }],
496
- afterResponse: [handleUnauthorized]
497
- }
498
- });
499
- /**
500
- * Returns an HTTP client scoped to the current app.
501
- */
502
- function getAppClient() {
503
- return base44Client.extend({ prefixUrl: new URL(`/api/apps/${getAppId()}/`, getBase44ApiUrl()).href });
504
- }
505
-
506
- //#endregion
507
- //#region src/core/resources/entity/api.ts
508
- async function pushEntities(entities) {
509
- const appClient = getAppClient();
510
- const schemaSyncPayload = Object.fromEntries(entities.map((entity) => [entity.name, entity]));
511
- const response = await appClient.put("entities-schemas/sync-all", {
512
- json: { entityNameToSchema: schemaSyncPayload },
513
- throwHttpErrors: false
514
- });
515
- if (!response.ok) {
516
- const errorJson = await response.json();
517
- if (response.status === 428) throw new Error(`Failed to delete entity: ${errorJson.message}`);
518
- throw new Error(`Error occurred while syncing entities ${errorJson.message}`);
519
- }
520
- return SyncEntitiesResponseSchema.parse(await response.json());
295
+ if (!response.ok) {
296
+ const errorJson = await response.json();
297
+ if (response.status === 428) throw new Error(`Failed to delete entity: ${errorJson.message}`);
298
+ throw new Error(`Error occurred while syncing entities ${errorJson.message}`);
299
+ }
300
+ return SyncEntitiesResponseSchema.parse(await response.json());
521
301
  }
522
302
 
523
303
  //#endregion
@@ -641,6 +421,365 @@ async function readProjectConfig(projectRoot) {
641
421
  };
642
422
  }
643
423
 
424
+ //#endregion
425
+ //#region src/core/project/schema.ts
426
+ const TemplateSchema = z.object({
427
+ id: z.string(),
428
+ name: z.string(),
429
+ description: z.string(),
430
+ path: z.string()
431
+ });
432
+ const TemplatesConfigSchema = z.object({ templates: z.array(TemplateSchema) });
433
+ const SiteConfigSchema = z.object({
434
+ buildCommand: z.string().optional(),
435
+ serveCommand: z.string().optional(),
436
+ outputDirectory: z.string().optional(),
437
+ installCommand: z.string().optional()
438
+ });
439
+ const AppConfigSchema = z.object({
440
+ name: z.string().min(1, "App name cannot be empty"),
441
+ description: z.string().optional(),
442
+ site: SiteConfigSchema.optional(),
443
+ domains: z.array(z.string()).optional()
444
+ });
445
+ const CreateProjectResponseSchema = z.looseObject({ id: z.string() });
446
+
447
+ //#endregion
448
+ //#region src/core/project/api.ts
449
+ async function createProject(projectName, description) {
450
+ const response = await base44Client.post("api/apps", { json: {
451
+ name: projectName,
452
+ user_description: description ?? `Backend for '${projectName}'`,
453
+ app_type: "baas"
454
+ } });
455
+ return { projectId: CreateProjectResponseSchema.parse(await response.json()).id };
456
+ }
457
+
458
+ //#endregion
459
+ //#region src/core/project/template.ts
460
+ async function listTemplates() {
461
+ const parsed = await readJsonFile(join(getTemplatesDir(), "templates.json"));
462
+ return TemplatesConfigSchema.parse(parsed).templates;
463
+ }
464
+ /**
465
+ * Render a template directory to a destination path.
466
+ * - Files ending in .ejs are rendered with EJS and written without the .ejs extension
467
+ * - All other files are copied directly
468
+ */
469
+ async function renderTemplate(template, destPath, data) {
470
+ const templateDir = join(getTemplatesDir(), template.path);
471
+ const files = await globby("**/*", {
472
+ cwd: templateDir,
473
+ dot: true,
474
+ onlyFiles: true
475
+ });
476
+ for (const file of files) {
477
+ const srcPath = join(templateDir, file);
478
+ if (file.endsWith(".ejs")) await writeFile$1(join(destPath, file.slice(0, -4)), await ejs.renderFile(srcPath, data));
479
+ else await copyFile$1(srcPath, join(destPath, file));
480
+ }
481
+ }
482
+
483
+ //#endregion
484
+ //#region src/core/project/create.ts
485
+ async function createProjectFiles(options) {
486
+ const { name, description, path: basePath, template } = options;
487
+ const existingConfigs = await globby(getProjectConfigPatterns(), {
488
+ cwd: basePath,
489
+ absolute: true
490
+ });
491
+ if (existingConfigs.length > 0) throw new Error(`A Base44 project already exists at ${existingConfigs[0]}. Please choose a different location.`);
492
+ const { projectId } = await createProject(name, description);
493
+ await renderTemplate(template, basePath, {
494
+ name,
495
+ description,
496
+ projectId
497
+ });
498
+ return { projectDir: basePath };
499
+ }
500
+
501
+ //#endregion
502
+ //#region src/core/config.ts
503
+ const __dirname = dirname(fileURLToPath(import.meta.url));
504
+ const PROJECT_SUBDIR = "base44";
505
+ const FUNCTION_CONFIG_FILE = "function.jsonc";
506
+ const AUTH_CLIENT_ID = "base44_cli";
507
+ function getBase44Dir() {
508
+ return join(homedir(), ".base44");
509
+ }
510
+ function getAuthFilePath() {
511
+ return join(getBase44Dir(), "auth", "auth.json");
512
+ }
513
+ function getTemplatesDir() {
514
+ return join(__dirname, "templates");
515
+ }
516
+ function getProjectConfigPatterns() {
517
+ return [
518
+ `${PROJECT_SUBDIR}/config.jsonc`,
519
+ `${PROJECT_SUBDIR}/config.json`,
520
+ "config.jsonc",
521
+ "config.json"
522
+ ];
523
+ }
524
+ /**
525
+ * Load .env.local from the project root if it exists.
526
+ * Values won't override existing process.env variables.
527
+ * Safe to call multiple times - only loads once.
528
+ */
529
+ async function loadProjectEnv(projectRoot) {
530
+ const found = projectRoot ? { root: projectRoot } : await findProjectRoot();
531
+ if (!found) return;
532
+ config({
533
+ path: join(found.root, PROJECT_SUBDIR, ".env.local"),
534
+ override: false,
535
+ quiet: true
536
+ });
537
+ }
538
+ /**
539
+ * Get the Base44 API URL.
540
+ * Priority: process.env.BASE44_API_URL > .env.local > default
541
+ */
542
+ function getBase44ApiUrl() {
543
+ return process.env.BASE44_API_URL || "https://app.base44.com";
544
+ }
545
+ /**
546
+ * Get the Base44 Client ID (app ID).
547
+ * Priority: process.env.BASE44_CLIENT_ID > .env.local
548
+ * Returns undefined if not set.
549
+ */
550
+ function getBase44ClientId() {
551
+ return process.env.BASE44_CLIENT_ID;
552
+ }
553
+
554
+ //#endregion
555
+ //#region src/core/auth/authClient.ts
556
+ /**
557
+ * Separate ky instance for OAuth endpoints.
558
+ * These don't need Authorization headers (they use client_id + tokens in body).
559
+ */
560
+ const authClient = ky.create({
561
+ prefixUrl: getBase44ApiUrl(),
562
+ headers: { "User-Agent": "Base44 CLI" }
563
+ });
564
+ var authClient_default = authClient;
565
+
566
+ //#endregion
567
+ //#region src/core/auth/api.ts
568
+ async function generateDeviceCode() {
569
+ const response = await authClient_default.post("oauth/device/code", {
570
+ json: {
571
+ client_id: AUTH_CLIENT_ID,
572
+ scope: "apps:read apps:write"
573
+ },
574
+ throwHttpErrors: false
575
+ });
576
+ if (!response.ok) throw new AuthApiError(`Failed to generate device code: ${response.status} ${response.statusText}`);
577
+ const result = DeviceCodeResponseSchema.safeParse(await response.json());
578
+ if (!result.success) throw new AuthValidationError(`Invalid device code response from server: ${result.error.message}`);
579
+ return result.data;
580
+ }
581
+ async function getTokenFromDeviceCode(deviceCode) {
582
+ const searchParams = new URLSearchParams();
583
+ searchParams.set("grant_type", "urn:ietf:params:oauth:grant-type:device_code");
584
+ searchParams.set("device_code", deviceCode);
585
+ searchParams.set("client_id", AUTH_CLIENT_ID);
586
+ const response = await authClient_default.post("oauth/token", {
587
+ body: searchParams.toString(),
588
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
589
+ throwHttpErrors: false
590
+ });
591
+ const json = await response.json();
592
+ if (!response.ok) {
593
+ const errorResult = OAuthErrorSchema.safeParse(json);
594
+ if (!errorResult.success) throw new AuthValidationError(`Token request failed: ${errorResult.error.message}`);
595
+ const { error, error_description } = errorResult.data;
596
+ if (error === "authorization_pending" || error === "slow_down") return null;
597
+ throw new AuthApiError(error_description ?? `OAuth error: ${error}`);
598
+ }
599
+ const result = TokenResponseSchema.safeParse(json);
600
+ if (!result.success) throw new AuthValidationError(`Invalid token response from server: ${result.error.message}`);
601
+ return result.data;
602
+ }
603
+ async function renewAccessToken(refreshToken) {
604
+ const searchParams = new URLSearchParams();
605
+ searchParams.set("grant_type", "refresh_token");
606
+ searchParams.set("refresh_token", refreshToken);
607
+ searchParams.set("client_id", AUTH_CLIENT_ID);
608
+ const response = await authClient_default.post("oauth/token", {
609
+ body: searchParams.toString(),
610
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
611
+ throwHttpErrors: false
612
+ });
613
+ const json = await response.json();
614
+ if (!response.ok) {
615
+ const errorResult = OAuthErrorSchema.safeParse(json);
616
+ if (!errorResult.success) throw new AuthApiError(`Token refresh failed: ${response.statusText}`);
617
+ const { error, error_description } = errorResult.data;
618
+ throw new AuthApiError(error_description ?? `OAuth error: ${error}`);
619
+ }
620
+ const result = TokenResponseSchema.safeParse(json);
621
+ if (!result.success) throw new AuthValidationError(`Invalid token response from server: ${result.error.message}`);
622
+ return result.data;
623
+ }
624
+ async function getUserInfo(accessToken) {
625
+ const response = await authClient_default.get("oauth/userinfo", { headers: { Authorization: `Bearer ${accessToken}` } });
626
+ if (!response.ok) throw new AuthApiError(`Failed to fetch user info: ${response.status}`);
627
+ const result = UserInfoSchema.safeParse(await response.json());
628
+ if (!result.success) throw new AuthValidationError(`Invalid UserInfo response from server: ${result.error.message}`);
629
+ return result.data;
630
+ }
631
+
632
+ //#endregion
633
+ //#region src/cli/utils/runCommand.ts
634
+ const base44Color = chalk.bgHex("#E86B3C");
635
+ /**
636
+ * Wraps a command function with the Base44 intro banner.
637
+ * All CLI commands should use this utility to ensure consistent branding.
638
+ * Also loads .env.local from the project root if available.
639
+ *
640
+ * @param commandFn - The async function to execute as the command
641
+ */
642
+ async function runCommand(commandFn) {
643
+ intro(base44Color(" Base 44 "));
644
+ await loadProjectEnv();
645
+ try {
646
+ await commandFn();
647
+ } catch (e) {
648
+ if (e instanceof Error) log.error(e.stack ?? e.message);
649
+ else log.error(String(e));
650
+ process.exit(1);
651
+ }
652
+ }
653
+
654
+ //#endregion
655
+ //#region src/cli/utils/runTask.ts
656
+ /**
657
+ * Wraps an async operation with automatic spinner management.
658
+ * The spinner is automatically started, and stopped on both success and error.
659
+ *
660
+ * @param startMessage - Message to show when spinner starts
661
+ * @param operation - The async operation to execute
662
+ * @param options - Optional configuration
663
+ * @returns The result of the operation
664
+ */
665
+ async function runTask(startMessage, operation, options) {
666
+ const s = spinner();
667
+ s.start(startMessage);
668
+ try {
669
+ const result = await operation();
670
+ s.stop(options?.successMessage || startMessage);
671
+ return result;
672
+ } catch (error) {
673
+ s.stop(options?.errorMessage || "Failed");
674
+ throw error;
675
+ }
676
+ }
677
+
678
+ //#endregion
679
+ //#region src/cli/utils/prompts.ts
680
+ /**
681
+ * Standard onCancel handler for prompt groups.
682
+ * Exits the process gracefully when the user cancels.
683
+ */
684
+ const onPromptCancel = () => {
685
+ cancel("Operation cancelled.");
686
+ process.exit(0);
687
+ };
688
+
689
+ //#endregion
690
+ //#region src/cli/utils/banner.ts
691
+ const orange = chalk.hex("#E86B3C");
692
+ const BANNER = `
693
+ ${orange("██████╗ █████╗ ███████╗███████╗ ██╗ ██╗██╗ ██╗")}
694
+ ${orange("██╔══██╗██╔══██╗██╔════╝██╔════╝ ██║ ██║██║ ██║")}
695
+ ${orange("██████╔╝███████║███████╗█████╗ ███████║███████║")}
696
+ ${orange("██╔══██╗██╔══██║╚════██║██╔══╝ ╚════██║╚════██║")}
697
+ ${orange("██████╔╝██║ ██║███████║███████╗ ██║ ██║")}
698
+ ${orange("╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═╝")}
699
+ `;
700
+ function printBanner() {
701
+ console.log(BANNER);
702
+ }
703
+
704
+ //#endregion
705
+ //#region src/cli/commands/auth/login.ts
706
+ async function generateAndDisplayDeviceCode() {
707
+ const deviceCodeResponse = await runTask("Generating device code...", async () => {
708
+ return await generateDeviceCode();
709
+ }, {
710
+ successMessage: "Device code generated",
711
+ errorMessage: "Failed to generate device code"
712
+ });
713
+ log.info(`Your code is: ${chalk.bold(deviceCodeResponse.userCode)}\nPlease visit: ${deviceCodeResponse.verificationUriComplete}`);
714
+ return deviceCodeResponse;
715
+ }
716
+ async function waitForAuthentication(deviceCode, expiresIn, interval) {
717
+ let tokenResponse;
718
+ try {
719
+ await runTask("Waiting for you to complete authentication...", async () => {
720
+ await pWaitFor(async () => {
721
+ const result = await getTokenFromDeviceCode(deviceCode);
722
+ if (result !== null) {
723
+ tokenResponse = result;
724
+ return true;
725
+ }
726
+ return false;
727
+ }, {
728
+ interval: interval * 1e3,
729
+ timeout: expiresIn * 1e3
730
+ });
731
+ }, {
732
+ successMessage: "Authentication completed!",
733
+ errorMessage: "Authentication failed"
734
+ });
735
+ } catch (error) {
736
+ if (error instanceof Error && error.message.includes("timed out")) throw new Error("Authentication timed out. Please try again.");
737
+ throw error;
738
+ }
739
+ if (tokenResponse === void 0) throw new Error("Failed to retrieve authentication token.");
740
+ return tokenResponse;
741
+ }
742
+ async function saveAuthData(response, userInfo) {
743
+ const expiresAt = Date.now() + response.expiresIn * 1e3;
744
+ await writeAuth({
745
+ accessToken: response.accessToken,
746
+ refreshToken: response.refreshToken,
747
+ expiresAt,
748
+ email: userInfo.email,
749
+ name: userInfo.name
750
+ });
751
+ }
752
+ async function login() {
753
+ const deviceCodeResponse = await generateAndDisplayDeviceCode();
754
+ const token = await waitForAuthentication(deviceCodeResponse.deviceCode, deviceCodeResponse.expiresIn, deviceCodeResponse.interval);
755
+ const userInfo = await getUserInfo(token.accessToken);
756
+ await saveAuthData(token, userInfo);
757
+ log.success(`Successfully logged in as ${chalk.bold(userInfo.email)}`);
758
+ }
759
+ const loginCommand = new Command("login").description("Authenticate with Base44").action(async () => {
760
+ await runCommand(login);
761
+ });
762
+
763
+ //#endregion
764
+ //#region src/cli/commands/auth/whoami.ts
765
+ async function whoami() {
766
+ const auth = await readAuth();
767
+ log.info(`Logged in as: ${auth.name} (${auth.email})`);
768
+ }
769
+ const whoamiCommand = new Command("whoami").description("Display current authenticated user").action(async () => {
770
+ await runCommand(whoami);
771
+ });
772
+
773
+ //#endregion
774
+ //#region src/cli/commands/auth/logout.ts
775
+ async function logout() {
776
+ await deleteAuth();
777
+ log.info("Logged out successfully");
778
+ }
779
+ const logoutCommand = new Command("logout").description("Logout from current device").action(async () => {
780
+ await runCommand(logout);
781
+ });
782
+
644
783
  //#endregion
645
784
  //#region src/cli/commands/project/show-project.ts
646
785
  async function showProject() {
@@ -657,21 +796,6 @@ const showProjectCommand = new Command("show-project").description("Display proj
657
796
  await runCommand(showProject);
658
797
  });
659
798
 
660
- //#endregion
661
- //#region src/core/project/schema.ts
662
- const SiteConfigSchema = z.object({
663
- buildCommand: z.string().optional(),
664
- serveCommand: z.string().optional(),
665
- outputDirectory: z.string().optional(),
666
- installCommand: z.string().optional()
667
- });
668
- const AppConfigSchema = z.object({
669
- name: z.string().min(1, "App name cannot be empty"),
670
- description: z.string().optional(),
671
- site: SiteConfigSchema.optional(),
672
- domains: z.array(z.string()).optional()
673
- });
674
-
675
799
  //#endregion
676
800
  //#region src/cli/commands/entities/push.ts
677
801
  async function pushEntitiesAction() {
@@ -696,6 +820,62 @@ const entitiesPushCommand = new Command("entities").description("Manage project
696
820
  await runCommand(pushEntitiesAction);
697
821
  }));
698
822
 
823
+ //#endregion
824
+ //#region src/cli/commands/project/create.ts
825
+ async function create() {
826
+ printBanner();
827
+ await loadProjectEnv();
828
+ const templateOptions = (await listTemplates()).map((t) => ({
829
+ value: t,
830
+ label: t.name,
831
+ hint: t.description
832
+ }));
833
+ const { template, name, description, projectPath } = await group({
834
+ template: () => select({
835
+ message: "Select a project template",
836
+ options: templateOptions
837
+ }),
838
+ name: () => text({
839
+ message: "What is the name of your project?",
840
+ placeholder: "my-app-backend",
841
+ validate: (value) => {
842
+ if (!value || value.trim().length === 0) return "Project name is required";
843
+ }
844
+ }),
845
+ description: () => text({
846
+ message: "Project description (optional)",
847
+ placeholder: "A brief description of your project"
848
+ }),
849
+ projectPath: () => text({
850
+ message: "Where should we create the base44 folder?",
851
+ placeholder: "./",
852
+ initialValue: "./"
853
+ })
854
+ }, { onCancel: onPromptCancel });
855
+ const resolvedPath = resolve(projectPath || "./");
856
+ await runTask("Creating project...", async () => {
857
+ return await createProjectFiles({
858
+ name: name.trim(),
859
+ description: description ? description.trim() : void 0,
860
+ path: resolvedPath,
861
+ template
862
+ });
863
+ }, {
864
+ successMessage: "Project created successfully",
865
+ errorMessage: "Failed to create project"
866
+ });
867
+ log.success(`Project ${chalk.bold(name)} has been initialized!`);
868
+ }
869
+ const createCommand = new Command("create").description("Create a new Base44 project").action(async () => {
870
+ try {
871
+ await create();
872
+ } catch (e) {
873
+ if (e instanceof Error) log.error(e.stack ?? e.message);
874
+ else log.error(String(e));
875
+ process.exit(1);
876
+ }
877
+ });
878
+
699
879
  //#endregion
700
880
  //#region package.json
701
881
  var version = "0.0.1";
@@ -707,6 +887,7 @@ program.name("base44").description("Base44 CLI - Unified interface for managing
707
887
  program.addCommand(loginCommand);
708
888
  program.addCommand(whoamiCommand);
709
889
  program.addCommand(logoutCommand);
890
+ program.addCommand(createCommand);
710
891
  program.addCommand(showProjectCommand);
711
892
  program.addCommand(entitiesPushCommand);
712
893
  program.parse();