@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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 handsome-65
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,13 @@
1
+ # dsh-task-hub attribution
2
+
3
+ The TAPD client adapts the list request/query, response wrapper, pagination,
4
+ and story URL conventions from [dsh-task-hub `lib/tapd.js`][source], pinned to
5
+ commit `053282f1fe1a79bb257439926c3af06b3ef5f0a1`. Copyright © 2026 handsome-65;
6
+ licensed under the MIT License, preserved in [dsh-task-hub.LICENSE][license].
7
+
8
+ This adaptation restricts requests to the official API, does not follow
9
+ redirects or retry with credentials in the query, adds separate Task support,
10
+ and validates, filters, and normalizes complete scans before returning results.
11
+
12
+ [source]: https://github.com/handsomeboy65/dsh-task-hub/blob/053282f1fe1a79bb257439926c3af06b3ef5f0a1/lib/tapd.js
13
+ [license]: ./dsh-task-hub.LICENSE
@@ -0,0 +1,25 @@
1
+ Arc UI free components and motion tokens
2
+ https://uiarc.dev/license#free
3
+ https://github.com/kuratlielia/arc-library/blob/main/LICENSE
4
+
5
+ MIT License
6
+
7
+ Copyright (c) 2026 Elia Kuratli
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
@@ -0,0 +1,12 @@
1
+ # Arc UI attribution
2
+
3
+ The components under `ui/arc/` are adapted from the official free registry (`meta.tier: free`), retrieved 2026-11-20:
4
+
5
+ - [Input](https://uiarc.dev/r/input.json)
6
+ - [Select](https://uiarc.dev/r/select.json)
7
+ - [Accordion](https://uiarc.dev/r/accordion.json)
8
+ - [Arc motion tokens](https://uiarc.dev/r/arc-motion-tokens.json)
9
+
10
+ Arc UI licenses the free registry source under [MIT](https://uiarc.dev/license#free). The copyright notice and full terms are in [uiarc-MIT.txt](./uiarc-MIT.txt). No Arc Pro code or preview assets are included.
11
+
12
+ Tavlo adapted the local CSS modules to the DSH theme and allows externally labeled fields. Select renders one accessible label, with the upstream directional animation applied on entry. Accordion supports individual disclosure sections with an optional annotation; its closed content is inert while it animates. The packaged browser bundle includes third-party dependency notices in `lib/client.js.LEGAL.txt`.
@@ -0,0 +1,24 @@
1
+ react-remove-scroll-bar (used by Radix Select)
2
+ https://github.com/theKashey/react-remove-scroll-bar/blob/master/LICENSE
3
+
4
+ MIT License
5
+
6
+ Copyright (c) 2025 Anton Korzunov <thekashey@gmail.com>
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in all
16
+ copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ SOFTWARE.
package/metadata.js ADDED
@@ -0,0 +1,235 @@
1
+ import { z } from 'zod'
2
+ import { requestTapdData, TapdError } from './tapd.js'
3
+
4
+ // The official workspace catalog endpoints explicitly return all matches without pagination.
5
+ // https://open.tapd.cn/document/api-doc/API文档/api_reference/workspace/projects.html
6
+ // https://open.tapd.cn/document/api-doc/API文档/api_reference/workspace/user_participant_projects.html
7
+ const COMPANY_PROJECTS = '/workspaces/projects'
8
+ const PARTICIPANT_PROJECTS = '/workspaces/user_participant_projects'
9
+ // https://open.tapd.cn/document/api-doc/API文档/api_reference/workspace/get_workspace_info.html
10
+ const WORKSPACE_INFO = '/workspaces/get_workspace_info'
11
+ // These field-definition endpoints expose status options for the given project.
12
+ // https://open.tapd.cn/document/api-doc/API文档/api_reference/story/get_story_fields_info.html
13
+ // https://open.tapd.cn/document/api-doc/API文档/api_reference/task/get_task_fields_info.html
14
+ const STORY_FIELDS = '/stories/get_fields_info'
15
+ const TASK_FIELDS = '/tasks/get_fields_info'
16
+ // The workflow status map supports stories, not tasks. The story category ID is required.
17
+ // https://open.tapd.cn/document/api-doc/API文档/api_reference/story/get_workitem_types.html
18
+ // https://open.tapd.cn/document/api-doc/API文档/api_reference/workflow/get_workflow_status_map.html
19
+ const STORY_TYPES = '/workitem_types'
20
+ const WORKFLOW_STATUSES = '/workflows/status_map'
21
+ const MAX_PROJECTS = 500
22
+ const MAX_STATUS_OPTIONS = 512
23
+ const MAX_STORY_TYPES = 8
24
+ const TIMEOUT_MS = 8_000
25
+ const ID = /^\d{1,32}$/u
26
+ const STATUS_KEY = /^[A-Za-z0-9_.-]{1,64}$/u
27
+ const CONTROL = /[\p{Cc}\u2028\u2029]/u
28
+
29
+ const isRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value)
30
+ const decimalId = value => Number.isSafeInteger(value) ? String(value) : value
31
+ const malformed = () => new TapdError('tapd/malformed')
32
+
33
+ function displayText(value) {
34
+ if (typeof value !== 'string' || value.length > 1024 || CONTROL.test(value) || !value.trim()) throw malformed()
35
+ return value.trim()
36
+ }
37
+
38
+ export const tapdNickname = z.string().trim().max(128).refine(value => !/[<>|;,\p{Cc}\u2028\u2029]/u.test(value))
39
+ export const requiredTapdNickname = tapdNickname.refine(value => value.length > 0)
40
+
41
+ // Keep the underlying error code/status while identifying a failure of nick-only project enumeration.
42
+ export class AutomaticProjectListError extends TapdError {}
43
+
44
+ async function lookupCurrentNickname(get) {
45
+ try {
46
+ const data = await get('/users/info')
47
+ const nick = requiredTapdNickname.safeParse(isRecord(data) && Object.hasOwn(data, 'nick') ? data.nick : undefined)
48
+ // The identity ID and any other fields are not needed or returned to the caller.
49
+ if (nick.success) return nick.data
50
+ } catch (error) {
51
+ if (!(error instanceof TapdError) || !(error.status === 403 || error.status === 404
52
+ || error.code === 'tapd/api' || error.code === 'tapd/malformed')) throw error
53
+ }
54
+ throw new TapdError('tapd/current-user-unavailable')
55
+ }
56
+
57
+ function projectCatalog(data, auto = false) {
58
+ if (!Array.isArray(data)) throw malformed()
59
+ const projects = new Map()
60
+ for (const row of data.slice(0, MAX_PROJECTS)) {
61
+ const workspace = isRecord(row) && Object.hasOwn(row, 'Workspace') ? row.Workspace : auto ? row : undefined
62
+ if (!isRecord(workspace)) throw malformed()
63
+ if (auto && workspace.category === 'organization') continue
64
+ const id = decimalId(workspace.id)
65
+ if (typeof id !== 'string' || !ID.test(id)) throw malformed()
66
+ const name = displayText(workspace.name)
67
+ if (projects.has(id) && projects.get(id) !== name) throw malformed()
68
+ projects.set(id, name)
69
+ }
70
+ return {
71
+ projects: Array.from(projects, ([id, name]) => ({ id, name })),
72
+ ...(data.length > MAX_PROJECTS ? { truncated: true } : {}),
73
+ }
74
+ }
75
+
76
+ export async function discoverProjects({ auth, auto = false, companyId, seedWorkspaceId, nick, authorization, signal, fetchImpl }) {
77
+ const bearer = auth === 'bearer'
78
+ const get = (path, params) => requestTapdData({ path, params, authorization, signal, fetchImpl, timeoutMs: TIMEOUT_MS })
79
+ if (auto || (bearer && companyId === undefined && seedWorkspaceId === undefined)) {
80
+ if (!bearer) throw new TapdError('tapd/invalid-input')
81
+ // Jiangluowen623/dsh-plugin-tapd (src/tapd.ts) uses this PAT flow. The public
82
+ // docs list /users/info for OAuth and document company_id as required for the list.
83
+ const currentNick = await lookupCurrentNickname(get)
84
+ try {
85
+ const catalog = projectCatalog(await get(PARTICIPANT_PROJECTS, { nick: currentNick }), true)
86
+ return { scope: 'participant', ...catalog, currentNick }
87
+ } catch (error) {
88
+ if (!(error instanceof TapdError)) throw error
89
+ throw new AutomaticProjectListError(error.code, error)
90
+ }
91
+ }
92
+ if (companyId === undefined) {
93
+ const workspace = await readWorkspace(get, seedWorkspaceId)
94
+ companyId = decimalId(workspace.company_id)
95
+ if (typeof companyId !== 'string' || !ID.test(companyId)) throw malformed()
96
+ }
97
+ const params = bearer ? { company_id: companyId, nick } : { company_id: companyId, category: 'project' }
98
+ const catalog = projectCatalog(await get(bearer ? PARTICIPANT_PROJECTS : COMPANY_PROJECTS, params))
99
+ // Basic lists company projects, not the personal access rights of a TAPD member.
100
+ return { ...catalog, companyId, scope: bearer ? 'participant' : 'company' }
101
+ }
102
+
103
+ async function readWorkspace(get, id) {
104
+ const info = await get(WORKSPACE_INFO, { workspace_id: id })
105
+ const workspace = isRecord(info) && Object.hasOwn(info, 'Workspace') ? info.Workspace : undefined
106
+ if (!isRecord(workspace) || decimalId(workspace.id) !== id) throw malformed()
107
+ return workspace
108
+ }
109
+
110
+ // Resolve known IDs without requiring permission to enumerate projects or identify the account.
111
+ export async function discoverProjectNames({ workspaceIds, authorization, signal, fetchImpl }) {
112
+ const deadline = performance.now() + TIMEOUT_MS
113
+ const projects = []
114
+ let next = 0
115
+ let stop = false
116
+ async function worker() {
117
+ while (!stop && !signal?.aborted && next < workspaceIds.length) {
118
+ const timeoutMs = Math.floor(deadline - performance.now())
119
+ if (timeoutMs < 1) break
120
+ const id = workspaceIds[next++]
121
+ try {
122
+ const workspace = await readWorkspace((path, params) => requestTapdData({
123
+ path, params, authorization, signal, fetchImpl, timeoutMs,
124
+ }), id)
125
+ projects.push({ id, name: displayText(workspace.name) })
126
+ } catch (error) {
127
+ if (!(error instanceof TapdError)) throw error
128
+ if (error.status === 401 || error.code === 'tapd/rate-limit') stop = true
129
+ // Errors for a single project don't discard names already read.
130
+ }
131
+ }
132
+ }
133
+ await Promise.all(Array.from({ length: Math.min(4, workspaceIds.length) }, worker))
134
+ if (signal?.aborted) throw new TapdError('tapd/aborted')
135
+ return { projects }
136
+ }
137
+
138
+ function mergeStatusMap(data, options = new Map()) {
139
+ if (!isRecord(data)) throw malformed()
140
+ for (const key in data) {
141
+ if (!Object.hasOwn(data, key)) continue
142
+ if (!STATUS_KEY.test(key)) throw malformed()
143
+ const label = displayText(data[key])
144
+ if (options.has(key) && options.get(key) !== label) throw malformed()
145
+ options.set(key, label)
146
+ if (options.size > MAX_STATUS_OPTIONS) throw new TapdError('tapd/discovery-limit')
147
+ }
148
+ return options
149
+ }
150
+
151
+ const projectStatusOptions = options => Array.from(options, ([key, label]) => ({ key, label }))
152
+
153
+ function fieldStatusOptions(data) {
154
+ if (!isRecord(data) || !Object.hasOwn(data, 'status') || !isRecord(data.status)
155
+ || !Object.hasOwn(data.status, 'options')) throw malformed()
156
+ return projectStatusOptions(mergeStatusMap(data.status.options))
157
+ }
158
+
159
+ async function workflowStoryOptions(get, workspaceId) {
160
+ // Ask for one extra row so an incomplete catalog is never presented as complete.
161
+ const types = await get(STORY_TYPES, {
162
+ entity_type: 'story', fields: 'id,workspace_id,entity_type', limit: MAX_STORY_TYPES + 1, page: 1,
163
+ })
164
+ if (!Array.isArray(types)) throw malformed()
165
+ if (types.length > MAX_STORY_TYPES) throw new TapdError('tapd/discovery-limit')
166
+ const ids = new Set()
167
+ for (const row of types) {
168
+ const type = isRecord(row) && Object.hasOwn(row, 'WorkitemType') ? row.WorkitemType : undefined
169
+ if (!isRecord(type) || decimalId(type.workspace_id) !== workspaceId || type.entity_type !== 'story') throw malformed()
170
+ const id = decimalId(type.id)
171
+ if (typeof id !== 'string' || !ID.test(id)) throw malformed()
172
+ ids.add(id)
173
+ }
174
+ const options = new Map()
175
+ for (const id of ids) {
176
+ mergeStatusMap(await get(WORKFLOW_STATUSES, { system: 'story', workitem_type_id: id }), options)
177
+ }
178
+ return projectStatusOptions(options)
179
+ }
180
+
181
+ async function storyStatusOptions(get, workspaceId) {
182
+ const deadline = performance.now() + TIMEOUT_MS
183
+ try {
184
+ return fieldStatusOptions(await get(STORY_FIELDS))
185
+ } catch (error) {
186
+ // A different documented definition can help when the field metadata is absent or
187
+ // unreadable. Do not retry permission, TAPD API, network, quota or cancellation errors.
188
+ if (!(error instanceof TapdError) || !(error.code === 'tapd/malformed'
189
+ || (error.code === 'tapd/http' && (error.status === 404 || error.status === 405)))) throw error
190
+ }
191
+ return workflowStoryOptions((path, params) => {
192
+ const remaining = Math.floor(deadline - performance.now())
193
+ if (remaining < 1) throw new TapdError('tapd/timeout')
194
+ return get(path, params, remaining)
195
+ }, workspaceId)
196
+ }
197
+
198
+ export function discoveryErrorCode(error) {
199
+ if (!(error instanceof TapdError)) return undefined
200
+ return error.code === 'tapd/auth' && error.status === 403 ? 'tapd/discovery-forbidden' : error.code
201
+ }
202
+
203
+ export async function discoverStatuses({ workspaceId, authorization, signal, fetchImpl }) {
204
+ if (typeof workspaceId !== 'string' || !ID.test(workspaceId)) throw new TapdError('tapd/invalid-input')
205
+ const get = (path, params, timeoutMs = TIMEOUT_MS) => requestTapdData({
206
+ path, params: { ...params, workspace_id: workspaceId }, authorization, signal, fetchImpl, timeoutMs,
207
+ })
208
+ const failures = []
209
+ const track = promise => promise.catch(error => { failures.push(error); throw error })
210
+ const [storyResult, taskResult] = await Promise.allSettled([
211
+ track(storyStatusOptions(get, workspaceId)), track(get(TASK_FIELDS).then(fieldStatusOptions)),
212
+ ])
213
+ // Cancellation cancels the whole operation. If neither type is usable, preserve the
214
+ // first failure as the existing RPC error rather than reporting an empty success.
215
+ if (signal?.aborted) throw new TapdError('tapd/aborted')
216
+ if (failures.length === 2) throw failures[0]
217
+ const errors = {}
218
+ const read = (kind, result) => {
219
+ if (result.status === 'fulfilled') return result.value
220
+ const code = discoveryErrorCode(result.reason)
221
+ if (code === undefined) throw result.reason
222
+ errors[kind] = code
223
+ return []
224
+ }
225
+ const stories = read('stories', storyResult)
226
+ const tasks = read('tasks', taskResult)
227
+ const taskFailure = taskResult.status === 'rejected' ? taskResult.reason : undefined
228
+ // The documented standard task statuses can be offered as unverified choices only
229
+ // after the same project returned usable story metadata. Never mask an explicit auth,
230
+ // rate-limit, network or server failure; this flag makes no claim about task access.
231
+ const standardTaskOptions = stories.length > 0 && taskFailure && (
232
+ ['tapd/api', 'tapd/malformed'].includes(taskFailure.code)
233
+ || (taskFailure.code === 'tapd/http' && [400, 404, 405, 422, 501].includes(taskFailure.status)))
234
+ return { stories, tasks, ...(failures.length ? { errors } : {}), ...(standardTaskOptions ? { standardTaskOptions: true } : {}) }
235
+ }
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@tavlo-dsh/dsh-plugin-tapd",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.0",
4
+ "description": "将 TAPD 需求和任务单向同步到 Tavlo 任务看板,可按项目指定 DSH 工作区",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public",
8
+ "registry": "https://registry.npmjs.org/"
9
+ },
10
+ "type": "module",
11
+ "icon": "./icon.png",
12
+ "exports": {
13
+ ".": "./index.js",
14
+ "./client": "./lib/client.js",
15
+ "./icon": "./icon.png",
16
+ "./package.json": "./package.json"
17
+ },
18
+ "files": [
19
+ "index.js",
20
+ "runtime.js",
21
+ "settings.js",
22
+ "metadata.js",
23
+ "lib/client.js",
24
+ "lib/client.js.LEGAL.txt",
25
+ "tapd.js",
26
+ "sync.js",
27
+ "icon.png",
28
+ "cordis.patch.yml",
29
+ "tapd.example.patch.yml",
30
+ "licenses/"
31
+ ],
32
+ "engines": {
33
+ "dsh": "0.2.2-rc.1",
34
+ "node": ">=24.0.0"
35
+ },
36
+ "dsh": {
37
+ "bundle": {
38
+ "patch": "./cordis.patch.yml"
39
+ },
40
+ "client": {
41
+ "platform": "web"
42
+ }
43
+ },
44
+ "scripts": {
45
+ "build": "node --check index.js && node --check runtime.js && node --check settings.js && node --check metadata.js && node --check client.js && node --check tapd.js && node --check sync.js && node scripts/build-client.mjs && node --check lib/client.js",
46
+ "test": "node --test tests/*.test.js",
47
+ "prepack": "npm run build"
48
+ },
49
+ "dependencies": {
50
+ "@deepseek-ai/dsh-client-connection": "0.2.2-rc.1",
51
+ "@deepseek-ai/dsh-credentials": "0.2.2-rc.1",
52
+ "@deepseek-ai/dsh-storage-domain": "0.2.2-rc.1",
53
+ "@deepseek-ai/schemastery": "3.19.0",
54
+ "html-to-text": "9.0.5",
55
+ "zod": "4.4.3"
56
+ },
57
+ "devDependencies": {
58
+ "@emotion/is-prop-valid": "1.4.0",
59
+ "@radix-ui/react-accordion": "1.3.1",
60
+ "@radix-ui/react-select": "2.4.1",
61
+ "esbuild": "0.28.2",
62
+ "lucide-react": "0.577.0",
63
+ "motion": "12.43.0",
64
+ "react": "18.3.1",
65
+ "react-dom": "18.3.1"
66
+ }
67
+ }
package/runtime.js ADDED
@@ -0,0 +1,191 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { credentialRef } from '@deepseek-ai/dsh-credentials'
3
+ import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain'
4
+ import { z } from 'zod'
5
+
6
+ export const DEFAULTS = Object.freeze({
7
+ enabled: false, owner: '', projects: [], auth: 'bearer',
8
+ tokenRef: 'TAVLO_TAPD_TOKEN', apiUserRef: 'TAVLO_TAPD_API_USER', apiKeyRef: 'TAVLO_TAPD_API_KEY',
9
+ intervalSeconds: 300, maxNewPerScope: 25,
10
+ })
11
+
12
+ const numericId = z.string().regex(/^[0-9]{1,32}$/)
13
+ const workspaceUuid = z.uuid()
14
+ const statuses = z.array(z.string().regex(/^[A-Za-z0-9_.-]{1,64}$/)).max(32)
15
+ export const projectConfig = z.strictObject({ workspaceId: numericId, stories: statuses, tasks: statuses, targetWorkspaceId: workspaceUuid.optional() })
16
+ const refName = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(128)
17
+ const enabledConfig = z.strictObject({
18
+ enabled: z.literal(true),
19
+ owner: z.string().trim().min(1).max(128).refine(value => !/[<>|;,\p{Cc}]/u.test(value)),
20
+ projects: z.array(projectConfig).min(1).max(20),
21
+ auth: z.enum(['bearer', 'basic']), tokenRef: refName, apiUserRef: refName, apiKeyRef: refName,
22
+ intervalSeconds: z.number().int().min(30).max(86400), maxNewPerScope: z.number().int().min(1).max(1000),
23
+ lookbackDays: z.number().int().min(1).max(365).optional(),
24
+ companyId: numericId.optional(),
25
+ seedWorkspaceId: numericId.optional(),
26
+ })
27
+
28
+ class BridgeFailure extends Error {
29
+ constructor(code) { super(code); this.code = code }
30
+ }
31
+
32
+ /** No credentials, network, timers or storage when disabled or invalid. */
33
+ export function parseConfig(config = {}) {
34
+ const complete = { ...DEFAULTS, ...config }
35
+ if (complete.enabled === false) return null
36
+ const parsed = enabledConfig.safeParse({
37
+ ...complete,
38
+ projects: Array.isArray(complete.projects)
39
+ ? complete.projects.map(project => project && typeof project === 'object'
40
+ ? { stories: [], tasks: [], ...project } : project)
41
+ : complete.projects,
42
+ })
43
+ if (!parsed.success) throw new BridgeFailure('invalid-config')
44
+ const { owner, projects, ...options } = parsed.data
45
+ if (new Set(projects.map(project => project.workspaceId)).size !== projects.length) {
46
+ throw new BridgeFailure('duplicate-project')
47
+ }
48
+ const scopes = projects.flatMap(({ workspaceId, targetWorkspaceId, stories, tasks }) =>
49
+ [['story', stories], ['task', tasks]].filter(([, values]) => values.length)
50
+ .map(([objectType, values]) => ({ workspaceId, objectType, owner, statuses: [...new Set(values)],
51
+ ...(targetWorkspaceId ? { targetWorkspaceId } : {}) })))
52
+ if (!scopes.length) throw new BridgeFailure('missing-scopes')
53
+ return { ...options, scopes }
54
+ }
55
+
56
+ /** Resolve fresh for each round. Never fall back between auth modes or put secrets in a URL. */
57
+ export async function resolveAuthorization(credentials, config, signal) {
58
+ async function read(ref) {
59
+ signal?.throwIfAborted()
60
+ let record
61
+ try { record = await credentials.resolve(credentialRef(ref)) }
62
+ catch { throw new BridgeFailure('credentials-unavailable') }
63
+ signal?.throwIfAborted()
64
+ if (typeof record?.value !== 'string' || !record.value.trim()) throw new BridgeFailure('missing-credentials')
65
+ return record.value
66
+ }
67
+ if (config.auth === 'bearer') return authorizationHeader('bearer', { token: await read(config.tokenRef) })
68
+ return authorizationHeader('basic', { apiUser: await read(config.apiUserRef), apiKey: await read(config.apiKeyRef) })
69
+ }
70
+
71
+ export function authorizationHeader(auth, secret) {
72
+ if (auth === 'bearer') {
73
+ const token = secret.token?.trim()
74
+ if (!token || !/^[-A-Za-z0-9._~+/]+=*$/.test(token)) throw new BridgeFailure('invalid-credentials')
75
+ return `Bearer ${token}`
76
+ }
77
+ const user = secret.apiUser?.trim()
78
+ const key = secret.apiKey
79
+ if (!user || !key?.trim() || /[:\p{Cc}]/u.test(user) || /\p{Cc}/u.test(key)) throw new BridgeFailure('invalid-credentials')
80
+ return `Basic ${Buffer.from(`${user}:${key}`, 'utf8').toString('base64')}`
81
+ }
82
+
83
+ const externalRef = z.strictObject({
84
+ provider: z.literal('tapd'), connectionId: z.uuid(), scopeId: numericId,
85
+ objectType: z.enum(['story', 'task']), objectId: numericId,
86
+ url: z.string(),
87
+ }).superRefine((ref, issue) => {
88
+ const path = ref.objectType === 'story' ? 'stories' : 'tasks'
89
+ if (ref.url !== `https://www.tapd.cn/${ref.scopeId}/prong/${path}/view/${ref.objectId}`) {
90
+ issue.addIssue({ code: 'custom', path: ['url'], message: 'Invalid source URL' })
91
+ }
92
+ })
93
+ const ledgerRecord = z.discriminatedUnion('kind', [
94
+ z.strictObject({ kind: z.literal('imported') }),
95
+ z.strictObject({ kind: z.literal('pending'), input: z.strictObject({
96
+ requestId: z.string().regex(/^[A-Za-z0-9._~-]{1,128}$/), title: z.string().trim().min(1),
97
+ brief: z.string(), dueDate: z.iso.date().optional(), workspaceId: workspaceUuid.optional(), externalRef,
98
+ }) }),
99
+ ])
100
+
101
+ export const tapdDomain = defineDomain({
102
+ name: 'tavlo_tapd_bridge', version: 1, layout: 'per-record',
103
+ global: { initial: {}, schema: z.strictObject({ connectionId: z.uuid().optional() }) },
104
+ tables: { imports: domainTable(ledgerRecord) },
105
+ })
106
+
107
+ /** Only pending intent and lightweight receipt records are persisted; never credentials. */
108
+ export async function connectionLedger(domain, signal) {
109
+ const table = domain.table('imports')
110
+ let { connectionId } = domain.global.get()
111
+ if (!connectionId) {
112
+ if (table.size) throw new BridgeFailure('ledger-invalid')
113
+ signal.throwIfAborted()
114
+ connectionId = randomUUID()
115
+ await domain.global.set({ connectionId })
116
+ }
117
+ function checkIdentity(key, record) {
118
+ if (record?.kind !== 'pending') return
119
+ const ref = record.input.externalRef
120
+ if (ref.connectionId !== connectionId || key !== `${ref.scopeId}:${ref.objectType}:${ref.objectId}`) {
121
+ throw new BridgeFailure('ledger-invalid')
122
+ }
123
+ }
124
+ function storageKey(key) {
125
+ // The JSON per-record backend uses each key as one filesystem component.
126
+ if (!/^[0-9]{1,32}:(story|task):[0-9]{1,32}$/.test(key)) throw new BridgeFailure('ledger-invalid')
127
+ return key.replaceAll(':', '-')
128
+ }
129
+ return {
130
+ connectionId,
131
+ ledger: {
132
+ get(key) {
133
+ const record = table.get(storageKey(key))
134
+ checkIdentity(key, record)
135
+ return record
136
+ },
137
+ put(key, value) {
138
+ signal.throwIfAborted()
139
+ const parsed = ledgerRecord.safeParse(value)
140
+ if (!parsed.success) throw new BridgeFailure('ledger-invalid')
141
+ checkIdentity(key, parsed.data)
142
+ return table.put(storageKey(key), parsed.data)
143
+ },
144
+ },
145
+ }
146
+ }
147
+
148
+ const MAX_TIMER_MS = 2_147_483_647
149
+
150
+ /** Run immediately, then wait after completion (not setInterval). Stop also drains the round. */
151
+ export function startPolling({ intervalMs, run, onError, now = Date.now, schedule = setTimeout, cancel = clearTimeout }) {
152
+ const controller = new AbortController()
153
+ const { signal } = controller
154
+ let timer
155
+ let active
156
+ let stopPromise
157
+
158
+ function arm(deadline) {
159
+ if (signal.aborted) return
160
+ timer = schedule(() => {
161
+ timer = undefined
162
+ if (signal.aborted) return
163
+ if (deadline > now()) { arm(deadline); return }
164
+ tick()
165
+ }, Math.max(0, Math.min(MAX_TIMER_MS, deadline - now())))
166
+ timer?.unref?.()
167
+ }
168
+ function tick() {
169
+ active = (async () => {
170
+ let delay = intervalMs
171
+ try {
172
+ const result = await run(signal)
173
+ const retry = result?.retryAfterMs
174
+ if (Number.isFinite(retry) && retry > delay) delay = Math.min(retry, Number.MAX_SAFE_INTEGER - now())
175
+ } catch (error) {
176
+ if (!signal.aborted) onError(error)
177
+ } finally {
178
+ if (!signal.aborted) arm(now() + delay)
179
+ }
180
+ })()
181
+ }
182
+ arm(now())
183
+ return () => {
184
+ if (!stopPromise) {
185
+ controller.abort()
186
+ if (timer !== undefined) cancel(timer)
187
+ stopPromise = (async () => { await active })()
188
+ }
189
+ return stopPromise
190
+ }
191
+ }