@kweaver-ai/kweaver-sdk 0.8.2 → 0.8.4

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 (107) hide show
  1. package/README.md +26 -52
  2. package/README.zh.md +27 -46
  3. package/dist/api/agent-chat.d.ts +10 -2
  4. package/dist/api/agent-chat.js +19 -5
  5. package/dist/api/datasources.d.ts +14 -0
  6. package/dist/api/datasources.js +14 -0
  7. package/dist/api/resources.d.ts +94 -0
  8. package/dist/api/resources.js +166 -0
  9. package/dist/cli.js +103 -23
  10. package/dist/client.d.ts +10 -4
  11. package/dist/client.js +12 -6
  12. package/dist/commands/agent-members.js +27 -11
  13. package/dist/commands/agent.js +383 -272
  14. package/dist/commands/auth.js +184 -71
  15. package/dist/commands/bkn-metric.js +37 -16
  16. package/dist/commands/bkn-ops.d.ts +1 -1
  17. package/dist/commands/bkn-ops.js +192 -93
  18. package/dist/commands/bkn-query.js +99 -31
  19. package/dist/commands/bkn-schema.d.ts +3 -3
  20. package/dist/commands/bkn-schema.js +127 -86
  21. package/dist/commands/bkn.js +158 -116
  22. package/dist/commands/call.js +23 -13
  23. package/dist/commands/config.js +22 -12
  24. package/dist/commands/context-loader.js +98 -92
  25. package/dist/commands/dataflow.js +14 -6
  26. package/dist/commands/ds.d.ts +0 -31
  27. package/dist/commands/ds.js +18 -426
  28. package/dist/commands/explore-bkn.d.ts +7 -1
  29. package/dist/commands/explore-bkn.js +32 -3
  30. package/dist/commands/explore.js +18 -15
  31. package/dist/commands/model.js +53 -42
  32. package/dist/commands/resource.d.ts +1 -0
  33. package/dist/commands/{dataview.js → resource.js} +62 -84
  34. package/dist/commands/skill.js +201 -65
  35. package/dist/commands/token.js +11 -0
  36. package/dist/commands/tool.js +46 -29
  37. package/dist/commands/toolbox.js +31 -15
  38. package/dist/commands/vega.js +466 -250
  39. package/dist/help/format.d.ts +65 -0
  40. package/dist/help/format.js +141 -0
  41. package/dist/index.d.ts +3 -3
  42. package/dist/index.js +2 -2
  43. package/dist/resources/datasources.d.ts +7 -0
  44. package/dist/resources/datasources.js +7 -0
  45. package/dist/resources/{dataviews.d.ts → resources.d.ts} +10 -11
  46. package/dist/resources/{dataviews.js → resources.js} +12 -13
  47. package/dist/templates/explorer/bkn.js +860 -9
  48. package/dist/templates/explorer/index.html +1 -0
  49. package/dist/templates/explorer/style.css +225 -0
  50. package/dist/templates/explorer/vendor/g6.min.js +68 -0
  51. package/dist/trace-ai/eval-set/schemas.d.ts +1 -0
  52. package/dist/trace-ai/eval-set/schemas.js +4 -0
  53. package/dist/trace-ai/eval-set/types.d.ts +2 -0
  54. package/dist/trace-ai/exp/capture-fingerprint.d.ts +10 -0
  55. package/dist/trace-ai/exp/capture-fingerprint.js +12 -0
  56. package/dist/trace-ai/exp/context/context-assembler.d.ts +18 -0
  57. package/dist/trace-ai/exp/context/context-assembler.js +42 -0
  58. package/dist/trace-ai/exp/context/failure-analyzer.d.ts +22 -0
  59. package/dist/trace-ai/exp/context/failure-analyzer.js +59 -0
  60. package/dist/trace-ai/exp/context/kn-data-prober.d.ts +13 -0
  61. package/dist/trace-ai/exp/context/kn-data-prober.js +38 -0
  62. package/dist/trace-ai/exp/context/kn-schema-client.d.ts +14 -0
  63. package/dist/trace-ai/exp/context/kn-schema-client.js +41 -0
  64. package/dist/trace-ai/exp/context/retrieval-health.d.ts +32 -0
  65. package/dist/trace-ai/exp/context/retrieval-health.js +138 -0
  66. package/dist/trace-ai/exp/context/vega-catalog-client.d.ts +14 -0
  67. package/dist/trace-ai/exp/context/vega-catalog-client.js +15 -0
  68. package/dist/trace-ai/exp/coordinator.d.ts +34 -21
  69. package/dist/trace-ai/exp/coordinator.js +246 -24
  70. package/dist/trace-ai/exp/eval-runner.js +4 -2
  71. package/dist/trace-ai/exp/exp-store/events-jsonl.d.ts +1 -0
  72. package/dist/trace-ai/exp/exp-store/events-jsonl.js +18 -0
  73. package/dist/trace-ai/exp/exp-store/expected-fingerprint.d.ts +3 -0
  74. package/dist/trace-ai/exp/exp-store/expected-fingerprint.js +31 -0
  75. package/dist/trace-ai/exp/exp-store/index.d.ts +63 -2
  76. package/dist/trace-ai/exp/exp-store/index.js +2 -1
  77. package/dist/trace-ai/exp/exp-store/rollback-yaml.d.ts +12 -0
  78. package/dist/trace-ai/exp/exp-store/rollback-yaml.js +29 -0
  79. package/dist/trace-ai/exp/index.d.ts +2 -0
  80. package/dist/trace-ai/exp/index.js +68 -3
  81. package/dist/trace-ai/exp/info.js +1 -1
  82. package/dist/trace-ai/exp/patch/index.d.ts +13 -2
  83. package/dist/trace-ai/exp/patch/index.js +65 -10
  84. package/dist/trace-ai/exp/patch/kn-api-client.d.ts +40 -0
  85. package/dist/trace-ai/exp/patch/kn-api-client.js +14 -0
  86. package/dist/trace-ai/exp/patch/kn.d.ts +8 -0
  87. package/dist/trace-ai/exp/patch/kn.js +36 -0
  88. package/dist/trace-ai/exp/patch/skill-api-client.d.ts +17 -0
  89. package/dist/trace-ai/exp/patch/skill-api-client.js +14 -0
  90. package/dist/trace-ai/exp/patch/skill-content.d.ts +9 -0
  91. package/dist/trace-ai/exp/patch/skill-content.js +12 -0
  92. package/dist/trace-ai/exp/preflight.d.ts +77 -0
  93. package/dist/trace-ai/exp/preflight.js +148 -0
  94. package/dist/trace-ai/exp/providers/synthesizer-client.d.ts +3 -14
  95. package/dist/trace-ai/exp/providers/synthesizer-client.js +53 -35
  96. package/dist/trace-ai/exp/providers/triage-client.d.ts +15 -2
  97. package/dist/trace-ai/exp/providers/triage-client.js +143 -28
  98. package/dist/trace-ai/exp/run-preflight.d.ts +19 -0
  99. package/dist/trace-ai/exp/run-preflight.js +56 -0
  100. package/dist/trace-ai/exp/schemas.d.ts +402 -44
  101. package/dist/trace-ai/exp/schemas.js +131 -18
  102. package/dist/utils/deprecation.d.ts +1 -0
  103. package/dist/utils/deprecation.js +18 -0
  104. package/package.json +2 -1
  105. package/dist/api/dataviews.d.ts +0 -117
  106. package/dist/api/dataviews.js +0 -265
  107. package/dist/commands/dataview.d.ts +0 -8
