UNPKG

@jss-rule-engine/workflow

Version:

394 lines 21 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { 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; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DatabaseService = void 0; var client_1 = require("@libsql/client"); var helper_1 = require("./lib/helper"); var DatabaseService = /** @class */ (function () { function DatabaseService(options) { if (!options.url) { throw new Error('Database URL is required for @libsql/client'); } this.client = (0, client_1.createClient)({ fetch: fetch, url: options.url, authToken: options.authToken, }); } DatabaseService.prototype.addEmbedding = function (item) { var _a, _b; return __awaiter(this, void 0, void 0, function () { var model, args, sqlResponse, error_1; return __generator(this, function (_c) { switch (_c.label) { case 0: _c.trys.push([0, 3, , 4]); if (!((_b = (_a = item === null || item === void 0 ? void 0 : item.content) === null || _a === void 0 ? void 0 : _a.trim()) === null || _b === void 0 ? void 0 : _b.length)) { //nothing to index return [2 /*return*/]; } return [4 /*yield*/, (0, helper_1.generateEmbeddings)(item.content)]; case 1: model = _c.sent(); console.log('Generated embedding.'); args = [ item.id || '', item.name || '', item.path || '', item.parentId || '', item.content, new Float32Array(model.embedding.embedding).buffer, item.indexId || '' ]; return [4 /*yield*/, this.client.execute({ sql: 'INSERT OR REPLACE INTO rag_embeddings (id, name, path, parent_id, content, embedding, index_id) VALUES (?, ?, ?, ?, ?, ?, ?)', args: args })]; case 2: sqlResponse = _c.sent(); console.log('Added to db - ', sqlResponse); return [3 /*break*/, 4]; case 3: error_1 = _c.sent(); console.error('Failed to generate embeddings for item', item.id, ':', error_1); return [3 /*break*/, 4]; case 4: return [2 /*return*/]; } }); }); }; DatabaseService.prototype.findRelevantEmbeddings = function (data, indexId, topN, thresold) { return __awaiter(this, void 0, void 0, function () { var model, result, resultArr, error_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 3, , 4]); return [4 /*yield*/, (0, helper_1.generateEmbeddings)(data)]; case 1: model = _a.sent(); console.log('Searching RAG content in DB'); return [4 /*yield*/, this.client.execute({ sql: "SELECT *, vector_distance_cos(embedding, ?) as distance \n FROM rag_embeddings \n WHERE index_id = ? AND distance < ? AND embedding IS NOT NULL\n ORDER BY distance ASC LIMIT ?", args: [new Float32Array(model.embedding.embedding).buffer, indexId, thresold, topN] })]; case 2: result = _a.sent(); resultArr = result.rows.map(function (row) { return ({ id: row.id, name: row.name, path: row.path, parentId: row.parent_id, content: row.content, embedding: row.embedding, indexId: row.index_id, distance: row.distance }); }); console.log('Found relevant embeddings - ', resultArr === null || resultArr === void 0 ? void 0 : resultArr.length); return [2 /*return*/, resultArr]; case 3: error_2 = _a.sent(); console.error('Failed to find relevant embeddings:', error_2); return [2 /*return*/, []]; case 4: return [2 /*return*/]; } }); }); }; DatabaseService.prototype.getEmbeddingsByParentId = function (parentId, indexId) { return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.execute({ sql: 'SELECT * FROM rag_embeddings WHERE parent_id = ? AND index_id = ?', args: [parentId, indexId] })]; case 1: result = _a.sent(); return [2 /*return*/, result.rows]; } }); }); }; DatabaseService.prototype.removeEmbedding = function (id, indexId) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.execute({ sql: 'DELETE FROM rag_embeddings WHERE id = ? AND index_id = ?', args: [id, indexId] })]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; DatabaseService.prototype.cleanDb = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: // Delete all rows from both tables return [4 /*yield*/, this.client.execute('DELETE FROM workflow_visitors')]; case 1: // Delete all rows from both tables _a.sent(); return [4 /*yield*/, this.client.execute('DELETE FROM workflow_scheduled_tasks')]; case 2: _a.sent(); return [4 /*yield*/, this.client.execute('DELETE FROM rag_embeddings')]; case 3: _a.sent(); return [2 /*return*/]; } }); }); }; DatabaseService.prototype.getScheduledTasks = function () { return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.execute('SELECT * FROM workflow_scheduled_tasks')]; case 1: result = _a.sent(); return [2 /*return*/, result.rows.map(function (row) { var _a; return ({ id: row.id, visitorId: row.visitor_id, workflowId: row.workflow_id, taskType: row.task_type, scheduledTime: row.scheduled_time, payload: (_a = row.payload) !== null && _a !== void 0 ? _a : undefined }); })]; } }); }); }; DatabaseService.prototype.init = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: // Ensure the table exists return [4 /*yield*/, this.client.execute("\n CREATE TABLE IF NOT EXISTS workflow_visitors (\n visitor_id TEXT NOT NULL,\n state_id TEXT NOT NULL,\n workflow_id TEXT NOT NULL\n )\n ")]; case 1: // Ensure the table exists _a.sent(); return [4 /*yield*/, this.client.execute("\n CREATE TABLE IF NOT EXISTS workflow_scheduled_tasks (\n id TEXT PRIMARY KEY,\n visitor_id TEXT NOT NULL,\n workflow_id TEXT NOT NULL,\n task_type TEXT NOT NULL,\n scheduled_time INTEGER NOT NULL,\n payload TEXT\n )\n ")]; case 2: _a.sent(); return [4 /*yield*/, this.client.execute("\n CREATE TABLE IF NOT EXISTS rag_embeddings (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n path TEXT NOT NULL,\n parent_id TEXT NOT NULL,\n content TEXT NOT NULL,\n embedding F32_BLOB(768),\n index_id TEXT NOT NULL\n );")]; case 3: _a.sent(); return [4 /*yield*/, this.client.execute(" \n CREATE INDEX IF NOT EXISTS idx_rag_embeddings \n ON rag_embeddings (libsql_vector_idx(embedding));")]; case 4: _a.sent(); return [2 /*return*/]; } }); }); }; DatabaseService.prototype.addScheduledTask = function (params) { var _a; return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, this.client.execute("INSERT INTO workflow_scheduled_tasks (id, visitor_id, workflow_id, task_type, scheduled_time, payload)\n VALUES (?, ?, ?, ?, ?, ?)", [params.id, params.visitorId, params.workflowId, params.taskType, params.scheduledTime, (_a = params.payload) !== null && _a !== void 0 ? _a : null])]; case 1: _b.sent(); return [2 /*return*/]; } }); }); }; DatabaseService.prototype.updateScheduledTask = function (id, fields) { return __awaiter(this, void 0, void 0, function () { var updates, values; return __generator(this, function (_a) { switch (_a.label) { case 0: updates = []; values = []; if (fields.visitorId !== undefined) { updates.push('visitor_id = ?'); values.push(fields.visitorId); } if (fields.workflowId !== undefined) { updates.push('workflow_id = ?'); values.push(fields.workflowId); } if (fields.taskType !== undefined) { updates.push('task_type = ?'); values.push(fields.taskType); } if (fields.scheduledTime !== undefined) { updates.push('scheduled_time = ?'); values.push(fields.scheduledTime); } if (fields.payload !== undefined) { updates.push('payload = ?'); values.push(fields.payload); } if (updates.length === 0) { return [2 /*return*/]; } values.push(id); return [4 /*yield*/, this.client.execute("UPDATE workflow_scheduled_tasks SET ".concat(updates.join(', '), " WHERE id = ?"), values)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; DatabaseService.prototype.deleteScheduledTask = function (id) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.execute('DELETE FROM workflow_scheduled_tasks WHERE id = ?', [id])]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; DatabaseService.prototype.addVisitor = function (visitorId, stateId, workflowId) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.execute('INSERT INTO workflow_visitors (visitor_id, state_id, workflow_id) VALUES (?, ?, ?)', [visitorId, stateId, workflowId])]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; DatabaseService.prototype.getVisitorState = function (visitorId, workflowId) { return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.execute('SELECT state_id FROM workflow_visitors WHERE visitor_id = ? AND workflow_id = ?', [visitorId, workflowId])]; case 1: result = _a.sent(); return [2 /*return*/, result.rows.length > 0 ? result.rows[0].state_id : null]; } }); }); }; DatabaseService.prototype.updateVisitorState = function (visitorId, nextStateId, workflowId) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: console.log("Changing visitor ".concat(visitorId, " state ").concat(nextStateId, " for workflow ").concat(workflowId)); return [4 /*yield*/, this.client.execute('UPDATE workflow_visitors SET state_id = ? WHERE visitor_id = ? AND workflow_id = ?', [nextStateId, visitorId, workflowId])]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; DatabaseService.prototype.removeVisitor = function (visitorId, workflowId) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.execute('DELETE FROM workflow_visitors WHERE visitor_id = ? AND workflow_id = ?', [visitorId, workflowId])]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; DatabaseService.prototype.getStateVisitors = function (stateId, workflowId) { return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.execute('SELECT visitor_id FROM workflow_visitors WHERE state_id = ? AND workflow_id = ?', [stateId, workflowId])]; case 1: result = _a.sent(); return [2 /*return*/, result.rows.map(function (row) { return row.visitor_id; })]; } }); }); }; DatabaseService.prototype.debugPrintTables = function () { return __awaiter(this, void 0, void 0, function () { var visitors, tasks; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.execute('SELECT * FROM workflow_visitors')]; case 1: visitors = _a.sent(); console.log('workflow_visitors:', visitors.rows); return [4 /*yield*/, this.client.execute('SELECT * FROM workflow_scheduled_tasks')]; case 2: tasks = _a.sent(); console.log('workflow_scheduled_tasks:', tasks.rows); return [2 /*return*/]; } }); }); }; DatabaseService.prototype.dispose = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.close()]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; return DatabaseService; }()); exports.DatabaseService = DatabaseService; //# sourceMappingURL=databaseService.js.map