@arcticdata/dsh-datarc-assistant 26.39.0 → 26.39.1

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 (149) hide show
  1. package/README.md +45 -10
  2. package/api-operations.js +404 -0
  3. package/client.js +452 -87
  4. package/cordis.patch.yml +4 -4
  5. package/entry/SKILL.md +34 -0
  6. package/icon.png +0 -0
  7. package/index.js +35 -47
  8. package/locale/en.json +6 -6
  9. package/locale/zh.json +6 -6
  10. package/native-api.mjs +326 -0
  11. package/native-contracts.js +195 -0
  12. package/native-execution.js +184 -0
  13. package/native-runner.mjs +107 -0
  14. package/native-state.js +67 -0
  15. package/native-tools.js +241 -0
  16. package/operations.js +1260 -0
  17. package/package.json +65 -51
  18. package/{skills → runtime}/datarc-access-permissions/SKILL.md +30 -30
  19. package/{skills → runtime}/datarc-access-permissions/references/api.md +31 -31
  20. package/{skills → runtime}/datarc-access-permissions/references/write-order.md +16 -16
  21. package/{skills → runtime}/datarc-analysis-report/SKILL.md +125 -125
  22. package/{skills → runtime}/datarc-analysis-report/agents/openai.yaml +6 -6
  23. package/{skills → runtime}/datarc-analysis-report/references/analyst-frameworks.md +215 -215
  24. package/{skills → runtime}/datarc-analysis-report/references/api-contracts.md +478 -478
  25. package/{skills → runtime}/datarc-analysis-report/references/direct-card-fallback-design.md +66 -66
  26. package/{skills → runtime}/datarc-analysis-report/references/human-in-the-loop.md +142 -142
  27. package/{skills → runtime}/datarc-analysis-report/references/loop-personalization-policy.md +138 -138
  28. package/{skills → runtime}/datarc-analysis-report/references/manifest-example.json +779 -779
  29. package/{skills → runtime}/datarc-analysis-report/references/narrative-schema.md +160 -160
  30. package/{skills → runtime}/datarc-analysis-report/references/question-syntax.md +151 -151
  31. package/{skills → runtime}/datarc-analysis-report/scripts/run_analysis_report.py +2225 -2225
  32. package/{skills → runtime}/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -1914
  33. package/{skills → runtime}/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -5295
  34. package/{skills → runtime}/datarc-data-search/SKILL.md +243 -243
  35. package/{skills → runtime}/datarc-data-search/scripts/calculate.py +116 -116
  36. package/{skills → runtime}/datarc-data-search/scripts/data-search.mjs +628 -628
  37. package/{skills/datarc-dataseek-search → runtime/datarc-data-search}/scripts/datarc-client.mjs +464 -464
  38. package/{skills → runtime}/datarc-data-search/scripts/search-result.mjs +211 -211
  39. package/{skills → runtime}/datarc-dataseek-batch-evaluation/SKILL.md +59 -59
  40. package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -36
  41. package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -30
  42. package/{skills/datarc-data-search → runtime/datarc-dataseek-batch-evaluation}/scripts/datarc-client.mjs +464 -464
  43. package/{skills → runtime}/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -1020
  44. package/{skills → runtime}/datarc-dataseek-search/SKILL.md +96 -96
  45. package/{skills/datarc-dataseek-batch-evaluation → runtime/datarc-dataseek-search}/scripts/datarc-client.mjs +464 -464
  46. package/{skills → runtime}/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -257
  47. package/{skills → runtime}/datarc-dataseek-semantic-debugging/SKILL.md +44 -44
  48. package/{skills → runtime}/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -4
  49. package/{skills → runtime}/datarc-dataseek-semantic-debugging/evals/evals.json +165 -165
  50. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/dataset.md +77 -77
  51. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -93
  52. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/interventions.md +64 -64
  53. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -47
  54. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/rollback.md +11 -11
  55. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -95
  56. package/{skills → runtime}/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -29
  57. package/{skills → runtime}/datarc-dataseek-testset-generation/SKILL.md +47 -47
  58. package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -464
  59. package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -526
  60. package/{skills → runtime}/datarc-datasource/SKILL.md +97 -97
  61. package/{skills → runtime}/datarc-oauth/SKILL.md +50 -50
  62. package/{skills → runtime}/datarc-oauth/scripts/auth.mjs +192 -192
  63. package/{skills → runtime}/datarc-oauth/scripts/credentials.mjs +237 -237
  64. package/{skills → runtime}/datarc-report-add-card/SKILL.md +90 -90
  65. package/{skills → runtime}/datarc-report-add-card/agents/openai.yaml +4 -4
  66. package/runtime/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
  67. package/{skills → runtime}/datarc-report-add-card/scripts/report-card.mjs +439 -439
  68. package/{skills → runtime}/datarc-semantic-alias/SKILL.md +20 -20
  69. package/{skills → runtime}/datarc-semantic-alias/scripts/alias-plan.mjs +422 -422
  70. package/{skills → runtime}/datarc-semantic-alias/scripts/alias.mjs +11 -11
  71. package/{skills → runtime}/datarc-semantic-calibration/SKILL.md +20 -20
  72. package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -683
  73. package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration.mjs +11 -11
  74. package/{skills → runtime}/datarc-semantic-core/SKILL.md +12 -12
  75. package/{skills → runtime}/datarc-semantic-core/scripts/artifact-journal.mjs +853 -830
  76. package/{skills → runtime}/datarc-semantic-core/scripts/canonical.mjs +48 -48
  77. package/{skills → runtime}/datarc-semantic-core/scripts/case-model.mjs +608 -608
  78. package/{skills → runtime}/datarc-semantic-core/scripts/cli.mjs +180 -180
  79. package/{skills → runtime}/datarc-semantic-core/scripts/datarc-client.mjs +180 -180
  80. package/{skills → runtime}/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -57
  81. package/{skills → runtime}/datarc-semantic-core/scripts/interventions.mjs +693 -693
  82. package/{skills → runtime}/datarc-semantic-core/scripts/live-resolution.mjs +305 -305
  83. package/{skills → runtime}/datarc-semantic-core/scripts/model-scope.mjs +49 -49
  84. package/{skills → runtime}/datarc-semantic-core/scripts/reproduction.mjs +330 -330
  85. package/{skills → runtime}/datarc-semantic-core/scripts/semantic-cli.mjs +799 -740
  86. package/{skills → runtime}/datarc-semantic-core/scripts/shared.mjs +312 -312
  87. package/{skills → runtime}/datarc-semantic-core/scripts/verification.mjs +1111 -1014
  88. package/{skills → runtime}/datarc-semantic-dataset/SKILL.md +20 -20
  89. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -749
  90. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -813
  91. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset.mjs +11 -11
  92. package/{skills → runtime}/datarc-semantic-knowledge/SKILL.md +38 -38
  93. package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -61
  94. package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-generation.json +16 -16
  95. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -347
  96. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -848
  97. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -31
  98. package/{skills → runtime}/datarc-semantic-prompt/SKILL.md +20 -20
  99. package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt-plan.mjs +598 -447
  100. package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt.mjs +15 -15
  101. package/{skills → runtime}/datarc-semantic-synonym/SKILL.md +20 -20
  102. package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -688
  103. package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym.mjs +11 -11
  104. package/{skills → runtime}/datarc-viz-analysis-report/SKILL.md +108 -108
  105. package/{skills → runtime}/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -8
  106. package/{skills → runtime}/datarc-viz-analysis-report/assets/echarts.min.js +45 -45
  107. package/{skills → runtime}/datarc-viz-analysis-report/references/api-contracts.md +163 -163
  108. package/{skills → runtime}/datarc-viz-analysis-report/references/derivation-log.md +157 -157
  109. package/{skills → runtime}/datarc-viz-analysis-report/references/evidence-framework.md +76 -76
  110. package/{skills → runtime}/datarc-viz-analysis-report/references/html-template.md +92 -92
  111. package/{skills → runtime}/datarc-viz-analysis-report/references/provenance-format.md +56 -56
  112. package/{skills → runtime}/datarc-viz-analysis-report/references/question-syntax.md +151 -151
  113. package/{skills → runtime}/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -1708
  114. package/{skills → runtime}/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -964
  115. package/{skills → runtime}/datarc-workspace-configuration/SKILL.md +59 -59
  116. package/{skills → runtime}/datarc-workspace-configuration/references/artifacts.md +75 -75
  117. package/{skills → runtime}/datarc-workspace-configuration/references/verification.md +20 -20
  118. package/{skills → runtime}/datarc-workspace-configuration/scripts/configuration.mjs +722 -662
  119. package/{skills → runtime}/datarc-workspace-context/SKILL.md +43 -43
  120. package/{skills → runtime}/datarc-workspace-context/agents/openai.yaml +4 -4
  121. package/{skills → runtime}/datarc-workspace-context/scripts/datarc-client.mjs +31 -31
  122. package/{skills → runtime}/datarc-workspace-context/scripts/query-display.mjs +114 -114
  123. package/{skills → runtime}/datarc-workspace-context/scripts/workspace-context.mjs +58 -58
  124. package/{skills → runtime}/datarc-workspace-custom-tables/SKILL.md +89 -89
  125. package/{skills → runtime}/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -165
  126. package/{skills → runtime}/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -601
  127. package/{skills → runtime}/datarc-workspace-keywords/SKILL.md +197 -197
  128. package/{skills → runtime}/datarc-workspace-keywords/agents/openai.yaml +4 -4
  129. package/{skills → runtime}/datarc-workspace-keywords/references/api-fields.md +79 -79
  130. package/{skills → runtime}/datarc-workspace-keywords/references/derived-measures.md +177 -177
  131. package/{skills → runtime}/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -145
  132. package/{skills → runtime}/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -2421
  133. package/{skills → runtime}/datarc-workspace-membership/SKILL.md +29 -29
  134. package/{skills → runtime}/datarc-workspace-membership/references/api.md +19 -19
  135. package/{skills → runtime}/datarc-workspace-modeling/SKILL.md +209 -209
  136. package/{skills → runtime}/datarc-workspace-modeling/agents/openai.yaml +4 -4
  137. package/{skills → runtime}/datarc-workspace-modeling/references/join-preview.md +38 -38
  138. package/{skills → runtime}/datarc-workspace-modeling/references/model-plan.md +300 -300
  139. package/{skills → runtime}/datarc-workspace-modeling/references/model-tags.md +95 -95
  140. package/{skills → runtime}/datarc-workspace-modeling/references/modeling-contract.json +29 -29
  141. package/{skills → runtime}/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -2423
  142. package/{skills → runtime}/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -137
  143. package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -238
  144. package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -1261
  145. package/skills-provider.js +51 -0
  146. package/workflow-index.json +434 -0
  147. package/icon.svg +0 -4
  148. package/skills/datarc-report-add-card/scripts/datarc-client.mjs +0 -464
  149. package/skills-index.json +0 -194
