-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·1203 lines (1082 loc) · 34 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { Command } from "commander";
import chalk from "chalk";
import fs from "fs-extra";
import path from "path";
import { input, select, number, expand } from "@inquirer/prompts";
import crypto from "crypto";
const configPath = path.join(process.env.HOME, ".ecli", "config.json");
const componentsDir = path.join(process.cwd(), "Components");
const stateFilePath = path.join(componentsDir, ".ecli-state.json");
// File path constants for the new architecture
const getComponentPaths = (componentName) => ({
form: path.join(componentsDir, componentName, "form.json"),
inputs: path.join(componentsDir, componentName, "inputs.json"),
workflow: path.join(componentsDir, componentName, "workflow.json"),
test: path.join(componentsDir, componentName, "test.json"),
credits: path.join(componentsDir, componentName, "credits.js"),
api: path.join(componentsDir, componentName, "api.json"),
body: path.join(componentsDir, componentName, "body.json"),
});
async function fetchGetComponent(config, name) {
try {
const url = `${config.apiUrl}/workflows/name/${name}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // API already returns { data, error } structure
} catch (error) {
return { data: null, error: `Failed to fetch component: ${error.message}` };
}
}
async function fetchGetServers(config) {
try {
const url = `${config.apiUrl}/servers`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // API already returns { data, error } structure
} catch (error) {
return { data: null, error: `Failed to fetch servers: ${error.message}` };
}
}
async function fetchCreateComponent(config, data) {
try {
const url = `${config.apiUrl}/workflows`;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // API already returns { data, error } structure
} catch (error) {
return {
data: null,
error: `Failed to create component: ${error.message}`,
};
}
}
async function fetchRemoveComponent(config, id) {
try {
const url = `${config.apiUrl}/workflows/${id}`;
const response = await fetch(url, {
method: "DELETE",
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // API already returns { data, error } structure
} catch (error) {
return {
data: null,
error: `Failed to remove component: ${error.message}`,
};
}
}
async function fetchUpdateComponent(config, id, data) {
try {
const url = `${config.apiUrl}/workflows/${id}`;
const response = await fetch(url, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // API already returns { data, error } structure
} catch (error) {
return {
data: null,
error: `Failed to update component: ${error.message}`,
};
}
}
async function fetchGetFormConfig(config, name) {
try {
const url = name
? `${config.apiUrl}/form-configs/name/${name}`
: `${config.apiUrl}/form-configs`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
} catch (error) {
return {
data: null,
error: `Failed to fetch form config: ${error.message}`,
};
}
}
async function fetchCreateFormConfig(config, name, data) {
try {
const url = `${config.apiUrl}/form-configs`;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name,
data,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
} catch (error) {
return {
data: null,
error: `Failed to create form config: ${error.message}`,
};
}
}
async function fetchDeleteFormConfig(config, id) {
try {
const url = `${config.apiUrl}/form-configs/${id}`;
const response = await fetch(url, {
method: "DELETE",
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
} catch (error) {
return {
data: null,
error: `Failed to delete form config: ${error.message}`,
};
}
}
async function initConfig() {
try {
const defaultConfig = {
currentEnv: "dev",
environments: {
dev: {
apiUrl: "https://cycle-16-dev-api-openstudio.emprops.ai",
},
},
};
await fs.ensureDir(path.dirname(configPath));
await fs.writeJson(configPath, defaultConfig, { spaces: 2 });
console.log(chalk.green("Configuration file created successfully!"));
} catch (error) {
console.error(
chalk.red(`Failed to initialize configuration: ${error.message}`),
);
}
}
async function getCurrentEnvironment() {
try {
const config = await fs.readJson(configPath);
return {
name: config.currentEnv,
...config.environments[config.currentEnv],
};
} catch (error) {
console.error(
chalk.red(`Failed to get current environment: ${error.message}`),
);
process.exit(1);
}
}
async function addEnvironment(name, apiUrl) {
try {
const config = await fs.readJson(configPath);
if (config.environments[name]) {
console.error(chalk.red(`Environment "${name}" already exists`));
return;
}
config.environments[name] = { apiUrl };
await fs.writeJson(configPath, config, { spaces: 2 });
console.log(chalk.green(`Environment "${name}" added successfully`));
} catch (error) {
console.error(chalk.red(`Failed to add environment: ${error.message}`));
}
}
async function removeEnvironment(name) {
try {
const config = await fs.readJson(configPath);
if (!config.environments[name]) {
console.error(chalk.red(`Environment "${name}" does not exist`));
return;
}
if (config.currentEnv === name) {
console.error(chalk.red(`Cannot remove current environment "${name}"`));
return;
}
delete config.environments[name];
await fs.writeJson(configPath, config, { spaces: 2 });
console.log(chalk.green(`Environment "${name}" removed successfully`));
} catch (error) {
console.error(chalk.red(`Failed to remove environment: ${error.message}`));
}
}
async function setEnvironment(name) {
try {
const config = await fs.readJson(configPath);
if (!config.environments[name]) {
console.error(chalk.red(`Environment "${name}" does not exist`));
return;
}
config.currentEnv = name;
await fs.writeJson(configPath, config, { spaces: 2 });
console.log(chalk.green(`Switched to environment "${name}"`));
} catch (error) {
console.error(chalk.red(`Failed to switch environment: ${error.message}`));
}
}
async function listEnvironments() {
try {
const config = await fs.readJson(configPath);
console.log(chalk.blue("\nAvailable Environments:"));
Object.entries(config.environments).forEach(([name, env]) => {
const isCurrent = name === config.currentEnv;
const prefix = isCurrent ? chalk.green("* ") : " ";
console.log(`${prefix}${name}: ${env.apiUrl}`);
});
} catch (error) {
console.error(chalk.red(`Failed to list environments: ${error.message}`));
}
}
async function newComponent() {
try {
const config = await getCurrentEnvironment();
const { data: servers, error: fetchServersError } =
await fetchGetServers(config);
if (fetchServersError) {
console.error(chalk.red(fetchServersError));
return;
}
const serverChoices = servers
.map((server) => ({
name: server.name,
value: server.id,
}))
.concat({ name: "None", value: undefined });
let componentData;
try {
componentData = {
name: await input({
message: "Enter the name of the component",
required: true,
}),
label: await input({
message: "Enter the label of the component",
required: true,
}),
description: await input({
message: "Enter the description of the component",
required: true,
}),
server_id: await select({
message: "Select the server",
choices: serverChoices,
}),
output_mime_type: await input({
message: "Enter the output mime type",
initial: "image/png",
}),
type: await select({
message: "Select the type of the component",
choices: [
{ title: "Basic", value: "basic" },
{ title: "Comfy Workflow", value: "comfy_workflow" },
{ title: "Fetch API", value: "fetch_api" },
],
}),
order: await number({
message: "Enter the order of the component",
default: 0,
}),
display: false,
};
} catch (error) {
return;
}
// Check if the component already exists
const componentPath = path.join(componentsDir, componentData.name);
const { error: componentCreationError } = await fetchCreateComponent(
config,
componentData,
);
if (componentCreationError) {
console.error(chalk.red(componentCreationError));
return;
}
if (!(await fs.pathExists(componentPath))) {
const paths = getComponentPaths(componentData.name);
try {
// Create component directory
await fs.ensureDir(componentPath);
// Create ref directory only for comfy_workflow type
if (componentData.type === "comfy_workflow") {
await fs.mkdir(path.join(componentPath, "ref"));
}
if (componentData.type === "comfy_workflow") {
// Create all required files with empty objects/default content
await fs.writeJson(
paths.form,
{ main: [], advanced: [] },
{ spaces: 2 },
);
await fs.writeJson(paths.inputs, {}, { spaces: 2 });
await fs.writeJson(paths.workflow, {}, { spaces: 2 });
await fs.writeJson(paths.test, {}, { spaces: 2 });
await fs.writeFile(
paths.credits,
`function computeCost(context) {\n return { cost: 1 };\n}`,
);
} else if (componentData.type === "fetch_api") {
// For fetch_api, create credits.js, form.json, inputs.json, body.json and api.json
await fs.writeJson(
paths.form,
{ main: [], advanced: [] },
{ spaces: 2 },
);
await fs.writeJson(paths.api, {}, { spaces: 2 });
await fs.writeJson(paths.inputs, {}, { spaces: 2 });
await fs.writeJson(paths.body, {}, { spaces: 2 });
await fs.writeFile(
paths.credits,
`function computeCost(context) {\n return { cost: 1 };\n}`,
);
} else if (componentData.type === "basic") {
// For basic, only create credits.js
await fs.writeFile(
paths.credits,
`function computeCost(context) {\n return { cost: 1 };\n}`,
);
}
console.log(
chalk.green(`Component "${componentData.name}" added successfully!`),
);
} catch (fsError) {
console.error(
chalk.red(`Failed to create component files: ${fsError.message}`),
);
// Attempt to rollback the API creation
const { data: component } = await fetchGetComponent(
config,
componentData.name,
);
if (component?.id) {
await fetchRemoveComponent(config, component.id);
}
}
}
} catch (error) {
console.error(chalk.red(`Unexpected error: ${error.message}`));
}
}
async function removeComponent(componentName) {
try {
const config = await getCurrentEnvironment();
const { data: component, error: getComponentError } =
await fetchGetComponent(config, componentName);
if (getComponentError) {
console.error(chalk.red(getComponentError));
return;
}
const { error: removeComponentError } = await fetchRemoveComponent(
config,
component.id,
);
if (removeComponentError) {
console.error(chalk.red(removeComponentError));
return;
}
const componentPath = path.join(componentsDir, componentName);
if (!(await fs.pathExists(componentPath))) {
console.error(chalk.red(`Component "${componentName}" does not exist!`));
return;
}
await fs.remove(componentPath);
console.log(
chalk.green(`Component "${componentName}" removed successfully!`),
);
} catch (error) {
console.error(chalk.red(`Unexpected error: ${error.message}`));
}
}
async function applyComponents(componentName, options = { verbose: false }) {
try {
const config = await getCurrentEnvironment();
const paths = getComponentPaths(componentName);
const { error: componentError, data: component } = await fetchGetComponent(
config,
componentName,
);
if (componentError) {
console.error(chalk.red(componentError));
return;
}
// Check for required files based on component type
let requiredFiles = [];
if (component.type === "fetch_api") {
requiredFiles = [
{ path: paths.form, name: "Form" },
{ path: paths.api, name: "API" },
{ path: paths.credits, name: "Credits" },
];
} else if (component.type === "basic") {
requiredFiles = [{ path: paths.credits, name: "Credits" }];
} else if (component.type === "comfy_workflow") {
requiredFiles = [
{ path: paths.form, name: "Form" },
{ path: paths.inputs, name: "Inputs" },
{ path: paths.workflow, name: "Workflow" },
{ path: paths.test, name: "Test" },
{ path: paths.credits, name: "Credits" },
];
}
for (const file of requiredFiles) {
if (!(await fs.pathExists(file.path))) {
console.error(
chalk.red(
`${file.name} file not found for component "${componentName}"!`,
),
);
return;
}
}
// Read files based on component type
let form = undefined;
let inputs = undefined;
let workflow = undefined;
let test = undefined;
let api = undefined;
let body = undefined;
let credits = undefined;
if (component.type === "comfy_workflow") {
form = await fs.readJson(paths.form);
inputs = await fs.readJson(paths.inputs);
workflow = await fs.readJson(paths.workflow);
if (await fs.pathExists(paths.test)) {
test = await fs.readJson(paths.test);
}
credits = await fs.readFile(paths.credits, "utf8");
} else if (component.type === "fetch_api") {
form = await fs.readJson(paths.form);
api = await fs.readJson(paths.api);
if (await fs.pathExists(paths.inputs)) {
inputs = await fs.readJson(paths.inputs);
}
if (await fs.pathExists(paths.body)) {
body = await fs.readJson(paths.body);
}
credits = await fs.readFile(paths.credits, "utf8");
} else if (component.type === "basic") {
credits = await fs.readFile(paths.credits, "utf8");
}
console.log(chalk.green(`Applying component "${componentName}"...`));
const data = {
form,
inputs,
workflow,
test,
api,
body,
credits_script: credits,
output_node_id: workflow?.output_node_id || null,
};
if (options.verbose) {
console.log(chalk.blue("\nSubmitting data:"));
console.log(JSON.stringify(data, null, 2));
}
const { error: updateError } = await fetchUpdateComponent(
config,
component.id,
{
data,
},
);
if (updateError) {
console.error(chalk.red(`Failed to update component: ${updateError}`));
return;
}
console.log(
chalk.green(`Component "${componentName}" applied successfully!`),
);
} catch (error) {
console.error(chalk.red(`Unexpected error: ${error.message}`));
}
}
async function getComponent(componentName, options) {
try {
console.log(`Getting details of component "${componentName}"...`);
const config = await getCurrentEnvironment();
const paths = getComponentPaths(componentName);
if (options.form) {
if (await fs.pathExists(paths.form)) {
const form = await fs.readJson(paths.form);
console.log(chalk.magentaBright(JSON.stringify(form, null, 2)));
} else {
console.log(chalk.yellow("Form not found"));
}
} else if (options.input) {
if (await fs.pathExists(paths.inputs)) {
const inputs = await fs.readJson(paths.inputs);
console.log(chalk.magentaBright(JSON.stringify(inputs, null, 2)));
} else {
console.log(chalk.yellow("Inputs not found"));
}
} else if (options.workflow) {
if (await fs.pathExists(paths.workflow)) {
const workflow = await fs.readJson(paths.workflow);
console.log(chalk.magentaBright(JSON.stringify(workflow, null, 2)));
} else {
console.log(chalk.yellow("Workflow not found"));
}
} else if (options.credits) {
if (await fs.pathExists(paths.credits)) {
const credits = await fs.readFile(paths.credits, "utf8");
console.log(chalk.magenta(credits));
} else {
console.log(chalk.yellow("Credits not found"));
}
} else {
// Fetch and display all component data
const { data: component, error } = await fetchGetComponent(
config,
componentName,
);
if (error) {
console.error(chalk.red(error));
return;
}
console.log(JSON.stringify(component, null, 2));
}
} catch (error) {
console.error(chalk.red(`Unexpected error: ${error.message}`));
}
}
async function displayComponents(componentName) {
try {
const config = await getCurrentEnvironment();
const { data: components, error: getComponentError } =
await fetchGetComponent(config, componentName);
if (getComponentError) {
console.error(chalk.red(getComponentError));
return;
}
const answer = await expand({
message: `Do you want to display/hide the ${componentName}?`,
default: "n",
choices: [
{
key: "y",
name: "Display",
value: "yes",
},
{
key: "n",
name: "Hide",
value: "no",
},
{
key: "x",
name: "Abort",
value: "abort",
},
],
});
switch (answer) {
case "yes": {
const { error } = await fetchUpdateComponent(config, components.id, {
display: true,
});
if (error) {
console.error(chalk.red(`Failed to update component: ${error}`));
return;
}
console.log(chalk.green("Component displayed successfully!"));
break;
}
case "no": {
const { error } = await fetchUpdateComponent(config, components.id, {
display: false,
});
if (error) {
console.error(chalk.red(`Failed to update component: ${error}`));
return;
}
console.log(chalk.green("Component hidden successfully!"));
break;
}
case "abort":
break;
}
} catch (error) {
console.error(chalk.red(`Unexpected error: ${error.message}`));
}
}
async function calculateFileHash(filePath) {
try {
const content = await fs.readFile(filePath, "utf8");
return crypto.createHash("sha256").update(content).digest("hex");
} catch (error) {
return null;
}
}
async function getComponentHash(componentName) {
const paths = getComponentPaths(componentName);
// Get component type first
const config = await getCurrentEnvironment();
const { data: component } = await fetchGetComponent(config, componentName);
const hashes = {
credits: await calculateFileHash(paths.credits),
};
if (component.type === "comfy_workflow") {
hashes.form = await calculateFileHash(paths.form);
hashes.inputs = await calculateFileHash(paths.inputs);
hashes.workflow = await calculateFileHash(paths.workflow);
hashes.test = await calculateFileHash(paths.test);
} else if (component.type === "fetch_api") {
hashes.form = await calculateFileHash(paths.form);
hashes.api = await calculateFileHash(paths.api);
}
return hashes;
}
async function loadState() {
try {
if (await fs.pathExists(stateFilePath)) {
return await fs.readJson(stateFilePath);
}
return { components: {} };
} catch (error) {
console.error(
chalk.yellow(`Warning: Could not load state file: ${error.message}`),
);
return { components: {} };
}
}
async function saveState(state) {
try {
await fs.writeJson(stateFilePath, state, { spaces: 2 });
} catch (error) {
console.error(
chalk.yellow(`Warning: Could not save state file: ${error.message}`),
);
}
}
async function getValidComponents() {
try {
const items = await fs.readdir(componentsDir);
return items.filter(
(item) =>
!item.startsWith("_") &&
item !== "p52vid" &&
item !== ".ecli-state.json" &&
fs.statSync(path.join(componentsDir, item)).isDirectory(),
);
} catch (error) {
console.error(
chalk.red(`Error reading components directory: ${error.message}`),
);
return [];
}
}
async function hasComponentChanged(componentName, state) {
const currentHashes = await getComponentHash(componentName);
const storedState = state.components[componentName];
if (!storedState) {
return true;
}
const storedHashes = storedState.fileHashes;
return Object.entries(currentHashes).some(
([file, hash]) => hash !== storedHashes[file],
);
}
async function applyChangedComponents(
options = { force: false, dryRun: false },
) {
try {
const state = await loadState();
const components = await getValidComponents();
if (components.length === 0) {
console.log(chalk.yellow("No valid components found."));
return;
}
console.log(chalk.blue("Checking for changed components..."));
const changedComponents = [];
for (const component of components) {
const changed =
options.force || (await hasComponentChanged(component, state));
if (changed) {
changedComponents.push(component);
}
}
if (changedComponents.length === 0) {
console.log(chalk.green("No components have changed."));
return;
}
console.log(
chalk.blue(`\nFound ${changedComponents.length} changed components:`),
);
changedComponents.forEach((component) =>
console.log(chalk.cyan(`- ${component}`)),
);
if (options.dryRun) {
console.log(chalk.yellow("\nDry run - no changes will be made."));
return;
}
console.log(chalk.blue("\nApplying changes..."));
const results = {
success: [],
failure: [],
};
for (const component of changedComponents) {
try {
console.log(chalk.cyan(`\nApplying ${component}...`));
await applyComponents(component);
// Update state after successful apply
state.components[component] = {
lastApplied: new Date().toISOString(),
fileHashes: await getComponentHash(component),
};
results.success.push(component);
console.log(chalk.green(`✓ ${component} applied successfully`));
} catch (error) {
results.failure.push({ component, error: error.message });
console.log(
chalk.red(`✗ Failed to apply ${component}: ${error.message}`),
);
}
}
// Save state only after all successful applications
await saveState(state);
// Print summary
console.log(chalk.blue("\nSummary:"));
console.log(
chalk.green(`✓ Successfully applied: ${results.success.length}`),
);
if (results.failure.length > 0) {
console.log(chalk.red(`✗ Failed to apply: ${results.failure.length}`));
console.log(chalk.red("\nFailed components:"));
results.failure.forEach(({ component, error }) =>
console.log(chalk.red(`- ${component}: ${error}`)),
);
}
} catch (error) {
console.error(chalk.red(`\nUnexpected error: ${error.message}`));
}
}
async function updateComponent(componentName) {
try {
const config = await getCurrentEnvironment();
// Get current component data
const { data: component, error: componentError } = await fetchGetComponent(
config,
componentName,
);
if (componentError) {
console.error(chalk.red(componentError));
return;
}
const { data: servers, error: fetchServersError } =
await fetchGetServers(config);
if (fetchServersError) {
console.error(chalk.red(fetchServersError));
return;
}
const serverChoices = servers
.map((server) => ({
name: server.name,
value: server.id,
}))
.concat({ name: "None", value: undefined });
let updatedData;
try {
updatedData = {
name: await input({
message: "Enter the new name of the component",
default: component.name,
required: true,
}),
label: await input({
message: "Enter the new label of the component",
default: component.label,
required: true,
}),
description: await input({
message: "Enter the new description of the component",
default: component.description,
required: true,
}),
server_id: await select({
message: "Select the new server",
choices: serverChoices,
default: component.server_id,
}),
output_mime_type: await input({
message: "Enter the new output mime type",
default: component.output_mime_type || "image/png",
}),
type: await select({
message: "Select the new type of the component",
choices: [
{ title: "Basic", value: "basic" },
{ title: "Comfy Workflow", value: "comfy_workflow" },
{ title: "Fetch API", value: "fetch_api" },
],
default: component.type,
}),
order: await number({
message: "Enter the new order of the component",
default: component.order || 0,
}),
};
} catch (error) {
return;
}
// Update the component on the server
const { error: updateError } = await fetchUpdateComponent(
config,
component.id,
updatedData,
);
if (updateError) {
console.error(chalk.red(updateError));
return;
}
console.log(
chalk.green(`✓ Component ${componentName} updated successfully`),
);
} catch (error) {
console.error(chalk.red(`Failed to update component: ${error.message}`));
}
}
async function getFormConfig(fileName) {
try {
const config = await getCurrentEnvironment();
const result = await fetchGetFormConfig(config, fileName);
if (result.error) {
console.error(chalk.red(result.error));
return;
}
console.log(JSON.stringify(result.data, null, 2));
} catch (error) {
console.error(chalk.red(`Error: ${error.message}`));
}
}
async function newFormConfig(fileName) {
try {
const config = await getCurrentEnvironment();
const formConfigPath = path.join(componentsDir, "_form_confs", fileName);
if (!fs.existsSync(formConfigPath)) {
console.error(
chalk.red(
`Error: File ${fileName} not found in Components/_form_confs`,
),
);
return;
}
const fileData = await fs.readJson(formConfigPath);
const result = await fetchCreateFormConfig(config, fileName, fileData);
if (result.error) {
console.error(chalk.red(result.error));
return;
}
console.log(chalk.green(`Successfully created form config: ${fileName}`));
console.log(JSON.stringify(result.data, null, 2));
} catch (error) {
console.error(chalk.red(`Error: ${error.message}`));
}
}
async function deleteFormConfig(fileName, options) {
try {
const config = await getCurrentEnvironment();
const formConfigPath = path.join(componentsDir, "_form_confs", fileName);
const { data: formConfig, error: getFormConfigError } =
await fetchGetFormConfig(config, fileName);