@warriorteam/redai-api-sdk
Version:
TypeScript SDK for RedAI Backend API
796 lines (783 loc) • 23.4 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var axios = require('axios');
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
var axios__default = /*#__PURE__*/_interopDefault(axios);
// src/core/http-client.ts
var HttpClient = class {
constructor(config) {
this.authToken = null;
this.client = axios__default.default.create({
baseURL: config.baseUrl,
timeout: config.timeout ?? 3e4,
headers: {
"Content-Type": "application/json",
...config.headers
}
});
this.client.interceptors.request.use((requestConfig) => {
if (this.authToken && requestConfig.headers) {
requestConfig.headers.Authorization = `Bearer ${this.authToken}`;
}
return requestConfig;
});
}
/**
* Set authentication token
*/
setAuthToken(token) {
this.authToken = token;
}
/**
* Clear authentication token
*/
clearAuthToken() {
this.authToken = null;
}
/**
* Get current auth token
*/
getAuthToken() {
return this.authToken;
}
/**
* GET request
*/
async get(url, config) {
const response = await this.client.get(url, config);
return response.data;
}
/**
* POST request
*/
async post(url, data, config) {
const response = await this.client.post(url, data, config);
return response.data;
}
/**
* PUT request
*/
async put(url, data, config) {
const response = await this.client.put(url, data, config);
return response.data;
}
/**
* PATCH request
*/
async patch(url, data, config) {
const response = await this.client.patch(url, data, config);
return response.data;
}
/**
* DELETE request
*/
async delete(url, config) {
const response = await this.client.delete(url, config);
return response.data;
}
};
// src/modules/dashboard-generic/services/api.service.ts
var ApiService = class {
constructor(httpClient) {
this.httpClient = httpClient;
this.basePath = "/dashboard-generic/apis";
}
/**
* Get all API configurations with pagination and filtering
*
* @param query - Query parameters for filtering and pagination
* @returns Paginated list of API configurations
*
* @example
* ```typescript
* const result = await apiService.findAll({
* page: 1,
* limit: 10,
* method: 'GET',
* status: 'active',
* });
* ```
*/
async findAll(query) {
const params = new URLSearchParams();
if (query) {
Object.entries(query).forEach(([key, value]) => {
if (value !== void 0 && value !== null) {
if (Array.isArray(value)) {
value.forEach((v) => params.append(key, String(v)));
} else {
params.append(key, String(value));
}
}
});
}
const queryString = params.toString();
const url = queryString ? `${this.basePath}?${queryString}` : this.basePath;
return this.httpClient.get(url);
}
/**
* Get API configuration by ID
*
* @param id - API configuration ID (UUID)
* @returns API configuration details
*
* @example
* ```typescript
* const api = await apiService.findOne('123e4567-e89b-12d3-a456-426614174000');
* ```
*/
async findOne(id) {
return this.httpClient.get(`${this.basePath}/${id}`);
}
/**
* Get API configuration by code
*
* @param code - API configuration code
* @returns API configuration details
*
* @example
* ```typescript
* const api = await apiService.findByCode('getUser');
* ```
*/
async findByCode(code) {
return this.httpClient.get(`${this.basePath}/by-code/${code}`);
}
/**
* Update API configuration
*
* @param id - API configuration ID (UUID)
* @param data - Update data
* @returns Updated API configuration
*
* @example
* ```typescript
* const updated = await apiService.update('123e4567-e89b-12d3-a456-426614174000', {
* status: 'inactive',
* timeoutMs: 60000,
* });
* ```
*/
async update(id, data) {
return this.httpClient.put(`${this.basePath}/${id}`, data);
}
/**
* Delete API configuration
*
* @param id - API configuration ID (UUID)
* @returns Null on success
*
* @example
* ```typescript
* await apiService.remove('123e4567-e89b-12d3-a456-426614174000');
* ```
*/
async remove(id) {
return this.httpClient.delete(`${this.basePath}/${id}`);
}
/**
* Get list of available dashboard modules
*
* @returns List of dashboard modules with multi-language labels
*
* @example
* ```typescript
* const modules = await apiService.getModules();
* // [{ value: 'MARKETING', label: { vi: 'Marketing', en: 'Marketing' } }, ...]
* ```
*/
async getModules() {
return this.httpClient.get(`${this.basePath}/modules/list`);
}
/**
* Get API statistics
*
* @returns Statistics and overview information about API configurations
*
* @example
* ```typescript
* const stats = await apiService.getStatistics();
* console.log(stats.result.totalApis);
* console.log(stats.result.apisByMethod);
* ```
*/
async getStatistics() {
return this.httpClient.get(`${this.basePath}/statistics/overview`);
}
};
// src/modules/dashboard-generic/services/page-template.service.ts
var PageTemplateService = class {
constructor(httpClient) {
this.httpClient = httpClient;
this.basePath = "/dashboard-generic/page-templates";
}
/**
* Create a new Page Template
*
* @param data - Page template creation data
* @returns Created page template
*
* @example
* ```typescript
* const template = await pageTemplateService.create({
* name: 'Customer Dashboard',
* code: 'export default function Page({ apis }) { return <div>Hello</div>; }',
* description: 'Dashboard for customer analytics',
* tags: ['customer', 'dashboard'],
* apiIds: ['123e4567-e89b-12d3-a456-426614174000'],
* });
* ```
*/
async create(data) {
return this.httpClient.post(this.basePath, data);
}
/**
* Get all Page Templates with pagination and filtering
*
* @param query - Query parameters for filtering and pagination
* @returns Paginated list of page templates
*
* @example
* ```typescript
* const result = await pageTemplateService.findAll({
* page: 1,
* limit: 10,
* status: 'active',
* type: 'USER',
* });
* ```
*/
async findAll(query) {
const params = new URLSearchParams();
if (query) {
Object.entries(query).forEach(([key, value]) => {
if (value !== void 0 && value !== null) {
if (Array.isArray(value)) {
value.forEach((v) => params.append(key, String(v)));
} else {
params.append(key, String(value));
}
}
});
}
const queryString = params.toString();
const url = queryString ? `${this.basePath}?${queryString}` : this.basePath;
return this.httpClient.get(url);
}
/**
* Get Page Template by ID
*
* @param id - Page template ID (UUID)
* @returns Page template details
*
* @example
* ```typescript
* const template = await pageTemplateService.findOne('123e4567-e89b-12d3-a456-426614174000');
* ```
*/
async findOne(id) {
return this.httpClient.get(`${this.basePath}/${id}`);
}
/**
* Update Page Template
*
* @param id - Page template ID (UUID)
* @param data - Update data
* @returns Updated page template
*
* @example
* ```typescript
* const updated = await pageTemplateService.update('123e4567-e89b-12d3-a456-426614174000', {
* name: 'Updated Dashboard',
* code: 'export default function Page({ apis }) { return <div>Updated</div>; }',
* });
* ```
*/
async update(id, data) {
return this.httpClient.put(`${this.basePath}/${id}`, data);
}
/**
* Rename Page Template
*
* @param id - Page template ID (UUID)
* @param name - New name for the template
* @returns Updated page template
*
* @example
* ```typescript
* const renamed = await pageTemplateService.rename('123e4567-e89b-12d3-a456-426614174000', 'New Dashboard Name');
* ```
*/
async rename(id, name) {
const data = { name };
return this.httpClient.patch(`${this.basePath}/${id}/rename`, data);
}
/**
* Delete Page Template
*
* @param id - Page template ID (UUID)
* @returns Null on success
*
* @example
* ```typescript
* await pageTemplateService.remove('123e4567-e89b-12d3-a456-426614174000');
* ```
*/
async remove(id) {
return this.httpClient.delete(`${this.basePath}/${id}`);
}
/**
* Associate APIs with a page template
*
* @param id - Page template ID (UUID)
* @param apiIds - List of API IDs to associate
* @returns Null on success
*
* @example
* ```typescript
* await pageTemplateService.associateApis('123e4567-e89b-12d3-a456-426614174000', [
* '456e7890-e89b-12d3-a456-426614174001',
* '789e0123-e89b-12d3-a456-426614174002',
* ]);
* ```
*/
async associateApis(id, apiIds) {
const data = { apiIds };
return this.httpClient.post(`${this.basePath}/${id}/apis`, data);
}
/**
* Create Page Template from System Template
*
* @param templateId - System template ID (UUID) to copy from
* @param customization - Optional customization for the new template
* @returns Created page template
*
* @example
* ```typescript
* const template = await pageTemplateService.createFromTemplate(
* '123e4567-e89b-12d3-a456-426614174000',
* { name: 'My Custom Dashboard', description: 'Customized version' }
* );
* ```
*/
async createFromTemplate(templateId, customization) {
return this.httpClient.post(
`${this.basePath}/from-template/${templateId}`,
customization || {}
);
}
/**
* Create Page Template with Template Data
*
* @param data - Template creation request with templateData structure
* @returns Created page template
*
* @example
* ```typescript
* const template = await pageTemplateService.createWithTemplateData({
* templateData: {
* name: 'Customer Dashboard',
* code: 'export default function Page({ apis }) { return <div>Dashboard</div>; }',
* description: 'A comprehensive dashboard',
* },
* apiIds: ['123e4567-e89b-12d3-a456-426614174000'],
* userCustomToolIds: ['789e0123-e89b-12d3-a456-426614174000'],
* });
* ```
*/
async createWithTemplateData(data) {
return this.httpClient.post(`${this.basePath}/with-template-data`, data);
}
};
// src/modules/dashboard-generic/services/execute-api.service.ts
var ExecuteApiService = class {
constructor(httpClient) {
this.httpClient = httpClient;
this.basePath = "/dashboard-generic/execute";
}
/**
* Execute multiple dashboard APIs
*
* @param request - Execute API request with list of APIs
* @returns Execution results for each API
*
* @example
* ```typescript
* const result = await executeApiService.execute({
* apis: [
* {
* module: 'BUSINESS',
* code: 'BUSINESS_REVENUE_OVERVIEW',
* type: 'overview',
* begin: 1704067200000,
* end: 1735689600000,
* },
* {
* module: 'BUSINESS',
* code: 'BUSINESS_REVENUE_PIECHART',
* type: 'piechart',
* begin: 1704067200000,
* end: 1735689600000,
* },
* ],
* });
* ```
*/
async execute(request) {
return this.httpClient.post(this.basePath, request);
}
/**
* Execute resources (single or batch)
* Supports unified resourceId format and legacy format
*
* Resource ID Format: "prefix:uuid"
* - pta:uuid - PageTemplateApiEntity
* - api:uuid - API Entity
* - tool:uuid - Custom Tool
*
* @param request - Execute resource request
* @returns Array of execution results
*
* @example Single execution with unified resourceId
* ```typescript
* const result = await executeApiService.executeResource({
* resourceId: 'api:660e8400-e29b-41d4-a716-446655440001',
* parameters: {
* query_param: { filter: 'recent' },
* body: { name: 'Test' },
* },
* });
* ```
*
* @example Batch execution
* ```typescript
* const result = await executeApiService.executeResource({
* resources: [
* {
* resourceId: 'pta:550e8400-e29b-41d4-a716-446655440000',
* parameters: { query_param: { page: 1 } },
* },
* {
* resourceId: 'api:660e8400-e29b-41d4-a716-446655440001',
* parameters: { query_param: { limit: 20 } },
* },
* {
* resourceId: 'tool:770e8400-e29b-41d4-a716-446655440002',
* integrationId: '880e8400-e29b-41d4-a716-446655440003',
* parameters: { body: { name: 'Test' } },
* },
* ],
* });
* ```
*
* @example Legacy format (deprecated)
* ```typescript
* const result = await executeApiService.executeResource({
* pageTemplateApiId: '550e8400-e29b-41d4-a716-446655440000',
* parameters: { query_param: { page: 1, limit: 10 } },
* });
* ```
*/
async executeResource(request) {
return this.httpClient.post(`${this.basePath}/resource`, request);
}
/**
* Helper: Execute single API resource
*
* @param apiId - API entity ID
* @param parameters - Input parameters
* @returns Execution result
*/
async executeApi(apiId, parameters) {
return this.executeResource({
resourceId: `api:${apiId}`,
parameters
});
}
/**
* Helper: Execute single PageTemplateApi resource
*
* @param pageTemplateApiId - PageTemplateApi entity ID
* @param parameters - Input parameters
* @returns Execution result
*/
async executePageTemplateApi(pageTemplateApiId, parameters) {
return this.executeResource({
resourceId: `pta:${pageTemplateApiId}`,
parameters
});
}
/**
* Helper: Execute single Custom Tool resource
*
* @param customToolId - Custom tool ID
* @param integrationId - Integration ID for OAuth
* @param parameters - Input parameters
* @returns Execution result
*/
async executeCustomTool(customToolId, integrationId, parameters) {
return this.executeResource({
resourceId: `tool:${customToolId}`,
integrationId,
parameters
});
}
};
// src/modules/dashboard-generic/services/ai-page-generator.service.ts
var AiPageGeneratorService = class {
constructor(httpClient) {
this.httpClient = httpClient;
this.basePath = "/dashboard-generic/ai-page-generator";
}
/**
* Generate page template from AI using API definitions
*
* Workflow:
* 1. Lấy thông tin chi tiết của APIs theo IDs
* 2. AI phân tích API schemas và tạo React code phù hợp
* 3. Generate code với React Live compatible code
* 4. Nếu isSave = TRUE: Lưu template vào database
* 5. Nếu isSave = FALSE: Chỉ trả về code để preview
*
* Processing Time: 30-120 giây (tùy độ phức tạp)
*
* @param request - Generate page request
* @returns Generated page template response
*
* @example Generate from existing PageTemplate
* ```typescript
* const result = await aiPageGeneratorService.generate({
* pageTemplateId: '123e4567-e89b-12d3-a456-426614174000',
* prompt: 'Tạo dashboard với line chart hiển thị doanh thu theo thời gian',
* isSave: 'FALSE',
* });
* ```
*
* @example Generate with APIs
* ```typescript
* const result = await aiPageGeneratorService.generate({
* apiIds: ['123e4567-e89b-12d3-a456-426614174000'],
* prompt: 'Tạo dashboard với line chart hiển thị doanh thu theo thời gian',
* pattern: 'self-contained',
* isSave: 'FALSE',
* });
* ```
*
* @example Generate and save template
* ```typescript
* const result = await aiPageGeneratorService.generate({
* apiIds: ['456e7890-e89b-12d3-a456-426614174001'],
* prompt: 'Tạo trang quản lý danh sách khách hàng với bảng dữ liệu',
* pattern: 'self-contained',
* isSave: 'TRUE',
* name: 'Quản Lý Khách Hàng',
* description: 'Trang quản lý danh sách khách hàng',
* });
* ```
*/
async generate(request) {
return this.httpClient.post(`${this.basePath}/generate`, request);
}
/**
* Generate dashboard from AI with dynamic component builder
*
* Khác biệt với generate():
* - Sử dụng buildDynamicComponentsContent() thay vì buildComponentsContent()
* - Hỗ trợ React 18, TypeScript 5.7, Tailwind CSS 3.3, Recharts 2.15, React Hook Form 7.60
* - Tập trung vào dashboard patterns với charts, tables, forms
*
* Processing Time: 30-120 giây (tùy độ phức tạp)
*
* @param request - Generate dashboard request
* @returns Generated dashboard template response
*
* @example Generate dashboard from existing PageTemplate
* ```typescript
* const result = await aiPageGeneratorService.generateDashboard({
* pageTemplateId: '123e4567-e89b-12d3-a456-426614174000',
* prompt: 'Tạo dashboard với line chart hiển thị doanh thu theo thời gian',
* isSave: 'FALSE',
* });
* ```
*
* @example Generate dashboard with APIs and Custom Tools
* ```typescript
* const result = await aiPageGeneratorService.generateDashboard({
* apiIds: ['123e4567-e89b-12d3-a456-426614174000'],
* userCustomToolIds: ['789e0123-e89b-12d3-a456-426614174000'],
* prompt: 'Tạo dashboard kết hợp APIs và Custom Tools với charts và tables',
* isSave: 'FALSE',
* });
* ```
*
* @example Generate and save dashboard template
* ```typescript
* const result = await aiPageGeneratorService.generateDashboard({
* apiIds: ['456e7890-e89b-12d3-a456-426614174001'],
* prompt: 'Tạo trang quản lý danh sách khách hàng với bảng dữ liệu',
* isSave: 'TRUE',
* name: 'Quản Lý Khách Hàng Dashboard',
* description: 'Dashboard quản lý danh sách khách hàng với dynamic components',
* });
* ```
*/
async generateDashboard(request) {
return this.httpClient.post(`${this.basePath}/generate-dashboard`, request);
}
/**
* Helper: Generate page with self-contained pattern
* Component tự fetch data với useExecuteResource hook
*
* @param apiIds - List of API IDs
* @param prompt - AI prompt
* @param options - Additional options
*/
async generateSelfContained(apiIds, prompt, options) {
return this.generate({
apiIds,
prompt,
pattern: "self-contained",
...options
});
}
/**
* Helper: Generate page with props-driven pattern
* Component nhận data từ props, không tự fetch data
*
* @param apiIds - List of API IDs
* @param prompt - AI prompt
* @param options - Additional options
*/
async generatePropsDriven(apiIds, prompt, options) {
return this.generate({
apiIds,
prompt,
pattern: "props-driven",
...options
});
}
/**
* Helper: Generate page with all-in-one pattern
* Component tự fetch data với pageTemplateApiId
*
* @param apiIds - List of API IDs
* @param prompt - AI prompt
* @param options - Additional options
*/
async generateAllInOne(apiIds, prompt, options) {
return this.generate({
apiIds,
prompt,
pattern: "all-in-one",
...options
});
}
};
// src/modules/dashboard-generic/types/common.types.ts
var SortDirection = /* @__PURE__ */ ((SortDirection2) => {
SortDirection2["ASC"] = "ASC";
SortDirection2["DESC"] = "DESC";
return SortDirection2;
})(SortDirection || {});
var PageTemplateType = /* @__PURE__ */ ((PageTemplateType2) => {
PageTemplateType2["TEMPLATE"] = "TEMPLATE";
PageTemplateType2["USER"] = "USER";
PageTemplateType2["ADMIN"] = "ADMIN";
return PageTemplateType2;
})(PageTemplateType || {});
var DashboardModule = /* @__PURE__ */ ((DashboardModule2) => {
DashboardModule2["BUSINESS"] = "BUSINESS";
DashboardModule2["MARKETING"] = "MARKETING";
DashboardModule2["AGENT"] = "AGENT";
DashboardModule2["RPOINT"] = "RPOINT";
DashboardModule2["DATA"] = "DATA";
DashboardModule2["USER_TOOL_CUSTOM"] = "USER_TOOL_CUSTOM";
return DashboardModule2;
})(DashboardModule || {});
var DashboardChartType = /* @__PURE__ */ ((DashboardChartType2) => {
DashboardChartType2["PIECHART"] = "PIECHART";
DashboardChartType2["LINECHART"] = "LINECHART";
DashboardChartType2["OVERVIEW"] = "OVERVIEW";
DashboardChartType2["AREACHART"] = "AREACHART";
DashboardChartType2["FUNNELCHART"] = "FUNNELCHART";
DashboardChartType2["HEATMAP"] = "HEATMAP";
DashboardChartType2["TABLECHART"] = "TABLECHART";
DashboardChartType2["TIMELINECHART"] = "TIMELINECHART";
DashboardChartType2["COHORTCHART"] = "COHORTCHART";
return DashboardChartType2;
})(DashboardChartType || {});
var RESOURCE_PREFIX = {
PAGE_TEMPLATE_API: "pta",
API: "api",
CUSTOM_TOOL: "tool"
};
// src/modules/dashboard-generic/index.ts
var DashboardGenericModule = class {
constructor(httpClient) {
this.api = new ApiService(httpClient);
this.pageTemplate = new PageTemplateService(httpClient);
this.execute = new ExecuteApiService(httpClient);
this.aiPageGenerator = new AiPageGeneratorService(httpClient);
}
};
function createDashboardGenericModule(config) {
const httpClient = new HttpClient(config);
const module = new DashboardGenericModule(httpClient);
return {
...module,
api: module.api,
pageTemplate: module.pageTemplate,
execute: module.execute,
aiPageGenerator: module.aiPageGenerator,
setAuthToken: (token) => httpClient.setAuthToken(token),
clearAuthToken: () => httpClient.clearAuthToken()
};
}
// src/index.ts
var RedAiSdk = class {
constructor(config) {
this.httpClient = new HttpClient(config);
this.dashboardGeneric = new DashboardGenericModule(this.httpClient);
}
/**
* Set authentication token for all API requests
*
* @param token - JWT token
*/
setAuthToken(token) {
this.httpClient.setAuthToken(token);
}
/**
* Clear authentication token
*/
clearAuthToken() {
this.httpClient.clearAuthToken();
}
/**
* Get current authentication token
*/
getAuthToken() {
return this.httpClient.getAuthToken();
}
};
function createRedAiSdk(config) {
return new RedAiSdk(config);
}
var index_default = RedAiSdk;
exports.AiPageGeneratorService = AiPageGeneratorService;
exports.ApiService = ApiService;
exports.DashboardChartType = DashboardChartType;
exports.DashboardGenericModule = DashboardGenericModule;
exports.DashboardModule = DashboardModule;
exports.ExecuteApiService = ExecuteApiService;
exports.HttpClient = HttpClient;
exports.PageTemplateService = PageTemplateService;
exports.PageTemplateType = PageTemplateType;
exports.RESOURCE_PREFIX = RESOURCE_PREFIX;
exports.RedAiSdk = RedAiSdk;
exports.SortDirection = SortDirection;
exports.createDashboardGenericModule = createDashboardGenericModule;
exports.createRedAiSdk = createRedAiSdk;
exports.default = index_default;
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map