@@ -1,439 +1,439 @@
1
- #!/usr/bin/env node
2
- import { resolveResultInput } from "../../datarc-data-search/scripts/search-result.mjs";
3
- import { resolveCredentials } from "../../datarc-oauth/scripts/credentials.mjs";
4
- import { isDeepStrictEqual } from "node:util";
5
- import { pathToFileURL } from "node:url";
6
- import {
7
- createClient,
8
- DatarcError,
9
- parseArgs,
10
- readJson,
11
- required,
12
- runCli,
13
- } from "./datarc-client.mjs";
14
-
15
- const PINBOARD_UID_PATTERN = /^[0-9a-fA-F]{32}$/;
16
- // 深度按对象跳数计:DataSeek 每层嵌套(actions/children/steps)约 3 跳,5 层嵌套约 15 跳。
17
- const MAX_WALK_DEPTH = 16;
18
-
19
- /** 列出全部直接结果卡片:公共客户端的 primaryCards 只取第一张,选卡要看到所有候选。 */
20
- export function directCards(cards = []) {
21
- if (!Array.isArray(cards)) return [];
22
- return cards.filter((card) => card && Number(card.resultType ?? card.result_type ?? 0) === 0);
23
- }
24
-
25
- export function mergeReports(recentItems = [], allItems = [], limit = 10) {
26
- const editable = new Set(
27
- (Array.isArray(allItems) ? allItems : [])
28
- .map((item) => item?.uid)
29
- .filter(Boolean),
30
- );
31
- const seen = new Set();
32
- const reports = [];
33
- const push = (item, recent) => {
34
- if (!item?.uid || seen.has(item.uid)) return;
35
- seen.add(item.uid);
36
- reports.push({ ...item, recent });
37
- };
38
- for (const item of Array.isArray(recentItems) ? recentItems : [])
39
- if (editable.has(item?.uid)) push(item, true);
40
- for (const item of Array.isArray(allItems) ? allItems : []) push(item, false);
41
- return limit > 0 ? reports.slice(0, limit) : reports;
42
- }
43
-
44
- export function extractCardTargets(input) {
45
- const context = { targets: [], sawCard: false, seen: new Set() };
46
- collectTargets(unwrapEnvelope(input), context, 0);
47
- if (context.targets.length) return context.targets;
48
- if (context.sawCard)
49
- throw new DatarcError(
50
- "输入缺少问题 tokens(answer.tokens);请保存包含 answer 的完整搜索结果 JSON,而不是单独的卡片对象",
51
- "CARD_TOKENS_MISSING",
52
- );
53
- throw new DatarcError("输入中没有找到可加入报告的数据卡片", "NO_CARDS");
54
- }
55
-
56
- function unwrapEnvelope(value) {
57
- if (
58
- value &&
59
- typeof value === "object" &&
60
- !Array.isArray(value) &&
61
- Object.hasOwn(value, "ok")
62
- ) {
63
- if (value.ok) return unwrapEnvelope(value.data);
64
- const error = value.error ?? {};
65
- throw new DatarcError(
66
- error.message ?? "上一步脚本输出失败",
67
- error.code ?? "UPSTREAM_FAILED",
68
- error.details,
69
- );
70
- }
71
- return value;
72
- }
73
-
74
- function collectTargets(node, context, depth) {
75
- if (
76
- !node ||
77
- typeof node !== "object" ||
78
- context.seen.has(node) ||
79
- depth > MAX_WALK_DEPTH
80
- )
81
- return;
82
- context.seen.add(node);
83
- if (Array.isArray(node)) {
84
- for (const item of node) collectTargets(item, context, depth + 1);
85
- return;
86
- }
87
- if (node.status === "calculation_required") {
88
- context.targets.push({ question: node.question, tokens: [], cards: [] });
89
- return;
90
- }
91
- if (isCardSource(node.answer)) {
92
- context.targets.push({
93
- question: node.question ?? null,
94
- tokens: node.answer.tokens,
95
- cards: directCards(node.answer.cards ?? []),
96
- });
97
- return;
98
- }
99
- if (isCardSource(node)) {
100
- context.targets.push({
101
- question: node.question ?? null,
102
- tokens: node.tokens,
103
- cards: directCards(node.cards ?? []),
104
- });
105
- return;
106
- }
107
- if (looksLikeCard(node)) {
108
- context.sawCard = true;
109
- return;
110
- }
111
- for (const child of Object.values(node)) collectTargets(child, context, depth + 1);
112
- }
113
-
114
- function isCardSource(value) {
115
- return Boolean(
116
- value &&
117
- typeof value === "object" &&
118
- !Array.isArray(value) &&
119
- Array.isArray(value.tokens) &&
120
- Array.isArray(value.cards),
121
- );
122
- }
123
-
124
- function looksLikeCard(node) {
125
- return Boolean(
126
- node &&
127
- typeof node === "object" &&
128
- !Array.isArray(node) &&
129
- (node.card_type !== undefined ||
130
- node.cardType !== undefined ||
131
- (typeof node.title === "string" && Array.isArray(node.data))),
132
- );
133
- }
134
-
135
- export function buildAddPayload(tokens, card, uid) {
136
- if (!Array.isArray(tokens) || !tokens.length)
137
- throw new DatarcError(
138
- "卡片缺少问题 tokens(answer.tokens),无法加入报告",
139
- "CARD_TOKENS_MISSING",
140
- );
141
- if (typeof uid !== "string" || !PINBOARD_UID_PATTERN.test(uid))
142
- throw new DatarcError("报告 uid 必须是 32 位十六进制字符串", "INVALID_ARGUMENT");
143
- const cardType = card?.card_type ?? card?.cardType;
144
- const title = typeof card?.title === "string" && card.title ? card.title : null;
145
- return {
146
- data: tokens,
147
- uids: [uid],
148
- ...(cardType === undefined ? {} : { card_type: cardType }),
149
- params: {
150
- tuids: Array.isArray(card?.tuids) ? card.tuids : [],
151
- ...(cardType === undefined ? {} : { cardType }),
152
- ...(title ? { chartName: title } : {}),
153
- },
154
- };
155
- }
156
-
157
- export function identifyAddedPin(before, after, expected = {}) {
158
- const beforeContent = contentListOf(before, "before");
159
- const afterContent = contentListOf(after, "after");
160
- const beforeIds = new Set(beforeContent.map(pinIdOf).filter(Boolean));
161
- const afterIds = new Set(afterContent.map(pinIdOf).filter(Boolean));
162
- let removedCount = 0;
163
- for (const id of beforeIds) if (!afterIds.has(id)) removedCount += 1;
164
- if (removedCount)
165
- throw verifyFailed({ removedCount, reason: "removed-existing-pin" });
166
- const added = [...afterIds].filter((id) => !beforeIds.has(id));
167
- if (added.length !== 1) throw verifyFailed({ addedCount: added.length });
168
- const pin = afterContent.find((item) => pinIdOf(item) === added[0]);
169
- if (pin?.type !== 2) throw verifyFailed({ pinType: pin?.type ?? null });
170
- const params = pin.params ?? {};
171
- if (expected.data !== undefined && !isDeepStrictEqual(pin.data, expected.data))
172
- throw verifyFailed({ addedCount: 1, reason: "signature-data" });
173
- const cardType = params.cardType ?? params.card_type;
174
- if (
175
- expected.cardType !== undefined &&
176
- Number(cardType) !== Number(expected.cardType)
177
- )
178
- throw verifyFailed({ addedCount: 1, reason: "signature-card-type" });
179
- if (
180
- expected.tuids !== undefined &&
181
- !isDeepStrictEqual(params.tuids ?? [], expected.tuids)
182
- )
183
- throw verifyFailed({ addedCount: 1, reason: "signature-tuids" });
184
- if (
185
- expected.chartName !== undefined &&
186
- params.chartName !== expected.chartName
187
- )
188
- throw verifyFailed({ addedCount: 1, reason: "signature-chart-name" });
189
- return { pinId: added[0] };
190
- }
191
-
192
- function verifyFailed(details) {
193
- return new DatarcError(
194
- "添加后回读未确认到恰好一张新卡片;已停止,不重试添加请求",
195
- "CARD_VERIFY_FAILED",
196
- details,
197
- );
198
- }
199
-
200
- function contentListOf(report, stage) {
201
- const content = report?.content;
202
- if (!Array.isArray(content))
203
- throw verifyFailed({ reason: `missing-${stage}-content` });
204
- return content;
205
- }
206
-
207
- function pinIdOf(pin) {
208
- return typeof pin?.i === "string" ? pin.i : null;
209
- }
210
-
211
- export function reportUrl(endpoint, uid, projectId) {
212
- let url;
213
- try {
214
- url = new URL(String(endpoint ?? ""));
215
- } catch {
216
- throw new DatarcError(
217
- "DATARC_ENDPOINT 必须是合法的 http(s) 地址",
218
- "INVALID_ARGUMENT",
219
- );
220
- }
221
- if (!["http:", "https:"].includes(url.protocol) || !url.hostname)
222
- throw new DatarcError(
223
- "DATARC_ENDPOINT 必须是合法的 http(s) 地址",
224
- "INVALID_ARGUMENT",
225
- );
226
- if (url.username || url.password)
227
- throw new DatarcError(
228
- "DATARC_ENDPOINT 不得包含用户信息",
229
- "INVALID_ARGUMENT",
230
- );
231
- const id = Number(projectId);
232
- if (!Number.isInteger(id) || id <= 0)
233
- throw new DatarcError("projectId 必须是正整数", "INVALID_ARGUMENT");
234
- if (typeof uid !== "string" || !PINBOARD_UID_PATTERN.test(uid))
235
- throw new DatarcError("报告 uid 必须是 32 位十六进制字符串", "INVALID_ARGUMENT");
236
- return `${url.origin}/#/pinboard/${uid}?projectId=${id}`;
237
- }
238
-
239
- export async function execute(argv, options = {}) {
240
- const args = parseArgs(argv);
241
- const command = args._[0];
242
- if (command === "select") return (await selectCard(args, options)).selection;
243
- const client = options.client ?? createClient(options);
244
- const projectId = required(args, "project-id");
245
- if (command === "list") return listReports(client, projectId, args);
246
- if (command === "create") return createReport(client, projectId, args, options);
247
- if (command === "add") return addCard(client, projectId, args, options);
248
- throw new DatarcError("请使用 select 确认卡片、list 选择报告,再用 create 或 add 完成保存", "INVALID_ARGUMENT");
249
- }
250
-
251
- const ALL_PAGE_SIZE = 50;
252
-
253
- async function listReports(client, projectId, args) {
254
- const q = typeof args.q === "string" ? args.q : "";
255
- const limit = num(args.limit, 10);
256
- const recentLimit = num(args["recent-limit"], 30);
257
- const query = { offset: 0, limit: recentLimit, ...(q ? { q } : {}) };
258
- const recent = await client.request(
259
- "GET",
260
- `/api/v3/account-projects/${projectId}/pinboards/recent/`,
261
- { query },
262
- );
263
- const { allReports } = await fetchAllEditablePages(client, projectId, {
264
- q,
265
- recentUids: (Array.isArray(recent) ? recent : [])
266
- .map((item) => item?.uid)
267
- .filter(Boolean),
268
- minCandidates: limit,
269
- });
270
- const reports = mergeReports(recent, allReports, limit);
271
- return {
272
- count: reports.length,
273
- reports: reports.map((item) => ({
274
- uid: item.uid,
275
- name: item.name,
276
- desc: item.desc ?? "",
277
- tags: (Array.isArray(item.tags) ? item.tags : [])
278
- .map((tag) => tag?.name)
279
- .filter(Boolean),
280
- ownerName: item.owner?.nickname || item.owner?.username || null,
281
- updatedAt: item.updatedAt ?? null,
282
- recent: Boolean(item.recent),
283
- })),
284
- };
285
- }
286
-
287
- // 分页拉取可编辑报告,直到每个 recent UID 的编辑权限都已判定,
288
- // 且积累了足够的兜底候选(按更新时间排序)。服务端返回短页后仍未
289
- // 覆盖的 recent UID 才视为不可编辑。
290
- async function fetchAllEditablePages(client, projectId, { q = "", recentUids = [], minCandidates = 10 }) {
291
- const recentUidSet = new Set(recentUids);
292
- const allReports = [];
293
- const editableUids = new Set();
294
- const queryExtra = q ? { q } : {};
295
- for (let offset = 0; ; offset += ALL_PAGE_SIZE) {
296
- const page =
297
- (await client.request(
298
- "GET",
299
- `/api/v3/account-projects/${projectId}/pinboards/all/`,
300
- {
301
- query: { offset, limit: ALL_PAGE_SIZE, canEdit: "true", ...queryExtra },
302
- },
303
- )) ?? [];
304
- if (!page.length) break;
305
- for (const item of page) {
306
- if (item?.uid) editableUids.add(item.uid);
307
- allReports.push(item);
308
- }
309
- const covered = [...recentUidSet].every((uid) => editableUids.has(uid));
310
- const fallbackCount = allReports.filter(
311
- (item) => !recentUidSet.has(item?.uid),
312
- ).length;
313
- if (covered && fallbackCount >= minCandidates) break;
314
- if (page.length < ALL_PAGE_SIZE) break;
315
- }
316
- return { allReports, editableUids };
317
- }
318
-
319
- async function createReport(client, projectId, args, options) {
320
- const name = String(required(args, "name"));
321
- if (!name.trim() || name.length > 255)
322
- throw new DatarcError("报告名称必须是 1 至 255 个字符", "INVALID_NAME");
323
- const desc = args.desc === undefined ? null : String(args.desc);
324
- if (desc !== null && desc.length > 255)
325
- throw new DatarcError("报告介绍不得超过 255 个字符", "INVALID_ARGUMENT");
326
- const created = await client.request(
327
- "POST",
328
- `/api/v3/account-projects/${projectId}/pinboards/`,
329
- {
330
- body: {
331
- name,
332
- ...(desc === null ? {} : { desc }),
333
- tags: [],
334
- },
335
- },
336
- );
337
- const uid = created?.uid;
338
- if (typeof uid !== "string" || !PINBOARD_UID_PATTERN.test(uid))
339
- throw new DatarcError("创建报告未返回有效 uid", "API_ERROR", {
340
- response: { name: created?.name ?? null },
341
- });
342
- return {
343
- uid,
344
- name: created.name ?? name,
345
- url: reportUrl(resolveEndpoint(options), uid, projectId),
346
- };
347
- }
348
-
349
- async function selectCard(args, options) {
350
- const input = await readJson(required(args, "card-file"));
351
- const targets = extractCardTargets(await resolveResultInput(input, args["project-id"], options));
352
- const candidates = targets.map((target, resultIndex) => ({
353
- resultIndex,
354
- question: target.question,
355
- cards: target.cards.map((card, cardIndex) => ({
356
- cardIndex,
357
- title: card.title ?? `卡片 ${cardIndex + 1}`,
358
- cardType: card.card_type ?? card.cardType ?? null,
359
- })),
360
- }));
361
- if (!candidates.some((result) => result.cards.length))
362
- throw new DatarcError("查询结果没有可加入报告的数据卡片,请选择含数据卡片的查询结果。", "NO_CARDS");
363
- const readIndex = (name) => {
364
- if (args[name] === undefined) return undefined;
365
- const value = required(args, name);
366
- if (typeof value !== "string" || !/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)))
367
- throw new DatarcError(`请为 --${name} 提供从零开始的卡片或结果序号。`, "INVALID_ARGUMENT");
368
- return Number(value);
369
- };
370
- const resultIndex = readIndex("result-index");
371
- const cardIndex = readIndex("card-index");
372
- const matches = candidates.filter((result) => resultIndex === undefined || result.resultIndex === resultIndex)
373
- .flatMap((result) => result.cards.filter((card) => cardIndex === undefined || card.cardIndex === cardIndex)
374
- .map((card) => ({ resultIndex: result.resultIndex, question: result.question, ...card })));
375
- if (!matches.length)
376
- throw new DatarcError("序号没有匹配的卡片,请按候选的问题和标题重新选择。", "CARD_INDEX_OUT_OF_RANGE", { candidates });
377
- if (matches.length > 1)
378
- throw new DatarcError("有多张卡片符合条件,请按问题或图表标题选定一张再保存。", "CARD_SELECTION_REQUIRED", { candidates });
379
- const [selection] = matches;
380
- const target = targets[selection.resultIndex];
381
- if (!target.tokens.length)
382
- throw new DatarcError("选中卡片缺少问题 tokens,请提供包含有效 answer.tokens 的完整搜索结果。", "CARD_TOKENS_MISSING");
383
- return { selection, tokens: target.tokens, card: target.cards[selection.cardIndex] };
384
- }
385
-
386
- async function addCard(client, projectId, args, options) {
387
- const uids = [].concat(args["pinboard-uid"] ?? []).filter(Boolean);
388
- if (!uids.length)
389
- throw new DatarcError("缺少参数 --pinboard-uid", "INVALID_ARGUMENT");
390
- if (uids.length > 1)
391
- throw new DatarcError(
392
- "一次只能加入一个报告;多报告批量添加暂未开放",
393
- "INVALID_ARGUMENT",
394
- );
395
- const uid = String(uids[0]);
396
- if (!PINBOARD_UID_PATTERN.test(uid))
397
- throw new DatarcError("报告 uid 必须是 32 位十六进制字符串", "INVALID_ARGUMENT");
398
- const { tokens, card } = await selectCard(args, options);
399
- const payload = buildAddPayload(tokens, card, uid);
400
- const detailPath = `/api/v3/account-projects/${projectId}/pinboards/${uid}/`;
401
- const before = await client.request("GET", detailPath);
402
- await client.request(
403
- "POST",
404
- `/api/v3/account-projects/${projectId}/pinboards/add-to-pinboards/`,
405
- { body: payload },
406
- );
407
- const after = await client.request("GET", detailPath);
408
- const { pinId } = identifyAddedPin(before, after, {
409
- data: payload.data,
410
- ...(payload.card_type === undefined
411
- ? {}
412
- : { cardType: payload.card_type }),
413
- tuids: payload.params.tuids,
414
- ...(payload.params.chartName === undefined
415
- ? {}
416
- : { chartName: payload.params.chartName }),
417
- });
418
- return {
419
- report: { uid, name: after?.name ?? before?.name ?? null },
420
- pinId,
421
- cardType: payload.card_type ?? null,
422
- chartName: card.title ?? null,
423
- url: reportUrl(resolveEndpoint(options), uid, projectId),
424
- };
425
- }
426
-
427
- function resolveEndpoint(options = {}) {
428
- return resolveCredentials(options).endpoint;
429
- }
430
-
431
- function num(value, fallback) {
432
- const result = Number(value ?? fallback);
433
- if (!Number.isInteger(result) || result < 0)
434
- throw new DatarcError("数值参数必须是非负整数", "INVALID_ARGUMENT");
435
- return result;
436
- }
437
-
438
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
439
- await runCli(() => execute(process.argv.slice(2)));
1
+ #!/usr/bin/env node
2
+ import { resolveResultInput } from "../../datarc-data-search/scripts/search-result.mjs";
3
+ import { resolveCredentials } from "../../datarc-oauth/scripts/credentials.mjs";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { pathToFileURL } from "node:url";
6
+ import {
7
+ createClient,
8
+ DatarcError,
9
+ parseArgs,
10
+ readJson,
11
+ required,
12
+ runCli,
13
+ } from "./datarc-client.mjs";
14
+
15
+ const PINBOARD_UID_PATTERN = /^[0-9a-fA-F]{32}$/;
16
+ // 深度按对象跳数计:DataSeek 每层嵌套(actions/children/steps)约 3 跳,5 层嵌套约 15 跳。
17
+ const MAX_WALK_DEPTH = 16;
18
+
19
+ /** 列出全部直接结果卡片:公共客户端的 primaryCards 只取第一张,选卡要看到所有候选。 */
20
+ export function directCards(cards = []) {
21
+ if (!Array.isArray(cards)) return [];
22
+ return cards.filter((card) => card && Number(card.resultType ?? card.result_type ?? 0) === 0);
23
+ }
24
+
25
+ export function mergeReports(recentItems = [], allItems = [], limit = 10) {
26
+ const editable = new Set(
27
+ (Array.isArray(allItems) ? allItems : [])
28
+ .map((item) => item?.uid)
29
+ .filter(Boolean),
30
+ );
31
+ const seen = new Set();
32
+ const reports = [];
33
+ const push = (item, recent) => {
34
+ if (!item?.uid || seen.has(item.uid)) return;
35
+ seen.add(item.uid);
36
+ reports.push({ ...item, recent });
37
+ };
38
+ for (const item of Array.isArray(recentItems) ? recentItems : [])
39
+ if (editable.has(item?.uid)) push(item, true);
40
+ for (const item of Array.isArray(allItems) ? allItems : []) push(item, false);
41
+ return limit > 0 ? reports.slice(0, limit) : reports;
42
+ }
43
+
44
+ export function extractCardTargets(input) {
45
+ const context = { targets: [], sawCard: false, seen: new Set() };
46
+ collectTargets(unwrapEnvelope(input), context, 0);
47
+ if (context.targets.length) return context.targets;
48
+ if (context.sawCard)
49
+ throw new DatarcError(
50
+ "输入缺少问题 tokens(answer.tokens);请保存包含 answer 的完整搜索结果 JSON,而不是单独的卡片对象",
51
+ "CARD_TOKENS_MISSING",
52
+ );
53
+ throw new DatarcError("输入中没有找到可加入报告的数据卡片", "NO_CARDS");
54
+ }
55
+
56
+ function unwrapEnvelope(value) {
57
+ if (
58
+ value &&
59
+ typeof value === "object" &&
60
+ !Array.isArray(value) &&
61
+ Object.hasOwn(value, "ok")
62
+ ) {
63
+ if (value.ok) return unwrapEnvelope(value.data);
64
+ const error = value.error ?? {};
65
+ throw new DatarcError(
66
+ error.message ?? "上一步脚本输出失败",
67
+ error.code ?? "UPSTREAM_FAILED",
68
+ error.details,
69
+ );
70
+ }
71
+ return value;
72
+ }
73
+
74
+ function collectTargets(node, context, depth) {
75
+ if (
76
+ !node ||
77
+ typeof node !== "object" ||
78
+ context.seen.has(node) ||
79
+ depth > MAX_WALK_DEPTH
80
+ )
81
+ return;
82
+ context.seen.add(node);
83
+ if (Array.isArray(node)) {
84
+ for (const item of node) collectTargets(item, context, depth + 1);
85
+ return;
86
+ }
87
+ if (node.status === "calculation_required") {
88
+ context.targets.push({ question: node.question, tokens: [], cards: [] });
89
+ return;
90
+ }
91
+ if (isCardSource(node.answer)) {
92
+ context.targets.push({
93
+ question: node.question ?? null,
94
+ tokens: node.answer.tokens,
95
+ cards: directCards(node.answer.cards ?? []),
96
+ });
97
+ return;
98
+ }
99
+ if (isCardSource(node)) {
100
+ context.targets.push({
101
+ question: node.question ?? null,
102
+ tokens: node.tokens,
103
+ cards: directCards(node.cards ?? []),
104
+ });
105
+ return;
106
+ }
107
+ if (looksLikeCard(node)) {
108
+ context.sawCard = true;
109
+ return;
110
+ }
111
+ for (const child of Object.values(node)) collectTargets(child, context, depth + 1);
112
+ }
113
+
114
+ function isCardSource(value) {
115
+ return Boolean(
116
+ value &&
117
+ typeof value === "object" &&
118
+ !Array.isArray(value) &&
119
+ Array.isArray(value.tokens) &&
120
+ Array.isArray(value.cards),
121
+ );
122
+ }
123
+
124
+ function looksLikeCard(node) {
125
+ return Boolean(
126
+ node &&
127
+ typeof node === "object" &&
128
+ !Array.isArray(node) &&
129
+ (node.card_type !== undefined ||
130
+ node.cardType !== undefined ||
131
+ (typeof node.title === "string" && Array.isArray(node.data))),
132
+ );
133
+ }
134
+
135
+ export function buildAddPayload(tokens, card, uid) {
136
+ if (!Array.isArray(tokens) || !tokens.length)
137
+ throw new DatarcError(
138
+ "卡片缺少问题 tokens(answer.tokens),无法加入报告",
139
+ "CARD_TOKENS_MISSING",
140
+ );
141
+ if (typeof uid !== "string" || !PINBOARD_UID_PATTERN.test(uid))
142
+ throw new DatarcError("报告 uid 必须是 32 位十六进制字符串", "INVALID_ARGUMENT");
143
+ const cardType = card?.card_type ?? card?.cardType;
144
+ const title = typeof card?.title === "string" && card.title ? card.title : null;
145
+ return {
146
+ data: tokens,
147
+ uids: [uid],
148
+ ...(cardType === undefined ? {} : { card_type: cardType }),
149
+ params: {
150
+ tuids: Array.isArray(card?.tuids) ? card.tuids : [],
151
+ ...(cardType === undefined ? {} : { cardType }),
152
+ ...(title ? { chartName: title } : {}),
153
+ },
154
+ };
155
+ }
156
+
157
+ export function identifyAddedPin(before, after, expected = {}) {
158
+ const beforeContent = contentListOf(before, "before");
159
+ const afterContent = contentListOf(after, "after");
160
+ const beforeIds = new Set(beforeContent.map(pinIdOf).filter(Boolean));
161
+ const afterIds = new Set(afterContent.map(pinIdOf).filter(Boolean));
162
+ let removedCount = 0;
163
+ for (const id of beforeIds) if (!afterIds.has(id)) removedCount += 1;
164
+ if (removedCount)
165
+ throw verifyFailed({ removedCount, reason: "removed-existing-pin" });
166
+ const added = [...afterIds].filter((id) => !beforeIds.has(id));
167
+ if (added.length !== 1) throw verifyFailed({ addedCount: added.length });
168
+ const pin = afterContent.find((item) => pinIdOf(item) === added[0]);
169
+ if (pin?.type !== 2) throw verifyFailed({ pinType: pin?.type ?? null });
170
+ const params = pin.params ?? {};
171
+ if (expected.data !== undefined && !isDeepStrictEqual(pin.data, expected.data))
172
+ throw verifyFailed({ addedCount: 1, reason: "signature-data" });
173
+ const cardType = params.cardType ?? params.card_type;
174
+ if (
175
+ expected.cardType !== undefined &&
176
+ Number(cardType) !== Number(expected.cardType)
177
+ )
178
+ throw verifyFailed({ addedCount: 1, reason: "signature-card-type" });
179
+ if (
180
+ expected.tuids !== undefined &&
181
+ !isDeepStrictEqual(params.tuids ?? [], expected.tuids)
182
+ )
183
+ throw verifyFailed({ addedCount: 1, reason: "signature-tuids" });
184
+ if (
185
+ expected.chartName !== undefined &&
186
+ params.chartName !== expected.chartName
187
+ )
188
+ throw verifyFailed({ addedCount: 1, reason: "signature-chart-name" });
189
+ return { pinId: added[0] };
190
+ }
191
+
192
+ function verifyFailed(details) {
193
+ return new DatarcError(
194
+ "添加后回读未确认到恰好一张新卡片;已停止,不重试添加请求",
195
+ "CARD_VERIFY_FAILED",
196
+ details,
197
+ );
198
+ }
199
+
200
+ function contentListOf(report, stage) {
201
+ const content = report?.content;
202
+ if (!Array.isArray(content))
203
+ throw verifyFailed({ reason: `missing-${stage}-content` });
204
+ return content;
205
+ }
206
+
207
+ function pinIdOf(pin) {
208
+ return typeof pin?.i === "string" ? pin.i : null;
209
+ }
210
+
211
+ export function reportUrl(endpoint, uid, projectId) {
212
+ let url;
213
+ try {
214
+ url = new URL(String(endpoint ?? ""));
215
+ } catch {
216
+ throw new DatarcError(
217
+ "DATARC_ENDPOINT 必须是合法的 http(s) 地址",
218
+ "INVALID_ARGUMENT",
219
+ );
220
+ }
221
+ if (!["http:", "https:"].includes(url.protocol) || !url.hostname)
222
+ throw new DatarcError(
223
+ "DATARC_ENDPOINT 必须是合法的 http(s) 地址",
224
+ "INVALID_ARGUMENT",
225
+ );
226
+ if (url.username || url.password)
227
+ throw new DatarcError(
228
+ "DATARC_ENDPOINT 不得包含用户信息",
229
+ "INVALID_ARGUMENT",
230
+ );
231
+ const id = Number(projectId);
232
+ if (!Number.isInteger(id) || id <= 0)
233
+ throw new DatarcError("projectId 必须是正整数", "INVALID_ARGUMENT");
234
+ if (typeof uid !== "string" || !PINBOARD_UID_PATTERN.test(uid))
235
+ throw new DatarcError("报告 uid 必须是 32 位十六进制字符串", "INVALID_ARGUMENT");
236
+ return `${url.origin}/#/pinboard/${uid}?projectId=${id}`;
237
+ }
238
+
239
+ export async function execute(argv, options = {}) {
240
+ const args = parseArgs(argv);
241
+ const command = args._[0];
242
+ if (command === "select") return (await selectCard(args, options)).selection;
243
+ const client = options.client ?? createClient(options);
244
+ const projectId = required(args, "project-id");
245
+ if (command === "list") return listReports(client, projectId, args);
246
+ if (command === "create") return createReport(client, projectId, args, options);
247
+ if (command === "add") return addCard(client, projectId, args, options);
248
+ throw new DatarcError("请使用 select 确认卡片、list 选择报告,再用 create 或 add 完成保存", "INVALID_ARGUMENT");
249
+ }
250
+
251
+ const ALL_PAGE_SIZE = 50;
252
+
253
+ async function listReports(client, projectId, args) {
254
+ const q = typeof args.q === "string" ? args.q : "";
255
+ const limit = num(args.limit, 10);
256
+ const recentLimit = num(args["recent-limit"], 30);
257
+ const query = { offset: 0, limit: recentLimit, ...(q ? { q } : {}) };
258
+ const recent = await client.request(
259
+ "GET",
260
+ `/api/v3/account-projects/${projectId}/pinboards/recent/`,
261
+ { query },
262
+ );
263
+ const { allReports } = await fetchAllEditablePages(client, projectId, {
264
+ q,
265
+ recentUids: (Array.isArray(recent) ? recent : [])
266
+ .map((item) => item?.uid)
267
+ .filter(Boolean),
268
+ minCandidates: limit,
269
+ });
270
+ const reports = mergeReports(recent, allReports, limit);
271
+ return {
272
+ count: reports.length,
273
+ reports: reports.map((item) => ({
274
+ uid: item.uid,
275
+ name: item.name,
276
+ desc: item.desc ?? "",
277
+ tags: (Array.isArray(item.tags) ? item.tags : [])
278
+ .map((tag) => tag?.name)
279
+ .filter(Boolean),
280
+ ownerName: item.owner?.nickname || item.owner?.username || null,
281
+ updatedAt: item.updatedAt ?? null,
282
+ recent: Boolean(item.recent),
283
+ })),
284
+ };
285
+ }
286
+
287
+ // 分页拉取可编辑报告,直到每个 recent UID 的编辑权限都已判定,
288
+ // 且积累了足够的兜底候选(按更新时间排序)。服务端返回短页后仍未
289
+ // 覆盖的 recent UID 才视为不可编辑。
290
+ async function fetchAllEditablePages(client, projectId, { q = "", recentUids = [], minCandidates = 10 }) {
291
+ const recentUidSet = new Set(recentUids);
292
+ const allReports = [];
293
+ const editableUids = new Set();
294
+ const queryExtra = q ? { q } : {};
295
+ for (let offset = 0; ; offset += ALL_PAGE_SIZE) {
296
+ const page =
297
+ (await client.request(
298
+ "GET",
299
+ `/api/v3/account-projects/${projectId}/pinboards/all/`,
300
+ {
301
+ query: { offset, limit: ALL_PAGE_SIZE, canEdit: "true", ...queryExtra },
302
+ },
303
+ )) ?? [];
304
+ if (!page.length) break;
305
+ for (const item of page) {
306
+ if (item?.uid) editableUids.add(item.uid);
307
+ allReports.push(item);
308
+ }
309
+ const covered = [...recentUidSet].every((uid) => editableUids.has(uid));
310
+ const fallbackCount = allReports.filter(
311
+ (item) => !recentUidSet.has(item?.uid),
312
+ ).length;
313
+ if (covered && fallbackCount >= minCandidates) break;
314
+ if (page.length < ALL_PAGE_SIZE) break;
315
+ }
316
+ return { allReports, editableUids };
317
+ }
318
+
319
+ async function createReport(client, projectId, args, options) {
320
+ const name = String(required(args, "name"));
321
+ if (!name.trim() || name.length > 255)
322
+ throw new DatarcError("报告名称必须是 1 至 255 个字符", "INVALID_NAME");
323
+ const desc = args.desc === undefined ? null : String(args.desc);
324
+ if (desc !== null && desc.length > 255)
325
+ throw new DatarcError("报告介绍不得超过 255 个字符", "INVALID_ARGUMENT");
326
+ const created = await client.request(
327
+ "POST",
328
+ `/api/v3/account-projects/${projectId}/pinboards/`,
329
+ {
330
+ body: {
331
+ name,
332
+ ...(desc === null ? {} : { desc }),
333
+ tags: [],
334
+ },
335
+ },
336
+ );
337
+ const uid = created?.uid;
338
+ if (typeof uid !== "string" || !PINBOARD_UID_PATTERN.test(uid))
339
+ throw new DatarcError("创建报告未返回有效 uid", "API_ERROR", {
340
+ response: { name: created?.name ?? null },
341
+ });
342
+ return {
343
+ uid,
344
+ name: created.name ?? name,
345
+ url: reportUrl(resolveEndpoint(options), uid, projectId),
346
+ };
347
+ }
348
+
349
+ async function selectCard(args, options) {
350
+ const input = await readJson(required(args, "card-file"));
351
+ const targets = extractCardTargets(await resolveResultInput(input, args["project-id"], options));
352
+ const candidates = targets.map((target, resultIndex) => ({
353
+ resultIndex,
354
+ question: target.question,
355
+ cards: target.cards.map((card, cardIndex) => ({
356
+ cardIndex,
357
+ title: card.title ?? `卡片 ${cardIndex + 1}`,
358
+ cardType: card.card_type ?? card.cardType ?? null,
359
+ })),
360
+ }));
361
+ if (!candidates.some((result) => result.cards.length))
362
+ throw new DatarcError("查询结果没有可加入报告的数据卡片,请选择含数据卡片的查询结果。", "NO_CARDS");
363
+ const readIndex = (name) => {
364
+ if (args[name] === undefined) return undefined;
365
+ const value = required(args, name);
366
+ if (typeof value !== "string" || !/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)))
367
+ throw new DatarcError(`请为 --${name} 提供从零开始的卡片或结果序号。`, "INVALID_ARGUMENT");
368
+ return Number(value);
369
+ };
370
+ const resultIndex = readIndex("result-index");
371
+ const cardIndex = readIndex("card-index");
372
+ const matches = candidates.filter((result) => resultIndex === undefined || result.resultIndex === resultIndex)
373
+ .flatMap((result) => result.cards.filter((card) => cardIndex === undefined || card.cardIndex === cardIndex)
374
+ .map((card) => ({ resultIndex: result.resultIndex, question: result.question, ...card })));
375
+ if (!matches.length)
376
+ throw new DatarcError("序号没有匹配的卡片,请按候选的问题和标题重新选择。", "CARD_INDEX_OUT_OF_RANGE", { candidates });
377
+ if (matches.length > 1)
378
+ throw new DatarcError("有多张卡片符合条件,请按问题或图表标题选定一张再保存。", "CARD_SELECTION_REQUIRED", { candidates });
379
+ const [selection] = matches;
380
+ const target = targets[selection.resultIndex];
381
+ if (!target.tokens.length)
382
+ throw new DatarcError("选中卡片缺少问题 tokens,请提供包含有效 answer.tokens 的完整搜索结果。", "CARD_TOKENS_MISSING");
383
+ return { selection, tokens: target.tokens, card: target.cards[selection.cardIndex] };
384
+ }
385
+
386
+ async function addCard(client, projectId, args, options) {
387
+ const uids = [].concat(args["pinboard-uid"] ?? []).filter(Boolean);
388
+ if (!uids.length)
389
+ throw new DatarcError("缺少参数 --pinboard-uid", "INVALID_ARGUMENT");
390
+ if (uids.length > 1)
391
+ throw new DatarcError(
392
+ "一次只能加入一个报告;多报告批量添加暂未开放",
393
+ "INVALID_ARGUMENT",
394
+ );
395
+ const uid = String(uids[0]);
396
+ if (!PINBOARD_UID_PATTERN.test(uid))
397
+ throw new DatarcError("报告 uid 必须是 32 位十六进制字符串", "INVALID_ARGUMENT");
398
+ const { tokens, card } = await selectCard(args, options);
399
+ const payload = buildAddPayload(tokens, card, uid);
400
+ const detailPath = `/api/v3/account-projects/${projectId}/pinboards/${uid}/`;
401
+ const before = await client.request("GET", detailPath);
402
+ await client.request(
403
+ "POST",
404
+ `/api/v3/account-projects/${projectId}/pinboards/add-to-pinboards/`,
405
+ { body: payload },
406
+ );
407
+ const after = await client.request("GET", detailPath);
408
+ const { pinId } = identifyAddedPin(before, after, {
409
+ data: payload.data,
410
+ ...(payload.card_type === undefined
411
+ ? {}
412
+ : { cardType: payload.card_type }),
413
+ tuids: payload.params.tuids,
414
+ ...(payload.params.chartName === undefined
415
+ ? {}
416
+ : { chartName: payload.params.chartName }),
417
+ });
418
+ return {
419
+ report: { uid, name: after?.name ?? before?.name ?? null },
420
+ pinId,
421
+ cardType: payload.card_type ?? null,
422
+ chartName: card.title ?? null,
423
+ url: reportUrl(resolveEndpoint(options), uid, projectId),
424
+ };
425
+ }
426
+
427
+ function resolveEndpoint(options = {}) {
428
+ return resolveCredentials(options).endpoint;
429
+ }
430
+
431
+ function num(value, fallback) {
432
+ const result = Number(value ?? fallback);
433
+ if (!Number.isInteger(result) || result < 0)
434
+ throw new DatarcError("数值参数必须是非负整数", "INVALID_ARGUMENT");
435
+ return result;
436
+ }
437
+
438
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
439
+ await runCli(() => execute(process.argv.slice(2)));