@arcticdata/dsh-datarc-skills 0.0.0-stage → 26.39.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.
- package/README.md +20 -2
- package/cordis.patch.yml +4 -0
- package/icon.svg +4 -0
- package/index.js +35 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +37 -4
- package/skills/datarc-access-permissions/SKILL.md +30 -0
- package/skills/datarc-access-permissions/references/api.md +31 -0
- package/skills/datarc-access-permissions/references/write-order.md +16 -0
- package/skills/datarc-analysis-report/SKILL.md +125 -0
- package/skills/datarc-analysis-report/agents/openai.yaml +6 -0
- package/skills/datarc-analysis-report/references/analyst-frameworks.md +215 -0
- package/skills/datarc-analysis-report/references/api-contracts.md +478 -0
- package/skills/datarc-analysis-report/references/direct-card-fallback-design.md +66 -0
- package/skills/datarc-analysis-report/references/human-in-the-loop.md +142 -0
- package/skills/datarc-analysis-report/references/loop-personalization-policy.md +138 -0
- package/skills/datarc-analysis-report/references/manifest-example.json +779 -0
- package/skills/datarc-analysis-report/references/narrative-schema.md +160 -0
- package/skills/datarc-analysis-report/references/question-syntax.md +151 -0
- package/skills/datarc-analysis-report/scripts/run_analysis_report.py +2225 -0
- package/skills/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -0
- package/skills/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -0
- package/skills/datarc-data-search/SKILL.md +243 -0
- package/skills/datarc-data-search/scripts/calculate.py +116 -0
- package/skills/datarc-data-search/scripts/data-search.mjs +628 -0
- package/skills/datarc-data-search/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-data-search/scripts/search-result.mjs +211 -0
- package/skills/datarc-dataseek-batch-evaluation/SKILL.md +59 -0
- package/skills/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -0
- package/skills/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -0
- package/skills/datarc-dataseek-batch-evaluation/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -0
- package/skills/datarc-dataseek-search/SKILL.md +96 -0
- package/skills/datarc-dataseek-search/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -0
- package/skills/datarc-dataseek-semantic-debugging/SKILL.md +44 -0
- package/skills/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -0
- package/skills/datarc-dataseek-semantic-debugging/evals/evals.json +165 -0
- package/skills/datarc-dataseek-semantic-debugging/references/dataset.md +77 -0
- package/skills/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -0
- package/skills/datarc-dataseek-semantic-debugging/references/interventions.md +64 -0
- package/skills/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -0
- package/skills/datarc-dataseek-semantic-debugging/references/rollback.md +11 -0
- package/skills/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -0
- package/skills/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -0
- package/skills/datarc-dataseek-testset-generation/SKILL.md +47 -0
- package/skills/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -0
- package/skills/datarc-datasource/SKILL.md +97 -0
- package/skills/datarc-oauth/SKILL.md +47 -0
- package/skills/datarc-oauth/scripts/auth.mjs +130 -0
- package/skills/datarc-oauth/scripts/credentials.mjs +237 -0
- package/skills/datarc-report-add-card/SKILL.md +90 -0
- package/skills/datarc-report-add-card/agents/openai.yaml +4 -0
- package/skills/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-report-add-card/scripts/report-card.mjs +439 -0
- package/skills/datarc-semantic-alias/SKILL.md +20 -0
- package/skills/datarc-semantic-alias/scripts/alias-plan.mjs +422 -0
- package/skills/datarc-semantic-alias/scripts/alias.mjs +11 -0
- package/skills/datarc-semantic-calibration/SKILL.md +20 -0
- package/skills/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -0
- package/skills/datarc-semantic-calibration/scripts/calibration.mjs +11 -0
- package/skills/datarc-semantic-core/SKILL.md +12 -0
- package/skills/datarc-semantic-core/scripts/artifact-journal.mjs +830 -0
- package/skills/datarc-semantic-core/scripts/canonical.mjs +48 -0
- package/skills/datarc-semantic-core/scripts/case-model.mjs +608 -0
- package/skills/datarc-semantic-core/scripts/cli.mjs +180 -0
- package/skills/datarc-semantic-core/scripts/datarc-client.mjs +180 -0
- package/skills/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -0
- package/skills/datarc-semantic-core/scripts/interventions.mjs +693 -0
- package/skills/datarc-semantic-core/scripts/live-resolution.mjs +305 -0
- package/skills/datarc-semantic-core/scripts/model-scope.mjs +49 -0
- package/skills/datarc-semantic-core/scripts/reproduction.mjs +330 -0
- package/skills/datarc-semantic-core/scripts/semantic-cli.mjs +740 -0
- package/skills/datarc-semantic-core/scripts/shared.mjs +312 -0
- package/skills/datarc-semantic-core/scripts/verification.mjs +1014 -0
- package/skills/datarc-semantic-dataset/SKILL.md +20 -0
- package/skills/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -0
- package/skills/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -0
- package/skills/datarc-semantic-dataset/scripts/dataset.mjs +11 -0
- package/skills/datarc-semantic-knowledge/SKILL.md +38 -0
- package/skills/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -0
- package/skills/datarc-semantic-knowledge/references/knowledge-generation.json +16 -0
- package/skills/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -0
- package/skills/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -0
- package/skills/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -0
- package/skills/datarc-semantic-prompt/SKILL.md +20 -0
- package/skills/datarc-semantic-prompt/scripts/prompt-plan.mjs +447 -0
- package/skills/datarc-semantic-prompt/scripts/prompt.mjs +15 -0
- package/skills/datarc-semantic-synonym/SKILL.md +20 -0
- package/skills/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -0
- package/skills/datarc-semantic-synonym/scripts/synonym.mjs +11 -0
- package/skills/datarc-viz-analysis-report/SKILL.md +108 -0
- package/skills/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -0
- package/skills/datarc-viz-analysis-report/assets/echarts.min.js +45 -0
- package/skills/datarc-viz-analysis-report/references/api-contracts.md +163 -0
- package/skills/datarc-viz-analysis-report/references/derivation-log.md +157 -0
- package/skills/datarc-viz-analysis-report/references/evidence-framework.md +76 -0
- package/skills/datarc-viz-analysis-report/references/html-template.md +92 -0
- package/skills/datarc-viz-analysis-report/references/provenance-format.md +56 -0
- package/skills/datarc-viz-analysis-report/references/question-syntax.md +151 -0
- package/skills/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -0
- package/skills/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -0
- package/skills/datarc-workspace-configuration/SKILL.md +59 -0
- package/skills/datarc-workspace-configuration/references/artifacts.md +75 -0
- package/skills/datarc-workspace-configuration/references/verification.md +20 -0
- package/skills/datarc-workspace-configuration/scripts/configuration.mjs +662 -0
- package/skills/datarc-workspace-context/SKILL.md +43 -0
- package/skills/datarc-workspace-context/agents/openai.yaml +4 -0
- package/skills/datarc-workspace-context/scripts/datarc-client.mjs +31 -0
- package/skills/datarc-workspace-context/scripts/query-display.mjs +114 -0
- package/skills/datarc-workspace-context/scripts/workspace-context.mjs +58 -0
- package/skills/datarc-workspace-custom-tables/SKILL.md +89 -0
- package/skills/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -0
- package/skills/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -0
- package/skills/datarc-workspace-keywords/SKILL.md +197 -0
- package/skills/datarc-workspace-keywords/agents/openai.yaml +4 -0
- package/skills/datarc-workspace-keywords/references/api-fields.md +79 -0
- package/skills/datarc-workspace-keywords/references/derived-measures.md +177 -0
- package/skills/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -0
- package/skills/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -0
- package/skills/datarc-workspace-membership/SKILL.md +29 -0
- package/skills/datarc-workspace-membership/references/api.md +19 -0
- package/skills/datarc-workspace-modeling/SKILL.md +209 -0
- package/skills/datarc-workspace-modeling/agents/openai.yaml +4 -0
- package/skills/datarc-workspace-modeling/references/join-preview.md +38 -0
- package/skills/datarc-workspace-modeling/references/model-plan.md +300 -0
- package/skills/datarc-workspace-modeling/references/model-tags.md +95 -0
- package/skills/datarc-workspace-modeling/references/modeling-contract.json +29 -0
- package/skills/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -0
- package/skills/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -0
- package/skills/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -0
- package/skills/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -0
- package/skills-index.json +194 -0
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
import { resolveCredentials } from "../../datarc-oauth/scripts/credentials.mjs";
|
|
2
|
+
import { createWriteStream } from "node:fs";
|
|
3
|
+
import { mkdir, readFile, rename, rm, stat } from "node:fs/promises";
|
|
4
|
+
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
|
5
|
+
import { Readable } from "node:stream";
|
|
6
|
+
import { pipeline } from "node:stream/promises";
|
|
7
|
+
|
|
8
|
+
export class DatarcError extends Error {
|
|
9
|
+
constructor(message, code = "DATARC_ERROR", details) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = "DatarcError";
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.details = details;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function parseArgs(argv) {
|
|
18
|
+
const result = { _: [] };
|
|
19
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
20
|
+
if (!argv[i].startsWith("--")) {
|
|
21
|
+
result._.push(argv[i]);
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
const key = argv[i].slice(2);
|
|
25
|
+
const next = argv[i + 1];
|
|
26
|
+
if (next === undefined || next.startsWith("--")) result[key] = true;
|
|
27
|
+
else {
|
|
28
|
+
result[key] =
|
|
29
|
+
result[key] === undefined ? next : [].concat(result[key], next);
|
|
30
|
+
i += 1;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function required(args, key) {
|
|
37
|
+
if (args[key] === undefined || args[key] === true || args[key] === "")
|
|
38
|
+
throw new DatarcError(`缺少参数 --${key}`, "INVALID_ARGUMENT");
|
|
39
|
+
return args[key];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function readJson(path) {
|
|
43
|
+
const text = path === "-" ? await stdin() : await readFile(path, "utf8");
|
|
44
|
+
try {
|
|
45
|
+
return JSON.parse(text);
|
|
46
|
+
} catch {
|
|
47
|
+
throw new DatarcError("输入不是有效 JSON", "INVALID_JSON");
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function createClient(options = {}) {
|
|
52
|
+
const { endpoint, token } = resolveCredentials(options);
|
|
53
|
+
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
54
|
+
const sleep =
|
|
55
|
+
options.sleep ??
|
|
56
|
+
((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
57
|
+
if (!endpoint)
|
|
58
|
+
throw new DatarcError("未配置 DATARC_ENDPOINT", "MISSING_ENDPOINT");
|
|
59
|
+
if (!token) throw new DatarcError("未配置 DATARC_TOKEN", "MISSING_TOKEN");
|
|
60
|
+
|
|
61
|
+
async function request(method, path, { query, body } = {}) {
|
|
62
|
+
const url = new URL(`${endpoint}${path}`);
|
|
63
|
+
for (const [key, value] of Object.entries(query ?? {}))
|
|
64
|
+
for (const item of [].concat(value ?? []))
|
|
65
|
+
if (item !== "") url.searchParams.append(key, item);
|
|
66
|
+
let response;
|
|
67
|
+
try {
|
|
68
|
+
response = await fetchImpl(url, {
|
|
69
|
+
method,
|
|
70
|
+
headers: {
|
|
71
|
+
Authorization: token,
|
|
72
|
+
...(body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
73
|
+
},
|
|
74
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
75
|
+
});
|
|
76
|
+
} catch (error) {
|
|
77
|
+
throw new DatarcError(`网络请求失败:${error.message}`, "NETWORK_ERROR");
|
|
78
|
+
}
|
|
79
|
+
const text = await response.text();
|
|
80
|
+
let payload;
|
|
81
|
+
try {
|
|
82
|
+
payload = text ? JSON.parse(text) : {};
|
|
83
|
+
} catch {
|
|
84
|
+
throw new DatarcError(
|
|
85
|
+
`服务返回非 JSON(HTTP ${response.status})`,
|
|
86
|
+
"INVALID_RESPONSE",
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
if (!response.ok || (payload.status && payload.status !== "SUCCESS"))
|
|
90
|
+
throw new DatarcError(
|
|
91
|
+
payload.message || `请求失败(HTTP ${response.status})`,
|
|
92
|
+
apiErrorCode(response.status, payload),
|
|
93
|
+
{
|
|
94
|
+
httpStatus: response.status,
|
|
95
|
+
status: payload.status,
|
|
96
|
+
errorCode: payload.code ?? payload.errcode,
|
|
97
|
+
},
|
|
98
|
+
);
|
|
99
|
+
return payload.data;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function poll(workspaceId, uid, taskType, options = {}) {
|
|
103
|
+
const started = Date.now();
|
|
104
|
+
const maxWaitMs = Number(options.maxWaitMs ?? 600000);
|
|
105
|
+
const intervalMs = Number(options.intervalMs ?? 2000);
|
|
106
|
+
const pending = taskType === 4 ? [0, 1, 4, 5] : [0, 1];
|
|
107
|
+
while (Date.now() - started <= maxWaitMs) {
|
|
108
|
+
const task = await request(
|
|
109
|
+
"GET",
|
|
110
|
+
`/api/v2/account-projects/${workspaceId}/async-tasks/${uid}/`,
|
|
111
|
+
);
|
|
112
|
+
if (Number(task.status) === 2) {
|
|
113
|
+
const result = task.result;
|
|
114
|
+
if (
|
|
115
|
+
[8, 11].includes(Number(taskType)) &&
|
|
116
|
+
(!result ||
|
|
117
|
+
typeof result !== "object" ||
|
|
118
|
+
result.status !== "SUCCESS" ||
|
|
119
|
+
!Object.hasOwn(result, "data"))
|
|
120
|
+
)
|
|
121
|
+
throw new DatarcError(
|
|
122
|
+
"异步任务成功状态缺少有效结果",
|
|
123
|
+
"INVALID_TASK_RESULT",
|
|
124
|
+
{ status: task.status, result: safeTaskResult(result) },
|
|
125
|
+
);
|
|
126
|
+
return result;
|
|
127
|
+
}
|
|
128
|
+
if (!pending.includes(Number(task.status)))
|
|
129
|
+
throw new DatarcError("异步任务失败、取消或过期", "TASK_FAILED", {
|
|
130
|
+
status: task.status,
|
|
131
|
+
result: safeTaskResult(task.result),
|
|
132
|
+
});
|
|
133
|
+
await sleep(intervalMs);
|
|
134
|
+
}
|
|
135
|
+
throw new DatarcError("异步任务轮询超时", "TASK_TIMEOUT");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function download(url, destination) {
|
|
139
|
+
const targetUrl = new URL(url);
|
|
140
|
+
const headers =
|
|
141
|
+
targetUrl.origin === new URL(endpoint).origin
|
|
142
|
+
? { Authorization: token }
|
|
143
|
+
: {};
|
|
144
|
+
let response;
|
|
145
|
+
try {
|
|
146
|
+
response = await fetchImpl(targetUrl, { headers, redirect: "follow" });
|
|
147
|
+
} catch (error) {
|
|
148
|
+
throw new DatarcError(`下载失败:${error.message}`, "NETWORK_ERROR");
|
|
149
|
+
}
|
|
150
|
+
if (!response.ok || !response.body)
|
|
151
|
+
throw new DatarcError(
|
|
152
|
+
`下载失败(HTTP ${response.status})`,
|
|
153
|
+
apiErrorCode(response.status, {}),
|
|
154
|
+
);
|
|
155
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
156
|
+
const temporary = `${destination}.part`;
|
|
157
|
+
let overwritten = false;
|
|
158
|
+
try {
|
|
159
|
+
await stat(destination);
|
|
160
|
+
overwritten = true;
|
|
161
|
+
} catch (error) {
|
|
162
|
+
if (error.code !== "ENOENT") throw error;
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
await pipeline(
|
|
166
|
+
Readable.fromWeb(response.body),
|
|
167
|
+
createWriteStream(temporary),
|
|
168
|
+
);
|
|
169
|
+
await rm(destination, { force: true });
|
|
170
|
+
await rename(temporary, destination);
|
|
171
|
+
return { size: (await stat(destination)).size, overwritten };
|
|
172
|
+
} catch (error) {
|
|
173
|
+
await rm(temporary, { force: true });
|
|
174
|
+
throw new DatarcError(
|
|
175
|
+
`保存下载文件失败:${error.message}`,
|
|
176
|
+
"DOWNLOAD_FAILED",
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return { request, poll, sleep, download };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function primaryCards(cards = []) {
|
|
184
|
+
if (!Array.isArray(cards)) return [];
|
|
185
|
+
const direct = cards.find(
|
|
186
|
+
(card) => Number(card?.resultType ?? card?.result_type ?? 0) === 0,
|
|
187
|
+
);
|
|
188
|
+
return direct ? [direct] : [];
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function seriesOf(cards = []) {
|
|
192
|
+
return cards.flatMap((card, cardIndex) =>
|
|
193
|
+
(card.data ?? []).map((series, seriesIndex) => ({
|
|
194
|
+
cardIndex,
|
|
195
|
+
seriesIndex,
|
|
196
|
+
title: card.title ?? `卡片 ${cardIndex + 1}`,
|
|
197
|
+
cardType: card.card_type,
|
|
198
|
+
columns: series.columns ?? [],
|
|
199
|
+
query: series.data,
|
|
200
|
+
})),
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function collectCards(value) {
|
|
205
|
+
const cards = [];
|
|
206
|
+
const seen = new Set();
|
|
207
|
+
function visit(current) {
|
|
208
|
+
if (!current || typeof current !== "object" || seen.has(current)) return;
|
|
209
|
+
seen.add(current);
|
|
210
|
+
if (Array.isArray(current.cards))
|
|
211
|
+
cards.push(...primaryCards(current.cards));
|
|
212
|
+
for (const [key, child] of Object.entries(current)) {
|
|
213
|
+
if (key !== "cards") visit(child);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
visit(value);
|
|
217
|
+
if (!cards.length && Array.isArray(value)) return value;
|
|
218
|
+
return cards;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export async function preview(client, workspaceId, cards, options = {}) {
|
|
222
|
+
const output = [];
|
|
223
|
+
const seriesList = seriesOf(cards);
|
|
224
|
+
for (const series of seriesList) {
|
|
225
|
+
try {
|
|
226
|
+
if (!series.query?.qKey)
|
|
227
|
+
throw new DatarcError("卡片缺少 qKey", "MISSING_QKEY");
|
|
228
|
+
const queryWorkspaceId = series.query.project ?? workspaceId;
|
|
229
|
+
const task = await client.request(
|
|
230
|
+
"POST",
|
|
231
|
+
`/api/v2/account-projects/${queryWorkspaceId}/async-tasks/`,
|
|
232
|
+
{
|
|
233
|
+
body: {
|
|
234
|
+
taskType: 8,
|
|
235
|
+
params: {
|
|
236
|
+
qKey: series.query.qKey,
|
|
237
|
+
params: queryPageParams(series.query.params, options),
|
|
238
|
+
},
|
|
239
|
+
},
|
|
240
|
+
},
|
|
241
|
+
);
|
|
242
|
+
output.push({
|
|
243
|
+
...series,
|
|
244
|
+
data: unwrapTaskResult(
|
|
245
|
+
await client.poll(queryWorkspaceId, task.uid, 8, options),
|
|
246
|
+
),
|
|
247
|
+
});
|
|
248
|
+
} catch (error) {
|
|
249
|
+
rethrowGlobalError(error);
|
|
250
|
+
output.push({ ...series, error: errorJson(error) });
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return output;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export function unwrapTaskResult(value) {
|
|
257
|
+
if (
|
|
258
|
+
value &&
|
|
259
|
+
typeof value === "object" &&
|
|
260
|
+
value.status === "SUCCESS" &&
|
|
261
|
+
Object.hasOwn(value, "data")
|
|
262
|
+
)
|
|
263
|
+
return value.data;
|
|
264
|
+
return value;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export async function exportAll(client, workspaceId, cards, options = {}) {
|
|
268
|
+
const extension = String(options.extension ?? ".csv").replace(/^(?!\.)/, ".");
|
|
269
|
+
if (![".csv", ".xlsx"].includes(extension))
|
|
270
|
+
throw new DatarcError("导出格式仅支持 csv 或 xlsx", "INVALID_ARGUMENT");
|
|
271
|
+
const output = [];
|
|
272
|
+
const seriesList = seriesOf(cards);
|
|
273
|
+
for (const series of seriesList) {
|
|
274
|
+
if ([1, 12].includes(Number(series.cardType))) {
|
|
275
|
+
output.push({
|
|
276
|
+
...series,
|
|
277
|
+
extension,
|
|
278
|
+
status: "skipped",
|
|
279
|
+
reasonCode: "NUMBER_CARD_NOT_EXPORTABLE",
|
|
280
|
+
message: "数字卡不支持导出 CSV 或 Excel",
|
|
281
|
+
});
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
try {
|
|
285
|
+
if (!series.query?.qKey)
|
|
286
|
+
throw new DatarcError("卡片缺少 qKey", "MISSING_QKEY");
|
|
287
|
+
const title = fileTitle(
|
|
288
|
+
options.title ?? series.title,
|
|
289
|
+
seriesList.length > 1 ? series.seriesIndex + 1 : undefined,
|
|
290
|
+
);
|
|
291
|
+
const task = await client.request(
|
|
292
|
+
"POST",
|
|
293
|
+
`/api/v2/account-projects/${workspaceId}/async-tasks/`,
|
|
294
|
+
{
|
|
295
|
+
body: {
|
|
296
|
+
taskType: 4,
|
|
297
|
+
params: {
|
|
298
|
+
title,
|
|
299
|
+
extension,
|
|
300
|
+
data: [{ data: series.query, columns: series.columns }],
|
|
301
|
+
},
|
|
302
|
+
},
|
|
303
|
+
},
|
|
304
|
+
);
|
|
305
|
+
const exported = {
|
|
306
|
+
...series,
|
|
307
|
+
exportTitle: title,
|
|
308
|
+
extension,
|
|
309
|
+
data: await client.poll(workspaceId, task.uid, 4, options),
|
|
310
|
+
};
|
|
311
|
+
if (options.download) {
|
|
312
|
+
const url = exported.data?.url;
|
|
313
|
+
if (!url)
|
|
314
|
+
throw new DatarcError("导出结果缺少下载地址", "MISSING_DOWNLOAD_URL");
|
|
315
|
+
const directory = outputDirectory(options.outputDir, options.taskId);
|
|
316
|
+
const filePath = resolve(
|
|
317
|
+
directory.absolutePath,
|
|
318
|
+
`${title}${extension}`,
|
|
319
|
+
);
|
|
320
|
+
const saved = await client.download(url, filePath);
|
|
321
|
+
exported.file = {
|
|
322
|
+
relativePath: relative(process.cwd(), filePath),
|
|
323
|
+
absolutePath: filePath,
|
|
324
|
+
size: saved.size,
|
|
325
|
+
overwritten: Boolean(saved.overwritten),
|
|
326
|
+
};
|
|
327
|
+
exported.directory = directory;
|
|
328
|
+
}
|
|
329
|
+
output.push(exported);
|
|
330
|
+
} catch (error) {
|
|
331
|
+
rethrowGlobalError(error);
|
|
332
|
+
output.push({ ...series, extension, error: errorJson(error) });
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
return output;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export function outputDirectory(value = ".datarc-downloads", taskId) {
|
|
339
|
+
if (typeof value !== "string" || !value)
|
|
340
|
+
throw new DatarcError(
|
|
341
|
+
"--output-dir 必须是非空相对路径",
|
|
342
|
+
"INVALID_ARGUMENT",
|
|
343
|
+
);
|
|
344
|
+
if (isAbsolute(value))
|
|
345
|
+
throw new DatarcError(
|
|
346
|
+
"--output-dir 必须是当前工作目录下的相对路径",
|
|
347
|
+
"INVALID_ARGUMENT",
|
|
348
|
+
);
|
|
349
|
+
if (
|
|
350
|
+
typeof taskId !== "string" ||
|
|
351
|
+
!/^[A-Za-z0-9._-]{1,80}$/.test(taskId) ||
|
|
352
|
+
[".", ".."].includes(taskId)
|
|
353
|
+
)
|
|
354
|
+
throw new DatarcError(
|
|
355
|
+
"下载时必须提供仅含字母、数字、点、下划线或连字符的 --task-id",
|
|
356
|
+
"INVALID_ARGUMENT",
|
|
357
|
+
);
|
|
358
|
+
const cwd = resolve(process.cwd());
|
|
359
|
+
const absolutePath = resolve(cwd, value, taskId);
|
|
360
|
+
const fromCwd = relative(cwd, absolutePath);
|
|
361
|
+
if (fromCwd.startsWith("..") || isAbsolute(fromCwd))
|
|
362
|
+
throw new DatarcError(
|
|
363
|
+
"--output-dir 不得超出当前工作目录",
|
|
364
|
+
"INVALID_ARGUMENT",
|
|
365
|
+
);
|
|
366
|
+
return { taskId, relativePath: fromCwd || ".", absolutePath };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export function assertAccess(data) {
|
|
370
|
+
if (data?.canAccessData === false)
|
|
371
|
+
throw new DatarcError("当前用户没有数据访问权限", "DATA_ACCESS_DENIED");
|
|
372
|
+
if (data?.noPermissionTokens?.length)
|
|
373
|
+
throw new DatarcError("查询包含无权访问的字段", "FIELD_ACCESS_DENIED", {
|
|
374
|
+
tokens: data.noPermissionTokens.map(({ word, prop }) => ({ word, prop })),
|
|
375
|
+
});
|
|
376
|
+
return data;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
export function isGlobalError(error) {
|
|
380
|
+
return [
|
|
381
|
+
"MISSING_ENDPOINT",
|
|
382
|
+
"MISSING_TOKEN",
|
|
383
|
+
"NETWORK_ERROR",
|
|
384
|
+
"INVALID_RESPONSE",
|
|
385
|
+
"AUTHENTICATION_FAILED",
|
|
386
|
+
"PERMISSION_DENIED",
|
|
387
|
+
"RATE_LIMITED",
|
|
388
|
+
"DATA_ACCESS_DENIED",
|
|
389
|
+
"FIELD_ACCESS_DENIED",
|
|
390
|
+
].includes(error?.code);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
export function rethrowGlobalError(error) {
|
|
394
|
+
if (isGlobalError(error)) throw error;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
export function errorJson(error) {
|
|
398
|
+
return {
|
|
399
|
+
code: error?.code ?? "UNEXPECTED_ERROR",
|
|
400
|
+
message: error?.message ?? String(error),
|
|
401
|
+
...(error?.details === undefined ? {} : { details: error.details }),
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
export async function runCli(main) {
|
|
405
|
+
try {
|
|
406
|
+
process.stdout.write(
|
|
407
|
+
`${JSON.stringify({ ok: true, data: await main() }, null, 2)}\n`,
|
|
408
|
+
);
|
|
409
|
+
} catch (error) {
|
|
410
|
+
process.stdout.write(
|
|
411
|
+
`${JSON.stringify({ ok: false, error: errorJson(error) }, null, 2)}\n`,
|
|
412
|
+
);
|
|
413
|
+
process.exitCode = 1;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function apiErrorCode(httpStatus, payload) {
|
|
418
|
+
const businessCodes = [payload.status, payload.code, payload.errcode]
|
|
419
|
+
.filter((value) => value !== undefined && value !== null)
|
|
420
|
+
.map(String);
|
|
421
|
+
if (httpStatus === 401) return "AUTHENTICATION_FAILED";
|
|
422
|
+
if (httpStatus === 403) return "PERMISSION_DENIED";
|
|
423
|
+
if (httpStatus === 429 || businessCodes.includes("0110001"))
|
|
424
|
+
return "RATE_LIMITED";
|
|
425
|
+
return "API_ERROR";
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function queryPageParams(value, options) {
|
|
429
|
+
const params =
|
|
430
|
+
value && typeof value === "object" && !Array.isArray(value)
|
|
431
|
+
? { ...value }
|
|
432
|
+
: {};
|
|
433
|
+
if (options.offset !== undefined) params.offset = Number(options.offset);
|
|
434
|
+
else if (params.offset === undefined) params.offset = 0;
|
|
435
|
+
if (options.limit !== undefined) params.limit = Number(options.limit);
|
|
436
|
+
else if (params.limit === undefined) params.limit = 100;
|
|
437
|
+
return params;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function safeTaskResult(value) {
|
|
441
|
+
if (value === null || value === undefined) return value;
|
|
442
|
+
if (typeof value === "string") return { message: "异步任务执行失败" };
|
|
443
|
+
if (typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
444
|
+
return {
|
|
445
|
+
...(value.status === undefined ? {} : { status: value.status }),
|
|
446
|
+
...(value.message === undefined ? {} : { message: "异步任务执行失败" }),
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function fileTitle(value, seriesNumber) {
|
|
451
|
+
const safeTitle = basename(String(value ?? "data"))
|
|
452
|
+
.replace(/[\\/:*?"<>|]/g, "_")
|
|
453
|
+
.trim()
|
|
454
|
+
.replace(/[. ]+$/g, "")
|
|
455
|
+
.slice(0, 100);
|
|
456
|
+
const base = safeTitle || "data";
|
|
457
|
+
return seriesNumber === undefined ? base : `${base}-${seriesNumber}`;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
async function stdin() {
|
|
461
|
+
const chunks = [];
|
|
462
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
463
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
464
|
+
}
|