create-mastra 0.16.0-alpha.1 → 0.17.0-alpha.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/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #! /usr/bin/env node
2
2
  import { Command } from 'commander';
3
3
  import { randomUUID } from 'node:crypto';
4
- import * as fs4__default from 'node:fs';
5
- import fs4__default__default, { existsSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import * as fs3__default from 'node:fs';
5
+ import fs3__default__default, { existsSync, readFileSync, writeFileSync } from 'node:fs';
6
6
  import os from 'node:os';
7
- import path3, { dirname } from 'node:path';
7
+ import path, { dirname } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { PostHog } from 'posthog-node';
10
10
  import util, { stripVTControlCharacters } from 'node:util';
@@ -12,18 +12,18 @@ import y$1, { stdout, stdin } from 'node:process';
12
12
  import * as g from 'node:readline';
13
13
  import g__default from 'node:readline';
14
14
  import { Writable } from 'node:stream';
15
- import fs5 from 'node:fs/promises';
15
+ import fs4 from 'node:fs/promises';
16
16
  import child_process from 'node:child_process';
17
17
  import tty from 'node:tty';
18
- import pino from 'pino';
19
- import pretty from 'pino-pretty';
20
- import { execa } from 'execa';
21
18
  import fsExtra, { readJSON, ensureFile, writeJSON } from 'fs-extra/esm';
22
19
  import prettier from 'prettier';
20
+ import { execa } from 'execa';
21
+ import pino from 'pino';
22
+ import pretty from 'pino-pretty';
23
23
  import fsExtra$1 from 'fs-extra';
24
24
 
25
25
  var __filename = fileURLToPath(import.meta.url);
26
- var __dirname = path3.dirname(__filename);
26
+ var __dirname = path.dirname(__filename);
27
27
  var analyticsInstance = null;
28
28
  function getAnalytics() {
29
29
  return analyticsInstance;
@@ -39,7 +39,7 @@ var PosthogAnalytics = class {
39
39
  host = "https://app.posthog.com"
40
40
  }) {
41
41
  this.version = version;
42
- const cliConfigPath = path3.join(__dirname, "mastra-cli.json");
42
+ const cliConfigPath = path.join(__dirname, "mastra-cli.json");
43
43
  if (existsSync(cliConfigPath)) {
44
44
  try {
45
45
  const { distinctId, sessionId } = JSON.parse(readFileSync(cliConfigPath, "utf-8"));
@@ -67,7 +67,7 @@ var PosthogAnalytics = class {
67
67
  }
68
68
  writeCliConfig({ distinctId, sessionId }) {
69
69
  try {
70
- writeFileSync(path3.join(__dirname, "mastra-cli.json"), JSON.stringify({ distinctId, sessionId }));
70
+ writeFileSync(path.join(__dirname, "mastra-cli.json"), JSON.stringify({ distinctId, sessionId }));
71
71
  } catch {
72
72
  }
73
73
  }
@@ -422,7 +422,7 @@ ${color2.gray(d)} ${t}
422
422
  `):process.stdout.write(`${w} ${l}
423
423
  `),E(),s();};return {start:H,stop:N,message:(m="")=>{l=R(m??l);}}},Ce=async(t,n)=>{const r={},i=Object.keys(t);for(const s of i){const c=t[s],a=await c({results:r})?.catch(l=>{throw l});if(typeof n?.onCancel=="function"&&pD(a)){r[s]="canceled",n.onCancel({results:r});continue}r[s]=a;}return r};
424
424
 
425
- var shellQuote$1 = {};
425
+ var shellQuote = {};
426
426
 
427
427
  var quote;
428
428
  var hasRequiredQuote;
@@ -688,16 +688,16 @@ function requireParse () {
688
688
  var hasRequiredShellQuote;
689
689
 
690
690
  function requireShellQuote () {
691
- if (hasRequiredShellQuote) return shellQuote$1;
691
+ if (hasRequiredShellQuote) return shellQuote;
692
692
  hasRequiredShellQuote = 1;
693
693
 
694
- shellQuote$1.quote = requireQuote();
695
- shellQuote$1.parse = requireParse();
696
- return shellQuote$1;
694
+ shellQuote.quote = requireQuote();
695
+ shellQuote.parse = requireParse();
696
+ return shellQuote;
697
697
  }
698
698
 
699
699
  var shellQuoteExports = requireShellQuote();
700
- var shellQuote = /*@__PURE__*/getDefaultExportFromCjs(shellQuoteExports);
700
+ var shellQuote2 = /*@__PURE__*/getDefaultExportFromCjs(shellQuoteExports);
701
701
 
702
702
  // eslint-disable-next-line no-warning-comments
703
703
  // TODO: Use a better method when it's added to Node.js (https://github.com/nodejs/node/pull/40240)
@@ -724,18 +724,13 @@ const format = (open, close) => {
724
724
  // Handle nested colors.
725
725
 
726
726
  // We could have done this, but it's too slow (as of Node.js 22).
727
- // return openCode + string.replaceAll(closeCode, (close === 22 ? closeCode : '') + openCode) + closeCode;
727
+ // return openCode + string.replaceAll(closeCode, openCode) + closeCode;
728
728
 
729
729
  let result = openCode;
730
730
  let lastIndex = 0;
731
731
 
732
- // SGR 22 resets both bold (1) and dim (2). When we encounter a nested
733
- // close for styles that use 22, we need to re-open the outer style.
734
- const reopenOnNestedClose = close === 22;
735
- const replaceCode = (reopenOnNestedClose ? closeCode : '') + openCode;
736
-
737
732
  while (index !== -1) {
738
- result += string.slice(lastIndex, index) + replaceCode;
733
+ result += string.slice(lastIndex, index) + openCode;
739
734
  lastIndex = index + closeCode.length;
740
735
  index = string.indexOf(closeCode, lastIndex);
741
736
  }
@@ -1178,282 +1173,6 @@ var PinoLogger = class extends MastraLogger {
1178
1173
  }
1179
1174
  };
1180
1175
 
1181
- function getPackageManager() {
1182
- const userAgent = process.env.npm_config_user_agent || "";
1183
- const execPath = process.env.npm_execpath || "";
1184
- if (userAgent.includes("yarn")) {
1185
- return "yarn";
1186
- }
1187
- if (userAgent.includes("pnpm")) {
1188
- return "pnpm";
1189
- }
1190
- if (userAgent.includes("npm")) {
1191
- return "npm";
1192
- }
1193
- if (execPath.includes("yarn")) {
1194
- return "yarn";
1195
- }
1196
- if (execPath.includes("pnpm")) {
1197
- return "pnpm";
1198
- }
1199
- if (execPath.includes("npm")) {
1200
- return "npm";
1201
- }
1202
- return "npm";
1203
- }
1204
- var logger = createLogger(false);
1205
- function createLogger(debug = false) {
1206
- return new PinoLogger({
1207
- name: "Mastra CLI",
1208
- level: debug ? "debug" : "info"
1209
- });
1210
- }
1211
- var exec = util.promisify(child_process.exec);
1212
- async function cloneTemplate(options) {
1213
- const { template, projectName, targetDir } = options;
1214
- const projectPath = targetDir ? path3.resolve(targetDir, projectName) : path3.resolve(projectName);
1215
- const spinner5 = yoctoSpinner({ text: `Cloning template "${template.title}"...` }).start();
1216
- try {
1217
- if (await directoryExists(projectPath)) {
1218
- spinner5.error(`Directory ${projectName} already exists`);
1219
- throw new Error(`Directory ${projectName} already exists`);
1220
- }
1221
- await cloneRepositoryWithoutGit(template.githubUrl, projectPath);
1222
- await updatePackageJson(projectPath, projectName);
1223
- const envExamplePath = path3.join(projectPath, ".env.example");
1224
- if (await fileExists(envExamplePath)) {
1225
- await fs5.copyFile(envExamplePath, path3.join(projectPath, ".env"));
1226
- }
1227
- spinner5.success(`Template "${template.title}" cloned successfully to ${projectName}`);
1228
- return projectPath;
1229
- } catch (error) {
1230
- spinner5.error(`Failed to clone template: ${error instanceof Error ? error.message : "Unknown error"}`);
1231
- throw error;
1232
- }
1233
- }
1234
- async function directoryExists(dirPath) {
1235
- try {
1236
- const stat = await fs5.stat(dirPath);
1237
- return stat.isDirectory();
1238
- } catch {
1239
- return false;
1240
- }
1241
- }
1242
- async function fileExists(filePath) {
1243
- try {
1244
- const stat = await fs5.stat(filePath);
1245
- return stat.isFile();
1246
- } catch {
1247
- return false;
1248
- }
1249
- }
1250
- async function cloneRepositoryWithoutGit(repoUrl, targetPath) {
1251
- await fs5.mkdir(targetPath, { recursive: true });
1252
- try {
1253
- const degitRepo = repoUrl.replace("https://github.com/", "");
1254
- const degitCommand = shellQuote.quote(["npx", "degit", degitRepo, targetPath]);
1255
- await exec(degitCommand, {
1256
- cwd: process.cwd()
1257
- });
1258
- } catch {
1259
- try {
1260
- const gitCommand = shellQuote.quote(["git", "clone", repoUrl, targetPath]);
1261
- await exec(gitCommand, {
1262
- cwd: process.cwd()
1263
- });
1264
- const gitDir = path3.join(targetPath, ".git");
1265
- if (await directoryExists(gitDir)) {
1266
- await fs5.rm(gitDir, { recursive: true, force: true });
1267
- }
1268
- } catch (gitError) {
1269
- throw new Error(`Failed to clone repository: ${gitError instanceof Error ? gitError.message : "Unknown error"}`);
1270
- }
1271
- }
1272
- }
1273
- async function updatePackageJson(projectPath, projectName) {
1274
- const packageJsonPath = path3.join(projectPath, "package.json");
1275
- try {
1276
- const packageJsonContent = await fs5.readFile(packageJsonPath, "utf-8");
1277
- const packageJson = JSON.parse(packageJsonContent);
1278
- packageJson.name = projectName;
1279
- await fs5.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2), "utf-8");
1280
- } catch (error) {
1281
- logger.warn(`Could not update package.json: ${error instanceof Error ? error.message : "Unknown error"}`);
1282
- }
1283
- }
1284
- async function installDependencies(projectPath, packageManager) {
1285
- const spinner5 = yoctoSpinner({ text: "Installing dependencies..." }).start();
1286
- try {
1287
- const pm = packageManager || getPackageManager();
1288
- const installCommand = shellQuote.quote([pm, "install"]);
1289
- await exec(installCommand, {
1290
- cwd: projectPath
1291
- });
1292
- spinner5.success("Dependencies installed successfully");
1293
- } catch (error) {
1294
- spinner5.error(`Failed to install dependencies: ${error instanceof Error ? error.message : "Unknown error"}`);
1295
- throw error;
1296
- }
1297
- }
1298
- var TEMPLATES_API_URL = process.env.MASTRA_TEMPLATES_API_URL || "https://mastra.ai/api/templates.json";
1299
- async function loadTemplates() {
1300
- try {
1301
- const response = await fetch(TEMPLATES_API_URL);
1302
- if (!response.ok) {
1303
- throw new Error(`Failed to fetch templates: ${response.statusText}`);
1304
- }
1305
- const templates = await response.json();
1306
- return templates;
1307
- } catch (error) {
1308
- console.error("Error loading templates:", error);
1309
- throw new Error("Failed to load templates. Please check your internet connection and try again.");
1310
- }
1311
- }
1312
- function pluralize(count, singular, plural) {
1313
- return count === 1 ? singular : plural || `${singular}s`;
1314
- }
1315
- async function selectTemplate(templates) {
1316
- const choices = templates.map((template) => {
1317
- const parts = [];
1318
- if (template.agents?.length) {
1319
- parts.push(`${template.agents.length} ${pluralize(template.agents.length, "agent")}`);
1320
- }
1321
- if (template.tools?.length) {
1322
- parts.push(`${template.tools.length} ${pluralize(template.tools.length, "tool")}`);
1323
- }
1324
- if (template.workflows?.length) {
1325
- parts.push(`${template.workflows.length} ${pluralize(template.workflows.length, "workflow")}`);
1326
- }
1327
- if (template.mcp?.length) {
1328
- parts.push(`${template.mcp.length} ${pluralize(template.mcp.length, "MCP server")}`);
1329
- }
1330
- if (template.networks?.length) {
1331
- parts.push(`${template.networks.length} ${pluralize(template.networks.length, "agent network")}`);
1332
- }
1333
- return {
1334
- value: template,
1335
- label: template.title,
1336
- hint: parts.join(", ") || "Template components"
1337
- };
1338
- });
1339
- const selected = await ve({
1340
- message: "Select a template:",
1341
- options: choices
1342
- });
1343
- if (pD(selected)) {
1344
- return null;
1345
- }
1346
- return selected;
1347
- }
1348
- function findTemplateByName(templates, templateName) {
1349
- let template = templates.find((t) => t.slug === templateName);
1350
- if (template) return template;
1351
- const slugWithPrefix = `template-${templateName}`;
1352
- template = templates.find((t) => t.slug === slugWithPrefix);
1353
- if (template) return template;
1354
- template = templates.find((t) => t.title.toLowerCase() === templateName.toLowerCase());
1355
- if (template) return template;
1356
- return null;
1357
- }
1358
- function getDefaultProjectName(template) {
1359
- return template.slug.replace(/^template-/, "");
1360
- }
1361
- function getPackageManagerAddCommand(pm) {
1362
- switch (pm) {
1363
- case "npm":
1364
- return "install --audit=false --fund=false --loglevel=error --progress=false --update-notifier=false";
1365
- case "yarn":
1366
- return "add";
1367
- case "pnpm":
1368
- return "add --loglevel=error";
1369
- case "bun":
1370
- return "add";
1371
- default:
1372
- return "add";
1373
- }
1374
- }
1375
- var DepsService = class {
1376
- packageManager;
1377
- constructor() {
1378
- this.packageManager = this.getPackageManager();
1379
- }
1380
- findLockFile(dir) {
1381
- const lockFiles = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "bun.lock"];
1382
- for (const file of lockFiles) {
1383
- if (fs4__default__default.existsSync(path3.join(dir, file))) {
1384
- return file;
1385
- }
1386
- }
1387
- const parentDir = path3.resolve(dir, "..");
1388
- if (parentDir !== dir) {
1389
- return this.findLockFile(parentDir);
1390
- }
1391
- return null;
1392
- }
1393
- getPackageManager() {
1394
- const lockFile = this.findLockFile(process.cwd());
1395
- switch (lockFile) {
1396
- case "pnpm-lock.yaml":
1397
- return "pnpm";
1398
- case "package-lock.json":
1399
- return "npm";
1400
- case "yarn.lock":
1401
- return "yarn";
1402
- case "bun.lock":
1403
- return "bun";
1404
- default:
1405
- return "npm";
1406
- }
1407
- }
1408
- async installPackages(packages) {
1409
- const pm = this.packageManager;
1410
- const installCommand = getPackageManagerAddCommand(pm);
1411
- const packageList = packages.join(" ");
1412
- return execa(`${pm} ${installCommand} ${packageList}`, {
1413
- all: true,
1414
- shell: true,
1415
- stdio: "inherit"
1416
- });
1417
- }
1418
- async checkDependencies(dependencies) {
1419
- try {
1420
- const packageJsonPath = path3.join(process.cwd(), "package.json");
1421
- try {
1422
- await fs5.access(packageJsonPath);
1423
- } catch {
1424
- return "No package.json file found in the current directory";
1425
- }
1426
- const packageJson = JSON.parse(await fs5.readFile(packageJsonPath, "utf-8"));
1427
- for (const dependency of dependencies) {
1428
- if (!packageJson.dependencies || !packageJson.dependencies[dependency]) {
1429
- return `Please install ${dependency} before running this command (${this.packageManager} install ${dependency})`;
1430
- }
1431
- }
1432
- return "ok";
1433
- } catch (err) {
1434
- console.error(err);
1435
- return "Could not check dependencies";
1436
- }
1437
- }
1438
- async getProjectName() {
1439
- try {
1440
- const packageJsonPath = path3.join(process.cwd(), "package.json");
1441
- const packageJson = await fs5.readFile(packageJsonPath, "utf-8");
1442
- const pkg = JSON.parse(packageJson);
1443
- return pkg.name;
1444
- } catch (err) {
1445
- throw err;
1446
- }
1447
- }
1448
- async addScriptsToPackageJson(scripts) {
1449
- const packageJson = JSON.parse(await fs5.readFile("package.json", "utf-8"));
1450
- packageJson.scripts = {
1451
- ...packageJson.scripts,
1452
- ...scripts
1453
- };
1454
- await fs5.writeFile("package.json", JSON.stringify(packageJson, null, 2));
1455
- }
1456
- };
1457
1176
  var args = ["-y", "@mastra/mcp-docs-server"];
1458
1177
  var createMcpConfig = (editor) => {
1459
1178
  if (editor === "vscode") {
@@ -1506,19 +1225,19 @@ async function writeMergedConfig(configPath, editor) {
1506
1225
  spaces: 2
1507
1226
  });
1508
1227
  }
1509
- var windsurfGlobalMCPConfigPath = path3.join(os.homedir(), ".codeium", "windsurf", "mcp_config.json");
1510
- var cursorGlobalMCPConfigPath = path3.join(os.homedir(), ".cursor", "mcp.json");
1511
- path3.join(process.cwd(), ".vscode", "mcp.json");
1512
- var vscodeGlobalMCPConfigPath = path3.join(
1228
+ var windsurfGlobalMCPConfigPath = path.join(os.homedir(), ".codeium", "windsurf", "mcp_config.json");
1229
+ var cursorGlobalMCPConfigPath = path.join(os.homedir(), ".cursor", "mcp.json");
1230
+ path.join(process.cwd(), ".vscode", "mcp.json");
1231
+ var vscodeGlobalMCPConfigPath = path.join(
1513
1232
  os.homedir(),
1514
- process.platform === "win32" ? path3.join("AppData", "Roaming", "Code", "User", "settings.json") : process.platform === "darwin" ? path3.join("Library", "Application Support", "Code", "User", "settings.json") : path3.join(".config", "Code", "User", "settings.json")
1233
+ process.platform === "win32" ? path.join("AppData", "Roaming", "Code", "User", "settings.json") : process.platform === "darwin" ? path.join("Library", "Application Support", "Code", "User", "settings.json") : path.join(".config", "Code", "User", "settings.json")
1515
1234
  );
1516
1235
  async function installMastraDocsMCPServer({ editor, directory }) {
1517
1236
  if (editor === `cursor`) {
1518
- await writeMergedConfig(path3.join(directory, ".cursor", "mcp.json"), "cursor");
1237
+ await writeMergedConfig(path.join(directory, ".cursor", "mcp.json"), "cursor");
1519
1238
  }
1520
1239
  if (editor === `vscode`) {
1521
- await writeMergedConfig(path3.join(directory, ".vscode", "mcp.json"), "vscode");
1240
+ await writeMergedConfig(path.join(directory, ".vscode", "mcp.json"), "vscode");
1522
1241
  }
1523
1242
  if (editor === `cursor-global`) {
1524
1243
  const alreadyInstalled = await globalMCPIsAlreadyInstalled(editor);
@@ -1566,6 +1285,102 @@ async function globalMCPIsAlreadyInstalled(editor) {
1566
1285
  return false;
1567
1286
  }
1568
1287
  }
1288
+ function getPackageManagerAddCommand(pm) {
1289
+ switch (pm) {
1290
+ case "npm":
1291
+ return "install --audit=false --fund=false --loglevel=error --progress=false --update-notifier=false";
1292
+ case "yarn":
1293
+ return "add";
1294
+ case "pnpm":
1295
+ return "add --loglevel=error";
1296
+ case "bun":
1297
+ return "add";
1298
+ default:
1299
+ return "add";
1300
+ }
1301
+ }
1302
+ var DepsService = class {
1303
+ packageManager;
1304
+ constructor() {
1305
+ this.packageManager = this.getPackageManager();
1306
+ }
1307
+ findLockFile(dir) {
1308
+ const lockFiles = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "bun.lock"];
1309
+ for (const file of lockFiles) {
1310
+ if (fs3__default__default.existsSync(path.join(dir, file))) {
1311
+ return file;
1312
+ }
1313
+ }
1314
+ const parentDir = path.resolve(dir, "..");
1315
+ if (parentDir !== dir) {
1316
+ return this.findLockFile(parentDir);
1317
+ }
1318
+ return null;
1319
+ }
1320
+ getPackageManager() {
1321
+ const lockFile = this.findLockFile(process.cwd());
1322
+ switch (lockFile) {
1323
+ case "pnpm-lock.yaml":
1324
+ return "pnpm";
1325
+ case "package-lock.json":
1326
+ return "npm";
1327
+ case "yarn.lock":
1328
+ return "yarn";
1329
+ case "bun.lock":
1330
+ return "bun";
1331
+ default:
1332
+ return "npm";
1333
+ }
1334
+ }
1335
+ async installPackages(packages) {
1336
+ const pm = this.packageManager;
1337
+ const installCommand = getPackageManagerAddCommand(pm);
1338
+ const packageList = packages.join(" ");
1339
+ return execa(`${pm} ${installCommand} ${packageList}`, {
1340
+ all: true,
1341
+ shell: true,
1342
+ stdio: "inherit"
1343
+ });
1344
+ }
1345
+ async checkDependencies(dependencies) {
1346
+ try {
1347
+ const packageJsonPath = path.join(process.cwd(), "package.json");
1348
+ try {
1349
+ await fs4.access(packageJsonPath);
1350
+ } catch {
1351
+ return "No package.json file found in the current directory";
1352
+ }
1353
+ const packageJson = JSON.parse(await fs4.readFile(packageJsonPath, "utf-8"));
1354
+ for (const dependency of dependencies) {
1355
+ if (!packageJson.dependencies || !packageJson.dependencies[dependency]) {
1356
+ return `Please install ${dependency} before running this command (${this.packageManager} install ${dependency})`;
1357
+ }
1358
+ }
1359
+ return "ok";
1360
+ } catch (err) {
1361
+ console.error(err);
1362
+ return "Could not check dependencies";
1363
+ }
1364
+ }
1365
+ async getProjectName() {
1366
+ try {
1367
+ const packageJsonPath = path.join(process.cwd(), "package.json");
1368
+ const packageJson = await fs4.readFile(packageJsonPath, "utf-8");
1369
+ const pkg = JSON.parse(packageJson);
1370
+ return pkg.name;
1371
+ } catch (err) {
1372
+ throw err;
1373
+ }
1374
+ }
1375
+ async addScriptsToPackageJson(scripts) {
1376
+ const packageJson = JSON.parse(await fs4.readFile("package.json", "utf-8"));
1377
+ packageJson.scripts = {
1378
+ ...packageJson.scripts,
1379
+ ...scripts
1380
+ };
1381
+ await fs4.writeFile("package.json", JSON.stringify(packageJson, null, 2));
1382
+ }
1383
+ };
1569
1384
  var EnvService = class {
1570
1385
  };
1571
1386
  var FileEnvService = class extends EnvService {
@@ -1576,7 +1391,7 @@ var FileEnvService = class extends EnvService {
1576
1391
  }
1577
1392
  readFile(filePath) {
1578
1393
  return new Promise((resolve, reject) => {
1579
- fs4__default.readFile(filePath, "utf8", (err, data) => {
1394
+ fs3__default.readFile(filePath, "utf8", (err, data) => {
1580
1395
  if (err) reject(err);
1581
1396
  else resolve(data);
1582
1397
  });
@@ -1584,7 +1399,7 @@ var FileEnvService = class extends EnvService {
1584
1399
  }
1585
1400
  writeFile({ filePath, data }) {
1586
1401
  return new Promise((resolve, reject) => {
1587
- fs4__default.writeFile(filePath, data, "utf8", (err) => {
1402
+ fs3__default.writeFile(filePath, data, "utf8", (err) => {
1588
1403
  if (err) reject(err);
1589
1404
  else resolve();
1590
1405
  });
@@ -1637,10 +1452,10 @@ var FileService = class {
1637
1452
  */
1638
1453
  async copyStarterFile(inputFile, outputFilePath, replaceIfExists) {
1639
1454
  const __filename = fileURLToPath(import.meta.url);
1640
- const __dirname = path3.dirname(__filename);
1641
- const filePath = path3.resolve(__dirname, "starter-files", inputFile);
1642
- const fileString = fs4__default__default.readFileSync(filePath, "utf8");
1643
- if (fs4__default__default.existsSync(outputFilePath) && !replaceIfExists) {
1455
+ const __dirname = path.dirname(__filename);
1456
+ const filePath = path.resolve(__dirname, "starter-files", inputFile);
1457
+ const fileString = fs3__default__default.readFileSync(filePath, "utf8");
1458
+ if (fs3__default__default.existsSync(outputFilePath) && !replaceIfExists) {
1644
1459
  console.info(`${outputFilePath} already exists`);
1645
1460
  return false;
1646
1461
  }
@@ -1648,14 +1463,14 @@ var FileService = class {
1648
1463
  return true;
1649
1464
  }
1650
1465
  async setupEnvFile({ dbUrl }) {
1651
- const envPath = path3.join(process.cwd(), ".env.development");
1466
+ const envPath = path.join(process.cwd(), ".env.development");
1652
1467
  await fsExtra.ensureFile(envPath);
1653
1468
  const fileEnvService = new FileEnvService(envPath);
1654
1469
  await fileEnvService.setEnvValue("DB_URL", dbUrl);
1655
1470
  }
1656
1471
  getFirstExistingFile(files) {
1657
1472
  for (const f of files) {
1658
- if (fs4__default__default.existsSync(f)) {
1473
+ if (fs3__default__default.existsSync(f)) {
1659
1474
  return f;
1660
1475
  }
1661
1476
  }
@@ -1665,14 +1480,14 @@ var FileService = class {
1665
1480
  filePath,
1666
1481
  replacements
1667
1482
  }) {
1668
- let fileContent = fs4__default__default.readFileSync(filePath, "utf8");
1483
+ let fileContent = fs3__default__default.readFileSync(filePath, "utf8");
1669
1484
  replacements.forEach(({ search, replace }) => {
1670
1485
  fileContent = fileContent.replaceAll(search, replace);
1671
1486
  });
1672
- fs4__default__default.writeFileSync(filePath, fileContent);
1487
+ fs3__default__default.writeFileSync(filePath, fileContent);
1673
1488
  }
1674
1489
  };
1675
- var exec2 = util.promisify(child_process.exec);
1490
+ var exec = util.promisify(child_process.exec);
1676
1491
  var getModelIdentifier = (llmProvider) => {
1677
1492
  if (llmProvider === "openai") {
1678
1493
  return `'openai/gpt-4o-mini'`;
@@ -1726,8 +1541,8 @@ export const weatherAgent = new Agent({
1726
1541
  parser: "typescript",
1727
1542
  singleQuote: true
1728
1543
  });
1729
- await fs5.writeFile(destPath, "");
1730
- await fs5.writeFile(destPath, formattedContent);
1544
+ await fs4.writeFile(destPath, "");
1545
+ await fs4.writeFile(destPath, formattedContent);
1731
1546
  }
1732
1547
  async function writeWorkflowSample(destPath) {
1733
1548
  const content = `import { createStep, createWorkflow } from '@mastra/core/workflows';
@@ -1920,7 +1735,7 @@ export { weatherWorkflow };`;
1920
1735
  semi: true,
1921
1736
  singleQuote: true
1922
1737
  });
1923
- await fs5.writeFile(destPath, formattedContent);
1738
+ await fs4.writeFile(destPath, formattedContent);
1924
1739
  }
1925
1740
  async function writeToolSample(destPath) {
1926
1741
  const fileService = new FileService();
@@ -1949,15 +1764,15 @@ var writeIndexFile = async ({
1949
1764
  addWorkflow
1950
1765
  }) => {
1951
1766
  const indexPath = dirPath + "/index.ts";
1952
- const destPath = path3.join(indexPath);
1767
+ const destPath = path.join(indexPath);
1953
1768
  try {
1954
- await fs5.writeFile(destPath, "");
1769
+ await fs4.writeFile(destPath, "");
1955
1770
  const filteredExports = [
1956
1771
  addWorkflow ? `workflows: { weatherWorkflow },` : "",
1957
1772
  addAgent ? `agents: { weatherAgent },` : ""
1958
1773
  ].filter(Boolean);
1959
1774
  if (!addExample) {
1960
- await fs5.writeFile(
1775
+ await fs4.writeFile(
1961
1776
  destPath,
1962
1777
  `
1963
1778
  import { Mastra } from '@mastra/core';
@@ -1967,7 +1782,7 @@ export const mastra = new Mastra()
1967
1782
  );
1968
1783
  return;
1969
1784
  }
1970
- await fs5.writeFile(
1785
+ await fs4.writeFile(
1971
1786
  destPath,
1972
1787
  `
1973
1788
  import { Mastra } from '@mastra/core/mastra';
@@ -2027,15 +1842,15 @@ var getAPIKey = async (provider) => {
2027
1842
  var writeAPIKey = async ({ provider, apiKey }) => {
2028
1843
  const envFileName = apiKey ? ".env" : ".env.example";
2029
1844
  const key = await getAPIKey(provider);
2030
- const escapedKey = shellQuote.quote([key]);
2031
- const escapedApiKey = shellQuote.quote([apiKey ? apiKey : "your-api-key"]);
2032
- await exec2(`echo ${escapedKey}=${escapedApiKey} >> ${envFileName}`);
1845
+ const escapedKey = shellQuote2.quote([key]);
1846
+ const escapedApiKey = shellQuote2.quote([apiKey ? apiKey : "your-api-key"]);
1847
+ await exec(`echo ${escapedKey}=${escapedApiKey} >> ${envFileName}`);
2033
1848
  };
2034
1849
  var createMastraDir = async (directory) => {
2035
1850
  let dir = directory.trim().split("/").filter((item) => item !== "");
2036
- const dirPath = path3.join(process.cwd(), ...dir, "mastra");
1851
+ const dirPath = path.join(process.cwd(), ...dir, "mastra");
2037
1852
  try {
2038
- await fs5.access(dirPath);
1853
+ await fs4.access(dirPath);
2039
1854
  return { ok: false };
2040
1855
  } catch {
2041
1856
  await fsExtra.ensureDir(dirPath);
@@ -2181,13 +1996,193 @@ This means the Mastra docs MCP server will be available in all your Windsurf pro
2181
1996
  );
2182
1997
  return mastraProject;
2183
1998
  };
1999
+ function getPackageManager() {
2000
+ const userAgent = process.env.npm_config_user_agent || "";
2001
+ const execPath = process.env.npm_execpath || "";
2002
+ if (userAgent.includes("yarn")) {
2003
+ return "yarn";
2004
+ }
2005
+ if (userAgent.includes("pnpm")) {
2006
+ return "pnpm";
2007
+ }
2008
+ if (userAgent.includes("npm")) {
2009
+ return "npm";
2010
+ }
2011
+ if (execPath.includes("yarn")) {
2012
+ return "yarn";
2013
+ }
2014
+ if (execPath.includes("pnpm")) {
2015
+ return "pnpm";
2016
+ }
2017
+ if (execPath.includes("npm")) {
2018
+ return "npm";
2019
+ }
2020
+ return "npm";
2021
+ }
2022
+ var logger = createLogger(false);
2023
+ function createLogger(debug = false) {
2024
+ return new PinoLogger({
2025
+ name: "Mastra CLI",
2026
+ level: debug ? "debug" : "info"
2027
+ });
2028
+ }
2029
+ var exec2 = util.promisify(child_process.exec);
2030
+ async function cloneTemplate(options) {
2031
+ const { template, projectName, targetDir } = options;
2032
+ const projectPath = targetDir ? path.resolve(targetDir, projectName) : path.resolve(projectName);
2033
+ const spinner5 = yoctoSpinner({ text: `Cloning template "${template.title}"...` }).start();
2034
+ try {
2035
+ if (await directoryExists(projectPath)) {
2036
+ spinner5.error(`Directory ${projectName} already exists`);
2037
+ throw new Error(`Directory ${projectName} already exists`);
2038
+ }
2039
+ await cloneRepositoryWithoutGit(template.githubUrl, projectPath);
2040
+ await updatePackageJson(projectPath, projectName);
2041
+ const envExamplePath = path.join(projectPath, ".env.example");
2042
+ if (await fileExists(envExamplePath)) {
2043
+ await fs4.copyFile(envExamplePath, path.join(projectPath, ".env"));
2044
+ }
2045
+ spinner5.success(`Template "${template.title}" cloned successfully to ${projectName}`);
2046
+ return projectPath;
2047
+ } catch (error) {
2048
+ spinner5.error(`Failed to clone template: ${error instanceof Error ? error.message : "Unknown error"}`);
2049
+ throw error;
2050
+ }
2051
+ }
2052
+ async function directoryExists(dirPath) {
2053
+ try {
2054
+ const stat = await fs4.stat(dirPath);
2055
+ return stat.isDirectory();
2056
+ } catch {
2057
+ return false;
2058
+ }
2059
+ }
2060
+ async function fileExists(filePath) {
2061
+ try {
2062
+ const stat = await fs4.stat(filePath);
2063
+ return stat.isFile();
2064
+ } catch {
2065
+ return false;
2066
+ }
2067
+ }
2068
+ async function cloneRepositoryWithoutGit(repoUrl, targetPath) {
2069
+ await fs4.mkdir(targetPath, { recursive: true });
2070
+ try {
2071
+ const degitRepo = repoUrl.replace("https://github.com/", "");
2072
+ const degitCommand = shellQuote2.quote(["npx", "degit", degitRepo, targetPath]);
2073
+ await exec2(degitCommand, {
2074
+ cwd: process.cwd()
2075
+ });
2076
+ } catch {
2077
+ try {
2078
+ const gitCommand = shellQuote2.quote(["git", "clone", repoUrl, targetPath]);
2079
+ await exec2(gitCommand, {
2080
+ cwd: process.cwd()
2081
+ });
2082
+ const gitDir = path.join(targetPath, ".git");
2083
+ if (await directoryExists(gitDir)) {
2084
+ await fs4.rm(gitDir, { recursive: true, force: true });
2085
+ }
2086
+ } catch (gitError) {
2087
+ throw new Error(`Failed to clone repository: ${gitError instanceof Error ? gitError.message : "Unknown error"}`);
2088
+ }
2089
+ }
2090
+ }
2091
+ async function updatePackageJson(projectPath, projectName) {
2092
+ const packageJsonPath = path.join(projectPath, "package.json");
2093
+ try {
2094
+ const packageJsonContent = await fs4.readFile(packageJsonPath, "utf-8");
2095
+ const packageJson = JSON.parse(packageJsonContent);
2096
+ packageJson.name = projectName;
2097
+ await fs4.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2), "utf-8");
2098
+ } catch (error) {
2099
+ logger.warn(`Could not update package.json: ${error instanceof Error ? error.message : "Unknown error"}`);
2100
+ }
2101
+ }
2102
+ async function installDependencies(projectPath, packageManager) {
2103
+ const spinner5 = yoctoSpinner({ text: "Installing dependencies..." }).start();
2104
+ try {
2105
+ const pm = packageManager || getPackageManager();
2106
+ const installCommand = shellQuote2.quote([pm, "install"]);
2107
+ await exec2(installCommand, {
2108
+ cwd: projectPath
2109
+ });
2110
+ spinner5.success("Dependencies installed successfully");
2111
+ } catch (error) {
2112
+ spinner5.error(`Failed to install dependencies: ${error instanceof Error ? error.message : "Unknown error"}`);
2113
+ throw error;
2114
+ }
2115
+ }
2116
+ var TEMPLATES_API_URL = process.env.MASTRA_TEMPLATES_API_URL || "https://mastra.ai/api/templates.json";
2117
+ async function loadTemplates() {
2118
+ try {
2119
+ const response = await fetch(TEMPLATES_API_URL);
2120
+ if (!response.ok) {
2121
+ throw new Error(`Failed to fetch templates: ${response.statusText}`);
2122
+ }
2123
+ const templates = await response.json();
2124
+ return templates;
2125
+ } catch (error) {
2126
+ console.error("Error loading templates:", error);
2127
+ throw new Error("Failed to load templates. Please check your internet connection and try again.");
2128
+ }
2129
+ }
2130
+ function pluralize(count, singular, plural) {
2131
+ return count === 1 ? singular : plural || `${singular}s`;
2132
+ }
2133
+ async function selectTemplate(templates) {
2134
+ const choices = templates.map((template) => {
2135
+ const parts = [];
2136
+ if (template.agents?.length) {
2137
+ parts.push(`${template.agents.length} ${pluralize(template.agents.length, "agent")}`);
2138
+ }
2139
+ if (template.tools?.length) {
2140
+ parts.push(`${template.tools.length} ${pluralize(template.tools.length, "tool")}`);
2141
+ }
2142
+ if (template.workflows?.length) {
2143
+ parts.push(`${template.workflows.length} ${pluralize(template.workflows.length, "workflow")}`);
2144
+ }
2145
+ if (template.mcp?.length) {
2146
+ parts.push(`${template.mcp.length} ${pluralize(template.mcp.length, "MCP server")}`);
2147
+ }
2148
+ if (template.networks?.length) {
2149
+ parts.push(`${template.networks.length} ${pluralize(template.networks.length, "agent network")}`);
2150
+ }
2151
+ return {
2152
+ value: template,
2153
+ label: template.title,
2154
+ hint: parts.join(", ") || "Template components"
2155
+ };
2156
+ });
2157
+ const selected = await ve({
2158
+ message: "Select a template:",
2159
+ options: choices
2160
+ });
2161
+ if (pD(selected)) {
2162
+ return null;
2163
+ }
2164
+ return selected;
2165
+ }
2166
+ function findTemplateByName(templates, templateName) {
2167
+ let template = templates.find((t) => t.slug === templateName);
2168
+ if (template) return template;
2169
+ const slugWithPrefix = `template-${templateName}`;
2170
+ template = templates.find((t) => t.slug === slugWithPrefix);
2171
+ if (template) return template;
2172
+ template = templates.find((t) => t.title.toLowerCase() === templateName.toLowerCase());
2173
+ if (template) return template;
2174
+ return null;
2175
+ }
2176
+ function getDefaultProjectName(template) {
2177
+ return template.slug.replace(/^template-/, "");
2178
+ }
2184
2179
  var s = Y();
2185
2180
  var init = async ({
2186
- directory,
2187
- addExample = false,
2181
+ directory = "src/",
2188
2182
  components,
2189
2183
  llmProvider = "openai",
2190
2184
  llmApiKey,
2185
+ addExample = false,
2191
2186
  configureEditorWithDocsMCP
2192
2187
  }) => {
2193
2188
  s.start("Initializing Mastra");
@@ -2318,7 +2313,7 @@ var createMastraProject = async ({
2318
2313
  defaultValue: "my-mastra-app",
2319
2314
  validate: (value) => {
2320
2315
  if (value.length === 0) return "Project name cannot be empty";
2321
- if (fs4__default__default.existsSync(value)) {
2316
+ if (fs3__default__default.existsSync(value)) {
2322
2317
  return `A directory named "${value}" already exists. Please choose a different name.`;
2323
2318
  }
2324
2319
  }
@@ -2338,7 +2333,7 @@ var createMastraProject = async ({
2338
2333
  try {
2339
2334
  s2.start("Creating project");
2340
2335
  try {
2341
- await fs5.mkdir(projectName);
2336
+ await fs4.mkdir(projectName);
2342
2337
  } catch (error) {
2343
2338
  if (error instanceof Error && "code" in error && error.code === "EEXIST") {
2344
2339
  s2.stop(`A directory named "${projectName}" already exists. Please choose a different name.`);
@@ -2370,7 +2365,7 @@ var createMastraProject = async ({
2370
2365
  s2.stop("Project structure created");
2371
2366
  s2.start(`Installing ${pm} dependencies`);
2372
2367
  try {
2373
- await exec3(`${pm} ${installCommand} zod@^3`);
2368
+ await exec3(`${pm} ${installCommand} zod@^4`);
2374
2369
  await exec3(`${pm} ${installCommand} typescript @types/node --save-dev`);
2375
2370
  await exec3(`echo '{
2376
2371
  "compilerOptions": {
@@ -2640,7 +2635,7 @@ async function createFromTemplate(args2) {
2640
2635
  async function getPackageVersion() {
2641
2636
  const __filename = fileURLToPath(import.meta.url);
2642
2637
  const __dirname = dirname(__filename);
2643
- const pkgJsonPath = path3.join(__dirname, "..", "package.json");
2638
+ const pkgJsonPath = path.join(__dirname, "..", "package.json");
2644
2639
  const content = await fsExtra$1.readJSON(pkgJsonPath);
2645
2640
  return content.version;
2646
2641
  }