@xpert-ai/plugin-sdk 3.27.0 → 3.29.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.
Files changed (60) hide show
  1. package/collaboration-client.cjs.js +31 -5
  2. package/collaboration-client.esm.js +31 -5
  3. package/data-workbench.cjs.js +0 -679
  4. package/data-workbench.esm.js +1 -676
  5. package/docs/artifact-presentations.md +2 -0
  6. package/docs/artifact-types.md +97 -0
  7. package/docs/data-workbench.md +37 -0
  8. package/index.cjs.js +481 -49
  9. package/index.esm.js +469 -49
  10. package/model-provider.cjs.js +7 -1
  11. package/model-provider.esm.js +7 -2
  12. package/package.json +2 -2
  13. package/src/data-workbench.d.ts +0 -2
  14. package/src/index.d.ts +2 -0
  15. package/src/lib/agent/handoff/types.d.ts +5 -0
  16. package/src/lib/agent/middleware/capabilities/assistant-task.d.ts +6 -1
  17. package/src/lib/agent/middleware/capabilities/execution-observability.d.ts +26 -0
  18. package/src/lib/agent/middleware/capabilities/index.d.ts +1 -0
  19. package/src/lib/agent/runtime/capability.d.ts +4 -0
  20. package/src/lib/agent/runtime/cli-model-profile.d.ts +1 -1
  21. package/src/lib/agent/runtime/execution-runner.d.ts +11 -0
  22. package/src/lib/agent/runtime/index.d.ts +2 -0
  23. package/src/lib/agent/runtime/managed.d.ts +94 -0
  24. package/src/lib/agent/runtime/process-supervisor.d.ts +1 -0
  25. package/src/lib/agent/runtime/strategy.d.ts +14 -0
  26. package/src/lib/agent/runtime/types.d.ts +30 -1
  27. package/src/lib/ai-model/native-model.d.ts +5 -1
  28. package/src/lib/artifact-type/definition.schema.d.ts +119 -0
  29. package/src/lib/artifact-type/index.d.ts +91 -0
  30. package/src/lib/artifact-type/registry.d.ts +25 -0
  31. package/src/lib/assistant-capability/index.d.ts +1 -0
  32. package/src/lib/assistant-capability/middleware.d.ts +10 -0
  33. package/src/lib/collaboration/types.d.ts +5 -0
  34. package/src/lib/content-resource/catalog.d.ts +88 -0
  35. package/src/lib/content-resource/editor-compatibility.d.ts +3 -0
  36. package/src/lib/content-resource/editor.d.ts +35 -3
  37. package/src/lib/content-resource/index.d.ts +3 -0
  38. package/src/lib/data/datasource/adapter.strategy.d.ts +3 -0
  39. package/src/lib/data/datasource/index.d.ts +0 -2
  40. package/src/lib/data/datasource/strategy.interface.d.ts +5 -1
  41. package/src/lib/data/datasource/types.d.ts +2 -2
  42. package/src/lib/data/datasource/workbench.d.ts +4 -3
  43. package/src/lib/execution-control/context.d.ts +7 -0
  44. package/src/lib/execution-control/index.d.ts +2 -0
  45. package/src/lib/managed-queue/index.d.ts +12 -0
  46. package/src/lib/runtime/capabilities/artifact-drafts.d.ts +10 -1
  47. package/src/lib/runtime/capabilities/artifact-library.d.ts +52 -0
  48. package/src/lib/runtime/capabilities/artifacts.d.ts +15 -0
  49. package/src/lib/runtime/capabilities/index.d.ts +1 -0
  50. package/src/lib/runtime/capabilities/mcp-client-runtime.d.ts +2 -0
  51. package/src/lib/runtime/capabilities/sandbox-jobs.d.ts +12 -3
  52. package/src/lib/sandbox/file-edit-command.d.ts +2 -0
  53. package/src/lib/sandbox/file-edit-diff.d.ts +1 -0
  54. package/src/lib/sandbox/protocol.d.ts +13 -1
  55. package/src/lib/sandbox/runtime-provider.d.ts +12 -0
  56. package/src/lib/data/datasource/workbench-adapter.d.ts +0 -51
  57. package/src/lib/data/datasource/workbench-pagination.d.ts +0 -6
  58. package/src/lib/data/datasource/workbench-sql-lexer.d.ts +0 -11
  59. package/src/lib/data/datasource/workbench-sql-syntax.d.ts +0 -3
  60. package/src/lib/data/datasource/workbench-sql.d.ts +0 -20
@@ -1,682 +1,7 @@
1
- import { _ as _extends } from './_extends.esm.js';
2
-
3
1
  const DataSourceRuntimeCapability = Object.freeze({
4
2
  id: 'platform.datasource.workbench',
5
3
  description: 'Scoped database workbench access; credentials remain host-owned.',
6
4
  __type: undefined
7
5
  });
8
6
 