package/README.md CHANGED
@@ -126,23 +126,19 @@ const graph = await client.bkn.querySubgraph("bkn-id", { /* path spec */ });
126
126
  await client.bkn.executeAction("bkn-id", "at-id", { /* params */ });
127
127
  const logs = await client.bkn.listActionLogs("bkn-id");
128
128
 
129
- // Data sources & data views
129
+ // Data sources & vega-backend resources
130
130
  const dsList = await client.datasources.list();
131
131
  const tables = await client.datasources.listTables("ds-id");
132
- const viewId = await client.dataviews.create({ name: "v", datasourceId: "ds-id", table: "orders" });
133
- const views = await client.dataviews.list({ datasourceId: "ds-id" });
134
- const fuzzy = await client.dataviews.find("BOM", { wait: false });
135
- const exact = await client.dataviews.find("orders", {
132
+ const resId = await client.resources.create({ name: "v", datasourceId: "ds-id", table: "orders" });
133
+ const resList = await client.resources.list({ datasourceId: "ds-id" });
134
+ const fuzzy = await client.resources.find("BOM", { wait: false });
135
+ const exact = await client.resources.find("orders", {
136
136
  datasourceId: "ds-id",
137
137
  exact: true,
138
138
  wait: true,
139
139
  });
140
- const dv = await client.dataviews.get(viewId);
141
- const queryRows = await client.dataviews.query(viewId, {
142
- sql: "SELECT id, name FROM orders LIMIT 10",
143
- limit: 10,
144
- needTotal: true,
145
- });
140
+ const res = await client.resources.get(resId);
141
+ const queryRows = await client.resources.query(resId, { limit: 10, needTotal: true });
146
142
 
147
143
  // Dataflow automation (CSV import pipeline, etc.)
148
144
  const result = await client.dataflows.execute({
@@ -190,50 +186,28 @@ Use `callTool(name, args)` when you need native MCP `tools/call` access for newl
190
186
 
191
187
  ## CLI Reference
192
188
 
189
+ `kweaver` follows a `gh`-style help layout (see [docs/cli_conventions.md §8](../../docs/cli_conventions.md#8-help-文本格式must)):
190
+
191
+ ```text
192
+ kweaver [--help|-h] # gh-style top-level overview
193
+ kweaver help <command> # forward to <command> --help
194
+ kweaver help all # full per-action signatures (migration fallback)
195
+ kweaver <command> [--help|-h] # subcommand overview + actions
196
+ kweaver <command> <subcommand> [--help|-h] # action-level flags + examples
193
197
  ```
194
- kweaver auth login <url> [--alias name] [--no-auth] [--no-browser] [-u user] [-p pass] [--new-password <pwd>] [--http-signin] [--insecure|-k]
195
- # -u/-p (with or without --http-signin): HTTP POST /oauth2/signin (yields refresh_token). Missing -u/-p are prompted from stdin (password hidden when TTY).
196
- # If the server returns error 401001017 (initial password), TTY users get a prompt to set a new password; non-interactive scripts must pass --new-password <pwd>.
197
- kweaver auth change-password [<url>] [-u <account>] [-o <old>] [-n <new>] [--insecure|-k]
198
- # EACP POST /api/eacp/v1/auth1/modifypassword — no OAuth token required. Omit -o/-n on a TTY to be prompted.
199
- kweaver auth login <url> --client-id ID --client-secret S --refresh-token T (headless login)
200
- kweaver auth export [url|alias] [--json] (export command to run on a headless host)
201
- kweaver auth status / whoami [url|alias] [--json] # whoami: --json; with KWEAVER_BASE_URL+KWEAVER_TOKEN when no ~/.kweaver/ platform
202
- kweaver auth list/use/delete/logout
203
- kweaver config show / list-bd / set-bd <value> # platform business domain — show/list-bd work with KWEAVER_BASE_URL (+ KWEAVER_TOKEN for list-bd)
204
- kweaver token
205
- kweaver ds list/get/delete/tables/connect
206
- kweaver ds import-csv <ds_id> --files <glob> [--table-prefix <p>] [--batch-size 500] [--recreate]
207
- kweaver dataflow list/run/runs/logs
208
- kweaver model llm list/get/add/edit/delete/test/chat/--template
209
- kweaver model small list/get/add/edit/delete/test/embeddings/rerank/--template
210
- kweaver dataview list/find/get/query/delete
211
- kweaver bkn list/get/stats/export/create/update/delete
212
- kweaver bkn create-from-ds <ds_id> --name <name> [--tables t1,t2] [--build]
213
- kweaver bkn create-from-csv <ds_id> --files <glob> --name <name> [--build]
214
- kweaver bkn validate/push/pull
215
- kweaver bkn object-type list/get/create/update/delete/query/properties
216
- kweaver bkn metric list/get/create/search/validate/update/delete/query/dry-run
217
- kweaver bkn relation-type list/get/create/update/delete
218
- kweaver bkn action-type list/query/execute
219
- kweaver bkn subgraph / search
220
- kweaver bkn action-execution get
221
- kweaver bkn action-log list/get/cancel
222
- kweaver agent list/get/create/update/delete/chat/sessions/history/publish/unpublish
223
- kweaver skill list/market/get/market-get/register/status/delete/update-metadata/update-package/history/republish/publish-history/content/read-file/download/install/management-content/management-read-file/management-download
224
- kweaver vega health/stats/inspect/sql/catalog/resource/connector-type
225
- kweaver context-loader help <subcommand>
226
- kweaver context-loader tools|resources|templates|prompts <kn-id>
227
- kweaver context-loader search-schema <kn-id> <query> [--scope object,relation,action,metric] [--concept-groups ids]
228
- kweaver context-loader tool-call <kn-id> <name> --args '<json>'
229
- kweaver context-loader kn-search|kn-schema-search <kn-id> <query> [...] (deprecated; use search-schema)
230
- kweaver context-loader query-object-instance|query-instance-subgraph|get-logic-properties|get-action-info|find-skills <kn-id> ...
231
- kweaver context-loader config set/use/list/show (deprecated; <kn-id> may be omitted to fall back to saved config)
232
- kweaver toolbox create/list/publish/unpublish/delete
233
- kweaver tool upload/list/enable/disable/execute/debug (execute and debug accept --path for OpenAPI path params)
234
- kweaver call <path> [-X METHOD] [-d BODY] [-H header] [-F key=value]
198
+
199
+ Top-level command groups:
200
+
201
+ ```text
202
+ AUTHENTICATION & CONFIG auth · token · config
203
+ DECISION AGENT agent · toolbox · tool
204
+ AI DATA PLATFORM bkn · ds · resource · dataflow · vega · context-loader
205
+ TRACE AI trace
206
+ FOUNDATION call · explore · model · skill · help
235
207
  ```
236
208
 
209
+ For a structured browsable index of every action and flag, run `kweaver help all`.
210
+
237
211
  ### Dataflow CLI examples
238
212
 
239
213
  ```bash
package/README.zh.md CHANGED
@@ -124,22 +124,18 @@ const graph = await client.bkn.querySubgraph("bkn-id", { /* 路径规格 */
124
124
  await client.bkn.executeAction("bkn-id", "at-id", { /* 参数 */ });
125
125
  const logs = await client.bkn.listActionLogs("bkn-id");
126
126
 
127
- // 数据源与数据视图
128
- const dsList = await client.datasources.list();
129
- const viewId = await client.dataviews.create({ name: "v", datasourceId: "ds-id", table: "orders" });
130
- const views = await client.dataviews.list({ datasourceId: "ds-id" });
131
- const fuzzy = await client.dataviews.find("BOM", { wait: false });
132
- const exact = await client.dataviews.find("orders", {
127
+ // 数据源 & vega-backend 资源
128
+ const dsList = await client.datasources.list();
129
+ const resId = await client.resources.create({ name: "v", datasourceId: "ds-id", table: "orders" });
130
+ const resList = await client.resources.list({ datasourceId: "ds-id" });
131
+ const fuzzy = await client.resources.find("BOM", { wait: false });
132
+ const exact = await client.resources.find("orders", {
133
133
  datasourceId: "ds-id",
134
134
  exact: true,
135
135
  wait: true,
136
136
  });
137
- const dv = await client.dataviews.get(viewId);
138
- const queryRows = await client.dataviews.query(viewId, {
139
- sql: "SELECT id, name FROM orders LIMIT 10",
140
- limit: 10,
141
- needTotal: true,
142
- });
137
+ const res = await client.resources.get(resId);
138
+ const queryRows = await client.resources.query(resId, { limit: 10, needTotal: true });
143
139
 
144
140
  // Vega — 可观测性与查询
145
141
  const catalogs = await client.vega.listCatalogs();
@@ -181,43 +177,28 @@ const history = await client.skills.history("skill-id");
181
177
 
182
178
  ## 命令速查
183
179
 
180
+ `kweaver` 采用 `gh` 风格 help 布局(详见 [docs/cli_conventions.md §8](../../docs/cli_conventions.md#8-help-文本格式must)):
181
+
182
+ ```text
183
+ kweaver --help # gh 风格顶层概览
184
+ kweaver help <command> # 转发到 `<command> --help`
185
+ kweaver help all # 完整 per-action 签名(迁移期兜底)
186
+ kweaver <command> --help # 子命令概览 + 动作列表
187
+ kweaver <command> <subcommand> --help # 动作级 flag + 示例
184
188
  ```
185
- kweaver auth login <url> [--alias name] [--no-auth] [--no-browser] [-u user] [-p pass] [--new-password <pwd>] [--http-signin] [--insecure|-k]
186
- # -u/-p(无论是否带 --http-signin):HTTP POST /oauth2/signin(可拿 refresh_token);缺失的用户名/密码会从 stdin 提示输入(TTY 下密码隐藏)
187
- # 若服务端返回 401001017(初始密码),交互终端会引导修改;非交互请使用 --new-password <pwd>。
188
- kweaver auth change-password [<url>] [-u <account>] [-o <old>] [-n <new>] [--insecure|-k]
189
- kweaver auth login <url> --client-id ID --client-secret S --refresh-token T (无浏览器登录)
190
- kweaver auth export [url|alias] [--json] (导出在无浏览器机器上运行的命令)
191
- kweaver auth status / whoami [url|alias] [--json] # whoami 支持 --json;无 ~/.kweaver/ 当前平台时可配 KWEAVER_BASE_URL+KWEAVER_TOKEN
192
- kweaver auth list/use/delete/logout
193
- kweaver config show / list-bd / set-bd <value> # 业务域;show/list-bd 在无已保存平台时可与 env 配对
194
- kweaver token
195
- kweaver ds list/get/delete/tables/connect
196
- kweaver dataflow list/run/runs/logs
197
- kweaver model llm list/get/add/edit/delete/test/chat/--template
198
- kweaver model small list/get/add/edit/delete/test/embeddings/rerank/--template
199
- kweaver dataview list/find/get/query/delete
200
- kweaver bkn list/get/stats/export/create/update/delete
201
- kweaver bkn object-type list/get/create/update/delete/query/properties
202
- kweaver bkn metric list/get/create/search/validate/update/delete/query/dry-run
203
- kweaver bkn relation-type list/get/create/update/delete
204
- kweaver bkn action-type list/query/execute
205
- kweaver bkn subgraph
206
- kweaver bkn action-execution get
207
- kweaver bkn action-log list/get/cancel
208
- kweaver agent list/get/chat/sessions/history
209
- kweaver skill list/market/get/market-get/register/status/delete/update-metadata/update-package/history/republish/publish-history/content/read-file/download/install/management-content/management-read-file/management-download
210
- kweaver vega health|stats|inspect|sql|catalog|resource|connector-type
211
- kweaver context-loader help <subcommand>
212
- kweaver context-loader tools|resources|templates|prompts <kn-id>
213
- kweaver context-loader search-schema <kn-id> <query> [--scope object,relation,action,metric] [--concept-groups ids]
214
- kweaver context-loader tool-call <kn-id> <name> --args '<json>'
215
- kweaver context-loader kn-search|kn-schema-search <kn-id> <query> [...] (deprecated;请使用 search-schema)
216
- kweaver context-loader query-object-instance|query-instance-subgraph|get-logic-properties|get-action-info|find-skills <kn-id> ...
217
- kweaver context-loader config set/use/list/show (deprecated;省略 <kn-id> 时回退到已保存配置)
218
- kweaver call <path> [-X METHOD] [-d BODY] [-H header]
189
+
190
+ 顶层命令分组:
191
+
192
+ ```text
193
+ AUTHENTICATION & CONFIG auth · token · config
194
+ DECISION AGENT agent · toolbox · tool
195
+ AI DATA PLATFORM bkn · ds · resource · dataflow · vega · context-loader
196
+ TRACE AI trace
197
+ FOUNDATION call · explore · model · skill · help
219
198
  ```
220
199
 
200
+ 需要查阅每个动作的完整签名(可浏览 / 可 grep)时,运行 `kweaver help all`。
201
+
221
202
  ### Dataflow CLI 示例
222
203
 
223
204
  ```bash
@@ -43,13 +43,21 @@ export interface AgentInfo {
43
43
  }
44
44
  export declare function buildChatUrl(baseUrl: string, agentKey: string): string;
45
45
  export declare function buildAgentInfoUrl(baseUrl: string, agentId: string, version: string): string;
46
- export declare function fetchAgentInfo(options: {
46
+ /** Options for fetching agent data from the agent-factory API. */
47
+ export interface AgentFetchOptions {
47
48
  baseUrl: string;
48
49
  accessToken: string;
49
50
  agentId: string;
50
51
  version: string;
51
52
  businessDomain?: string;
52
- }): Promise<AgentInfo>;
53
+ }
54
+ /**
55
+ * Fetch the full agent configuration body (system_prompt, llms, skills, …) from
56
+ * the agent-factory API. Returns the raw parsed JSON object unchanged — callers
57
+ * narrow it as needed (see fetchAgentInfo).
58
+ */
59
+ export declare function fetchAgentConfig(options: AgentFetchOptions): Promise<Record<string, unknown>>;
60
+ export declare function fetchAgentInfo(options: AgentFetchOptions): Promise<AgentInfo>;
53
61
  export declare function extractText(data: unknown): string;
54
62
  export declare function processIncrementalUpdate(data: {
55
63
  key?: string[];
@@ -17,7 +17,12 @@ function applyConversationOptions(body, conversationId) {
17
17
  body.conversation_id = conversationId;
18
18
  body.chat_option = { is_need_history: true };
19
19
  }
20
- export async function fetchAgentInfo(options) {
20
+ /**
21
+ * Fetch the full agent configuration body (system_prompt, llms, skills, …) from
22
+ * the agent-factory API. Returns the raw parsed JSON object unchanged — callers
23
+ * narrow it as needed (see fetchAgentInfo).
24
+ */
25
+ export async function fetchAgentConfig(options) {
21
26
  const { baseUrl, accessToken, agentId, version, businessDomain = "bd_public" } = options;
22
27
  const url = buildAgentInfoUrl(baseUrl, agentId, version);
23
28
  const agentHeaders = {
@@ -35,13 +40,22 @@ export async function fetchAgentInfo(options) {
35
40
  headers: agentHeaders,
36
41
  });
37
42
  const data = JSON.parse(body);
38
- if (!data.id || !data.key) {
43
+ if (data === null || typeof data !== "object") {
44
+ throw new Error("Agent config response was not a JSON object.");
45
+ }
46
+ return data;
47
+ }
48
+ export async function fetchAgentInfo(options) {
49
+ const data = await fetchAgentConfig(options);
50
+ const id = data["id"];
51
+ const key = data["key"];
52
+ if (typeof id !== "string" || !id || typeof key !== "string" || !key) {
39
53
  throw new Error("Agent info response did not include id and key.");
40
54
  }
41
55
  return {
42
- id: data.id,
43
- key: data.key,
44
- version: typeof data.version === "string" ? data.version : version,
56
+ id,
57
+ key,
58
+ version: typeof data["version"] === "string" ? data["version"] : options.version,
45
59
  };
46
60
  }
47
61
  function getByPath(obj, path) {
@@ -1,3 +1,17 @@
1
+ /**
2
+ * @deprecated The legacy `/datasources` API surface. The platform has migrated
3
+ * data-connection management to vega catalogs; prefer the equivalents from
4
+ * `../api/vega.js`:
5
+ *
6
+ * testDatasource → testVegaCatalogConnection
7
+ * createDatasource → createVegaCatalog
8
+ * listDatasources → listVegaCatalogs
9
+ * getDatasource → getVegaCatalog
10
+ * deleteDatasource → deleteVegaCatalogs
11
+ *
12
+ * Kept as thin back-compat shims for users on older backends; may be removed
13
+ * in a future major release.
14
+ */
1
15
  export interface TestDatasourceOptions {
2
16
  baseUrl: string;
3
17
  accessToken: string;
@@ -1,3 +1,17 @@
1
+ /**
2
+ * @deprecated The legacy `/datasources` API surface. The platform has migrated
3
+ * data-connection management to vega catalogs; prefer the equivalents from
4
+ * `../api/vega.js`:
5
+ *
6
+ * testDatasource → testVegaCatalogConnection
7
+ * createDatasource → createVegaCatalog
8
+ * listDatasources → listVegaCatalogs
9
+ * getDatasource → getVegaCatalog
10
+ * deleteDatasource → deleteVegaCatalogs
11
+ *
12
+ * Kept as thin back-compat shims for users on older backends; may be removed
13
+ * in a future major release.
14
+ */
1
15
  import { HttpError } from "../utils/http.js";
2
16
  import { encryptPassword } from "../utils/crypto.js";
3
17
  import { buildHeaders } from "./headers.js";
@@ -0,0 +1,94 @@
1
+ export declare const RESOURCE_LIST_DEFAULT_LIMIT = 30;
2
+ /** Field metadata for a resource schema. */
3
+ export interface ViewField {
4
+ name: string;
5
+ type: string;
6
+ display_name?: string;
7
+ comment?: string;
8
+ }
9
+ /** Normalized vega-backend Resource model. */
10
+ export interface Resource {
11
+ id: string;
12
+ name: string;
13
+ catalog_id: string;
14
+ category: string;
15
+ source_identifier?: string;
16
+ status?: string;
17
+ schema_definition?: ViewField[];
18
+ logic_definition?: unknown;
19
+ }
20
+ export declare function parseResource(raw: Record<string, unknown>): Resource;
21
+ export interface CreateResourceOptions {
22
+ baseUrl: string;
23
+ accessToken: string;
24
+ name: string;
25
+ datasourceId: string;
26
+ table: string;
27
+ fields?: Array<{
28
+ name: string;
29
+ type: string;
30
+ }>;
31
+ businessDomain?: string;
32
+ }
33
+ export declare function createResource(options: CreateResourceOptions): Promise<string>;
34
+ export interface ListResourcesOptions {
35
+ baseUrl: string;
36
+ accessToken: string;
37
+ businessDomain?: string;
38
+ /** Filter by catalog (data source) id. */
39
+ datasourceId?: string;
40
+ /** Server-side name filter. */
41
+ name?: string;
42
+ /** Category filter (e.g. "table", "logicview"). */
43
+ category?: string;
44
+ /** Max items; ignored when <= 0. */
45
+ limit?: number;
46
+ }
47
+ export declare function listResources(options: ListResourcesOptions): Promise<Resource[]>;
48
+ export interface DeleteResourceOptions {
49
+ baseUrl: string;
50
+ accessToken: string;
51
+ id: string;
52
+ businessDomain?: string;
53
+ }
54
+ export declare function deleteResource(options: DeleteResourceOptions): Promise<void>;
55
+ export interface GetResourceOptions {
56
+ baseUrl: string;
57
+ accessToken: string;
58
+ id: string;
59
+ businessDomain?: string;
60
+ }
61
+ export declare function getResource(options: GetResourceOptions): Promise<Resource>;
62
+ export interface FindResourceOptions {
63
+ baseUrl: string;
64
+ accessToken: string;
65
+ businessDomain?: string;
66
+ /** Resource name to search for. */
67
+ name: string;
68
+ /** Filter by catalog (data source) id. */
69
+ datasourceId?: string;
70
+ /** When true, apply client-side exact name match after server filter (default false). */
71
+ exact?: boolean;
72
+ /** When true, poll until a result appears or timeout (default false). */
73
+ wait?: boolean;
74
+ /** Total wait budget in ms (default 30000). Only used when wait is true. */
75
+ timeoutMs?: number;
76
+ }
77
+ export declare function findResource(options: FindResourceOptions): Promise<Resource[]>;
78
+ export interface QueryResourceOptions {
79
+ baseUrl: string;
80
+ accessToken: string;
81
+ id: string;
82
+ offset?: number;
83
+ limit?: number;
84
+ needTotal?: boolean;
85
+ filterCondition?: unknown;
86
+ sort?: string;
87
+ direction?: "asc" | "desc";
88
+ businessDomain?: string;
89
+ }
90
+ export interface ResourceQueryResult {
91
+ entries?: unknown;
92
+ total_count?: number;
93
+ }
94
+ export declare function queryResource(options: QueryResourceOptions): Promise<ResourceQueryResult>;
@@ -0,0 +1,166 @@
1
+ import { HttpError } from "../utils/http.js";
2
+ import { buildHeaders } from "./headers.js";
3
+ export const RESOURCE_LIST_DEFAULT_LIMIT = 30;
4
+ export function parseResource(raw) {
5
+ const res = {
6
+ id: String(raw.id ?? ""),
7
+ name: String(raw.name ?? ""),
8
+ catalog_id: String(raw.catalog_id ?? ""),
9
+ category: String(raw.category ?? ""),
10
+ };
11
+ if (raw.source_identifier != null)
12
+ res.source_identifier = String(raw.source_identifier);
13
+ if (raw.status != null)
14
+ res.status = String(raw.status);
15
+ if (Array.isArray(raw.schema_definition) && raw.schema_definition.length > 0) {
16
+ res.schema_definition = raw.schema_definition.map((f) => ({
17
+ name: String(f.name ?? ""),
18
+ type: String(f.type ?? "varchar"),
19
+ display_name: f.display_name != null ? String(f.display_name) : undefined,
20
+ comment: f.comment != null ? String(f.comment) : undefined,
21
+ }));
22
+ }
23
+ if (raw.logic_definition !== undefined)
24
+ res.logic_definition = raw.logic_definition;
25
+ return res;
26
+ }
27
+ function extractListPayload(data) {
28
+ if (Array.isArray(data))
29
+ return data;
30
+ if (data && typeof data === "object") {
31
+ const obj = data;
32
+ const items = obj.entries ?? obj.data;
33
+ if (Array.isArray(items))
34
+ return items;
35
+ }
36
+ return [];
37
+ }
38
+ export async function createResource(options) {
39
+ const { baseUrl, accessToken, name, datasourceId, table, fields = [], businessDomain = "bd_public", } = options;
40
+ const base = baseUrl.replace(/\/+$/, "");
41
+ const url = `${base}/api/vega-backend/v1/resources`;
42
+ const body = {
43
+ name,
44
+ catalog_id: datasourceId,
45
+ category: "table",
46
+ source_identifier: table,
47
+ };
48
+ if (fields.length > 0)
49
+ body.schema_definition = fields;
50
+ const response = await fetch(url, {
51
+ method: "POST",
52
+ headers: {
53
+ ...buildHeaders(accessToken, businessDomain),
54
+ "content-type": "application/json",
55
+ },
56
+ body: JSON.stringify(body),
57
+ });
58
+ const responseBody = await response.text();
59
+ if (!response.ok) {
60
+ throw new HttpError(response.status, response.statusText, responseBody);
61
+ }
62
+ const data = JSON.parse(responseBody);
63
+ return String(data.id ?? "");
64
+ }
65
+ export async function listResources(options) {
66
+ const { baseUrl, accessToken, businessDomain = "bd_public", datasourceId, name, category, limit = RESOURCE_LIST_DEFAULT_LIMIT, } = options;
67
+ const base = baseUrl.replace(/\/+$/, "");
68
+ const url = new URL(`${base}/api/vega-backend/v1/resources`);
69
+ if (datasourceId)
70
+ url.searchParams.set("catalog_id", datasourceId);
71
+ if (name)
72
+ url.searchParams.set("name", name);
73
+ if (category)
74
+ url.searchParams.set("category", category);
75
+ if (limit && limit > 0)
76
+ url.searchParams.set("limit", String(limit));
77
+ const response = await fetch(url.toString(), {
78
+ method: "GET",
79
+ headers: buildHeaders(accessToken, businessDomain),
80
+ });
81
+ const bodyText = await response.text();
82
+ if (!response.ok)
83
+ throw new HttpError(response.status, response.statusText, bodyText);
84
+ const parsed = JSON.parse(bodyText);
85
+ const items = extractListPayload(parsed);
86
+ return items
87
+ .filter((item) => item != null && typeof item === "object")
88
+ .map(parseResource);
89
+ }
90
+ export async function deleteResource(options) {
91
+ const { baseUrl, accessToken, id, businessDomain = "bd_public" } = options;
92
+ const base = baseUrl.replace(/\/+$/, "");
93
+ const url = `${base}/api/vega-backend/v1/resources/${encodeURIComponent(id)}`;
94
+ const response = await fetch(url, {
95
+ method: "DELETE",
96
+ headers: buildHeaders(accessToken, businessDomain),
97
+ });
98
+ const bodyText = await response.text();
99
+ if (!response.ok)
100
+ throw new HttpError(response.status, response.statusText, bodyText);
101
+ }
102
+ export async function getResource(options) {
103
+ const { baseUrl, accessToken, id, businessDomain = "bd_public" } = options;
104
+ const base = baseUrl.replace(/\/+$/, "");
105
+ const url = `${base}/api/vega-backend/v1/resources/${encodeURIComponent(id)}`;
106
+ const response = await fetch(url, {
107
+ method: "GET",
108
+ headers: buildHeaders(accessToken, businessDomain),
109
+ });
110
+ const body = await response.text();
111
+ if (!response.ok)
112
+ throw new HttpError(response.status, response.statusText, body);
113
+ const parsed = JSON.parse(body);
114
+ // vega-backend GET /:id returns { entries: [...] } (supports comma-separated ids)
115
+ const items = extractListPayload(parsed);
116
+ const raw = items.length > 0 ? items[0] : (parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null);
117
+ if (!raw || typeof raw !== "object")
118
+ throw new HttpError(500, "Invalid response", body);
119
+ return parseResource(raw);
120
+ }
121
+ function sleepMs(ms) {
122
+ return new Promise((resolve) => setTimeout(resolve, ms));
123
+ }
124
+ export async function findResource(options) {
125
+ const { baseUrl, accessToken, businessDomain = "bd_public", name, datasourceId, exact = false, wait = false, timeoutMs = 30_000, } = options;
126
+ const deadline = Date.now() + timeoutMs;
127
+ let attempt = 0;
128
+ while (true) {
129
+ const list = await listResources({ baseUrl, accessToken, businessDomain, datasourceId, name });
130
+ const results = exact ? list.filter((v) => v.name === name) : list;
131
+ if (results.length > 0 || !wait || Date.now() >= deadline)
132
+ return results;
133
+ const delayMs = Math.min(5000, 1000 * 2 ** attempt);
134
+ attempt += 1;
135
+ await sleepMs(delayMs);
136
+ }
137
+ }
138
+ export async function queryResource(options) {
139
+ const { baseUrl, accessToken, id, offset = 0, limit = 50, needTotal = false, filterCondition, sort, direction, businessDomain = "bd_public", } = options;
140
+ const base = baseUrl.replace(/\/+$/, "");
141
+ const url = `${base}/api/vega-backend/v1/resources/${encodeURIComponent(id)}/data`;
142
+ const body = { offset, limit, need_total: needTotal };
143
+ if (filterCondition !== undefined)
144
+ body.filter_condition = filterCondition;
145
+ if (sort !== undefined)
146
+ body.sort = sort;
147
+ if (direction !== undefined)
148
+ body.direction = direction;
149
+ const response = await fetch(url, {
150
+ method: "POST",
151
+ headers: {
152
+ ...buildHeaders(accessToken, businessDomain),
153
+ "content-type": "application/json",
154
+ "x-http-method-override": "GET",
155
+ },
156
+ body: JSON.stringify(body),
157
+ });
158
+ const bodyText = await response.text();
159
+ if (!response.ok)
160
+ throw new HttpError(response.status, response.statusText, bodyText);
161
+ const parsed = JSON.parse(bodyText);
162
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
163
+ return parsed;
164
+ }
165
+ return {};
166
+ }