ai-world-sdk 1.3.3 → 1.3.6

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.
@@ -1,151 +0,0 @@
1
- /**
2
- * Database Request Client
3
- * 数据库请求客户端
4
- * 通过后端 /api/database 提交建表/迁移请求,查看请求列表和详情
5
- * 所有登录用户可提交请求,管理员可审核
6
- */
7
- export interface DatabaseRequestClientConfig {
8
- baseUrl?: string;
9
- token?: string;
10
- headers?: Record<string, string>;
11
- }
12
- export type RequestType = "create" | "migrate";
13
- export type RequestStatus = "pending" | "approved" | "rejected";
14
- export interface ColumnDefinition {
15
- name: string;
16
- type: string;
17
- primary_key?: boolean;
18
- auto_increment?: boolean;
19
- nullable?: boolean;
20
- default?: unknown;
21
- length?: number;
22
- precision?: number;
23
- scale?: number;
24
- }
25
- export interface IndexDefinition {
26
- name: string;
27
- columns: string[];
28
- unique?: boolean;
29
- }
30
- export interface ForeignKeyDefinition {
31
- column: string;
32
- references_table: string;
33
- references_column: string;
34
- on_delete?: string;
35
- }
36
- export interface SchemaDefinition {
37
- columns: ColumnDefinition[];
38
- indexes?: IndexDefinition[];
39
- foreign_keys?: ForeignKeyDefinition[];
40
- }
41
- export interface SubmitCreateRequestOptions {
42
- tableName: string;
43
- schemaDefinition: SchemaDefinition;
44
- description?: string;
45
- }
46
- export interface SubmitMigrateRequestOptions {
47
- tableName: string;
48
- migrationSql: string;
49
- description?: string;
50
- }
51
- export interface DatabaseRequestInfo {
52
- id: number;
53
- requester_id: number;
54
- plugin_id: string;
55
- table_name: string;
56
- request_type: RequestType;
57
- schema_definition: SchemaDefinition | null;
58
- migration_sql: string | null;
59
- description: string | null;
60
- status: RequestStatus;
61
- reviewer_id: number | null;
62
- review_comment: string | null;
63
- created_at: string;
64
- reviewed_at: string | null;
65
- }
66
- export interface ListRequestsOptions {
67
- status?: RequestStatus;
68
- page?: number;
69
- pageSize?: number;
70
- }
71
- /**
72
- * Database Request Client
73
- * 数据库请求客户端类
74
- *
75
- * @example
76
- * ```typescript
77
- * import { DatabaseRequestClient, sdkConfig } from 'ai-world-sdk';
78
- *
79
- * sdkConfig.setPluginId('my-plugin');
80
- * const dbRequests = new DatabaseRequestClient();
81
- *
82
- * // 提交建表请求
83
- * const req = await dbRequests.submitCreateRequest({
84
- * tableName: 'user_scores',
85
- * schemaDefinition: {
86
- * columns: [
87
- * { name: 'id', type: 'integer', primary_key: true, auto_increment: true, nullable: false },
88
- * { name: 'user_id', type: 'integer', nullable: false },
89
- * { name: 'score', type: 'float', nullable: false },
90
- * ],
91
- * indexes: [{ name: 'idx_user_id', columns: ['user_id'] }],
92
- * },
93
- * description: '用户评分表',
94
- * });
95
- *
96
- * // 提交迁移请求
97
- * const migrateReq = await dbRequests.submitMigrateRequest({
98
- * tableName: 'user_scores',
99
- * migrationSql: 'ALTER TABLE my_plugin_user_scores ADD COLUMN level INTEGER DEFAULT 0;',
100
- * description: '添加 level 字段',
101
- * });
102
- *
103
- * // 列出我的请求
104
- * const list = await dbRequests.listRequests({ status: 'pending' });
105
- *
106
- * // 获取请求详情
107
- * const detail = await dbRequests.getRequest(req.id);
108
- *
109
- * // 获取请求总数
110
- * const total = await dbRequests.getRequestCount({ status: 'pending' });
111
- * ```
112
- */
113
- export declare class DatabaseRequestClient {
114
- private baseUrl;
115
- private headers;
116
- constructor(config?: DatabaseRequestClientConfig);
117
- private getPluginId;
118
- private handleErrorResponse;
119
- /**
120
- * Submit a table creation request
121
- * 提交建表请求
122
- */
123
- submitCreateRequest(options: SubmitCreateRequestOptions): Promise<DatabaseRequestInfo>;
124
- /**
125
- * Submit a migration request
126
- * 提交迁移请求
127
- */
128
- submitMigrateRequest(options: SubmitMigrateRequestOptions): Promise<DatabaseRequestInfo>;
129
- /**
130
- * List requests (admin sees all, regular users see own)
131
- * 列出请求列表(管理员看全部,普通用户看自己的)
132
- */
133
- listRequests(options?: ListRequestsOptions): Promise<DatabaseRequestInfo[]>;
134
- /**
135
- * Get request count
136
- * 获取请求总数
137
- */
138
- getRequestCount(options?: {
139
- status?: RequestStatus;
140
- }): Promise<number>;
141
- /**
142
- * Get request detail by ID
143
- * 获取请求详情
144
- */
145
- getRequest(requestId: number): Promise<DatabaseRequestInfo>;
146
- /**
147
- * Review a request (approve/reject) - requires can_manage_database permission
148
- * 审核请求(通过/拒绝)- 需要 can_manage_database 权限
149
- */
150
- reviewRequest(requestId: number, action: "approve" | "reject", comment?: string): Promise<DatabaseRequestInfo>;
151
- }
@@ -1,242 +0,0 @@
1
- "use strict";
2
- /**
3
- * Database Request Client
4
- * 数据库请求客户端
5
- * 通过后端 /api/database 提交建表/迁移请求,查看请求列表和详情
6
- * 所有登录用户可提交请求,管理员可审核
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.DatabaseRequestClient = void 0;
10
- const config_1 = require("./config");
11
- const log_1 = require("./log");
12
- // ==================== DatabaseRequestClient ====================
13
- /**
14
- * Database Request Client
15
- * 数据库请求客户端类
16
- *
17
- * @example
18
- * ```typescript
19
- * import { DatabaseRequestClient, sdkConfig } from 'ai-world-sdk';
20
- *
21
- * sdkConfig.setPluginId('my-plugin');
22
- * const dbRequests = new DatabaseRequestClient();
23
- *
24
- * // 提交建表请求
25
- * const req = await dbRequests.submitCreateRequest({
26
- * tableName: 'user_scores',
27
- * schemaDefinition: {
28
- * columns: [
29
- * { name: 'id', type: 'integer', primary_key: true, auto_increment: true, nullable: false },
30
- * { name: 'user_id', type: 'integer', nullable: false },
31
- * { name: 'score', type: 'float', nullable: false },
32
- * ],
33
- * indexes: [{ name: 'idx_user_id', columns: ['user_id'] }],
34
- * },
35
- * description: '用户评分表',
36
- * });
37
- *
38
- * // 提交迁移请求
39
- * const migrateReq = await dbRequests.submitMigrateRequest({
40
- * tableName: 'user_scores',
41
- * migrationSql: 'ALTER TABLE my_plugin_user_scores ADD COLUMN level INTEGER DEFAULT 0;',
42
- * description: '添加 level 字段',
43
- * });
44
- *
45
- * // 列出我的请求
46
- * const list = await dbRequests.listRequests({ status: 'pending' });
47
- *
48
- * // 获取请求详情
49
- * const detail = await dbRequests.getRequest(req.id);
50
- *
51
- * // 获取请求总数
52
- * const total = await dbRequests.getRequestCount({ status: 'pending' });
53
- * ```
54
- */
55
- class DatabaseRequestClient {
56
- constructor(config = {}) {
57
- this.baseUrl =
58
- config.baseUrl ||
59
- config_1.sdkConfig.getServerUrl() ||
60
- (typeof window !== "undefined" ? window.location.origin : "");
61
- const globalHeaders = config_1.sdkConfig.getHeaders();
62
- const globalToken = config.token || config_1.sdkConfig.getToken();
63
- this.headers = {
64
- "Content-Type": "application/json",
65
- ...globalHeaders,
66
- ...config.headers,
67
- };
68
- if (globalToken) {
69
- this.headers["Authorization"] = `Bearer ${globalToken}`;
70
- }
71
- }
72
- getPluginId() {
73
- const pluginId = this.headers["X-Plugin-Id"] || config_1.sdkConfig.getPluginId();
74
- if (!pluginId) {
75
- throw new Error("Plugin ID is required. Set it via sdkConfig.setPluginId() or pass pluginId in headers.");
76
- }
77
- return pluginId;
78
- }
79
- async handleErrorResponse(response) {
80
- let errorMessage = `Request failed: ${response.status} ${response.statusText}`;
81
- try {
82
- const errorText = await response.text();
83
- const errorJson = JSON.parse(errorText);
84
- errorMessage = errorJson.detail || errorMessage;
85
- }
86
- catch {
87
- // ignore parse error
88
- }
89
- throw new Error(errorMessage);
90
- }
91
- /**
92
- * Submit a table creation request
93
- * 提交建表请求
94
- */
95
- async submitCreateRequest(options) {
96
- config_1.sdkConfig.ensureVersionCompatible();
97
- const pluginId = this.getPluginId();
98
- const body = {
99
- plugin_id: pluginId,
100
- table_name: options.tableName,
101
- request_type: "create",
102
- schema_definition: options.schemaDefinition,
103
- description: options.description,
104
- };
105
- const apiUrl = `${this.baseUrl}/api/database/table-requests`;
106
- (0, log_1.debugLog)("Submit create request:", body);
107
- (0, log_1.logRequest)("POST", apiUrl, this.headers, body);
108
- const response = await fetch(apiUrl, {
109
- method: "POST",
110
- headers: this.headers,
111
- body: JSON.stringify(body),
112
- });
113
- if (!response.ok) {
114
- await this.handleErrorResponse(response);
115
- }
116
- const result = (await response.json());
117
- (0, log_1.logResponse)(response.status, response.statusText, response.headers, result);
118
- return result;
119
- }
120
- /**
121
- * Submit a migration request
122
- * 提交迁移请求
123
- */
124
- async submitMigrateRequest(options) {
125
- config_1.sdkConfig.ensureVersionCompatible();
126
- const pluginId = this.getPluginId();
127
- const body = {
128
- plugin_id: pluginId,
129
- table_name: options.tableName,
130
- request_type: "migrate",
131
- migration_sql: options.migrationSql,
132
- description: options.description,
133
- };
134
- const apiUrl = `${this.baseUrl}/api/database/table-requests`;
135
- (0, log_1.debugLog)("Submit migrate request:", body);
136
- (0, log_1.logRequest)("POST", apiUrl, this.headers, body);
137
- const response = await fetch(apiUrl, {
138
- method: "POST",
139
- headers: this.headers,
140
- body: JSON.stringify(body),
141
- });
142
- if (!response.ok) {
143
- await this.handleErrorResponse(response);
144
- }
145
- const result = (await response.json());
146
- (0, log_1.logResponse)(response.status, response.statusText, response.headers, result);
147
- return result;
148
- }
149
- /**
150
- * List requests (admin sees all, regular users see own)
151
- * 列出请求列表(管理员看全部,普通用户看自己的)
152
- */
153
- async listRequests(options = {}) {
154
- config_1.sdkConfig.ensureVersionCompatible();
155
- const params = new URLSearchParams();
156
- if (options.status)
157
- params.append("status", options.status);
158
- if (options.page)
159
- params.append("page", String(options.page));
160
- if (options.pageSize)
161
- params.append("page_size", String(options.pageSize));
162
- const apiUrl = `${this.baseUrl}/api/database/table-requests?${params.toString()}`;
163
- (0, log_1.debugLog)("List requests:", options);
164
- (0, log_1.logRequest)("GET", apiUrl, this.headers);
165
- const response = await fetch(apiUrl, {
166
- method: "GET",
167
- headers: this.headers,
168
- });
169
- if (!response.ok) {
170
- await this.handleErrorResponse(response);
171
- }
172
- const result = (await response.json());
173
- (0, log_1.logResponse)(response.status, response.statusText, response.headers, result);
174
- return result;
175
- }
176
- /**
177
- * Get request count
178
- * 获取请求总数
179
- */
180
- async getRequestCount(options = {}) {
181
- config_1.sdkConfig.ensureVersionCompatible();
182
- const params = new URLSearchParams();
183
- if (options.status)
184
- params.append("status", options.status);
185
- const apiUrl = `${this.baseUrl}/api/database/table-requests/count?${params.toString()}`;
186
- (0, log_1.debugLog)("Get request count:", options);
187
- (0, log_1.logRequest)("GET", apiUrl, this.headers);
188
- const response = await fetch(apiUrl, {
189
- method: "GET",
190
- headers: this.headers,
191
- });
192
- if (!response.ok) {
193
- await this.handleErrorResponse(response);
194
- }
195
- const result = (await response.json());
196
- (0, log_1.logResponse)(response.status, response.statusText, response.headers, result);
197
- return result.total;
198
- }
199
- /**
200
- * Get request detail by ID
201
- * 获取请求详情
202
- */
203
- async getRequest(requestId) {
204
- config_1.sdkConfig.ensureVersionCompatible();
205
- const apiUrl = `${this.baseUrl}/api/database/table-requests/${requestId}`;
206
- (0, log_1.debugLog)("Get request detail:", { requestId });
207
- (0, log_1.logRequest)("GET", apiUrl, this.headers);
208
- const response = await fetch(apiUrl, {
209
- method: "GET",
210
- headers: this.headers,
211
- });
212
- if (!response.ok) {
213
- await this.handleErrorResponse(response);
214
- }
215
- const result = (await response.json());
216
- (0, log_1.logResponse)(response.status, response.statusText, response.headers, result);
217
- return result;
218
- }
219
- /**
220
- * Review a request (approve/reject) - requires can_manage_database permission
221
- * 审核请求(通过/拒绝)- 需要 can_manage_database 权限
222
- */
223
- async reviewRequest(requestId, action, comment) {
224
- config_1.sdkConfig.ensureVersionCompatible();
225
- const body = { action, comment };
226
- const apiUrl = `${this.baseUrl}/api/database/table-requests/${requestId}`;
227
- (0, log_1.debugLog)("Review request:", { requestId, ...body });
228
- (0, log_1.logRequest)("PATCH", apiUrl, this.headers, body);
229
- const response = await fetch(apiUrl, {
230
- method: "PATCH",
231
- headers: this.headers,
232
- body: JSON.stringify(body),
233
- });
234
- if (!response.ok) {
235
- await this.handleErrorResponse(response);
236
- }
237
- const result = (await response.json());
238
- (0, log_1.logResponse)(response.status, response.statusText, response.headers, result);
239
- return result;
240
- }
241
- }
242
- exports.DatabaseRequestClient = DatabaseRequestClient;
@@ -1,68 +0,0 @@
1
- # 数据库请求
2
-
3
- 通过 `DatabaseRequestClient` 提交建表/迁移请求、查看请求列表和详情。所有登录用户可提交请求,管理员审核通过后自动执行。
4
-
5
- ## 基本用法
6
-
7
- ```typescript
8
- import { DatabaseRequestClient, sdkConfig } from 'ai-world-sdk';
9
-
10
- sdkConfig.setPluginId('my-plugin');
11
- const dbRequests = new DatabaseRequestClient();
12
-
13
- // 提交建表请求
14
- const req = await dbRequests.submitCreateRequest({
15
- tableName: 'user_scores',
16
- schemaDefinition: {
17
- columns: [
18
- { name: 'id', type: 'integer', primary_key: true, auto_increment: true, nullable: false },
19
- { name: 'user_id', type: 'integer', nullable: false },
20
- { name: 'score', type: 'float', nullable: false },
21
- ],
22
- indexes: [{ name: 'idx_user_id', columns: ['user_id'] }],
23
- },
24
- description: '用户评分表',
25
- });
26
-
27
- // 提交迁移请求
28
- await dbRequests.submitMigrateRequest({
29
- tableName: 'user_scores',
30
- migrationSql: 'ALTER TABLE my_plugin_user_scores ADD COLUMN level INTEGER DEFAULT 0;',
31
- description: '添加 level 字段',
32
- });
33
-
34
- // 列出请求(普通用户看自己的,管理员看全部)
35
- const list = await dbRequests.listRequests({ status: 'pending', page: 1, pageSize: 20 });
36
-
37
- // 获取请求总数
38
- const total = await dbRequests.getRequestCount({ status: 'pending' });
39
-
40
- // 获取请求详情
41
- const detail = await dbRequests.getRequest(req.id);
42
-
43
- // 审核请求(需 can_manage_database 权限)
44
- await dbRequests.reviewRequest(req.id, 'approve', '审核通过');
45
- ```
46
-
47
- ## 表名规则
48
-
49
- - 实际表名 = `{pluginId}_{tableName}`
50
- - 只允许 `[a-z0-9_]`
51
-
52
- ## 列类型白名单
53
-
54
- integer, bigint, varchar, text, boolean, float, decimal, date, datetime, timestamp, json, jsonb
55
-
56
- ## 迁移 SQL 限制
57
-
58
- 禁止: DROP DATABASE, TRUNCATE, DROP SCHEMA
59
-
60
- ## API 端点
61
-
62
- | 方法 | 路径 | 说明 |
63
- |------|------|------|
64
- | POST | `/api/database/table-requests` | 提交建表/迁移请求 |
65
- | GET | `/api/database/table-requests` | 列出请求 |
66
- | GET | `/api/database/table-requests/count` | 请求总数 |
67
- | GET | `/api/database/table-requests/{id}` | 请求详情 |
68
- | PATCH | `/api/database/table-requests/{id}` | 审核请求 |