9
- /** Mask comments and quoted content without changing source offsets. Shared by guards and pagination. */ function lexWorkbenchSql(source) {
10
- if (!source.trim() || source.length > 100000 || source.includes('\0')) throw new Error('invalid_sql');
11
- const masked = source.split('');
12
- const quoted = new Map();
13
- const hide = (start, end, kind)=>{
14
- for(let i = start; i < end; i++)if (masked[i] !== '\n') masked[i] = ' ';
15
- if (kind) {
16
- const marker = start + 1;
17
- quoted.set(marker, kind);
18
- masked[marker] = kind === 'literal' ? '?' : 'i';
19
- }
20
- };
21
- let index = 0;
22
- while(index < source.length){
23
- const start = index, c = source[index], next = source[index + 1];
24
- if (c === '-' && next === '-' || c === '#') {
25
- while(index < source.length && source[index] !== '\n')index++;
26
- hide(start, index);
27
- continue;
28
- }
29
- if (c === '/' && next === '*') {
30
- if (source[index + 2] === '!') throw new Error('executable_comment_not_supported');
31
- const end = source.indexOf('*/', index + 2);
32
- if (end < 0) throw new Error('unterminated_comment');
33
- index = end + 2;
34
- hide(start, index);
35
- continue;
36
- }
37
- if (c === "'" || c === '"' || c === '`') {
38
- let closed = false;
39
- index++;
40
- while(index < source.length){
41
- if (source[index] === '\\') throw new Error('use_parameters_for_backslash_literals');
42
- if (source[index] === c) {
43
- if (source[index + 1] === c) {
44
- index += 2;
45
- continue;
46
- }
47
- index++;
48
- closed = true;
49
- break;
50
- }
51
- index++;
52
- }
53
- if (!closed) throw new Error('unterminated_literal');
54
- hide(start, index, c === "'" ? 'literal' : 'identifier');
55
- continue;
56
- }
57
- if (c === '$') {
58
- var _source_slice_match;
59
- const tag = (_source_slice_match = source.slice(index).match(/^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/)) == null ? void 0 : _source_slice_match[0];
60
- if (tag) {
61
- const end = source.indexOf(tag, index + tag.length);
62
- if (end < 0) throw new Error('unterminated_literal');
63
- index = end + tag.length;
64
- hide(start, index, 'literal');
65
- continue;
66
- }
67
- }
68
- index++;
69
- }
70
- const text = masked.join('');
71
- const tokens = [
72
- ...text.matchAll(/[A-Z_][A-Z_0-9]*|[0-9]+|[^\s]/gi)
73
- ].map((match)=>{
74
- var _quoted_get;
75
- return {
76
- text: match[0].toUpperCase(),
77
- start: match.index,
78
- end: match.index + match[0].length,
79
- kind: (_quoted_get = quoted.get(match.index)) != null ? _quoted_get : /^[A-Z_]/i.test(match[0]) ? 'word' : /^[0-9]/.test(match[0]) ? 'number' : 'symbol'
80
- };
81
- });
82
- return {
83
- masked: text,
84
- tokens
85
- };
86
- }
87
-
88
- const MODIFIED_TYPES = new Set('DECIMAL NUMERIC CHAR VARCHAR NCHAR NVARCHAR BINARY VARBINARY DATETIME TIME TIMESTAMP'.split(' '));
89
- /** Positions where name(...) declares columns or a built-in type, rather than invoking a function. */ function sqlDeclarationPositions(tokens) {
90
- const declarations = new Set();
91
- const closing = new Map(), parents = new Map();
92
- const stack = [];
93
- tokens.forEach((token, index)=>{
94
- if (stack.length) parents.set(index, stack[stack.length - 1]);
95
- if (token.text === '(') stack.push(index);
96
- if (token.text === ')') {
97
- const open = stack.pop();
98
- if (open !== undefined) closing.set(open, index);
99
- }
100
- });
101
- const name = (index)=>{
102
- var _tokens_index;
103
- return [
104
- 'word',
105
- 'identifier'
106
- ].includes((_tokens_index = tokens[index]) == null ? void 0 : _tokens_index.kind);
107
- };
108
- const is = (index, word)=>{
109
- var _tokens_index;
110
- return ((_tokens_index = tokens[index]) == null ? void 0 : _tokens_index.text) === word;
111
- };
112
- for(let i = 0; i < tokens.length; i++){
113
- if (tokens[i].kind !== 'word' || !is(i, 'WITH')) continue;
114
- let cursor = i + 1;
115
- if (is(cursor, 'RECURSIVE')) cursor++;
116
- while(name(cursor)){
117
- const declaration = cursor++;
118
- let columns = false;
119
- if (is(cursor, '(')) {
120
- const end = closing.get(cursor);
121
- if (end === undefined || end === cursor + 1) break;
122
- const columnTokens = tokens.slice(cursor + 1, end);
123
- if (columnTokens.length % 2 === 0 || !columnTokens.every((token, n)=>n % 2 === 0 ? [
124
- 'word',
125
- 'identifier'
126
- ].includes(token.kind) : token.text === ',')) break;
127
- columns = true;
128
- cursor = end + 1;
129
- }
130
- if (!is(cursor++, 'AS')) break;
131
- if (is(cursor, 'NOT')) cursor++;
132
- if (is(cursor, 'MATERIALIZED')) cursor++;
133
- if (!is(cursor, '(')) break;
134
- const end = closing.get(cursor);
135
- if (end === undefined) break;
136
- if (columns) declarations.add(tokens[declaration].start);
137
- cursor = end + 1;
138
- if (!is(cursor, ',')) break;
139
- cursor++;
140
- }
141
- }
142
- tokens.forEach((token, i)=>{
143
- var _tokens_;
144
- if (token.kind !== 'word' || !MODIFIED_TYPES.has(token.text) || !is(i + 1, '(')) return;
145
- const end = closing.get(i + 1);
146
- if (end === undefined) return;
147
- const args = tokens.slice(i + 2, end);
148
- if (![
149
- 1,
150
- 3
151
- ].includes(args.length) || !args.every((arg, n)=>n % 2 ? arg.text === ',' : arg.kind === 'number')) return;
152
- const parent = parents.get(i);
153
- const owner = parent === undefined ? undefined : (_tokens_ = tokens[parent - 1]) == null ? void 0 : _tokens_.text;
154
- const cast = owner === 'CAST' && is(i - 1, 'AS');
155
- const convert = owner === 'CONVERT' && is(i - 1, ',');
156
- const postgresCast = is(i - 1, ':') && is(i - 2, ':');
157
- if (cast || convert || postgresCast) declarations.add(token.start);
158
- });
159
- return declarations;
160
- }
161
-
162
- const WRITE = new Set([
163
- 'INSERT',
164
- 'UPDATE',
165
- 'DELETE',
166
- 'CREATE',
167
- 'ALTER',
168
- 'DROP',
169
- 'TRUNCATE',
170
- 'RENAME'
171
- ]);
172
- const FORBIDDEN = new Set([
173
- 'INTO',
174
- 'OUTFILE',
175
- 'DUMPFILE',
176
- 'PROCEDURE',
177
- 'CALL',
178
- 'COPY',
179
- 'LOAD',
180
- 'EXPORT',
181
- 'IMPORT',
182
- 'GRANT',
183
- 'REVOKE',
184
- 'LOCK',
185
- 'UNLOCK',
186
- 'KILL',
187
- 'SET',
188
- 'RESET',
189
- 'ANALYZE',
190
- 'VACUUM',
191
- 'OPTIMIZE',
192
- 'ATTACH',
193
- 'DETACH'
194
- ]);
195
- // Legacy SQL Workbench policy shared by supported database plugins.
196
- // TODO: separate dialect function policies through plugin-owned strategies; preserve fail-closed checks.
197
- // Allowlisting permits parsing; the selected database still determines function availability.
198
- const SAFE_FUNCTIONS = new Set('ABS ACOS ASIN ATAN ATAN2 AVG CAST CEIL CEILING COALESCE CONCAT CONCAT_WS CONVERT COS COUNT CURDATE CURRENT_DATE CURRENT_TIMESTAMP DATE DATE_TRUNC DATE_ADD DATE_SUB DATE_FORMAT DATEDIFF DAY DAYOFMONTH DAYOFWEEK EXTRACT FLOOR FORMAT GREATEST GROUP_CONCAT IF IFNULL JSON_EXTRACT JSON_LENGTH JSON_UNQUOTE LEAST LEFT LENGTH LN LOG LOWER LPAD LTRIM MAX MD5 MIN MOD MONTH NOW NULLIF POWER RAND REPLACE REVERSE RIGHT ROUND ROW_NUMBER RANK DENSE_RANK LAG LEAD FIRST_VALUE LAST_VALUE LPAD RPAD RTRIM SIGN SIN SQRT STDDEV STDDEV_POP STDDEV_SAMP SUBSTR SUBSTRING SUM TAN TO_CHAR TO_DATE TO_TIMESTAMP TRIM TRUNC UPPER VAR_POP VAR_SAMP VERSION WEEK YEAR DATABASE CURRENT_DATABASE CURRENT_SCHEMA ARRAY_AGG STRING_AGG JSON_AGG JSON_BUILD_OBJECT PG_GET_VIEWDEF'.split(' '));
199
- // SQL keywords introduce grouped expressions/subqueries, not function calls.
200
- // Their contents are still scanned for unsafe or unknown calls (including inside CASE).
201
- // Compatibility heuristic, not a SQL grammar: migrate with plugin-owned dialect validation.
202
- const SQL_PARENS = new Set('IN AS EXISTS OVER PARTITION VALUES SELECT WITH FROM JOIN AND OR NOT ON USING FILTER GROUPING ROLLUP CUBE DISTINCT EXPLAIN WHERE HAVING CASE WHEN THEN ELSE'.split(' '));
203
- const UNSAFE_FUNCTIONS = /\b(pg_sleep|sleep|benchmark|dblink\w*|lo_\w+|pg_(?:read|write|ls|stat|terminate|cancel|reload|rotate|log|create|drop|promote|switch|backup|replication|advisory)\w*|get_lock|release_lock|load_file|nextval|setval|set_config|http\w*|s3|hdfs|jdbc|mysql|postgresql|file|url)\s*\(/i;
204
- /**
205
- * @deprecated Mixed-dialect Workbench policy. New adapters should own dialect-aware statement
206
- * validation. Existing callers must retain this guard until an equivalent replacement is in place.
207
- */ function splitWorkbenchSql(source) {
208
- const { masked, tokens } = lexWorkbenchSql(source);
209
- const statements = [];
210
- let start = 0;
211
- const finish = (end)=>{
212
- const text = masked.slice(start, end);
213
- if (text.trim()) {
214
- var _text_toUpperCase_match;
215
- const words = (_text_toUpperCase_match = text.toUpperCase().match(/[A-Z_][A-Z_0-9]*/g)) != null ? _text_toUpperCase_match : [];
216
- const first = words[0];
217
- let effect = 'unsupported';
218
- if (WRITE.has(first)) effect = 'write';
219
- if (first === 'SELECT' || first === 'WITH' || first === 'SHOW' || first === 'DESC' || first === 'DESCRIBE' || first === 'EXPLAIN') {
220
- effect = 'read';
221
- if (words.some((word, index)=>WRITE.has(word) && !(first === 'SHOW' && index === 1 && word === 'CREATE') || FORBIDDEN.has(word)) || UNSAFE_FUNCTIONS.test(text) || /\bFOR\s+(UPDATE|SHARE)\b/i.test(text) || /:=|\bEXPLAIN\s+ANALYZE\b|@/i.test(text)) effect = 'unsupported';
222
- // eslint-disable-next-line no-control-regex -- intentional: reject any non-ASCII/control input
223
- if (/[^\x00-\x7f]/.test(text) || /\.\s*[A-Z_][A-Z_0-9]*\s*\(/i.test(text)) effect = 'unsupported';
224
- const declarations = sqlDeclarationPositions(tokens.filter((token)=>token.start >= start && token.end <= end));
225
- if ([
226
- ...text.matchAll(/([A-Z_][A-Z_0-9]*)\s*\(/gi)
227
- ].some((match)=>!declarations.has(start + match.index) && !SAFE_FUNCTIONS.has(match[1].toUpperCase()) && !SQL_PARENS.has(match[1].toUpperCase()))) effect = 'unsupported';
228
- if (first === 'SHOW' && !/^(SHOW\s+(DATABASES|SCHEMAS|CATALOGS|TABLES|FULL\s+TABLES|COLUMNS|FULL\s+COLUMNS|INDEX|INDEXES|KEYS|CREATE\s+TABLE|CREATE\s+VIEW|PARTITIONS|VARIABLES|STATUS|GRANTS))\b/i.test(text.trim())) effect = 'unsupported';
229
- }
230
- // CREATE/ALTER routines, external resources and privileged SQL are outside this app.
231
- if (effect === 'write' && /\b(FUNCTION|PROCEDURE|TRIGGER|USER|ROLE|CATALOG|RESOURCE|SYSTEM|SERVER|EXTENSION|FILE|OUTFILE|DUMPFILE|EXECUTE)\b/i.test(text)) effect = 'unsupported';
232
- statements.push({
233
- sql: source.slice(start, end).trim(),
234
- words,
235
- effect
236
- });
237
- }
238
- start = end + 1;
239
- };
240
- for (const token of tokens){
241
- if (token.kind === 'symbol' && token.text === ';') finish(token.start);
242
- }
243
- finish(source.length);
244
- if (!statements.length || statements.length > 50) throw new Error('statement_count_exceeded');
245
- return statements;
246
- }
247
- /**
248
- * @deprecated Uses the legacy mixed-dialect policy. New adapters should enforce read-only execution
249
- * with dialect-aware validation and database permissions. Keep this guard until safely migrated.
250
- */ function requireReadStatement(sql) {
251
- const statements = splitWorkbenchSql(sql);
252
- if (statements.length !== 1 || statements[0].effect !== 'read') throw new Error('read_only_violation');
253
- return statements[0].sql;
254
- }
255
- /**
256
- * @deprecated Built-in engine switch. New adapters should own dialect-specific identifier quoting
257
- * while preserving identifier validation and escaping.
258
- */ function quoteDatabaseIdentifier(name, engine) {
259
- // eslint-disable-next-line no-control-regex -- intentional: reject control characters in identifiers
260
- if (!name || name.length > 256 || /[\0-\x1f]/.test(name)) throw new Error('invalid_identifier');
261
- const quote = engine === 'postgres' ? '"' : '`';
262
- return quote + name.split(quote).join(quote + quote) + quote;
263
- }
264
-
265
- /** Apply a page to a MySQL result without turning its (possibly duplicate) output names into table columns. */ function paginateMysqlQuery(sql, parameters = [], limit, offset) {
266
- const { tokens } = lexWorkbenchSql(sql);
267
- const top = [];
268
- let depth = 0;
269
- for (const token of tokens){
270
- if (token.text === '(') depth++;
271
- if (!depth) top.push(token);
272
- if (token.text === ')') depth--;
273
- if (depth < 0) throw new Error('unsupported_pagination');
274
- }
275
- if (depth) throw new Error('unsupported_pagination');
276
- const start = top.findIndex((token)=>token.kind === 'word' && token.text === 'LIMIT');
277
- if (start < 0) return {
278
- sql: `${sql}\nLIMIT ${limit + 1} OFFSET ${offset}`,
279
- parameters
280
- };
281
- const clause = top.slice(start + 1);
282
- const bindings = tokens.filter((token)=>token.text === '?' && token.kind === 'symbol');
283
- const consumed = new Set();
284
- const integer = (token)=>{
285
- if ((token == null ? void 0 : token.kind) === 'number') return BigInt(token.text);
286
- if ((token == null ? void 0 : token.kind) === 'symbol' && token.text === '?') {
287
- const index = bindings.indexOf(token), value = parameters[index];
288
- if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) {
289
- consumed.add(index);
290
- return BigInt(value);
291
- }
292
- }
293
- throw new Error('unsupported_pagination');
294
- };
295
- let count, skip = 0n;
296
- if (clause.length === 1) count = integer(clause[0]);
297
- else if (clause.length === 3 && clause[1].text === ',') {
298
- skip = integer(clause[0]);
299
- count = integer(clause[2]);
300
- } else if (clause.length === 3 && clause[1].kind === 'word' && clause[1].text === 'OFFSET') {
301
- count = integer(clause[0]);
302
- skip = integer(clause[2]);
303
- } else throw new Error('unsupported_pagination');
304
- const remaining = count > BigInt(offset) ? count - BigInt(offset) : 0n;
305
- const size = remaining < BigInt(limit + 1) ? remaining : BigInt(limit + 1);
306
- return {
307
- sql: `${sql.slice(0, top[start].start)}LIMIT ${size} OFFSET ${skip + BigInt(offset)}${sql.slice(clause[clause.length - 1].end)}`,
308
- parameters: parameters.filter((_, index)=>!consumed.has(index))
309
- };
310
- }
311
-
312
- const number = (value)=>Number(value != null ? value : 0);
313
- const string = (value)=>value == null ? '' : String(value);
314
- const cell = (result, row, name)=>row[result.columns.findIndex((column)=>column.name.toLowerCase() === name.toLowerCase())];
315
- /**
316
- * One adapter per physical connection. A host session must not share it across users.
317
- * @deprecated Legacy SDK-owned SQL dialects. New plugins should implement DatabaseWorkbenchAdapter
318
- * with plugin-owned dialect behavior. Retained for compatibility with existing plugins.
319
- */ class SqlDatabaseWorkbenchAdapter {
320
- quote(name) {
321
- return quoteDatabaseIdentifier(name, this.engine);
322
- }
323
- ref(object) {
324
- this.assertLocation(object);
325
- var _object_schema, _ref, _object_database;
326
- const namespace = this.engine === 'postgres' ? (_ref = (_object_schema = object.schema) != null ? _object_schema : this.initial.schema) != null ? _ref : 'public' : (_object_database = object.database) != null ? _object_database : this.initial.database;
327
- if (!namespace) throw new Error('database_required');
328
- return `${this.quote(namespace)}.${this.quote(object.name)}`;
329
- }
330
- assertLocation(location) {
331
- if (location.engineCatalog && location.engineCatalog !== 'internal') throw new Error('external_catalog_not_supported');
332
- if (this.engine === 'postgres' && location.database && location.database !== this.initial.database) throw new Error('database_requires_new_connection');
333
- }
334
- async raw(sql, parameters = [], maxRows = 1001, signal, timeoutMs = 30000) {
335
- if (this.closed) throw new Error('session_closed');
336
- return this.transport.execute(sql, parameters, {
337
- maxRows,
338
- timeoutMs,
339
- signal
340
- });
341
- }
342
- async capabilities() {
343
- if (!this.version) {
344
- var _result_rows_;
345
- const result = await this.raw(this.engine === 'doris' ? 'SELECT @@version_comment AS version' : 'SELECT version() AS version', [], 1);
346
- this.version = string((_result_rows_ = result.rows[0]) == null ? void 0 : _result_rows_[0]);
347
- }
348
- const supported = this.engine !== 'doris' || /(?:^|[^0-9])(?:2\.1|3\.\d+|4\.\d+)(?:[.\s_-]|$)/.test(this.version);
349
- return {
350
- engine: this.engine,
351
- version: this.version,
352
- query: true,
353
- explain: true,
354
- transactions: this.engine !== 'doris',
355
- cancel: true,
356
- import: supported,
357
- writes: supported,
358
- nativeReadOnly: this.engine !== 'doris',
359
- objectKinds: [
360
- 'table',
361
- 'view'
362
- ],
363
- diagnostics: this.engine === 'doris' ? [
364
- ...supported ? [] : [
365
- 'doris_version_unverified_writes_disabled'
366
- ],
367
- 'doris_permissions_enforce_read_only',
368
- 'external_catalog_not_supported',
369
- 'doris_transactions_not_exposed'
370
- ] : []
371
- };
372
- }
373
- async locations() {
374
- const result = await this.raw(this.engine === 'postgres' ? "SELECT schema_name AS name FROM information_schema.schemata WHERE schema_name NOT LIKE 'pg_%' AND schema_name <> 'information_schema' ORDER BY schema_name LIMIT 1000" : "SELECT schema_name AS name FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema','performance_schema','mysql','sys') ORDER BY schema_name LIMIT 1000");
375
- return result.rows.map((row)=>this.engine === 'postgres' ? {
376
- database: this.initial.database,
377
- schema: string(row[0])
378
- } : _extends({
379
- database: string(row[0])
380
- }, this.engine === 'doris' ? {
381
- engineCatalog: 'internal'
382
- } : {}));
383
- }
384
- async objects(input) {
385
- this.assertLocation(input);
386
- var _input_page, _input_pageSize;
387
- const page = Math.max(1, Math.min((_input_page = input.page) != null ? _input_page : 1, 10000)), pageSize = Math.max(1, Math.min((_input_pageSize = input.pageSize) != null ? _input_pageSize : 100, 1000));
388
- var _input_schema, _ref, _input_database;
389
- const namespace = this.engine === 'postgres' ? (_ref = (_input_schema = input.schema) != null ? _input_schema : this.initial.schema) != null ? _ref : 'public' : (_input_database = input.database) != null ? _input_database : this.initial.database;
390
- if (!namespace) return {
391
- items: [],
392
- page,
393
- pageSize,
394
- hasMore: false
395
- };
396
- const placeholder = (i)=>this.engine === 'postgres' ? `$${i}` : '?';
397
- var _input_search;
398
- const result = await this.raw(`SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = ${placeholder(1)} AND table_name LIKE ${placeholder(2)} ORDER BY table_name LIMIT ${pageSize + 1} OFFSET ${(page - 1) * pageSize}`, [
399
- namespace,
400
- `%${(_input_search = input.search) != null ? _input_search : ''}%`
401
- ], pageSize + 1);
402
- return {
403
- items: result.rows.slice(0, pageSize).map((row)=>({
404
- database: input.database,
405
- schema: input.schema,
406
- engineCatalog: input.engineCatalog,
407
- name: string(row[0]),
408
- kind: string(row[1]).includes('VIEW') ? 'view' : 'table'
409
- })),
410
- page,
411
- pageSize,
412
- hasMore: result.rows.length > pageSize
413
- };
414
- }
415
- async describe(object) {
416
- const reference = this.ref(object);
417
- var _object_schema, _ref, _object_database, _ref1;
418
- const namespace = this.engine === 'postgres' ? (_ref = (_object_schema = object.schema) != null ? _object_schema : this.initial.schema) != null ? _ref : 'public' : (_ref1 = (_object_database = object.database) != null ? _object_database : this.initial.database) != null ? _ref1 : '';
419
- const p = (i)=>this.engine === 'postgres' ? `$${i}` : '?';
420
- const metadata = await this.raw(this.engine === 'postgres' ? `SELECT a.attname AS column_name, pg_catalog.format_type(a.atttypid,a.atttypmod) AS data_type, CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END AS is_nullable, a.attnum AS ordinal_position, pg_get_expr(d.adbin,d.adrelid) AS column_default, pg_catalog.col_description(c.oid,a.attnum) AS column_comment FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid=a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum WHERE n.nspname=$1 AND c.relname=$2 AND a.attnum>0 AND NOT a.attisdropped ORDER BY a.attnum LIMIT 1000` : `SELECT column_name, column_type AS data_type, is_nullable, ordinal_position, column_default, column_comment FROM information_schema.columns WHERE table_schema = ${p(1)} AND table_name = ${p(2)} ORDER BY ordinal_position LIMIT 1000`, [
421
- namespace,
422
- object.name
423
- ]);
424
- const columns = metadata.rows.map((row, index)=>({
425
- id: `c${index}`,
426
- name: string(cell(metadata, row, 'column_name')),
427
- dataType: string(cell(metadata, row, 'data_type')),
428
- nullable: string(cell(metadata, row, 'is_nullable')) === 'YES',
429
- ordinal: number(cell(metadata, row, 'ordinal_position')),
430
- comment: string(cell(metadata, row, 'column_comment')) || undefined,
431
- defaultValue: cell(metadata, row, 'column_default') == null ? null : string(cell(metadata, row, 'column_default'))
432
- }));
433
- if (!columns.length) throw new Error('object_not_found_or_denied');
434
- const keys = [], diagnostics = [];
435
- let definition = '', model;
436
- if (this.engine === 'postgres') {
437
- const result = await this.raw(`SELECT tc.constraint_name, tc.constraint_type, kcu.column_name, kcu.ordinal_position, ccu.table_schema AS foreign_schema, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column FROM information_schema.table_constraints tc JOIN information_schema.key_column_usage kcu ON tc.constraint_catalog=kcu.constraint_catalog AND tc.constraint_schema=kcu.constraint_schema AND tc.constraint_name=kcu.constraint_name LEFT JOIN information_schema.referential_constraints rc ON rc.constraint_catalog=tc.constraint_catalog AND rc.constraint_schema=tc.constraint_schema AND rc.constraint_name=tc.constraint_name LEFT JOIN information_schema.key_column_usage ccu ON ccu.constraint_catalog=rc.unique_constraint_catalog AND ccu.constraint_schema=rc.unique_constraint_schema AND ccu.constraint_name=rc.unique_constraint_name AND ccu.ordinal_position=kcu.position_in_unique_constraint WHERE tc.table_schema=$1 AND tc.table_name=$2 ORDER BY tc.constraint_name,kcu.ordinal_position LIMIT 1000`, [
438
- namespace,
439
- object.name
440
- ]);
441
- for (const row of result.rows){
442
- const name = string(cell(result, row, 'constraint_name')), kind = string(cell(result, row, 'constraint_type'));
443
- let key = keys.find((item)=>item.name === name);
444
- if (!key) {
445
- key = {
446
- name,
447
- kind: kind === 'PRIMARY KEY' ? 'primary' : kind === 'FOREIGN KEY' ? 'foreign' : 'unique',
448
- columns: []
449
- };
450
- keys.push(key);
451
- }
452
- key.columns.push(string(cell(result, row, 'column_name')));
453
- if (key.kind === 'foreign') {
454
- var _key;
455
- key.referencedTable = {
456
- schema: string(cell(result, row, 'foreign_schema')),
457
- name: string(cell(result, row, 'foreign_table')),
458
- kind: 'table'
459
- };
460
- var _referencedColumns;
461
- ((_referencedColumns = (_key = key).referencedColumns) != null ? _referencedColumns : _key.referencedColumns = []).push(string(cell(result, row, 'foreign_column')));
462
- }
463
- }
464
- if (object.kind === 'view') {
465
- var _source_rows_;
466
- const source = await this.raw('SELECT pg_get_viewdef($1::regclass, true) AS definition', [
467
- reference
468
- ], 1);
469
- definition = `CREATE VIEW ${reference} AS\n${string((_source_rows_ = source.rows[0]) == null ? void 0 : _source_rows_[0])}`;
470
- } else {
471
- definition = `CREATE TABLE ${reference} (\n${columns.map((column)=>` ${this.quote(column.name)} ${column.dataType}${column.nullable ? '' : ' NOT NULL'}${column.defaultValue === null ? '' : ` DEFAULT ${column.defaultValue}`}`).join(',\n')}\n);`;
472
- diagnostics.push('definition_reconstructed_from_metadata');
473
- }
474
- } else {
475
- var _source_rows_1;
476
- const source = await this.raw(`SHOW CREATE ${object.kind === 'view' ? 'VIEW' : 'TABLE'} ${reference}`, [], 1);
477
- definition = string((_source_rows_1 = source.rows[0]) == null ? void 0 : _source_rows_1[1]);
478
- if (this.engine === 'doris') {
479
- const match = definition.match(/\b(UNIQUE|DUPLICATE|AGGREGATE)\s+KEY\s*\(([^)]*)\)/i);
480
- model = (match == null ? void 0 : match[1].toUpperCase()) === 'UNIQUE' ? 'unique' : (match == null ? void 0 : match[1].toUpperCase()) === 'DUPLICATE' ? 'duplicate' : (match == null ? void 0 : match[1].toUpperCase()) === 'AGGREGATE' ? 'aggregate' : undefined;
481
- if (model === 'unique' && match) keys.push({
482
- name: 'UNIQUE KEY',
483
- kind: 'primary',
484
- columns: [
485
- ...match[2].matchAll(/`((?:``|[^`])+)`/g)
486
- ].map((item)=>item[1].split('``').join('`'))
487
- });
488
- } else {
489
- const index = await this.raw(`SHOW INDEX FROM ${reference}`);
490
- for (const row of index.rows){
491
- const name = string(cell(index, row, 'Key_name'));
492
- let key = keys.find((item)=>item.name === name);
493
- if (!key) {
494
- key = {
495
- name,
496
- kind: name === 'PRIMARY' ? 'primary' : number(cell(index, row, 'Non_unique')) === 0 ? 'unique' : 'index',
497
- columns: []
498
- };
499
- keys.push(key);
500
- }
501
- key.columns.push(string(cell(index, row, 'Column_name')));
502
- }
503
- const foreign = await this.raw('SELECT constraint_name,column_name,referenced_table_schema,referenced_table_name,referenced_column_name FROM information_schema.key_column_usage WHERE table_schema=? AND table_name=? AND referenced_table_name IS NOT NULL ORDER BY constraint_name,ordinal_position LIMIT 1000', [
504
- namespace,
505
- object.name
506
- ]);
507
- for (const row of foreign.rows){
508
- var _key_referencedColumns;
509
- let key = keys.find((item)=>item.name === string(row[0]));
510
- if (!key) {
511
- key = {
512
- name: string(row[0]),
513
- kind: 'foreign',
514
- columns: [],
515
- referencedTable: {
516
- database: string(row[2]),
517
- name: string(row[3]),
518
- kind: 'table'
519
- },
520
- referencedColumns: []
521
- };
522
- keys.push(key);
523
- }
524
- key.columns.push(string(row[1]));
525
- (_key_referencedColumns = key.referencedColumns) == null ? void 0 : _key_referencedColumns.push(string(row[4]));
526
- }
527
- }
528
- }
529
- const editable = (this.engine !== 'doris' || (await this.capabilities()).writes) && object.kind === 'table' && keys.some((key)=>(key.kind === 'primary' || key.kind === 'unique') && key.columns.length > 0 && key.columns.every((name)=>{
530
- var _columns_find;
531
- return ((_columns_find = columns.find((column)=>column.name === name)) == null ? void 0 : _columns_find.nullable) === false;
532
- }));
533
- return {
534
- object,
535
- columns,
536
- keys,
537
- definition,
538
- model,
539
- editable,
540
- diagnostics
541
- };
542
- }
543
- async query(input, signal) {
544
- this.assertLocation(input);
545
- if (input.database && input.database !== this.initial.database) throw new Error('database_requires_new_connection');
546
- if (input.schema && input.schema !== this.initial.schema) throw new Error('schema_requires_new_connection');
547
- if (this.busy) throw new Error('session_busy');
548
- if (input.mode === 'read') {
549
- requireReadStatement(input.sql);
550
- }
551
- const statements = splitWorkbenchSql(input.sql);
552
- if (statements.length !== 1 || statements[0].effect === 'unsupported') throw new Error('unsupported_statement');
553
- var _input_limit, _input_offset;
554
- const limit = Math.max(1, Math.min((_input_limit = input.limit) != null ? _input_limit : 100, 1000)), offset = Math.max(0, Math.min((_input_offset = input.offset) != null ? _input_offset : 0, 100000));
555
- if (input.mode === 'write' && !(await this.capabilities()).writes) throw new Error('engine_version_writes_unavailable');
556
- if (input.mode === 'write' && offset) throw new Error('mutation_cannot_be_paginated');
557
- let sql = statements[0].sql;
558
- let parameters = input.parameters;
559
- if (input.mode === 'read' && [
560
- 'SELECT',
561
- 'WITH'
562
- ].includes(statements[0].words[0])) {
563
- if (this.engine === 'mysql') ({ sql, parameters } = paginateMysqlQuery(sql, parameters, limit, offset));
564
- else sql = `SELECT * FROM (\n${sql}\n) AS ${this.quote('_db_studio_page')} LIMIT ${limit + 1} OFFSET ${offset}`;
565
- } else if (offset) throw new Error('statement_cannot_be_paginated');
566
- this.busy = true;
567
- let readTransaction = false;
568
- try {
569
- if (input.mode === 'read' && this.engine !== 'doris' && !this.transactionOpen) {
570
- await this.raw(this.engine === 'postgres' ? 'BEGIN READ ONLY' : 'START TRANSACTION READ ONLY', [], 1);
571
- readTransaction = true;
572
- }
573
- var _input_timeoutMs;
574
- const result = await this.raw(sql, parameters, limit + 1, signal, Math.max(1, Math.min((_input_timeoutMs = input.timeoutMs) != null ? _input_timeoutMs : 30000, 120000)));
575
- const hasMore = result.rows.length > limit || result.truncated;
576
- return _extends({}, result, {
577
- rows: result.rows.slice(0, limit),
578
- hasMore,
579
- truncated: result.truncated
580
- });
581
- } finally{
582
- try {
583
- if (readTransaction) {
584
- try {
585
- await this.raw('ROLLBACK', [], 1);
586
- } catch (e) {
587
- await this.close();
588
- }
589
- }
590
- } finally{
591
- this.busy = false;
592
- }
593
- }
594
- }
595
- async explain(input, signal) {
596
- const sql = requireReadStatement(input.sql);
597
- if (!/^(SELECT|WITH)\b/i.test(sql)) throw new Error('explain_requires_select');
598
- const prefix = this.engine === 'postgres' ? 'EXPLAIN (FORMAT JSON) ' : this.engine === 'mysql' ? 'EXPLAIN FORMAT=JSON ' : 'EXPLAIN ';
599
- return this.query(_extends({}, input, {
600
- sql: prefix + sql,
601
- mode: 'read'
602
- }), signal);
603
- }
604
- async transaction(action) {
605
- if (this.engine === 'doris') throw new Error('transactions_not_supported');
606
- if (this.busy) throw new Error('session_busy');
607
- if (action === 'begin' && this.transactionOpen) throw new Error('transaction_already_open');
608
- if (action !== 'begin' && !this.transactionOpen) throw new Error('transaction_not_open');
609
- this.busy = true;
610
- try {
611
- await this.raw(action.toUpperCase(), [], 1);
612
- this.transactionOpen = action === 'begin';
613
- } finally{
614
- this.busy = false;
615
- }
616
- }
617
- async importRows(input, signal) {
618
- this.assertLocation(input);
619
- if (this.busy) throw new Error('session_busy');
620
- if (!(await this.capabilities()).import) throw new Error('engine_version_import_unavailable');
621
- if (new Set(input.columns).size !== input.columns.length) throw new Error('duplicate_import_columns');
622
- if (!input.rows.length || input.rows.length > 10000 || !input.columns.length || input.columns.length > 500 || input.rows.some((row)=>row.length !== input.columns.length)) throw new Error('invalid_import_shape');
623
- if (this.transport.importRows) {
624
- this.busy = true;
625
- try {
626
- return await this.transport.importRows(input, signal);
627
- } finally{
628
- this.busy = false;
629
- }
630
- }
631
- if (this.engine === 'doris') throw new Error('stream_load_required');
632
- const reference = this.ref(_extends({}, input, {
633
- name: input.table,
634
- kind: 'table'
635
- }));
636
- await this.transaction('begin');
637
- try {
638
- for(let i = 0; i < input.rows.length; i += 100){
639
- const batch = input.rows.slice(i, i + 100), values = batch.flat();
640
- let n = 0;
641
- const placeholders = batch.map((row)=>`(${row.map(()=>this.engine === 'postgres' ? `$${++n}` : '?').join(',')})`).join(',');
642
- await this.query({
643
- sql: `INSERT INTO ${reference} (${input.columns.map((name)=>this.quote(name)).join(',')}) VALUES ${placeholders}`,
644
- parameters: values,
645
- mode: 'write'
646
- }, signal);
647
- }
648
- await this.transaction('commit');
649
- return {
650
- outcome: 'succeeded',
651
- loadedRows: input.rows.length,
652
- filteredRows: 0,
653
- label: input.operationId,
654
- diagnostics: []
655
- };
656
- } catch (error) {
657
- try {
658
- await this.transaction('rollback');
659
- } catch (e) {
660
- await this.close();
661
- }
662
- throw error;
663
- }
664
- }
665
- async cancel() {
666
- await this.close();
667
- }
668
- async close() {
669
- this.closed = true;
670
- await this.transport.close();
671
- }
672
- constructor(engine, transport, initial = {}){
673
- this.transactionOpen = false;
674
- this.busy = false;
675
- this.closed = false;
676
- this.engine = engine;
677
- this.transport = transport;
678
- this.initial = initial;
679
- }
680
- }
681
-
682
- export { DataSourceRuntimeCapability, SqlDatabaseWorkbenchAdapter, quoteDatabaseIdentifier, requireReadStatement, splitWorkbenchSql };
7
+ export { DataSourceRuntimeCapability };