@tavlo-dsh/dsh-plugin-tapd 0.0.0-stage → 0.5.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/LICENSE +21 -0
- package/README.md +50 -2
- package/cordis.patch.yml +5 -0
- package/icon.png +0 -0
- package/index.js +130 -0
- package/lib/client.js +1069 -0
- package/lib/client.js.LEGAL.txt +1112 -0
- package/licenses/dsh-task-hub.LICENSE +21 -0
- package/licenses/dsh-task-hub.md +13 -0
- package/licenses/uiarc-MIT.txt +25 -0
- package/licenses/uiarc-attribution.md +12 -0
- package/licenses/uiarc-react-remove-scroll-bar-MIT.txt +24 -0
- package/metadata.js +235 -0
- package/package.json +65 -4
- package/runtime.js +191 -0
- package/settings.js +338 -0
- package/sync.js +245 -0
- package/tapd.example.patch.yml +21 -0
- package/tapd.js +279 -0
package/tapd.js
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
// The TAPD list request and work-item URL handling are adapted from
|
|
2
|
+
// dsh-task-hub's lib/tapd.js (MIT); see licenses/dsh-task-hub.md.
|
|
3
|
+
import { compile } from 'html-to-text';
|
|
4
|
+
|
|
5
|
+
const TAPD_API = 'https://api.tapd.cn';
|
|
6
|
+
const READ_PATHS = new Set([
|
|
7
|
+
'/stories', '/tasks', '/stories/get_fields_info', '/tasks/get_fields_info',
|
|
8
|
+
'/workitem_types', '/workflows/status_map',
|
|
9
|
+
'/workspaces/projects', '/workspaces/user_participant_projects', '/workspaces/get_workspace_info', '/users/info',
|
|
10
|
+
]);
|
|
11
|
+
const PAGE_SIZE = 100;
|
|
12
|
+
const MAX_PAGES = 10;
|
|
13
|
+
const REQUEST_TIMEOUT_MS = 20_000;
|
|
14
|
+
const ITEM_FIELDS = 'id,name,description,workspace_id,status,owner,due';
|
|
15
|
+
|
|
16
|
+
const toPlainText = compile({
|
|
17
|
+
wordwrap: false,
|
|
18
|
+
selectors: [
|
|
19
|
+
{ selector: 'a', options: { ignoreHref: true } },
|
|
20
|
+
...['img', 'svg', 'iframe', 'object', 'embed', 'audio', 'video', 'script', 'style']
|
|
21
|
+
.map((selector) => ({ selector, format: 'skip' })),
|
|
22
|
+
],
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const ERROR_MESSAGES = {
|
|
26
|
+
'tapd/invalid-input': 'Invalid TAPD scan settings.',
|
|
27
|
+
'tapd/auth': 'TAPD authentication failed.',
|
|
28
|
+
'tapd/rate-limit': 'TAPD rate limit reached.',
|
|
29
|
+
'tapd/http': 'TAPD returned an HTTP error.',
|
|
30
|
+
'tapd/network': 'Could not reach TAPD.',
|
|
31
|
+
'tapd/aborted': 'TAPD scan was cancelled.',
|
|
32
|
+
'tapd/timeout': 'TAPD request timed out.',
|
|
33
|
+
'tapd/malformed': 'TAPD returned a malformed response.',
|
|
34
|
+
'tapd/api': 'The TAPD API reported an error.',
|
|
35
|
+
'tapd/current-user-unavailable': 'TAPD could not provide a usable current-user nickname.',
|
|
36
|
+
'tapd/scan-limit': 'TAPD scan reached the page limit without a complete result.',
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export class TapdError extends Error {
|
|
40
|
+
constructor(code, { status, retryAfterMs } = {}) {
|
|
41
|
+
super(ERROR_MESSAGES[code] ?? 'TAPD scan failed.');
|
|
42
|
+
this.name = 'TapdError';
|
|
43
|
+
this.code = code;
|
|
44
|
+
if (status !== undefined) this.status = status;
|
|
45
|
+
if (retryAfterMs !== undefined) this.retryAfterMs = retryAfterMs;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function decimalId(value) {
|
|
50
|
+
// TAPD IDs can exceed Number.MAX_SAFE_INTEGER, so never coerce strings to Number.
|
|
51
|
+
const id = Number.isSafeInteger(value) ? String(value) : value;
|
|
52
|
+
return typeof id === 'string' && /^\d{1,32}$/.test(id) ? id : null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function isQueryLiteral(value) {
|
|
56
|
+
return typeof value === 'string' && value.length > 0 && value.trim() === value
|
|
57
|
+
&& !/[|;<>\p{Cc}\u2028\u2029]/u.test(value);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isAuthorization(value) {
|
|
61
|
+
return typeof value === 'string' && value.trim() === value
|
|
62
|
+
&& !/[^\x20-\x7e]/.test(value) && /^[a-z][a-z0-9+.-]* +\S/i.test(value);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function retryAfterDelay(response) {
|
|
66
|
+
const value = response.headers?.get('Retry-After')?.trim();
|
|
67
|
+
if (!value) return undefined;
|
|
68
|
+
if (/^\d+$/.test(value)) {
|
|
69
|
+
const delay = Number(value) * 1000;
|
|
70
|
+
return Number.isSafeInteger(delay) ? delay : undefined;
|
|
71
|
+
}
|
|
72
|
+
// Date.parse accepts many non-HTTP strings (including fractional numbers).
|
|
73
|
+
const time = Date.parse(value);
|
|
74
|
+
if (Number.isFinite(time) && new Date(time).toUTCString() === value) {
|
|
75
|
+
return Math.max(0, time - Date.now());
|
|
76
|
+
}
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function cancelBody(response) {
|
|
81
|
+
// Non-success responses are never read or logged.
|
|
82
|
+
void response.body?.cancel().catch(() => {});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function readData(url, authorization, signal, fetchImpl) {
|
|
86
|
+
let response;
|
|
87
|
+
try {
|
|
88
|
+
response = await fetchImpl(url.href, {
|
|
89
|
+
method: 'GET',
|
|
90
|
+
headers: { Accept: 'application/json', Authorization: authorization },
|
|
91
|
+
redirect: 'error',
|
|
92
|
+
credentials: 'omit',
|
|
93
|
+
signal,
|
|
94
|
+
});
|
|
95
|
+
} catch (error) {
|
|
96
|
+
throw new TapdError(error?.name === 'TimeoutError' ? 'tapd/timeout' : 'tapd/network');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const status = response?.status;
|
|
100
|
+
if (!Number.isInteger(status) || status < 100 || status > 599) {
|
|
101
|
+
throw new TapdError('tapd/malformed');
|
|
102
|
+
}
|
|
103
|
+
if (response.redirected || status < 200 || status >= 300) {
|
|
104
|
+
cancelBody(response);
|
|
105
|
+
if (status === 401 || status === 403) throw new TapdError('tapd/auth', { status });
|
|
106
|
+
if (status === 429) {
|
|
107
|
+
throw new TapdError('tapd/rate-limit', { status, retryAfterMs: retryAfterDelay(response) });
|
|
108
|
+
}
|
|
109
|
+
throw new TapdError('tapd/http', { status });
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
let body;
|
|
113
|
+
try {
|
|
114
|
+
body = await response.json();
|
|
115
|
+
} catch {
|
|
116
|
+
throw new TapdError('tapd/malformed');
|
|
117
|
+
}
|
|
118
|
+
if (!isRecord(body) || !Number.isInteger(body.status)) throw new TapdError('tapd/malformed');
|
|
119
|
+
if (body.status !== 1) throw new TapdError('tapd/api');
|
|
120
|
+
if (!Object.hasOwn(body, 'data')) throw new TapdError('tapd/malformed');
|
|
121
|
+
return body.data;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function requestData(url, authorization, signal, fetchImpl, timeoutMs) {
|
|
125
|
+
if (signal?.aborted) throw new TapdError('tapd/aborted');
|
|
126
|
+
const timeout = new AbortController();
|
|
127
|
+
const requestSignal = signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal;
|
|
128
|
+
const timer = setTimeout(() => timeout.abort(), timeoutMs);
|
|
129
|
+
let onAbort;
|
|
130
|
+
const aborted = new Promise((_, reject) => {
|
|
131
|
+
onAbort = () => reject(new TapdError(timeout.signal.aborted ? 'tapd/timeout' : 'tapd/aborted'));
|
|
132
|
+
requestSignal.addEventListener('abort', onAbort, { once: true });
|
|
133
|
+
});
|
|
134
|
+
try {
|
|
135
|
+
// Bound both the request and body consumption, even with an injected fetch adapter.
|
|
136
|
+
return await Promise.race([aborted, readData(url, authorization, requestSignal, fetchImpl)]);
|
|
137
|
+
} finally {
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
requestSignal.removeEventListener('abort', onAbort);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function isRecord(value) {
|
|
144
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Host-only, read-only transport for fixed official TAPD paths. */
|
|
148
|
+
export async function requestTapdData({
|
|
149
|
+
path, params, authorization, signal, fetchImpl = globalThis.fetch, timeoutMs = REQUEST_TIMEOUT_MS,
|
|
150
|
+
} = {}) {
|
|
151
|
+
if (!READ_PATHS.has(path) || !isAuthorization(authorization) || typeof fetchImpl !== 'function'
|
|
152
|
+
|| (signal != null && !(signal instanceof AbortSignal)) || !Number.isInteger(timeoutMs)
|
|
153
|
+
|| timeoutMs < 1 || timeoutMs > REQUEST_TIMEOUT_MS) throw new TapdError('tapd/invalid-input');
|
|
154
|
+
const url = new URL(path, TAPD_API);
|
|
155
|
+
url.search = new URLSearchParams(params);
|
|
156
|
+
return requestData(url, authorization, signal, fetchImpl, timeoutMs);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function validateRow(row, wrapper) {
|
|
160
|
+
if (!isRecord(row) || !Object.hasOwn(row, wrapper) || !isRecord(row[wrapper])) {
|
|
161
|
+
throw new TapdError('tapd/malformed');
|
|
162
|
+
}
|
|
163
|
+
const item = row[wrapper];
|
|
164
|
+
const id = decimalId(item.id);
|
|
165
|
+
const workspace = decimalId(item.workspace_id);
|
|
166
|
+
if (!id || !workspace || typeof item.name !== 'string' || !item.name.trim()
|
|
167
|
+
|| typeof item.owner !== 'string' || typeof item.status !== 'string' || !item.status.trim()
|
|
168
|
+
|| (item.description != null && typeof item.description !== 'string')
|
|
169
|
+
|| (item.due != null && typeof item.due !== 'string')) {
|
|
170
|
+
throw new TapdError('tapd/malformed');
|
|
171
|
+
}
|
|
172
|
+
return { item, id, workspace };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function dateOnly(value) {
|
|
176
|
+
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000-')) return undefined;
|
|
177
|
+
const date = new Date(`${value}T00:00:00.000Z`);
|
|
178
|
+
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value ? value : undefined;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function normalizeItem(item, id, workspace, collection) {
|
|
182
|
+
let description;
|
|
183
|
+
try {
|
|
184
|
+
description = toPlainText(item.description ?? '');
|
|
185
|
+
} catch {
|
|
186
|
+
throw new TapdError('tapd/malformed');
|
|
187
|
+
}
|
|
188
|
+
const dueDate = dateOnly(item.due);
|
|
189
|
+
return {
|
|
190
|
+
id,
|
|
191
|
+
title: item.name.trim(),
|
|
192
|
+
description,
|
|
193
|
+
...(dueDate === undefined ? {} : { dueDate }),
|
|
194
|
+
url: `https://www.tapd.cn/${encodeURIComponent(workspace)}/prong/${collection}/view/${encodeURIComponent(id)}`,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// TAPD's API uses timezone-less wall-clock timestamps. Use China standard time
|
|
199
|
+
// explicitly so a DSH Host's local timezone (and DST) cannot shift the window.
|
|
200
|
+
const DAY_MS = 86_400_000;
|
|
201
|
+
const CHINA_OFFSET_MS = 8 * 3_600_000;
|
|
202
|
+
function tapdClock(ms) {
|
|
203
|
+
return new Date(ms + CHINA_OFFSET_MS).toISOString().slice(0, 19).replace('T', ' ');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function readTapdClock(value) {
|
|
207
|
+
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(value) || value.startsWith('0000-')) return NaN;
|
|
208
|
+
const stamp = Date.parse(`${value.replace(' ', 'T')}+08:00`);
|
|
209
|
+
return Number.isFinite(stamp) && tapdClock(stamp) === value ? stamp : NaN;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export function tapdModifiedWindow(lookbackDays, nowMs = Date.now()) {
|
|
213
|
+
if (lookbackDays === undefined) return undefined;
|
|
214
|
+
if (!Number.isInteger(lookbackDays) || lookbackDays < 1 || lookbackDays > 365 || !Number.isFinite(nowMs)) {
|
|
215
|
+
throw new TapdError('tapd/invalid-input');
|
|
216
|
+
}
|
|
217
|
+
const now = Math.floor(nowMs / 1000) * 1000;
|
|
218
|
+
return { from: tapdClock(now - lookbackDays * DAY_MS), to: tapdClock(now) };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function compareIdDescending(left, right) {
|
|
222
|
+
const a = BigInt(left.id);
|
|
223
|
+
const b = BigInt(right.id);
|
|
224
|
+
return a > b ? -1 : a < b ? 1 : 0;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Read one complete, bounded list. A failed or truncated scan never returns a partial list. */
|
|
228
|
+
export async function scanTapd({
|
|
229
|
+
workspaceId, objectType, owner, statuses, authorization, signal, modifiedWindow,
|
|
230
|
+
fetchImpl = globalThis.fetch, timeoutMs = REQUEST_TIMEOUT_MS,
|
|
231
|
+
} = {}) {
|
|
232
|
+
const workspace = decimalId(workspaceId);
|
|
233
|
+
const statusSet = Array.isArray(statuses) ? new Set(statuses) : null;
|
|
234
|
+
if (!workspace || (objectType !== 'story' && objectType !== 'task') || !isQueryLiteral(owner)
|
|
235
|
+
|| !statusSet || ![...statusSet].every(isQueryLiteral) || !isAuthorization(authorization)
|
|
236
|
+
|| typeof fetchImpl !== 'function' || (signal != null && !(signal instanceof AbortSignal))
|
|
237
|
+
|| !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > REQUEST_TIMEOUT_MS) {
|
|
238
|
+
throw new TapdError('tapd/invalid-input');
|
|
239
|
+
}
|
|
240
|
+
if (signal?.aborted) throw new TapdError('tapd/aborted');
|
|
241
|
+
const from = readTapdClock(modifiedWindow?.from);
|
|
242
|
+
const to = readTapdClock(modifiedWindow?.to);
|
|
243
|
+
if (modifiedWindow !== undefined && (!Number.isFinite(from) || !Number.isFinite(to) || from > to)) {
|
|
244
|
+
throw new TapdError('tapd/invalid-input');
|
|
245
|
+
}
|
|
246
|
+
if (statusSet.size === 0) return [];
|
|
247
|
+
|
|
248
|
+
const [collection, wrapper] = objectType === 'story' ? ['stories', 'Story'] : ['tasks', 'Task'];
|
|
249
|
+
const params = new URLSearchParams({
|
|
250
|
+
workspace_id: workspace,
|
|
251
|
+
// USER_OR interprets each literal as a member of TAPD's multi-user field.
|
|
252
|
+
owner: `USER_OR<${owner}>`,
|
|
253
|
+
status: [...statusSet].join('|'),
|
|
254
|
+
limit: String(PAGE_SIZE),
|
|
255
|
+
fields: modifiedWindow ? `${ITEM_FIELDS},modified` : ITEM_FIELDS,
|
|
256
|
+
order: 'id desc',
|
|
257
|
+
});
|
|
258
|
+
if (modifiedWindow) params.set('modified', `${modifiedWindow.from}~${modifiedWindow.to}`);
|
|
259
|
+
|
|
260
|
+
const items = [];
|
|
261
|
+
for (let page = 1; page <= MAX_PAGES; page += 1) {
|
|
262
|
+
params.set('page', String(page));
|
|
263
|
+
const rows = await requestTapdData({ path: `/${collection}`, params, authorization, signal, fetchImpl, timeoutMs });
|
|
264
|
+
if (!Array.isArray(rows) || rows.length > PAGE_SIZE) throw new TapdError('tapd/malformed');
|
|
265
|
+
if (rows.length === PAGE_SIZE && page === MAX_PAGES) throw new TapdError('tapd/scan-limit');
|
|
266
|
+
for (const row of rows) {
|
|
267
|
+
const { item, id, workspace: rowWorkspace } = validateRow(row, wrapper);
|
|
268
|
+
// Never rely on the remote filter to enforce the configured import scope.
|
|
269
|
+
if (rowWorkspace !== workspace || !item.owner.split(';').includes(owner) || !statusSet.has(item.status)) continue;
|
|
270
|
+
if (modifiedWindow) {
|
|
271
|
+
const updated = readTapdClock(item.modified);
|
|
272
|
+
if (!Number.isFinite(updated)) throw new TapdError('tapd/malformed');
|
|
273
|
+
if (updated < from || updated > to) continue;
|
|
274
|
+
}
|
|
275
|
+
items.push(normalizeItem(item, id, workspace, collection));
|
|
276
|
+
}
|
|
277
|
+
if (rows.length < PAGE_SIZE) return items.sort(compareIdDescending);
|
|
278
|
+
}
|
|
279
|
+
}
|