microfox 1.0.11

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 (91) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +114 -0
  3. package/dist/agent-template.txt +486 -0
  4. package/dist/background-agent/.gitignore.txt +22 -0
  5. package/dist/background-agent/eslint.config.js.txt +48 -0
  6. package/dist/background-agent/microfox.json.txt +4 -0
  7. package/dist/background-agent/openapi.md.txt +1 -0
  8. package/dist/background-agent/package.json.txt +47 -0
  9. package/dist/background-agent/serverless.yml.txt +123 -0
  10. package/dist/background-agent/src/functions/cron-paginate.ts.txt +135 -0
  11. package/dist/background-agent/src/functions/cron-populate.ts.txt +33 -0
  12. package/dist/background-agent/src/functions/route-trigger-index.ts.txt +157 -0
  13. package/dist/background-agent/src/functions/route-trigger-populate.ts.txt +0 -0
  14. package/dist/background-agent/src/functions/sqs-index.ts.txt +147 -0
  15. package/dist/background-agent/src/helpers/ragRedis.ts.txt +78 -0
  16. package/dist/background-agent/src/index.ts.txt +69 -0
  17. package/dist/background-agent/tsconfig.json.txt +33 -0
  18. package/dist/chunk-4HNHBA2H.mjs +104 -0
  19. package/dist/chunk-4HNHBA2H.mjs.map +1 -0
  20. package/dist/chunk-ARAHSYJI.mjs +263 -0
  21. package/dist/chunk-ARAHSYJI.mjs.map +1 -0
  22. package/dist/chunk-JGAX4PD6.mjs +290 -0
  23. package/dist/chunk-JGAX4PD6.mjs.map +1 -0
  24. package/dist/chunk-KPJJOO76.mjs +12 -0
  25. package/dist/chunk-KPJJOO76.mjs.map +1 -0
  26. package/dist/chunk-TZQZMKHP.mjs +11 -0
  27. package/dist/chunk-TZQZMKHP.mjs.map +1 -0
  28. package/dist/chunk-UFRGJMF4.mjs +154 -0
  29. package/dist/chunk-UFRGJMF4.mjs.map +1 -0
  30. package/dist/chunk-UHWJTQKW.mjs +139 -0
  31. package/dist/chunk-UHWJTQKW.mjs.map +1 -0
  32. package/dist/chunk-UYROVW53.mjs +89 -0
  33. package/dist/chunk-UYROVW53.mjs.map +1 -0
  34. package/dist/chunk-XGFSFWK3.mjs +113 -0
  35. package/dist/chunk-XGFSFWK3.mjs.map +1 -0
  36. package/dist/cli.d.mts +2 -0
  37. package/dist/cli.d.ts +2 -0
  38. package/dist/cli.js +1154 -0
  39. package/dist/cli.js.map +1 -0
  40. package/dist/cli.mjs +52 -0
  41. package/dist/cli.mjs.map +1 -0
  42. package/dist/commands/add.d.mts +5 -0
  43. package/dist/commands/add.d.ts +5 -0
  44. package/dist/commands/add.js +126 -0
  45. package/dist/commands/add.js.map +1 -0
  46. package/dist/commands/add.mjs +10 -0
  47. package/dist/commands/add.mjs.map +1 -0
  48. package/dist/commands/code.d.mts +5 -0
  49. package/dist/commands/code.d.ts +5 -0
  50. package/dist/commands/code.js +187 -0
  51. package/dist/commands/code.js.map +1 -0
  52. package/dist/commands/code.mjs +9 -0
  53. package/dist/commands/code.mjs.map +1 -0
  54. package/dist/commands/install.d.mts +5 -0
  55. package/dist/commands/install.d.ts +5 -0
  56. package/dist/commands/install.js +296 -0
  57. package/dist/commands/install.js.map +1 -0
  58. package/dist/commands/install.mjs +9 -0
  59. package/dist/commands/install.mjs.map +1 -0
  60. package/dist/commands/kickstart.d.mts +5 -0
  61. package/dist/commands/kickstart.d.ts +5 -0
  62. package/dist/commands/kickstart.js +322 -0
  63. package/dist/commands/kickstart.js.map +1 -0
  64. package/dist/commands/kickstart.mjs +10 -0
  65. package/dist/commands/kickstart.mjs.map +1 -0
  66. package/dist/commands/push.d.mts +5 -0
  67. package/dist/commands/push.d.ts +5 -0
  68. package/dist/commands/push.js +137 -0
  69. package/dist/commands/push.js.map +1 -0
  70. package/dist/commands/push.mjs +9 -0
  71. package/dist/commands/push.mjs.map +1 -0
  72. package/dist/commands/status.d.mts +7 -0
  73. package/dist/commands/status.d.ts +7 -0
  74. package/dist/commands/status.js +148 -0
  75. package/dist/commands/status.js.map +1 -0
  76. package/dist/commands/status.mjs +13 -0
  77. package/dist/commands/status.mjs.map +1 -0
  78. package/dist/commands/update.d.mts +5 -0
  79. package/dist/commands/update.d.ts +5 -0
  80. package/dist/commands/update.js +172 -0
  81. package/dist/commands/update.js.map +1 -0
  82. package/dist/commands/update.mjs +9 -0
  83. package/dist/commands/update.mjs.map +1 -0
  84. package/dist/index.d.mts +20 -0
  85. package/dist/index.d.ts +20 -0
  86. package/dist/index.js +406 -0
  87. package/dist/index.js.map +1 -0
  88. package/dist/index.mjs +14 -0
  89. package/dist/index.mjs.map +1 -0
  90. package/dist/package-template.txt +494 -0
  91. package/package.json +68 -0
