@dainprotocol/cli 1.0.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.
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __generator = (this && this.__generator) || function (thisArg, body) {
35
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
36
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
37
+ function verb(n) { return function (v) { return step([n, v]); }; }
38
+ function step(op) {
39
+ if (f) throw new TypeError("Generator is already executing.");
40
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
41
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
42
+ if (y = 0, t) op = [op[0] & 2, t.value];
43
+ switch (op[0]) {
44
+ case 0: case 1: t = op; break;
45
+ case 4: _.label++; return { value: op[1], done: false };
46
+ case 5: _.label++; y = op[1]; op = [0]; continue;
47
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
48
+ default:
49
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
50
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
51
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
52
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
53
+ if (t[2]) _.ops.pop();
54
+ _.trys.pop(); continue;
55
+ }
56
+ op = body.call(thisArg, _);
57
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
58
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
+ }
60
+ };
61
+ var __importDefault = (this && this.__importDefault) || function (mod) {
62
+ return (mod && mod.__esModule) ? mod : { "default": mod };
63
+ };
64
+ Object.defineProperty(exports, "__esModule", { value: true });
65
+ exports.default = build;
66
+ var esbuild = __importStar(require("esbuild"));
67
+ var utils_1 = require("../utils");
68
+ var ora_1 = __importDefault(require("ora"));
69
+ var fs_extra_1 = __importDefault(require("fs-extra"));
70
+ var path_1 = __importDefault(require("path"));
71
+ function build() {
72
+ return __awaiter(this, void 0, void 0, function () {
73
+ var spinner, config, staticDir, error_1;
74
+ return __generator(this, function (_a) {
75
+ switch (_a.label) {
76
+ case 0:
77
+ spinner = (0, ora_1.default)('Building project...').start();
78
+ config = (0, utils_1.getDainConfig)();
79
+ _a.label = 1;
80
+ case 1:
81
+ _a.trys.push([1, 7, , 8]);
82
+ // Ensure build directory exists
83
+ return [4 /*yield*/, fs_extra_1.default.ensureDir('build')];
84
+ case 2:
85
+ // Ensure build directory exists
86
+ _a.sent();
87
+ // Build the main application
88
+ return [4 /*yield*/, esbuild.build({
89
+ entryPoints: [config['main-file']],
90
+ bundle: true,
91
+ platform: 'node',
92
+ target: 'node14',
93
+ outfile: 'build/index.js',
94
+ minify: true,
95
+ sourcemap: true,
96
+ })];
97
+ case 3:
98
+ // Build the main application
99
+ _a.sent();
100
+ staticDir = path_1.default.join(process.cwd(), 'static');
101
+ if (!fs_extra_1.default.existsSync(staticDir)) return [3 /*break*/, 5];
102
+ return [4 /*yield*/, fs_extra_1.default.copy(staticDir, 'build/static')];
103
+ case 4:
104
+ _a.sent();
105
+ (0, utils_1.logInfo)('Static files copied to build/static');
106
+ return [3 /*break*/, 6];
107
+ case 5:
108
+ (0, utils_1.logInfo)('No static directory found. Skipping static file copy.');
109
+ _a.label = 6;
110
+ case 6:
111
+ spinner.succeed('Build completed successfully.');
112
+ (0, utils_1.logSuccess)('Project built and ready for deployment.');
113
+ return [3 /*break*/, 8];
114
+ case 7:
115
+ error_1 = _a.sent();
116
+ spinner.fail('Build failed.');
117
+ (0, utils_1.logError)('Build process encountered an error', error_1);
118
+ process.exit(1);
119
+ return [3 /*break*/, 8];
120
+ case 8: return [2 /*return*/];
121
+ }
122
+ });
123
+ });
124
+ }
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.default = config;
43
+ var fs_extra_1 = __importDefault(require("fs-extra"));
44
+ var path_1 = __importDefault(require("path"));
45
+ var utils_1 = require("../utils");
46
+ function config(action, key, value) {
47
+ return __awaiter(this, void 0, void 0, function () {
48
+ var configPath, config_1, error_1;
49
+ return __generator(this, function (_a) {
50
+ switch (_a.label) {
51
+ case 0:
52
+ configPath = path_1.default.join(process.cwd(), 'dain.json');
53
+ _a.label = 1;
54
+ case 1:
55
+ _a.trys.push([1, 7, , 8]);
56
+ return [4 /*yield*/, fs_extra_1.default.readJSON(configPath)];
57
+ case 2:
58
+ config_1 = _a.sent();
59
+ if (!(action === 'view')) return [3 /*break*/, 3];
60
+ if (key) {
61
+ (0, utils_1.logInfo)("".concat(key, ": ").concat(config_1[key]));
62
+ }
63
+ else {
64
+ console.log(JSON.stringify(config_1, null, 2));
65
+ }
66
+ return [3 /*break*/, 6];
67
+ case 3:
68
+ if (!(action === 'edit' && key && value)) return [3 /*break*/, 5];
69
+ config_1[key] = value;
70
+ return [4 /*yield*/, fs_extra_1.default.writeJSON(configPath, config_1, { spaces: 2 })];
71
+ case 4:
72
+ _a.sent();
73
+ (0, utils_1.logSuccess)("Updated ".concat(key, " to ").concat(value));
74
+ return [3 /*break*/, 6];
75
+ case 5:
76
+ (0, utils_1.logError)('Invalid command. Use "view" or "edit <key> <value>"');
77
+ _a.label = 6;
78
+ case 6: return [3 /*break*/, 8];
79
+ case 7:
80
+ error_1 = _a.sent();
81
+ (0, utils_1.logError)('Error accessing configuration', error_1);
82
+ return [3 /*break*/, 8];
83
+ case 8: return [2 /*return*/];
84
+ }
85
+ });
86
+ });
87
+ }
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.default = deploy;
43
+ var build_1 = __importDefault(require("./build"));
44
+ var utils_1 = require("../utils");
45
+ var ora_1 = __importDefault(require("ora"));
46
+ var fs_extra_1 = __importDefault(require("fs-extra"));
47
+ function deploy() {
48
+ return __awaiter(this, void 0, void 0, function () {
49
+ var spinner, staticFilesPath, error_1;
50
+ return __generator(this, function (_a) {
51
+ switch (_a.label) {
52
+ case 0:
53
+ spinner = (0, ora_1.default)("Deploying project...").start();
54
+ _a.label = 1;
55
+ case 1:
56
+ _a.trys.push([1, 3, , 4]);
57
+ // First, build the project
58
+ return [4 /*yield*/, (0, build_1.default)()];
59
+ case 2:
60
+ // First, build the project
61
+ _a.sent();
62
+ // Here you would add your deployment logic
63
+ // For example, uploading the build/index.js file and static files to your server
64
+ (0, utils_1.logInfo)("Deployment logic to be implemented");
65
+ staticFilesPath = (0, utils_1.getStaticFilesPath)();
66
+ if (fs_extra_1.default.existsSync(staticFilesPath)) {
67
+ (0, utils_1.logInfo)("Static files are available at: ".concat(staticFilesPath));
68
+ // Here you would implement the logic to deploy these static files
69
+ }
70
+ else {
71
+ (0, utils_1.logInfo)("No static files to deploy.");
72
+ }
73
+ (0, utils_1.logSuccess)("Deployment completed successfully. (NO LOGIC HERE YET, JUST EXAMPLE)");
74
+ spinner.succeed("Deployment completed successfully.");
75
+ (0, utils_1.logSuccess)("Project deployed and running.");
76
+ return [3 /*break*/, 4];
77
+ case 3:
78
+ error_1 = _a.sent();
79
+ spinner.fail("Deployment failed.");
80
+ (0, utils_1.logError)("Error during deployment", error_1);
81
+ return [3 /*break*/, 4];
82
+ case 4: return [2 /*return*/];
83
+ }
84
+ });
85
+ });
86
+ }
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.default = dev;
43
+ var child_process_1 = require("child_process");
44
+ var utils_1 = require("../utils");
45
+ var ora_1 = __importDefault(require("ora"));
46
+ var chokidar_1 = __importDefault(require("chokidar"));
47
+ var path_1 = __importDefault(require("path"));
48
+ var childProcess = null;
49
+ function startProcess(command) {
50
+ var _a, _b;
51
+ if (childProcess) {
52
+ childProcess.kill();
53
+ }
54
+ var spinner = (0, ora_1.default)('Starting development server...').start();
55
+ childProcess = (0, child_process_1.exec)(command);
56
+ (_a = childProcess.stdout) === null || _a === void 0 ? void 0 : _a.on('data', function (data) {
57
+ spinner.succeed('Development server started.');
58
+ console.log(data);
59
+ });
60
+ (_b = childProcess.stderr) === null || _b === void 0 ? void 0 : _b.on('data', function (data) {
61
+ spinner.fail('Development server error.');
62
+ (0, utils_1.logError)(data);
63
+ });
64
+ childProcess.on('close', function (code) {
65
+ if (code !== 0) {
66
+ spinner.fail("Development server exited with code ".concat(code));
67
+ }
68
+ });
69
+ }
70
+ function dev(options) {
71
+ return __awaiter(this, void 0, void 0, function () {
72
+ var config, command, watchPaths, watcher;
73
+ return __generator(this, function (_a) {
74
+ switch (_a.label) {
75
+ case 0:
76
+ process.env.PORT = options.port;
77
+ config = (0, utils_1.getDainConfig)();
78
+ command = "ts-node ".concat(config['main-file']);
79
+ startProcess(command);
80
+ if (!!options.noproxy) return [3 /*break*/, 2];
81
+ return [4 /*yield*/, (0, utils_1.setupProxy)(options.port)];
82
+ case 1:
83
+ _a.sent();
84
+ _a.label = 2;
85
+ case 2:
86
+ watchPaths = [
87
+ path_1.default.dirname(config['main-file']),
88
+ (0, utils_1.getStaticFilesPath)()
89
+ ];
90
+ watcher = chokidar_1.default.watch(watchPaths, {
91
+ ignored: /(^|[\/\\])\../, // ignore dotfiles
92
+ persistent: true
93
+ });
94
+ watcher.on('change', function (path) {
95
+ (0, utils_1.logInfo)("File ".concat(path, " has been changed. Restarting..."));
96
+ startProcess(command);
97
+ });
98
+ (0, utils_1.logInfo)('Watching for file changes...');
99
+ return [2 /*return*/];
100
+ }
101
+ });
102
+ });
103
+ }
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.default = init;
43
+ var fs_extra_1 = __importDefault(require("fs-extra"));
44
+ var path_1 = __importDefault(require("path"));
45
+ var utils_1 = require("../utils");
46
+ var ora_1 = __importDefault(require("ora"));
47
+ function init(projectName) {
48
+ return __awaiter(this, void 0, void 0, function () {
49
+ var spinner, projectDir, templateDir, packageJsonPath, packageJson, error_1;
50
+ return __generator(this, function (_a) {
51
+ switch (_a.label) {
52
+ case 0:
53
+ spinner = (0, ora_1.default)('Initializing Dain project...').start();
54
+ projectDir = path_1.default.join(process.cwd(), projectName);
55
+ templateDir = path_1.default.join(__dirname, '..', '..', 'templates', 'default');
56
+ _a.label = 1;
57
+ case 1:
58
+ _a.trys.push([1, 6, , 7]);
59
+ // Create project directory
60
+ return [4 /*yield*/, fs_extra_1.default.ensureDir(projectDir)];
61
+ case 2:
62
+ // Create project directory
63
+ _a.sent();
64
+ // Copy template files
65
+ return [4 /*yield*/, fs_extra_1.default.copy(templateDir, projectDir)];
66
+ case 3:
67
+ // Copy template files
68
+ _a.sent();
69
+ packageJsonPath = path_1.default.join(projectDir, 'package.json');
70
+ return [4 /*yield*/, fs_extra_1.default.readJson(packageJsonPath)];
71
+ case 4:
72
+ packageJson = _a.sent();
73
+ packageJson.name = projectName;
74
+ return [4 /*yield*/, fs_extra_1.default.writeJson(packageJsonPath, packageJson, { spaces: 2 })];
75
+ case 5:
76
+ _a.sent();
77
+ spinner.succeed("Initialized Dain project: ".concat(projectName));
78
+ (0, utils_1.logSuccess)("Project created at ".concat(projectDir));
79
+ (0, utils_1.logInfo)('Run the following commands to get started:');
80
+ (0, utils_1.logInfo)(" cd ".concat(projectName));
81
+ (0, utils_1.logInfo)(' npm install');
82
+ (0, utils_1.logInfo)(' dain dev');
83
+ return [3 /*break*/, 7];
84
+ case 6:
85
+ error_1 = _a.sent();
86
+ spinner.fail('Project initialization failed');
87
+ (0, utils_1.logError)('Error initializing project', error_1);
88
+ return [3 /*break*/, 7];
89
+ case 7: return [2 /*return*/];
90
+ }
91
+ });
92
+ });
93
+ }
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = start;
4
+ var child_process_1 = require("child_process");
5
+ var utils_1 = require("../utils");
6
+ function start(options) {
7
+ process.env.PORT = options.port;
8
+ var command = "node ".concat((0, utils_1.getDainConfig)()['main-file']);
9
+ (0, child_process_1.exec)(command, function (error, stdout, stderr) {
10
+ if (error) {
11
+ console.error("Error: ".concat(error.message));
12
+ return;
13
+ }
14
+ if (stderr) {
15
+ console.error("Stderr: ".concat(stderr));
16
+ return;
17
+ }
18
+ console.log("Stdout: ".concat(stdout));
19
+ });
20
+ }
package/dist/index.js ADDED
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ var commander_1 = require("commander");
8
+ var init_1 = __importDefault(require("./commands/init"));
9
+ var dev_1 = __importDefault(require("./commands/dev"));
10
+ var deploy_1 = __importDefault(require("./commands/deploy"));
11
+ var build_1 = __importDefault(require("./commands/build"));
12
+ var start_1 = __importDefault(require("./commands/start"));
13
+ var program = new commander_1.Command();
14
+ program
15
+ .name('dain')
16
+ .description('CLI for Dain Protocol')
17
+ .version('1.0.0');
18
+ program
19
+ .command('init <projectName>')
20
+ .description('Initialize a new Dain project')
21
+ .action(function (projectName) {
22
+ if (!projectName) {
23
+ console.error('Error: Project name is required');
24
+ process.exit(1);
25
+ }
26
+ (0, init_1.default)(projectName);
27
+ });
28
+ program
29
+ .command('dev')
30
+ .description('Run the project in development mode')
31
+ .option('--port <port>', 'Set the port number', '2022')
32
+ .option('--noproxy', 'Disable localtunnel proxy')
33
+ .action(function (options) {
34
+ (0, dev_1.default)(options);
35
+ });
36
+ program
37
+ .command('deploy')
38
+ .description('Deploy the project')
39
+ .action(function () {
40
+ (0, deploy_1.default)();
41
+ });
42
+ program
43
+ .command('build')
44
+ .description('Build the project')
45
+ .action(function () {
46
+ (0, build_1.default)();
47
+ });
48
+ program
49
+ .command('start')
50
+ .description('Start the project')
51
+ .option('--port <port>', 'Set the port number', '2022')
52
+ .action(function (options) {
53
+ (0, start_1.default)(options);
54
+ });
55
+ program.parse(process.argv);
56
+ // Add a catch-all command for unknown commands
57
+ program.on('command:*', function () {
58
+ console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' '));
59
+ process.exit(1);
60
+ });
61
+ // Handle case when no command is provided
62
+ if (!process.argv.slice(2).length) {
63
+ program.outputHelp();
64
+ process.exit(1);
65
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "project-id": "",
3
+ "project-api-key": "",
4
+ "main-file": "src/index.ts"
5
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "dain-project",
3
+ "version": "1.0.0",
4
+ "description": "A Dain Protocol project",
5
+ "main": "src/index.ts",
6
+ "scripts": {
7
+ "start": "ts-node src/index.ts",
8
+ "dev": "dain dev",
9
+ "build": "dain build",
10
+ "deploy": "dain deploy"
11
+ },
12
+ "dependencies": {
13
+ "@dainprotocol/service-sdk": "^1.0.8",
14
+ "zod": "^3.23.8"
15
+ },
16
+ "devDependencies": {
17
+ "@types/express": "^4.17.13",
18
+ "ts-node": "^10.4.0",
19
+ "typescript": "^4.5.4"
20
+ }
21
+ }
@@ -0,0 +1,198 @@
1
+ import { z } from "zod";
2
+
3
+ import { DAINService } from "@dainprotocol/service-sdk";
4
+
5
+ const getWeatherConfig: DAINService.ToolConfig = {
6
+ id: "get-weather",
7
+ name: "Get Weather",
8
+ description: "Fetches current weather for a city",
9
+ input: z
10
+ .object({
11
+ city: z.string().describe("The name of the city to get weather for"),
12
+ })
13
+ .describe("Input parameters for the weather request"),
14
+ output: z
15
+ .object({
16
+ temperature: z.number().describe("Current temperature in Celsius"),
17
+ condition: z
18
+ .string()
19
+ .describe("Weather condition (e.g., Sunny, Rainy, Cloudy)"),
20
+ })
21
+ .describe("Weather information for the requested city"),
22
+ pricing: { pricePerUse: 0.01, currency: "USD" },
23
+ handler: async ({ city }, agentInfo) => {
24
+ console.log(`Agent ${agentInfo.agentId} requested weather for ${city}`);
25
+ return {
26
+ text: `The current weather in ${city} is 22°C and Sunny`,
27
+ data: { temperature: 22, condition: "Sunny" },
28
+ ui: {
29
+ type: "h2",
30
+ children: "Weather test",
31
+ },
32
+ };
33
+ },
34
+ };
35
+
36
+ const getWeatherForecastConfig: DAINService.ToolConfig = {
37
+ id: "get-weather-forecast",
38
+ name: "Get Weather Forecast",
39
+ description: "Fetches a 5-day weather forecast for a city",
40
+ input: z
41
+ .object({
42
+ city: z.string().describe("The name of the city to get the forecast for"),
43
+ })
44
+ .describe("Input parameters for the forecast request"),
45
+ output: z
46
+ .array(
47
+ z.object({
48
+ date: z.string().describe("Date of the forecast"),
49
+ temperature: z.number().describe("Forecasted temperature in Celsius"),
50
+ condition: z.string().describe("Forecasted weather condition"),
51
+ })
52
+ )
53
+ .describe("5-day weather forecast for the requested city"),
54
+ pricing: { pricePerUse: 0.02, currency: "USD" },
55
+ handler: async ({ city }, agentInfo) => {
56
+ console.log(
57
+ `Agent ${agentInfo.agentId} requested weather forecast for ${city}`
58
+ );
59
+ return {
60
+ text: `The 5-day weather forecast for ${city} is included in the attached data`,
61
+ data: [
62
+ { date: "2021-09-01", temperature: 22, condition: "Sunny" },
63
+ { date: "2021-09-02", temperature: 23, condition: "Partly Cloudy" },
64
+ { date: "2021-09-03", temperature: 21, condition: "Rainy" },
65
+ { date: "2021-09-04", temperature: 20, condition: "Cloudy" },
66
+ { date: "2021-09-05", temperature: 22, condition: "Sunny" },
67
+ ],
68
+ ui: {},
69
+ };
70
+ },
71
+ };
72
+
73
+ const getAirQualityConfig: DAINService.ToolConfig = {
74
+ id: "get-air-quality",
75
+ name: "Get Air Quality",
76
+ description: "Fetches air quality information for a city",
77
+ input: z
78
+ .object({
79
+ city: z.string().describe("The name of the city to get air quality for"),
80
+ })
81
+ .describe("Input parameters for the air quality request"),
82
+ output: z
83
+ .object({
84
+ aqi: z.number().describe("Air Quality Index"),
85
+ pollutant: z.string().describe("Main pollutant"),
86
+ level: z
87
+ .string()
88
+ .describe("Air quality level (e.g., Good, Moderate, Unhealthy)"),
89
+ })
90
+ .describe("Air quality information for the requested city"),
91
+ pricing: { pricePerUse: 0.015, currency: "USD" },
92
+ handler: async ({ city }, agentInfo) => {
93
+ console.log(`Agent ${agentInfo.agentId} requested air quality for ${city}`);
94
+ return {
95
+ text: `The air quality in ${city} is good`,
96
+ data: { aqi: 50, pollutant: "PM2.5", level: "Good" },
97
+ ui: {},
98
+ };
99
+ },
100
+ };
101
+
102
+ const getHistoricalWeatherConfig: DAINService.ToolConfig = {
103
+ id: "get-historical-weather",
104
+ name: "Get Historical Weather",
105
+ description: "Retrieves historical weather data for a specific date and city",
106
+ input: z
107
+ .object({
108
+ city: z.string().describe("The name of the city"),
109
+ date: z.string().describe("The date in YYYY-MM-DD format"),
110
+ })
111
+ .describe("Input parameters for the historical weather request"),
112
+ output: z
113
+ .object({
114
+ temperature: z.number().describe("Temperature in Celsius"),
115
+ condition: z.string().describe("Weather condition"),
116
+ precipitation: z.number().describe("Precipitation in mm"),
117
+ })
118
+ .describe("Historical weather information for the requested city and date"),
119
+ pricing: { pricePerUse: 0.03, currency: "USD" },
120
+ handler: async ({ city, date }, agentInfo) => {
121
+ console.log(
122
+ `Agent ${agentInfo.agentId} requested historical weather for ${city} on ${date}`
123
+ );
124
+ return {
125
+ text: `The historical weather in ${city} on ${date} was 20°C and Rainy`,
126
+ data: { temperature: 20, condition: "Rainy", precipitation: 5 },
127
+ ui: {},
128
+ };
129
+ },
130
+ };
131
+
132
+ const weatherServiceConfig: DAINService.ServiceConfig = {
133
+ id: "weather-service",
134
+ name: "Weather Service",
135
+ description: "Provides comprehensive weather information",
136
+ metadata: {
137
+ capabilities: [
138
+ "current-weather",
139
+ "weather-forecast",
140
+ "air-quality",
141
+ "historical-weather",
142
+ ],
143
+ languages: ["en"],
144
+ },
145
+ recommendedPrompt:
146
+ "Ask about weather, forecasts, air quality, or historical weather data",
147
+ recommendedTools: [
148
+ "get-weather",
149
+ "get-weather-forecast",
150
+ "get-air-quality",
151
+ "get-historical-weather",
152
+ ],
153
+ };
154
+
155
+ const weatherToolboxConfig: DAINService.ToolboxConfig = {
156
+ id: "weather-toolbox",
157
+ name: "Weather Toolbox",
158
+ description: "Collection of weather-related tools",
159
+ tools: [
160
+ "get-weather",
161
+ "get-weather-forecast",
162
+ "get-air-quality",
163
+ "get-historical-weather",
164
+ ],
165
+ metadata: {
166
+ complexity: "Medium",
167
+ applicableFields: ["Meteorology", "Travel", "Environmental Science"],
168
+ },
169
+ recommendedPrompt:
170
+ "Use these tools for various weather-related tasks and analyses",
171
+ };
172
+
173
+ const dainService = DAINService.defineDAINService({
174
+ metadata: {
175
+ title: "Comprehensive Weather DAIN Service",
176
+ description:
177
+ "A DAIN service for detailed weather information, forecasts, air quality, and historical data",
178
+ version: "1.1.0",
179
+ author: "Your Name",
180
+ tags: ["weather", "forecast", "air-quality", "historical-weather", "dain"],
181
+ },
182
+ identity: {
183
+ apiKey:
184
+ "sk_agent_3_0_49bhyNKMYYH3TtjqycgKQCBhUuTu4bnYvKzStv3bBmKaY55LMBmLVQR1wAtkizdGPM3wBAA2X6rfYpfpEuisx5Cc",
185
+ },
186
+ services: [weatherServiceConfig],
187
+ tools: [
188
+ getWeatherConfig,
189
+ getWeatherForecastConfig,
190
+ getAirQualityConfig,
191
+ getHistoricalWeatherConfig,
192
+ ],
193
+ toolboxes: [weatherToolboxConfig],
194
+ });
195
+
196
+ dainService.startNode({ port: 2022 }).then(() => {
197
+ console.log("Comprehensive Weather DAIN Service is running on port 2022");
198
+ });
package/dist/utils.js ADDED
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.getDainConfig = getDainConfig;
43
+ exports.setupProxy = setupProxy;
44
+ exports.logError = logError;
45
+ exports.logSuccess = logSuccess;
46
+ exports.logInfo = logInfo;
47
+ exports.getStaticFilesPath = getStaticFilesPath;
48
+ var fs_1 = __importDefault(require("fs"));
49
+ var path_1 = __importDefault(require("path"));
50
+ var client_1 = require("@dainprotocol/tunnel/client");
51
+ var ora_1 = __importDefault(require("ora"));
52
+ var chalk_1 = __importDefault(require("chalk"));
53
+ function getDainConfig() {
54
+ var configPath = path_1.default.join(process.cwd(), 'dain.json');
55
+ return JSON.parse(fs_1.default.readFileSync(configPath, 'utf-8'));
56
+ }
57
+ function setupProxy(port) {
58
+ return __awaiter(this, void 0, void 0, function () {
59
+ var spinner, client, tunnelUrl, error_1;
60
+ return __generator(this, function (_a) {
61
+ switch (_a.label) {
62
+ case 0:
63
+ spinner = (0, ora_1.default)('Setting up proxy...').start();
64
+ _a.label = 1;
65
+ case 1:
66
+ _a.trys.push([1, 3, , 4]);
67
+ client = new client_1.DainTunnel('ws://localhost:3000');
68
+ return [4 /*yield*/, client.start(parseInt(port))];
69
+ case 2:
70
+ tunnelUrl = _a.sent();
71
+ spinner.succeed(chalk_1.default.green("Proxy URL: ".concat(tunnelUrl)));
72
+ return [2 /*return*/, client];
73
+ case 3:
74
+ error_1 = _a.sent();
75
+ spinner.fail(chalk_1.default.red('Error setting up proxy'));
76
+ console.error(chalk_1.default.red(error_1));
77
+ return [3 /*break*/, 4];
78
+ case 4: return [2 /*return*/];
79
+ }
80
+ });
81
+ });
82
+ }
83
+ function logError(message, error) {
84
+ console.error(chalk_1.default.red("Error: ".concat(message)));
85
+ if (error) {
86
+ console.error(chalk_1.default.red(error));
87
+ }
88
+ }
89
+ function logSuccess(message) {
90
+ console.log(chalk_1.default.green("Success: ".concat(message)));
91
+ }
92
+ function logInfo(message) {
93
+ console.log(chalk_1.default.blue("Info: ".concat(message)));
94
+ }
95
+ function getStaticFilesPath() {
96
+ return path_1.default.join(process.cwd(), 'static');
97
+ }
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@dainprotocol/cli",
3
+ "version": "1.0.0",
4
+ "description": "CLI for Dain Protocol",
5
+ "main": "dist/index.js",
6
+ "bin": {
7
+ "dain": "./dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "templates"
12
+ ],
13
+ "dependencies": {
14
+ "@dainprotocol/tunnel": "^1.0.1",
15
+ "@types/fs-extra": "^11.0.4",
16
+ "@types/localtunnel": "^2.0.4",
17
+ "chalk": "^4.1.2",
18
+ "chokidar": "^3.6.0",
19
+ "commander": "^11.1.0",
20
+ "esbuild": "^0.23.1",
21
+ "fs-extra": "^11.2.0",
22
+ "localtunnel": "^2.0.2",
23
+ "ora": "^3.4.0"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^22.5.4",
27
+ "ts-node": "^10.9.2",
28
+ "typescript": "^5.5.4"
29
+ },
30
+ "scripts": {
31
+ "build": "tsc && cp -r templates dist/"
32
+ }
33
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "project-id": "",
3
+ "project-api-key": "",
4
+ "main-file": "src/index.ts"
5
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "dain-project",
3
+ "version": "1.0.0",
4
+ "description": "A Dain Protocol project",
5
+ "main": "src/index.ts",
6
+ "scripts": {
7
+ "start": "ts-node src/index.ts",
8
+ "dev": "dain dev",
9
+ "build": "dain build",
10
+ "deploy": "dain deploy"
11
+ },
12
+ "dependencies": {
13
+ "@dainprotocol/service-sdk": "^1.0.8",
14
+ "zod": "^3.23.8"
15
+ },
16
+ "devDependencies": {
17
+ "@types/express": "^4.17.13",
18
+ "ts-node": "^10.4.0",
19
+ "typescript": "^4.5.4"
20
+ }
21
+ }
@@ -0,0 +1,198 @@
1
+ import { z } from "zod";
2
+
3
+ import { DAINService } from "@dainprotocol/service-sdk";
4
+
5
+ const getWeatherConfig: DAINService.ToolConfig = {
6
+ id: "get-weather",
7
+ name: "Get Weather",
8
+ description: "Fetches current weather for a city",
9
+ input: z
10
+ .object({
11
+ city: z.string().describe("The name of the city to get weather for"),
12
+ })
13
+ .describe("Input parameters for the weather request"),
14
+ output: z
15
+ .object({
16
+ temperature: z.number().describe("Current temperature in Celsius"),
17
+ condition: z
18
+ .string()
19
+ .describe("Weather condition (e.g., Sunny, Rainy, Cloudy)"),
20
+ })
21
+ .describe("Weather information for the requested city"),
22
+ pricing: { pricePerUse: 0.01, currency: "USD" },
23
+ handler: async ({ city }, agentInfo) => {
24
+ console.log(`Agent ${agentInfo.agentId} requested weather for ${city}`);
25
+ return {
26
+ text: `The current weather in ${city} is 22°C and Sunny`,
27
+ data: { temperature: 22, condition: "Sunny" },
28
+ ui: {
29
+ type: "h2",
30
+ children: "Weather test",
31
+ },
32
+ };
33
+ },
34
+ };
35
+
36
+ const getWeatherForecastConfig: DAINService.ToolConfig = {
37
+ id: "get-weather-forecast",
38
+ name: "Get Weather Forecast",
39
+ description: "Fetches a 5-day weather forecast for a city",
40
+ input: z
41
+ .object({
42
+ city: z.string().describe("The name of the city to get the forecast for"),
43
+ })
44
+ .describe("Input parameters for the forecast request"),
45
+ output: z
46
+ .array(
47
+ z.object({
48
+ date: z.string().describe("Date of the forecast"),
49
+ temperature: z.number().describe("Forecasted temperature in Celsius"),
50
+ condition: z.string().describe("Forecasted weather condition"),
51
+ })
52
+ )
53
+ .describe("5-day weather forecast for the requested city"),
54
+ pricing: { pricePerUse: 0.02, currency: "USD" },
55
+ handler: async ({ city }, agentInfo) => {
56
+ console.log(
57
+ `Agent ${agentInfo.agentId} requested weather forecast for ${city}`
58
+ );
59
+ return {
60
+ text: `The 5-day weather forecast for ${city} is included in the attached data`,
61
+ data: [
62
+ { date: "2021-09-01", temperature: 22, condition: "Sunny" },
63
+ { date: "2021-09-02", temperature: 23, condition: "Partly Cloudy" },
64
+ { date: "2021-09-03", temperature: 21, condition: "Rainy" },
65
+ { date: "2021-09-04", temperature: 20, condition: "Cloudy" },
66
+ { date: "2021-09-05", temperature: 22, condition: "Sunny" },
67
+ ],
68
+ ui: {},
69
+ };
70
+ },
71
+ };
72
+
73
+ const getAirQualityConfig: DAINService.ToolConfig = {
74
+ id: "get-air-quality",
75
+ name: "Get Air Quality",
76
+ description: "Fetches air quality information for a city",
77
+ input: z
78
+ .object({
79
+ city: z.string().describe("The name of the city to get air quality for"),
80
+ })
81
+ .describe("Input parameters for the air quality request"),
82
+ output: z
83
+ .object({
84
+ aqi: z.number().describe("Air Quality Index"),
85
+ pollutant: z.string().describe("Main pollutant"),
86
+ level: z
87
+ .string()
88
+ .describe("Air quality level (e.g., Good, Moderate, Unhealthy)"),
89
+ })
90
+ .describe("Air quality information for the requested city"),
91
+ pricing: { pricePerUse: 0.015, currency: "USD" },
92
+ handler: async ({ city }, agentInfo) => {
93
+ console.log(`Agent ${agentInfo.agentId} requested air quality for ${city}`);
94
+ return {
95
+ text: `The air quality in ${city} is good`,
96
+ data: { aqi: 50, pollutant: "PM2.5", level: "Good" },
97
+ ui: {},
98
+ };
99
+ },
100
+ };
101
+
102
+ const getHistoricalWeatherConfig: DAINService.ToolConfig = {
103
+ id: "get-historical-weather",
104
+ name: "Get Historical Weather",
105
+ description: "Retrieves historical weather data for a specific date and city",
106
+ input: z
107
+ .object({
108
+ city: z.string().describe("The name of the city"),
109
+ date: z.string().describe("The date in YYYY-MM-DD format"),
110
+ })
111
+ .describe("Input parameters for the historical weather request"),
112
+ output: z
113
+ .object({
114
+ temperature: z.number().describe("Temperature in Celsius"),
115
+ condition: z.string().describe("Weather condition"),
116
+ precipitation: z.number().describe("Precipitation in mm"),
117
+ })
118
+ .describe("Historical weather information for the requested city and date"),
119
+ pricing: { pricePerUse: 0.03, currency: "USD" },
120
+ handler: async ({ city, date }, agentInfo) => {
121
+ console.log(
122
+ `Agent ${agentInfo.agentId} requested historical weather for ${city} on ${date}`
123
+ );
124
+ return {
125
+ text: `The historical weather in ${city} on ${date} was 20°C and Rainy`,
126
+ data: { temperature: 20, condition: "Rainy", precipitation: 5 },
127
+ ui: {},
128
+ };
129
+ },
130
+ };
131
+
132
+ const weatherServiceConfig: DAINService.ServiceConfig = {
133
+ id: "weather-service",
134
+ name: "Weather Service",
135
+ description: "Provides comprehensive weather information",
136
+ metadata: {
137
+ capabilities: [
138
+ "current-weather",
139
+ "weather-forecast",
140
+ "air-quality",
141
+ "historical-weather",
142
+ ],
143
+ languages: ["en"],
144
+ },
145
+ recommendedPrompt:
146
+ "Ask about weather, forecasts, air quality, or historical weather data",
147
+ recommendedTools: [
148
+ "get-weather",
149
+ "get-weather-forecast",
150
+ "get-air-quality",
151
+ "get-historical-weather",
152
+ ],
153
+ };
154
+
155
+ const weatherToolboxConfig: DAINService.ToolboxConfig = {
156
+ id: "weather-toolbox",
157
+ name: "Weather Toolbox",
158
+ description: "Collection of weather-related tools",
159
+ tools: [
160
+ "get-weather",
161
+ "get-weather-forecast",
162
+ "get-air-quality",
163
+ "get-historical-weather",
164
+ ],
165
+ metadata: {
166
+ complexity: "Medium",
167
+ applicableFields: ["Meteorology", "Travel", "Environmental Science"],
168
+ },
169
+ recommendedPrompt:
170
+ "Use these tools for various weather-related tasks and analyses",
171
+ };
172
+
173
+ const dainService = DAINService.defineDAINService({
174
+ metadata: {
175
+ title: "Comprehensive Weather DAIN Service",
176
+ description:
177
+ "A DAIN service for detailed weather information, forecasts, air quality, and historical data",
178
+ version: "1.1.0",
179
+ author: "Your Name",
180
+ tags: ["weather", "forecast", "air-quality", "historical-weather", "dain"],
181
+ },
182
+ identity: {
183
+ apiKey:
184
+ "sk_agent_3_0_49bhyNKMYYH3TtjqycgKQCBhUuTu4bnYvKzStv3bBmKaY55LMBmLVQR1wAtkizdGPM3wBAA2X6rfYpfpEuisx5Cc",
185
+ },
186
+ services: [weatherServiceConfig],
187
+ tools: [
188
+ getWeatherConfig,
189
+ getWeatherForecastConfig,
190
+ getAirQualityConfig,
191
+ getHistoricalWeatherConfig,
192
+ ],
193
+ toolboxes: [weatherToolboxConfig],
194
+ });
195
+
196
+ dainService.startNode({ port: 2022 }).then(() => {
197
+ console.log("Comprehensive Weather DAIN Service is running on port 2022");
198
+ });