package/dist/cli.js ADDED
@@ -0,0 +1,1154 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/cli.ts
27
+ var import_commander8 = require("commander");
28
+
29
+ // src/commands/kickstart.ts
30
+ var import_commander = require("commander");
31
+ var import_fs = __toESM(require("fs"));
32
+ var import_path = __toESM(require("path"));
33
+ var import_chalk = __toESM(require("chalk"));
34
+ var import_readline_sync = __toESM(require("readline-sync"));
35
+ var import_inquirer = __toESM(require("inquirer"));
36
+
37
+ // src/utils/getProjectRoot.ts
38
+ var getWorkingDirectory = () => {
39
+ return process.cwd();
40
+ };
41
+
42
+ // src/utils/npmChecker.ts
43
+ async function isPackageNameAvailable(packageName) {
44
+ try {
45
+ const controller = new AbortController();
46
+ const timeoutId = setTimeout(() => controller.abort(), 5e3);
47
+ const response = await fetch(`https://registry.npmjs.org/${packageName}`, {
48
+ signal: controller.signal
49
+ });
50
+ clearTimeout(timeoutId);
51
+ if (response.ok) {
52
+ return false;
53
+ }
54
+ if (response.status === 404) {
55
+ return true;
56
+ }
57
+ console.warn(
58
+ `Warning: Unexpected status ${response.status} when checking npm availability for ${packageName}. Proceeding with caution.`
59
+ );
60
+ return false;
61
+ } catch (error) {
62
+ if (error.name === "AbortError") {
63
+ console.warn(
64
+ `Warning: Timeout when checking npm availability for ${packageName}. Proceeding with caution.`
65
+ );
66
+ } else {
67
+ console.warn(
68
+ `Warning: Could not check npm availability for ${packageName}. Proceeding with caution.`
69
+ );
70
+ }
71
+ return false;
72
+ }
73
+ }
74
+ async function checkPackageNameAndPrompt(packageName) {
75
+ const readlineSync3 = require("readline-sync");
76
+ let currentName = (packageName == null ? void 0 : packageName.startsWith("@microfox/")) ? packageName : `@microfox/${packageName}`;
77
+ while (true) {
78
+ console.log(`\u{1F50D} Checking npm availability for "${currentName}"...`);
79
+ const isAvailable = await isPackageNameAvailable(currentName);
80
+ if (isAvailable) {
81
+ console.log(`\u2705 Package name "${currentName}" is available on npm!`);
82
+ return currentName;
83
+ } else {
84
+ console.log(`\u274C Package name "${currentName}" is already taken on npm.`);
85
+ const newName = readlineSync3.question(
86
+ "Please enter a new package name: "
87
+ );
88
+ if (!newName || newName.trim() === "") {
89
+ console.log("\u274C Invalid package name. Please try again.");
90
+ continue;
91
+ }
92
+ currentName = newName.trim();
93
+ }
94
+ }
95
+ }
96
+
97
+ // src/commands/kickstart.ts
98
+ async function createAgentProject(agentName) {
99
+ const workingDir = getWorkingDirectory();
100
+ const agentDir = import_path.default.join(workingDir, agentName);
101
+ if (import_fs.default.existsSync(agentDir)) {
102
+ throw new Error(`Directory already exists at ${agentDir}`);
103
+ }
104
+ console.log(
105
+ import_chalk.default.blue(
106
+ `\u{1F680} Creating agent ${import_chalk.default.bold(agentName)} at ${agentDir}
107
+ `
108
+ )
109
+ );
110
+ import_fs.default.mkdirSync(agentDir, { recursive: true });
111
+ const templatePath = import_path.default.resolve(__dirname, "agent-template.txt");
112
+ const templateContent = import_fs.default.readFileSync(templatePath, "utf-8");
113
+ const fileSections = templateContent.split("--- filename: ").slice(1);
114
+ for (const section of fileSections) {
115
+ const lines = section.split("\n");
116
+ const filePath = lines.shift().trim();
117
+ const content = lines.join("\n").replace(/<%= agentName %>/g, agentName);
118
+ const destPath = import_path.default.join(agentDir, filePath);
119
+ const destDir = import_path.default.dirname(destPath);
120
+ if (!import_fs.default.existsSync(destDir)) {
121
+ import_fs.default.mkdirSync(destDir, { recursive: true });
122
+ }
123
+ import_fs.default.writeFileSync(destPath, content);
124
+ console.log(import_chalk.default.green(`\u2705 Created ${filePath}`));
125
+ }
126
+ }
127
+ async function createPackageProject(packageName) {
128
+ const simpleName = packageName.includes("/") ? packageName.split("/")[1] : packageName;
129
+ const titleName = simpleName.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
130
+ const description = `A TypeScript SDK for ${titleName}.`;
131
+ const className = simpleName.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("") + "Sdk";
132
+ const workingDir = getWorkingDirectory();
133
+ const packageDir = import_path.default.join(workingDir, simpleName);
134
+ if (import_fs.default.existsSync(packageDir)) {
135
+ throw new Error(`Directory already exists at ${packageDir}`);
136
+ }
137
+ console.log(
138
+ import_chalk.default.blue(
139
+ `\u{1F680} Creating package ${import_chalk.default.bold(packageName)} at ${packageDir}
140
+ `
141
+ )
142
+ );
143
+ import_fs.default.mkdirSync(packageDir, { recursive: true });
144
+ const templatePath = import_path.default.resolve(__dirname, "package-template.txt");
145
+ const templateContent = import_fs.default.readFileSync(templatePath, "utf-8");
146
+ const fileSections = templateContent.split("--- filename: ").slice(1);
147
+ for (const section of fileSections) {
148
+ const lines = section.split("\n");
149
+ const filePath = lines.shift().trim().replace(/<%= simpleName %>/g, simpleName);
150
+ let content = lines.join("\n");
151
+ content = content.replace(/<%= packageName %>/g, packageName);
152
+ content = content.replace(/<%= simpleName %>/g, simpleName);
153
+ content = content.replace(/<%= titleName %>/g, titleName);
154
+ content = content.replace(/<%= description %>/g, description);
155
+ content = content.replace(/<%= className %>/g, className);
156
+ const destPath = import_path.default.join(packageDir, filePath);
157
+ const destDir = import_path.default.dirname(destPath);
158
+ if (!import_fs.default.existsSync(destDir)) {
159
+ import_fs.default.mkdirSync(destDir, { recursive: true });
160
+ }
161
+ import_fs.default.writeFileSync(destPath, content);
162
+ console.log(import_chalk.default.green(`\u2705 Created ${filePath}`));
163
+ }
164
+ const docsDir = import_path.default.join(packageDir, "docs");
165
+ const docsConstructors = import_path.default.join(docsDir, "constructors");
166
+ const docsFunctions = import_path.default.join(docsDir, "functions");
167
+ import_fs.default.mkdirSync(docsDir, { recursive: true });
168
+ import_fs.default.mkdirSync(docsConstructors, { recursive: true });
169
+ import_fs.default.mkdirSync(docsFunctions, { recursive: true });
170
+ }
171
+ async function createBackgroundAgentProject(agentName) {
172
+ const workingDir = getWorkingDirectory();
173
+ const agentDir = import_path.default.join(workingDir, agentName);
174
+ if (import_fs.default.existsSync(agentDir)) {
175
+ throw new Error(`Directory already exists at ${agentDir}`);
176
+ }
177
+ console.log(
178
+ import_chalk.default.blue(
179
+ `\u{1F680} Creating background agent ${import_chalk.default.bold(agentName)} at ${agentDir}
180
+ `
181
+ )
182
+ );
183
+ import_fs.default.mkdirSync(agentDir, { recursive: true });
184
+ const templateDir = import_path.default.resolve(__dirname, "background-agent");
185
+ const copyTemplates = (src, dest) => {
186
+ const entries = import_fs.default.readdirSync(src, { withFileTypes: true });
187
+ for (const entry of entries) {
188
+ const srcPath = import_path.default.join(src, entry.name);
189
+ const destPath = import_path.default.join(dest, entry.name.replace(/\.txt$/, ""));
190
+ if (entry.isDirectory()) {
191
+ import_fs.default.mkdirSync(destPath, { recursive: true });
192
+ copyTemplates(srcPath, destPath);
193
+ } else if (entry.name.endsWith(".txt")) {
194
+ const templateContent = import_fs.default.readFileSync(srcPath, "utf-8");
195
+ const content = templateContent.replace(/<%= agentName %>/g, agentName);
196
+ import_fs.default.writeFileSync(destPath, content);
197
+ console.log(import_chalk.default.green(`\u2705 Created ${import_path.default.relative(agentDir, destPath)}`));
198
+ }
199
+ }
200
+ };
201
+ copyTemplates(templateDir, agentDir);
202
+ }
203
+ async function kickstartAction() {
204
+ console.log(import_chalk.default.cyan("\u{1F680} Let's kickstart your new project!\n"));
205
+ const { boilerplateType } = await import_inquirer.default.prompt([
206
+ {
207
+ type: "list",
208
+ name: "boilerplateType",
209
+ message: "Select boilerplate type:",
210
+ choices: ["package", "agent"]
211
+ }
212
+ ]);
213
+ if (!boilerplateType) {
214
+ console.log(import_chalk.default.yellow("Operation cancelled."));
215
+ return;
216
+ }
217
+ if (boilerplateType === "agent") {
218
+ const { agentType } = await import_inquirer.default.prompt([
219
+ {
220
+ type: "list",
221
+ name: "agentType",
222
+ message: "Select agent type:",
223
+ choices: ["plain", "background"]
224
+ }
225
+ ]);
226
+ if (agentType === "plain") {
227
+ const agentName = import_readline_sync.default.question(
228
+ import_chalk.default.yellow("\u{1F4E6} Enter agent name: ")
229
+ );
230
+ if (!agentName.trim()) {
231
+ throw new Error("Agent name cannot be empty");
232
+ }
233
+ await createAgentProject(agentName.trim());
234
+ console.log(
235
+ import_chalk.default.green(
236
+ `
237
+ \u{1F389} Successfully created agent ${import_chalk.default.bold(agentName)}!`
238
+ )
239
+ );
240
+ console.log(import_chalk.default.gray(`\u{1F4CD} Located at ${import_path.default.join(getWorkingDirectory(), agentName)}`));
241
+ console.log(import_chalk.default.yellow("\n\u{1F4A1} Next steps:"));
242
+ console.log(import_chalk.default.yellow(` 1. cd ${agentName}`));
243
+ console.log(import_chalk.default.yellow(" 2. npm install"));
244
+ console.log(import_chalk.default.yellow(" 3. Configure your env.json"));
245
+ console.log(import_chalk.default.yellow(" 4. npm run dev"));
246
+ console.log(import_chalk.default.yellow(" 5. Start developing your agent!"));
247
+ } else if (agentType === "background") {
248
+ const agentName = import_readline_sync.default.question(
249
+ import_chalk.default.yellow("\u{1F4E6} Enter agent name: ")
250
+ );
251
+ if (!agentName.trim()) {
252
+ throw new Error("Agent name cannot be empty");
253
+ }
254
+ await createBackgroundAgentProject(agentName.trim());
255
+ console.log(
256
+ import_chalk.default.green(
257
+ `
258
+ \u{1F389} Successfully created background agent ${import_chalk.default.bold(agentName)}!`
259
+ )
260
+ );
261
+ console.log(import_chalk.default.gray(`\u{1F4CD} Located at ${import_path.default.join(getWorkingDirectory(), agentName)}`));
262
+ console.log(import_chalk.default.yellow("\n\u{1F4A1} Next steps:"));
263
+ console.log(import_chalk.default.yellow(` 1. cd ${agentName}`));
264
+ console.log(import_chalk.default.yellow(" 2. npm install"));
265
+ console.log(import_chalk.default.yellow(" 3. Configure your env.json"));
266
+ console.log(import_chalk.default.yellow(" 4. npm run dev"));
267
+ console.log(import_chalk.default.yellow(" 5. Start developing your agent!"));
268
+ }
269
+ } else if (boilerplateType === "package") {
270
+ const packageName = import_readline_sync.default.question(
271
+ import_chalk.default.yellow("\u{1F4E6} Enter package name: ")
272
+ );
273
+ if (!packageName.trim()) {
274
+ throw new Error("Package name cannot be empty");
275
+ }
276
+ const finalPackageName = await checkPackageNameAndPrompt(`@microfox/${packageName.trim()}`);
277
+ await createPackageProject(finalPackageName);
278
+ const simpleName = finalPackageName.includes("/") ? finalPackageName.split("/")[1] : finalPackageName;
279
+ console.log(
280
+ import_chalk.default.green(
281
+ `
282
+ \u{1F389} Successfully created package ${import_chalk.default.bold(finalPackageName)}!`
283
+ )
284
+ );
285
+ console.log(import_chalk.default.gray(`\u{1F4CD} Located at ${import_path.default.join(getWorkingDirectory(), simpleName)}`));
286
+ console.log(import_chalk.default.yellow("\n\u{1F4A1} Next steps:"));
287
+ console.log(import_chalk.default.yellow(` 1. cd ${simpleName}`));
288
+ console.log(import_chalk.default.yellow(" 2. npm install"));
289
+ console.log(import_chalk.default.yellow(" 3. npm run build"));
290
+ console.log(import_chalk.default.yellow(" 4. npm test"));
291
+ console.log(import_chalk.default.yellow(" 5. Start developing your SDK!"));
292
+ console.log(
293
+ import_chalk.default.gray(
294
+ `
295
+ \u{1F4DA} Your package is ready to be published to npm as "${finalPackageName}"`
296
+ )
297
+ );
298
+ } else {
299
+ console.log(import_chalk.default.red('Invalid boilerplate type selected. Please choose "package" or "agent".'));
300
+ }
301
+ }
302
+ var kickstartCommand = new import_commander.Command("kickstart").description("Kickstart a new TypeScript SDK or agent package").action(async () => {
303
+ try {
304
+ console.log(import_chalk.default.blue("\u{1F680} Package Kickstarter\n"));
305
+ await kickstartAction();
306
+ } catch (error) {
307
+ console.error(import_chalk.default.red("\u274C Error:"), error instanceof Error ? error.message : String(error));
308
+ process.exit(1);
309
+ }
310
+ });
311
+
312
+ // src/commands/add.ts
313
+ var import_commander2 = require("commander");
314
+ var import_fs2 = __toESM(require("fs"));
315
+ var import_path2 = __toESM(require("path"));
316
+ var import_chalk2 = __toESM(require("chalk"));
317
+ var import_inquirer2 = __toESM(require("inquirer"));
318
+ var import_readline_sync2 = __toESM(require("readline-sync"));
319
+ async function addBackgroundAgentFunctions(name) {
320
+ const workingDir = getWorkingDirectory();
321
+ const functionsDir = import_path2.default.join(workingDir, "src", "functions", name);
322
+ console.log(
323
+ import_chalk2.default.blue(
324
+ `\u{1F680} Adding background agent functions ${import_chalk2.default.bold(name)} at ${functionsDir}
325
+ `
326
+ )
327
+ );
328
+ import_fs2.default.mkdirSync(functionsDir, { recursive: true });
329
+ const templateDir = import_path2.default.resolve(__dirname, "background-agent", "src", "functions");
330
+ const entries = import_fs2.default.readdirSync(templateDir, { withFileTypes: true });
331
+ for (const entry of entries) {
332
+ const srcPath = import_path2.default.join(templateDir, entry.name);
333
+ const destPath = import_path2.default.join(functionsDir, entry.name.replace(/\.txt$/, ""));
334
+ if (!entry.isDirectory() && entry.name.endsWith(".txt")) {
335
+ const templateContent = import_fs2.default.readFileSync(srcPath, "utf-8");
336
+ const content = templateContent.replace(/<%= agentName %>/g, name);
337
+ import_fs2.default.writeFileSync(destPath, content);
338
+ console.log(import_chalk2.default.green(`\u2705 Created ${import_path2.default.relative(workingDir, destPath)}`));
339
+ }
340
+ }
341
+ }
342
+ async function addAction() {
343
+ console.log(import_chalk2.default.cyan("\u2728 Add new features to your project!\n"));
344
+ const workingDir = getWorkingDirectory();
345
+ const microfoxConfigPath = import_path2.default.join(workingDir, "microfox.json");
346
+ if (!import_fs2.default.existsSync(microfoxConfigPath)) {
347
+ console.log(import_chalk2.default.red("Error: `microfox.json` not found in the current directory."));
348
+ console.log(import_chalk2.default.red("Please run this command from the root of a Microfox project."));
349
+ return;
350
+ }
351
+ const { featureType } = await import_inquirer2.default.prompt([
352
+ {
353
+ type: "list",
354
+ name: "featureType",
355
+ message: "Select what you want to add:",
356
+ choices: ["background_agent_functions"]
357
+ }
358
+ ]);
359
+ if (!featureType) {
360
+ console.log(import_chalk2.default.yellow("Operation cancelled."));
361
+ return;
362
+ }
363
+ if (featureType === "background_agent_functions") {
364
+ const functionName = import_readline_sync2.default.question(
365
+ import_chalk2.default.yellow("\u{1F4E6} Enter a name for the new functions: ")
366
+ );
367
+ if (!functionName.trim()) {
368
+ throw new Error("Function name cannot be empty");
369
+ }
370
+ await addBackgroundAgentFunctions(functionName.trim());
371
+ console.log(
372
+ import_chalk2.default.green(
373
+ `
374
+ \u{1F389} Successfully added background agent functions ${import_chalk2.default.bold(functionName)}!`
375
+ )
376
+ );
377
+ console.log(import_chalk2.default.gray(`\u{1F4CD} Located at src/functions/${functionName.trim()}`));
378
+ console.log(import_chalk2.default.yellow("\n\u{1F4A1} Next steps:"));
379
+ console.log(import_chalk2.default.yellow(" 1. Check the new files in src/functions/"));
380
+ console.log(import_chalk2.default.yellow(" 2. Update your agent logic to use the new functions."));
381
+ }
382
+ }
383
+ var addCommand = new import_commander2.Command("add").description("Add features to a Microfox project").action(async () => {
384
+ try {
385
+ await addAction();
386
+ } catch (error) {
387
+ console.error(import_chalk2.default.red("\u274C Error:"), error instanceof Error ? error.message : String(error));
388
+ process.exit(1);
389
+ }
390
+ });
391
+
392
+ // src/commands/push.ts
393
+ var import_commander3 = require("commander");
394
+ var import_fs3 = __toESM(require("fs"));
395
+ var import_path3 = __toESM(require("path"));
396
+ var import_chalk3 = __toESM(require("chalk"));
397
+ var import_axios = __toESM(require("axios"));
398
+ var import_micromatch = __toESM(require("micromatch"));
399
+ var API_ENDPOINT = "https://staging-cicd.microfox.app/api/deployments/new-agent-cli";
400
+ var getDirectoryFiles = (dir, basePath = "", ignorePatterns) => {
401
+ const structure = [];
402
+ const items = import_fs3.default.readdirSync(dir, { withFileTypes: true });
403
+ for (const item of items) {
404
+ const relativePath = import_path3.default.join(basePath, item.name);
405
+ if (import_micromatch.default.isMatch(relativePath, ignorePatterns)) {
406
+ continue;
407
+ }
408
+ if (item.isDirectory()) {
409
+ structure.push(...getDirectoryFiles(import_path3.default.join(dir, item.name), relativePath, ignorePatterns));
410
+ } else {
411
+ structure.push({
412
+ type: "file",
413
+ name: item.name,
414
+ path: relativePath.replace(/\\/g, "/"),
415
+ content: import_fs3.default.readFileSync(import_path3.default.join(dir, item.name), "utf-8")
416
+ });
417
+ }
418
+ }
419
+ return structure;
420
+ };
421
+ async function pushAction() {
422
+ const cwd = process.cwd();
423
+ const microfoxConfigPath = import_path3.default.join(cwd, "microfox.json");
424
+ if (!import_fs3.default.existsSync(microfoxConfigPath)) {
425
+ console.error(import_chalk3.default.red("\u274C Error: `microfox.json` not found in the current directory."));
426
+ console.log(import_chalk3.default.yellow("This command must be run from the root of an agent project."));
427
+ process.exit(1);
428
+ }
429
+ console.log(import_chalk3.default.cyan("\u{1F680} Pushing your agent to Microfox..."));
430
+ const microfoxConfig = JSON.parse(import_fs3.default.readFileSync(microfoxConfigPath, "utf-8"));
431
+ let agentApiKey;
432
+ const envPath = import_path3.default.join(cwd, "env.json");
433
+ if (import_fs3.default.existsSync(envPath)) {
434
+ try {
435
+ const envConfig = JSON.parse(import_fs3.default.readFileSync(envPath, "utf-8"));
436
+ agentApiKey = envConfig.AGENT_API_KEY;
437
+ } catch (e) {
438
+ console.warn(import_chalk3.default.yellow("\u26A0\uFE0F Could not read or parse `env.json`. The AGENT_API_KEY will not be sent."));
439
+ }
440
+ }
441
+ const stage = microfoxConfig.stage || "prod";
442
+ const ignored = microfoxConfig.ignored || [];
443
+ const defaultIgnore = ["node_modules/**", ".git/**", "dist/**", ".build/**", ".serverless/**", ".DS_Store", "package-lock.json", "pnpm-lock.yaml"];
444
+ const allIgnored = [...defaultIgnore, ...ignored];
445
+ const files = getDirectoryFiles(cwd, "", allIgnored);
446
+ try {
447
+ console.log(import_chalk3.default.blue("\u{1F4E6} Bundling and deploying your agent..."));
448
+ const response = await import_axios.default.post(
449
+ API_ENDPOINT,
450
+ {
451
+ stage,
452
+ isLocal: false,
453
+ dir: files
454
+ },
455
+ {
456
+ headers: {
457
+ "x-agent-api-key": agentApiKey
458
+ }
459
+ }
460
+ );
461
+ if (response.status === 200) {
462
+ console.log(import_chalk3.default.green("\u2705 Deployment successful!"));
463
+ console.log(import_chalk3.default.green(` Run ID: ${response.data.runId}`));
464
+ console.log(import_chalk3.default.green(` Message: ${response.data.message}`));
465
+ } else {
466
+ console.error(import_chalk3.default.red(`\u274C Deployment failed with status: ${response.status}`));
467
+ console.error(response.data);
468
+ process.exit(1);
469
+ }
470
+ } catch (error) {
471
+ console.error(import_chalk3.default.red("\u274C An error occurred during deployment:"));
472
+ if (import_axios.default.isAxiosError(error) && error.response) {
473
+ console.error(import_chalk3.default.red(` Status: ${error.response.status}`));
474
+ console.error(import_chalk3.default.red(` Data: ${JSON.stringify(error.response.data, null, 2)}`));
475
+ } else {
476
+ console.error(error);
477
+ }
478
+ process.exit(1);
479
+ }
480
+ }
481
+ var pushCommand = new import_commander3.Command("push").description("Deploy your agent to the Microfox platform").action(async () => {
482
+ try {
483
+ await pushAction();
484
+ } catch (error) {
485
+ console.error(import_chalk3.default.red("\u274C Error:"), error instanceof Error ? error.message : String(error));
486
+ process.exit(1);
487
+ }
488
+ });
489
+
490
+ // src/commands/status.ts
491
+ var import_commander4 = require("commander");
492
+ var import_chalk4 = __toESM(require("chalk"));
493
+ var import_axios2 = __toESM(require("axios"));
494
+ var import_inquirer3 = __toESM(require("inquirer"));
495
+ var API_BASE_URL = "https://staging-cicd.microfox.app/api/deployment-status/agent/status/";
496
+ async function getRunId(runId) {
497
+ if (runId) {
498
+ return runId;
499
+ }
500
+ const { promptedRunId } = await import_inquirer3.default.prompt([
501
+ {
502
+ type: "input",
503
+ name: "promptedRunId",
504
+ message: "Please enter the deployment Run ID:",
505
+ validate: (input) => !!input || "Run ID cannot be empty."
506
+ }
507
+ ]);
508
+ return promptedRunId;
509
+ }
510
+ async function getDeploymentData(runId) {
511
+ var _a;
512
+ try {
513
+ const response = await import_axios2.default.get(`${API_BASE_URL}${runId}`);
514
+ return response.data;
515
+ } catch (error) {
516
+ if (import_axios2.default.isAxiosError(error) && ((_a = error.response) == null ? void 0 : _a.status) === 404) {
517
+ console.error(import_chalk4.default.red(`\u274C Error: Deployment with Run ID "${runId}" not found.`));
518
+ } else {
519
+ console.error(import_chalk4.default.red("\u274C An error occurred while fetching deployment status:"));
520
+ console.error(error);
521
+ }
522
+ process.exit(1);
523
+ }
524
+ }
525
+ async function statusAction(runId) {
526
+ const finalRunId = await getRunId(runId);
527
+ const data = await getDeploymentData(finalRunId);
528
+ const deployment = data.data.deployment;
529
+ console.log(import_chalk4.default.cyan.bold("\u{1F680} Deployment Status"));
530
+ console.log(import_chalk4.default.gray("----------------------------------------"));
531
+ console.log(`${import_chalk4.default.bold("Run ID:")} ${deployment.sha}`);
532
+ console.log(`${import_chalk4.default.bold("Status:")} ${import_chalk4.default.green(deployment.status)}`);
533
+ console.log(`${import_chalk4.default.bold("Description:")} ${deployment.statusDescription}`);
534
+ console.log(`${import_chalk4.default.bold("Stage:")} ${deployment.stage}`);
535
+ console.log(`${import_chalk4.default.bold("Start Time:")} ${deployment.startTime ? new Date(deployment.startTime).toLocaleString() : "N/A"}`);
536
+ console.log(`${import_chalk4.default.bold("End Time:")} ${deployment.endTime ? new Date(deployment.endTime).toLocaleString() : "N/A"}`);
537
+ console.log(`${import_chalk4.default.bold("Base URL:")} ${deployment.baseUrl ? import_chalk4.default.underline.blue(deployment.baseUrl) : "N/A"}`);
538
+ console.log(import_chalk4.default.gray("----------------------------------------"));
539
+ }
540
+ async function logsAction(runId) {
541
+ const finalRunId = await getRunId(runId);
542
+ const data = await getDeploymentData(finalRunId);
543
+ const logs = data.data.deploymentLogs;
544
+ console.log(import_chalk4.default.cyan.bold("\u{1F4DC} Deployment Logs"));
545
+ console.log(import_chalk4.default.gray("----------------------------------------"));
546
+ console.log(logs);
547
+ console.log(import_chalk4.default.gray("----------------------------------------"));
548
+ }
549
+ async function metricsAction(runId) {
550
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D;
551
+ const finalRunId = await getRunId(runId);
552
+ const data = await getDeploymentData(finalRunId);
553
+ const metrics = data.data.deployment.metrics;
554
+ console.log(import_chalk4.default.cyan.bold("\u{1F4CA} Deployment Metrics"));
555
+ console.log(import_chalk4.default.gray("----------------------------------------"));
556
+ console.log(import_chalk4.default.bold.underline("System"));
557
+ console.log(` Platform: ${metrics.system.platform}`);
558
+ console.log(` Architecture: ${metrics.system.arch}`);
559
+ console.log(` Node Version: ${metrics.system.nodeVersion}`);
560
+ console.log(import_chalk4.default.bold.underline("\nTiming (ms)"));
561
+ for (const [step, duration] of Object.entries(((_a = metrics == null ? void 0 : metrics.timing) == null ? void 0 : _a.stepDurations) || {})) {
562
+ console.log(` ${step}:`.padEnd(15) + `${duration ? `${duration}ms` : "N/A"}`);
563
+ }
564
+ console.log(` Total Duration:`.padEnd(15) + `${((_b = metrics == null ? void 0 : metrics.timing) == null ? void 0 : _b.totalDuration) ? `${metrics.timing.totalDuration}ms` : "N/A"}`);
565
+ console.log(import_chalk4.default.bold.underline("\nResources"));
566
+ console.log(import_chalk4.default.bold(" CPU:"));
567
+ console.log(` Peak: ${((_d = (_c = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _c.cpu) == null ? void 0 : _d.peak) ? `${(_f = (_e = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _e.cpu) == null ? void 0 : _f.peak}${(_h = (_g = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _g.cpu) == null ? void 0 : _h.usageUnits}` : "N/A"}`);
568
+ console.log(` Average: ${((_j = (_i = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _i.cpu) == null ? void 0 : _j.average) ? `${(_l = (_k = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _k.cpu) == null ? void 0 : _l.average}${(_n = (_m = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _m.cpu) == null ? void 0 : _n.usageUnits}` : "N/A"}`);
569
+ console.log(import_chalk4.default.bold(" Memory:"));
570
+ console.log(` Peak: ${((_p = (_o = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _o.memory) == null ? void 0 : _p.peak) ? `${(_r = (_q = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _q.memory) == null ? void 0 : _r.peak.toFixed(2)}${(_t = (_s = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _s.memory) == null ? void 0 : _t.usageUnits}` : "N/A"}`);
571
+ console.log(` Average: ${((_v = (_u = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _u.memory) == null ? void 0 : _v.average) ? `${(_x = (_w = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _w.memory) == null ? void 0 : _x.average.toFixed(2)}${(_z = (_y = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _y.memory) == null ? void 0 : _z.usageUnits}` : "N/A"}`);
572
+ console.log(import_chalk4.default.bold(" Disk:"));
573
+ console.log(` Final Size: ${((_B = (_A = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _A.diskSize) == null ? void 0 : _B.final) ? `${(((_D = (_C = metrics == null ? void 0 : metrics.resources) == null ? void 0 : _C.diskSize) == null ? void 0 : _D.final) / (1024 * 1024)).toFixed(2)} MB` : "N/A"}`);
574
+ console.log(import_chalk4.default.gray("----------------------------------------"));
575
+ }
576
+ var statusCommand = new import_commander4.Command("status").description("Check the deployment status of your agent").argument("[runId]", "The deployment Run ID").action(async (runId) => {
577
+ try {
578
+ await statusAction(runId);
579
+ } catch (error) {
580
+ }
581
+ });
582
+ var logsCommand = new import_commander4.Command("logs").description("View the deployment logs for your agent").argument("[runId]", "The deployment Run ID").action(async (runId) => {
583
+ try {
584
+ await logsAction(runId);
585
+ } catch (error) {
586
+ }
587
+ });
588
+ var metricsCommand = new import_commander4.Command("metrics").description("View the deployment metrics for your agent").argument("[runId]", "The deployment Run ID").action(async (runId) => {
589
+ try {
590
+ await metricsAction(runId);
591
+ } catch (error) {
592
+ }
593
+ });
594
+
595
+ // src/commands/code.ts
596
+ var import_commander5 = require("commander");
597
+ var import_chalk5 = __toESM(require("chalk"));
598
+ var import_axios3 = __toESM(require("axios"));
599
+ var import_child_process = require("child_process");
600
+
601
+ // src/utils/findProjectRoot.ts
602
+ var import_path4 = __toESM(require("path"));
603
+ var import_fs4 = __toESM(require("fs"));
604
+ async function findProjectRoot(startPath = process.cwd()) {
605
+ let currentPath = startPath;
606
+ let count = 0;
607
+ while (true) {
608
+ const microfoxRootPath = import_path4.default.join(currentPath, "microfox-root");
609
+ if (import_fs4.default.existsSync(microfoxRootPath)) {
610
+ return currentPath;
611
+ }
612
+ const parentPath = import_path4.default.dirname(currentPath);
613
+ if (parentPath === currentPath || count > 10) {
614
+ return null;
615
+ }
616
+ currentPath = parentPath;
617
+ }
618
+ }
619
+
620
+ // src/commands/code.ts
621
+ var import_path5 = __toESM(require("path"));
622
+ var import_readline = __toESM(require("readline"));
623
+ var NEXTJS_PORT = 3e3;
624
+ var API_URL = `http://localhost:${NEXTJS_PORT}/api/agent`;
625
+ var createLogger = (rl) => {
626
+ return (source, message, color) => {
627
+ import_readline.default.cursorTo(process.stdout, 0);
628
+ import_readline.default.clearLine(process.stdout, 0);
629
+ const prefix = color(`[${source}]`);
630
+ const lines = message.trim().split("\n");
631
+ for (const line of lines) {
632
+ console.log(`${prefix} ${line}`);
633
+ }
634
+ rl.prompt(true);
635
+ };
636
+ };
637
+ async function codeAction() {
638
+ var _a, _b;
639
+ let childProcess = null;
640
+ const killProcess = () => {
641
+ if (childProcess && childProcess.pid) {
642
+ console.log(import_chalk5.default.yellow("\nGracefully shutting down..."));
643
+ if (process.platform === "win32") {
644
+ (0, import_child_process.spawn)("taskkill", ["/pid", childProcess.pid.toString(), "/f", "/t"]);
645
+ } else {
646
+ childProcess.kill("SIGINT");
647
+ }
648
+ childProcess = null;
649
+ }
650
+ };
651
+ process.on("SIGINT", () => {
652
+ killProcess();
653
+ process.exit(0);
654
+ });
655
+ process.on("exit", killProcess);
656
+ try {
657
+ const projectRoot = await findProjectRoot();
658
+ if (!projectRoot) {
659
+ console.error(
660
+ import_chalk5.default.red("Error: Could not find project root. Make sure you are inside a Microfox project.")
661
+ );
662
+ process.exit(1);
663
+ }
664
+ const codeAppPath = import_path5.default.join(projectRoot, "apps", "code");
665
+ console.log(import_chalk5.default.cyan(`Starting Next.js server in ${codeAppPath}...`));
666
+ childProcess = (0, import_child_process.spawn)("npm", ["run", "dev"], {
667
+ cwd: codeAppPath,
668
+ shell: true,
669
+ env: { ...process.env, FORCE_COLOR: "true" }
670
+ });
671
+ const rl = import_readline.default.createInterface({
672
+ input: process.stdin,
673
+ output: process.stdout,
674
+ prompt: import_chalk5.default.cyan("> ")
675
+ });
676
+ const log3 = createLogger(rl);
677
+ let serverReady = false;
678
+ const onServerData = (data) => {
679
+ const output = data.toString();
680
+ if (!serverReady) {
681
+ process.stdout.write(output);
682
+ if (output.toLowerCase().includes("ready in") || output.toLowerCase().includes("compiled successfully")) {
683
+ serverReady = true;
684
+ console.log(import_chalk5.default.green("\nServer is ready. You can now type your queries."));
685
+ rl.prompt();
686
+ }
687
+ } else {
688
+ log3("nextjs", output, import_chalk5.default.gray);
689
+ }
690
+ };
691
+ (_a = childProcess.stdout) == null ? void 0 : _a.on("data", onServerData);
692
+ (_b = childProcess.stderr) == null ? void 0 : _b.on("data", onServerData);
693
+ childProcess.on("exit", (code) => {
694
+ log3("system", `Next.js process exited with code ${code}`, import_chalk5.default.red);
695
+ process.exit(code != null ? code : 1);
696
+ });
697
+ rl.on("line", async (line) => {
698
+ const query = line.trim();
699
+ if (!serverReady) {
700
+ log3("system", "Server is not ready yet, please wait.", import_chalk5.default.yellow);
701
+ rl.prompt();
702
+ return;
703
+ }
704
+ if (query.toLowerCase() === "exit") {
705
+ rl.close();
706
+ }
707
+ if (query) {
708
+ try {
709
+ const response = await import_axios3.default.post(API_URL, { prompt: query });
710
+ const responseData = typeof response.data === "object" ? JSON.stringify(response.data, null, 2) : response.data;
711
+ log3("agent", responseData, import_chalk5.default.green);
712
+ } catch (error) {
713
+ if (import_axios3.default.isAxiosError(error)) {
714
+ log3("agent", `Error: ${error.message}`, import_chalk5.default.red);
715
+ } else if (error instanceof Error) {
716
+ log3("agent", `An unknown error occurred: ${error.message}`, import_chalk5.default.red);
717
+ }
718
+ }
719
+ }
720
+ rl.prompt();
721
+ });
722
+ rl.on("close", () => {
723
+ killProcess();
724
+ process.exit(0);
725
+ });
726
+ } catch (error) {
727
+ killProcess();
728
+ if (error instanceof Error) {
729
+ console.error(import_chalk5.default.red(`Error: ${error.message}`));
730
+ }
731
+ process.exit(1);
732
+ }
733
+ }
734
+ var codeCommand = new import_commander5.Command("code").description("Run the code agent for your project").action(async () => {
735
+ try {
736
+ await codeAction();
737
+ } catch (error) {
738
+ console.error(import_chalk5.default.red("\u274C Error:"), error instanceof Error ? error.message : String(error));
739
+ process.exit(1);
740
+ }
741
+ });
742
+
743
+ // src/commands/install.ts
744
+ var import_commander6 = require("commander");
745
+
746
+ // src/utils/experimental-installer.ts
747
+ var import_fs5 = __toESM(require("fs"));
748
+ var import_path6 = __toESM(require("path"));
749
+ var import_child_process2 = require("child_process");
750
+ var import_chalk6 = __toESM(require("chalk"));
751
+ var CWD_PACKAGE_JSON = import_path6.default.join(process.cwd(), "package.json");
752
+ var CWD_NODE_MODULES = import_path6.default.join(process.cwd(), "node_modules");
753
+ var MICROFOX_NODE_MODULES;
754
+ function log(message, isError = false, isWarning = false) {
755
+ const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString();
756
+ let prefix;
757
+ if (isError) {
758
+ prefix = import_chalk6.default.red(`\u274C [install-microfox ${timestamp}]`);
759
+ } else if (isWarning) {
760
+ prefix = import_chalk6.default.yellow(`\u26A0\uFE0F [install-microfox ${timestamp}]`);
761
+ } else {
762
+ prefix = import_chalk6.default.blue(`\u2139\uFE0F [install-microfox ${timestamp}]`);
763
+ }
764
+ console.log(`${prefix} ${message}`);
765
+ }
766
+ function logSuccess(message) {
767
+ const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString();
768
+ console.log(import_chalk6.default.green(`\u2705 [install-microfox ${timestamp}] ${message}`));
769
+ }
770
+ function logSection(title) {
771
+ console.log("\n" + "=".repeat(60));
772
+ console.log(` ${title}`);
773
+ console.log("=".repeat(60));
774
+ }
775
+ function findSourceDir(targetDirName) {
776
+ let currentDir = process.cwd();
777
+ for (let i = 0; i < 10; i++) {
778
+ const gitDir = import_path6.default.join(currentDir, ".git");
779
+ if (import_fs5.default.existsSync(gitDir)) {
780
+ const parentDir = import_path6.default.dirname(currentDir);
781
+ const microfoxDir = import_path6.default.join(parentDir, targetDirName);
782
+ if (import_fs5.default.existsSync(microfoxDir)) {
783
+ return microfoxDir;
784
+ }
785
+ }
786
+ const parent = import_path6.default.dirname(currentDir);
787
+ if (parent === currentDir) {
788
+ break;
789
+ }
790
+ currentDir = parent;
791
+ }
792
+ return null;
793
+ }
794
+ function copyDirectory(src, dest) {
795
+ try {
796
+ const normalizedSrc = import_path6.default.resolve(src);
797
+ const normalizedDest = import_path6.default.resolve(dest);
798
+ log(`Copying from: ${normalizedSrc}`);
799
+ log(`Copying to: ${normalizedDest}`);
800
+ if (!import_fs5.default.existsSync(normalizedDest)) {
801
+ import_fs5.default.mkdirSync(normalizedDest, { recursive: true });
802
+ }
803
+ const isWindows = process.platform === "win32";
804
+ if (isWindows) {
805
+ try {
806
+ (0, import_child_process2.execSync)(`robocopy "${normalizedSrc}" "${normalizedDest}" /E /NFL /NDL /NJH /NJS /nc /ns /np`, { stdio: "pipe" });
807
+ } catch (error) {
808
+ if (error.status !== 1 && error.status !== 0) {
809
+ throw error;
810
+ }
811
+ }
812
+ } else {
813
+ (0, import_child_process2.execSync)(`cp -r "${normalizedSrc}/." "${normalizedDest}"`, { stdio: "pipe" });
814
+ }
815
+ if (import_fs5.default.existsSync(normalizedDest) && import_fs5.default.readdirSync(normalizedDest).length > 0) {
816
+ log(`\u2705 Copied ${normalizedSrc} -> ${normalizedDest}`);
817
+ return true;
818
+ } else {
819
+ log(`\u274C Copy verification failed: destination is empty`);
820
+ return false;
821
+ }
822
+ } catch (error) {
823
+ log(`\u274C Failed to copy ${src} -> ${dest}: ${error.message}`);
824
+ return false;
825
+ }
826
+ }
827
+ function updatePackageJson(packageName) {
828
+ var _a, _b, _c;
829
+ try {
830
+ log(`Updating package.json to add ${packageName} with "*" version...`);
831
+ if (!import_fs5.default.existsSync(CWD_PACKAGE_JSON)) {
832
+ log(`Package.json file not found at: ${CWD_PACKAGE_JSON}`, true);
833
+ return false;
834
+ }
835
+ const packageJson = JSON.parse(import_fs5.default.readFileSync(CWD_PACKAGE_JSON, "utf8"));
836
+ const existingVersion = ((_a = packageJson.dependencies) == null ? void 0 : _a[packageName]) || ((_b = packageJson.devDependencies) == null ? void 0 : _b[packageName]);
837
+ if (existingVersion && existingVersion !== "*") {
838
+ log(`Package ${packageName} already exists with version: ${existingVersion}`, false, true);
839
+ log(`Updating to "*" for local development...`, false, true);
840
+ }
841
+ if (!packageJson.dependencies) {
842
+ packageJson.dependencies = {};
843
+ }
844
+ packageJson.dependencies[packageName] = "*";
845
+ if ((_c = packageJson.devDependencies) == null ? void 0 : _c[packageName]) {
846
+ delete packageJson.devDependencies[packageName];
847
+ log(`Moved ${packageName} from devDependencies to dependencies`);
848
+ }
849
+ import_fs5.default.writeFileSync(CWD_PACKAGE_JSON, JSON.stringify(packageJson, null, 2) + "\n");
850
+ logSuccess(`Added ${packageName}: "*" to package.json`);
851
+ return true;
852
+ } catch (error) {
853
+ if (error.code === "ENOENT") {
854
+ log(`Package.json file not found at: ${CWD_PACKAGE_JSON}`, true);
855
+ } else if (error instanceof SyntaxError) {
856
+ log(`Invalid JSON in package.json: ${error.message}`, true);
857
+ } else if (error.code === "EACCES") {
858
+ log(`Permission denied writing to package.json`, true);
859
+ } else {
860
+ log(`Failed to update package.json: ${error.message}`, true);
861
+ }
862
+ return false;
863
+ }
864
+ }
865
+ function installSpecificPackage(packageName) {
866
+ logSection(`Installing Specific Package: ${packageName}`);
867
+ if (!packageName || typeof packageName !== "string" || !packageName.startsWith("@microfox/")) {
868
+ log(`Invalid package name format: "${packageName}". Must start with "@microfox/"`, true);
869
+ process.exit(1);
870
+ }
871
+ const packageShortName = packageName.replace("@microfox/", "");
872
+ if (!packageShortName || packageShortName.trim() === "") {
873
+ log(`Invalid package name: "${packageName}"`, true);
874
+ process.exit(1);
875
+ }
876
+ const microfoxDir = import_path6.default.join(MICROFOX_NODE_MODULES, "@microfox");
877
+ const srcDir = import_path6.default.join(microfoxDir, packageShortName);
878
+ log(`Searching for package: ${packageName}`);
879
+ log(`Source directory: ${srcDir}`);
880
+ if (!import_fs5.default.existsSync(microfoxDir)) {
881
+ log(`Microfox packages directory not found at: ${microfoxDir}`, true);
882
+ process.exit(1);
883
+ }
884
+ if (!import_fs5.default.existsSync(srcDir)) {
885
+ log(`Package "${packageName}" not found in source packages`, true);
886
+ log(`Searched in: ${srcDir}`, true);
887
+ process.exit(1);
888
+ }
889
+ if (!updatePackageJson(packageName)) {
890
+ process.exit(1);
891
+ }
892
+ const microfoxScopeDir = import_path6.default.join(CWD_NODE_MODULES, "@microfox");
893
+ if (!import_fs5.default.existsSync(microfoxScopeDir)) {
894
+ import_fs5.default.mkdirSync(microfoxScopeDir, { recursive: true });
895
+ }
896
+ const destDir = import_path6.default.join(CWD_NODE_MODULES, "@microfox", packageShortName);
897
+ log(`Copying package files...`);
898
+ if (copyDirectory(srcDir, destDir)) {
899
+ logSection(`\u2705 SUCCESS`);
900
+ logSuccess(`Package ${packageName} installed for local development!`);
901
+ log(`Package location: ${destDir}`);
902
+ } else {
903
+ log(`Failed to copy package files`, true);
904
+ process.exit(1);
905
+ }
906
+ }
907
+ function installAllPackages() {
908
+ log('Installing all @microfox/* packages with "*" version from package.json...');
909
+ const packageJson = JSON.parse(import_fs5.default.readFileSync(CWD_PACKAGE_JSON, "utf8"));
910
+ const dependencies = { ...packageJson.dependencies, ...packageJson.devDependencies };
911
+ const microfoxPackages = Object.entries(dependencies).filter(([name, version2]) => name.startsWith("@microfox/") && version2 === "*").map(([name]) => name);
912
+ if (microfoxPackages.length === 0) {
913
+ log('\u2139\uFE0F No @microfox/* packages with "*" version found in package.json');
914
+ return;
915
+ }
916
+ log(`Found ${microfoxPackages.length} @microfox/* packages to install:`);
917
+ microfoxPackages.forEach((pkg) => log(` - ${pkg}`));
918
+ const microfoxScopeDir = import_path6.default.join(CWD_NODE_MODULES, "@microfox");
919
+ if (!import_fs5.default.existsSync(microfoxScopeDir)) {
920
+ import_fs5.default.mkdirSync(microfoxScopeDir, { recursive: true });
921
+ }
922
+ let successCount = 0;
923
+ let failureCount = 0;
924
+ for (const packageName of microfoxPackages) {
925
+ const packageShortName = packageName.replace("@microfox/", "");
926
+ const srcDir = import_path6.default.join(MICROFOX_NODE_MODULES, "@microfox", packageShortName);
927
+ const destDir = import_path6.default.join(CWD_NODE_MODULES, "@microfox", packageShortName);
928
+ if (!import_fs5.default.existsSync(srcDir)) {
929
+ log(`\u26A0\uFE0F Package ${packageName} not found in source node_modules, skipping...`);
930
+ failureCount++;
931
+ continue;
932
+ }
933
+ if (copyDirectory(srcDir, destDir)) {
934
+ successCount++;
935
+ } else {
936
+ failureCount++;
937
+ }
938
+ }
939
+ log(`
940
+ \u{1F4CA} Installation Summary:`);
941
+ log(` \u2705 Successfully installed: ${successCount} packages`);
942
+ if (failureCount > 0) {
943
+ log(` \u274C Failed to install: ${failureCount} packages`);
944
+ }
945
+ }
946
+ async function runExperimentalInstall(packages, targetDirName) {
947
+ try {
948
+ logSection("Microfox Local Package Installer (Experimental)");
949
+ log(`Started at: ${(/* @__PURE__ */ new Date()).toLocaleString()}`);
950
+ log(`Working directory: ${process.cwd()}`);
951
+ const sourceDir = findSourceDir(targetDirName);
952
+ if (!sourceDir) {
953
+ log(`Could not find source directory '${targetDirName}' in any parent of a .git directory.`, true);
954
+ log(`Searched up to 10 levels from ${process.cwd()}`, true);
955
+ process.exit(1);
956
+ }
957
+ log(`Found source directory at: ${sourceDir}`);
958
+ MICROFOX_NODE_MODULES = import_path6.default.join(sourceDir, "node_modules");
959
+ if (!import_fs5.default.existsSync(MICROFOX_NODE_MODULES)) {
960
+ log(`Source node_modules directory not found at: ${MICROFOX_NODE_MODULES}`, true);
961
+ log(`Please run 'npm install' or 'pnpm install' in ${sourceDir}`, true);
962
+ process.exit(1);
963
+ }
964
+ if (!import_fs5.default.existsSync(CWD_PACKAGE_JSON)) {
965
+ log(`package.json not found in current directory: ${CWD_PACKAGE_JSON}`, true);
966
+ process.exit(1);
967
+ }
968
+ if (packages.length > 0) {
969
+ log(`Installing ${packages.length} specific package(s)...`);
970
+ for (let i = 0; i < packages.length; i++) {
971
+ const packageName = packages[i];
972
+ log(`
973
+ [${i + 1}/${packages.length}] Processing: ${packageName}`);
974
+ installSpecificPackage(packageName);
975
+ }
976
+ logSection("\u{1F389} All Specified Packages Installed Successfully");
977
+ } else {
978
+ installAllPackages();
979
+ }
980
+ } catch (error) {
981
+ log("", true);
982
+ log(`Unexpected error occurred: ${error.message}`, true);
983
+ if (error.stack) {
984
+ log(`Stack trace: ${error.stack}`, true);
985
+ }
986
+ process.exit(1);
987
+ }
988
+ }
989
+
990
+ // src/commands/install.ts
991
+ var installCommand = new import_commander6.Command("install").description("Install packages for local development.").argument("[packages...]", "Specific packages to install").option("--experimental", "Enable experimental features").option("--target <name>", "Specify the target source directory name", "Microfox").action(async (packages, options) => {
992
+ if (options.experimental) {
993
+ await runExperimentalInstall(packages, options.target);
994
+ } else {
995
+ console.log("This command is only available with the --experimental flag.");
996
+ process.exit(1);
997
+ }
998
+ });
999
+
1000
+ // src/commands/update.ts
1001
+ var import_commander7 = require("commander");
1002
+
1003
+ // src/utils/experimental-updater.ts
1004
+ var import_fs6 = __toESM(require("fs"));
1005
+ var import_path7 = __toESM(require("path"));
1006
+ var import_child_process3 = require("child_process");
1007
+ var import_chalk7 = __toESM(require("chalk"));
1008
+ var CWD_PACKAGE_JSON2 = import_path7.default.join(process.cwd(), "package.json");
1009
+ function log2(message, isError = false, isWarning = false) {
1010
+ const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString();
1011
+ let prefix;
1012
+ if (isError) {
1013
+ prefix = import_chalk7.default.red(`\u274C [update-microfox ${timestamp}]`);
1014
+ } else if (isWarning) {
1015
+ prefix = import_chalk7.default.yellow(`\u26A0\uFE0F [update-microfox ${timestamp}]`);
1016
+ } else {
1017
+ prefix = import_chalk7.default.blue(`\u2139\uFE0F [update-microfox ${timestamp}]`);
1018
+ }
1019
+ console.log(`${prefix} ${message}`);
1020
+ }
1021
+ function logSuccess2(message) {
1022
+ const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString();
1023
+ console.log(import_chalk7.default.green(`\u2705 [update-microfox ${timestamp}] ${message}`));
1024
+ }
1025
+ function logSection2(title) {
1026
+ console.log("\n" + "=".repeat(60));
1027
+ console.log(` ${title}`);
1028
+ console.log("=".repeat(60));
1029
+ }
1030
+ function updatePackage(packageName, isDev) {
1031
+ var _a;
1032
+ log2(`Updating package to latest: ${packageName}`);
1033
+ const saveFlag = isDev ? "--save-dev" : "--save";
1034
+ try {
1035
+ (0, import_child_process3.execSync)(`npm install ${packageName}@latest ${saveFlag}`, { cwd: process.cwd(), stdio: "pipe" });
1036
+ logSuccess2(`Successfully updated ${packageName} to the latest version from npm.`);
1037
+ return true;
1038
+ } catch (error) {
1039
+ log2(`Failed to update ${packageName}: ${error.message}`, true);
1040
+ log2(`Stderr: ${(_a = error.stderr) == null ? void 0 : _a.toString()}`, true);
1041
+ return false;
1042
+ }
1043
+ }
1044
+ function updateSpecificPackage(packageName, isDevFlag) {
1045
+ logSection2(`Updating Specific Package: ${packageName}`);
1046
+ if (!packageName || typeof packageName !== "string" || !packageName.startsWith("@microfox/")) {
1047
+ log2(`Invalid package name: "${packageName}". Must start with "@microfox/".`, true);
1048
+ process.exit(1);
1049
+ }
1050
+ const packageJson = JSON.parse(import_fs6.default.readFileSync(CWD_PACKAGE_JSON2, "utf8"));
1051
+ const dependencies = packageJson.dependencies || {};
1052
+ const devDependencies = packageJson.devDependencies || {};
1053
+ let isDev = !!devDependencies[packageName];
1054
+ if (!dependencies[packageName] && !devDependencies[packageName]) {
1055
+ log2(`Package "${packageName}" not found in dependencies.`, false, true);
1056
+ log2(`Attempting to install it as a new package...`, false, true);
1057
+ isDev = isDevFlag;
1058
+ } else {
1059
+ log2(`Package found in ${isDev ? "devDependencies" : "dependencies"}.`);
1060
+ }
1061
+ if (updatePackage(packageName, isDev)) {
1062
+ logSection2(`\u2705 SUCCESS`);
1063
+ logSuccess2(`Package ${packageName} updated successfully!`);
1064
+ } else {
1065
+ log2(`Failed to update ${packageName}`, true);
1066
+ process.exit(1);
1067
+ }
1068
+ }
1069
+ function updateAllPackages() {
1070
+ logSection2("Updating all @microfox/* packages to latest");
1071
+ const packageJson = JSON.parse(import_fs6.default.readFileSync(CWD_PACKAGE_JSON2, "utf8"));
1072
+ const dependencies = packageJson.dependencies || {};
1073
+ const devDependencies = packageJson.devDependencies || {};
1074
+ const allDependencies = { ...dependencies, ...devDependencies };
1075
+ const microfoxPackages = Object.entries(allDependencies).filter(([name]) => name.startsWith("@microfox/")).map(([name]) => name);
1076
+ if (microfoxPackages.length === 0) {
1077
+ log2("\u2139\uFE0F No @microfox/* packages found in package.json.");
1078
+ return;
1079
+ }
1080
+ log2(`Found ${microfoxPackages.length} packages to update:`);
1081
+ microfoxPackages.forEach((pkg) => log2(` - ${pkg}`));
1082
+ let successCount = 0;
1083
+ let failureCount = 0;
1084
+ for (const packageName of microfoxPackages) {
1085
+ const isDev = !!devDependencies[packageName];
1086
+ if (updatePackage(packageName, isDev)) {
1087
+ successCount++;
1088
+ } else {
1089
+ failureCount++;
1090
+ }
1091
+ }
1092
+ log2(`
1093
+ \u{1F4CA} Update Summary:`);
1094
+ log2(` \u2705 Successfully updated: ${successCount} packages`);
1095
+ if (failureCount > 0) {
1096
+ log2(` \u274C Failed to update: ${failureCount} packages`);
1097
+ }
1098
+ }
1099
+ async function runUpdate(packages, options) {
1100
+ try {
1101
+ logSection2("Microfox Package Updater (Experimental)");
1102
+ if (!import_fs6.default.existsSync(CWD_PACKAGE_JSON2)) {
1103
+ log2(`package.json not found in ${process.cwd()}`, true);
1104
+ process.exit(1);
1105
+ }
1106
+ if (packages.length > 0) {
1107
+ log2(`Updating ${packages.length} specific package(s)...`);
1108
+ packages.forEach((pkg) => updateSpecificPackage(pkg, !!options.dev));
1109
+ logSection2("\u{1F389} All specified packages processed.");
1110
+ } else {
1111
+ updateAllPackages();
1112
+ }
1113
+ } catch (error) {
1114
+ log2("", true);
1115
+ log2(`An unexpected error occurred: ${error.message}`, true);
1116
+ if (error.stack) {
1117
+ log2(`Stack trace: ${error.stack}`, true);
1118
+ }
1119
+ process.exit(1);
1120
+ }
1121
+ }
1122
+
1123
+ // src/commands/update.ts
1124
+ var updateCommand = new import_commander7.Command("update").description("Update @microfox packages to the latest versions from npm.").argument("[packages...]", "Specific packages to update").option("--experimental", "Enable experimental features").option("--dev", "Update packages in devDependencies").action(async (packages, options) => {
1125
+ if (options.experimental) {
1126
+ await runUpdate(packages, options);
1127
+ } else {
1128
+ console.log("This command is only available with the --experimental flag.");
1129
+ process.exit(1);
1130
+ }
1131
+ });
1132
+
1133
+ // package.json
1134
+ var version = "1.0.11";
1135
+
1136
+ // src/cli.ts
1137
+ var program = new import_commander8.Command();
1138
+ program.name("microfox").description("Universal CLI tool for creating and managing Microfox projects").version(version);
1139
+ program.addCommand(kickstartCommand);
1140
+ program.addCommand(addCommand);
1141
+ program.addCommand(pushCommand);
1142
+ program.addCommand(statusCommand);
1143
+ program.addCommand(logsCommand);
1144
+ program.addCommand(metricsCommand);
1145
+ program.addCommand(codeCommand);
1146
+ program.addCommand(installCommand);
1147
+ program.addCommand(updateCommand);
1148
+ program.action(() => {
1149
+ if (process.argv.length <= 2) {
1150
+ program.help();
1151
+ }
1152
+ });
1153
+ program.parse(process.argv);
1154
+ //# sourceMappingURL=cli.js.map