-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrefs.ts
More file actions
729 lines (625 loc) · 23.6 KB
/
Copy pathrefs.ts
File metadata and controls
729 lines (625 loc) · 23.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
import type { Channel, Group, Workspace } from '@doist/comms-sdk'
import { fetchWorkspaces, getGroup, getWorkspaceGroups, getCommsClient } from './api.js'
import { CliError, type ErrorCode } from './errors.js'
function normalizeRef(ref: string): string {
return ref.trim()
}
export const SUPPORTED_COMMS_HOSTS = [
'comms.todoist.com',
'comms.staging.todoist.com',
'comms.local.todoist.com',
] as const
export function isSupportedCommsHost(hostname: string): boolean {
return SUPPORTED_COMMS_HOSTS.includes(
hostname.toLowerCase() as (typeof SUPPORTED_COMMS_HOSTS)[number],
)
}
export function isIdRef(ref: string): boolean {
return normalizeRef(ref).startsWith('id:')
}
/**
* Returns the raw id portion of `123`, `id:123`, or `id:abc-xyz`. The Comms
* backend uses numeric ids for users and workspaces and base58 UUIDv7 strings
* for everything else, so this stays string-typed and consumers narrow as
* needed (`Number(...)` for numeric refs after validation).
*/
export function extractId(ref: string): string {
const normalized = normalizeRef(ref)
const idStr = isIdRef(normalized) ? normalized.slice(3).trim() : normalized
if (!idStr) {
throw new CliError('INVALID_ID', `Invalid ID: ${ref}`)
}
return idStr
}
export function extractNumericId(ref: string): number {
const idStr = extractId(ref)
if (!/^\d+$/.test(idStr)) {
throw new CliError('INVALID_ID', `Invalid numeric ID: ${ref}`)
}
return Number(idStr)
}
export function parseNumericIdRefs(refs: string, label = 'reference'): number[] | null {
const ids: number[] = []
for (const rawRef of refs.split(',')) {
const ref = rawRef.trim()
if (!ref) {
throw new CliError('INVALID_REF', `Invalid ${label} reference list: found empty value`)
}
const id = extractId(ref)
if (!/^\d+$/.test(id)) {
return null
}
ids.push(Number(id))
}
return ids
}
export function looksLikeRawId(ref: string): boolean {
const normalized = normalizeRef(ref)
if (!normalized || normalized.includes(' ')) return false
if (!/^[A-Za-z0-9_-]+$/.test(normalized)) return false
return /\d/.test(normalized)
}
function looksLikeOpaqueCommsId(ref: string): boolean {
return /^Cb[A-Za-z0-9_-]{18,}$/.test(ref)
}
function getOpaqueNameId(parsed: ParsedRef): string | null {
return parsed.type === 'name' && looksLikeOpaqueCommsId(parsed.name) ? parsed.name : null
}
export interface ParsedCommsUrl {
workspaceId?: number
channelId?: string
threadId?: string
commentId?: string
conversationId?: string
messageId?: string
}
function parseInboxOrSavedThreadRoute(
routeSegments: readonly string[],
): Pick<ParsedCommsUrl, 'threadId' | 'commentId'> | null {
const [threadMarker, threadId, commentMarker, commentId, ...extraSegments] = routeSegments
if (threadMarker !== 't' || !threadId || extraSegments.length > 0) {
return null
}
if (routeSegments.length === 2) {
return { threadId }
}
if (routeSegments.length === 4 && commentMarker === 'c' && commentId) {
return { threadId, commentId }
}
return null
}
export function parseCommsUrl(url: string): ParsedCommsUrl | null {
try {
const parsed = new URL(url)
if (
(parsed.protocol !== 'http:' && parsed.protocol !== 'https:') ||
!isSupportedCommsHost(parsed.hostname)
) {
return null
}
const segments = parsed.pathname.split('/').filter(Boolean)
const result: ParsedCommsUrl = {}
// Pattern: /a/{workspaceId}/... or /{workspaceId}/...
let routeStart = 0
if (segments[0] === 'a' && /^\d+$/.test(segments[1] ?? '')) {
result.workspaceId = Number(segments[1])
routeStart = 2
} else if (/^\d+$/.test(segments[0] ?? '')) {
result.workspaceId = Number(segments[0])
routeStart = 1
}
const parseRoutePairs = (start: number) => {
for (let index = start; index < segments.length - 1; index += 2) {
const value = segments[index + 1]
switch (segments[index]) {
case 'ch':
result.channelId = value
break
case 't':
result.threadId = value
break
case 'c':
result.commentId = value
break
case 'msg':
result.conversationId = value
break
case 'm':
result.messageId = value
break
}
}
}
const route = segments[routeStart]
if (route === 'inbox' || route === 'saved') {
// Inbox/saved routes only accept:
// t/{thread}
// t/{thread}/c/{comment}
// Other inbox/saved paths stay workspace-only so malformed URLs don't get
// misrouted as thread, comment, or conversation refs.
const threadRoute = parseInboxOrSavedThreadRoute(segments.slice(routeStart + 1))
if (threadRoute) {
result.threadId = threadRoute.threadId
if (threadRoute.commentId) {
result.commentId = threadRoute.commentId
}
}
} else {
parseRoutePairs(routeStart)
}
return Object.keys(result).length > 0 ? result : null
} catch {
return null
}
}
export type ParsedRef =
| { type: 'id'; id: string }
| { type: 'url'; parsed: ParsedCommsUrl }
| { type: 'name'; name: string }
export function parseRef(ref: string): ParsedRef {
const normalized = normalizeRef(ref)
if (isIdRef(normalized)) {
return { type: 'id', id: extractId(normalized) }
}
if (normalized.startsWith('http://') || normalized.startsWith('https://')) {
const parsed = parseCommsUrl(normalized)
if (parsed) {
return { type: 'url', parsed }
}
}
if (looksLikeRawId(normalized)) {
return { type: 'id', id: normalized }
}
return { type: 'name', name: normalized }
}
/**
* Match an entity by name: exact (case-insensitive) → unique substring → ambiguous/not-found.
*/
function matchByName<T extends { id: number | string; name: string }>(
items: T[],
query: string,
opts: {
ambiguousCode: ErrorCode
notFoundCode: ErrorCode
ref: string
listHint: string
},
): T {
const lower = query.toLowerCase()
const exact = items.find((item) => item.name.toLowerCase() === lower)
if (exact) return exact
const partial = items.filter((item) => item.name.toLowerCase().includes(lower))
if (partial.length === 1) return partial[0]
if (partial.length > 1) {
const matches = partial
.slice(0, 5)
.map((item) => `"${item.name}" (id:${item.id})`)
.join(', ')
throw new CliError(opts.ambiguousCode, `Multiple matches for "${opts.ref}": ${matches}`, [
'Use the numeric ID (e.g. id:123) to specify exactly which one.',
])
}
throw new CliError(opts.notFoundCode, `"${opts.ref}" not found`, [opts.listHint])
}
export async function resolveWorkspaceRef(ref: string): Promise<Workspace> {
const workspaces = await fetchWorkspaces()
const parsed = parseRef(ref)
if (parsed.type === 'id') {
const numericId = Number(parsed.id)
if (!Number.isFinite(numericId)) {
throw new CliError('WORKSPACE_NOT_FOUND', `Workspace with ID ${parsed.id} not found`, [
'Run: tdc workspaces to list available workspaces',
])
}
const workspace = workspaces.find((w) => w.id === numericId)
if (!workspace) {
throw new CliError('WORKSPACE_NOT_FOUND', `Workspace with ID ${parsed.id} not found`, [
'Run: tdc workspaces to list available workspaces',
])
}
return workspace
}
if (parsed.type === 'url' && parsed.parsed.workspaceId) {
const workspace = workspaces.find((w) => w.id === parsed.parsed.workspaceId)
if (!workspace) {
throw new CliError(
'WORKSPACE_NOT_FOUND',
`Workspace with ID ${parsed.parsed.workspaceId} not found`,
['Run: tdc workspaces to list available workspaces'],
)
}
return workspace
}
if (parsed.type === 'name') {
return matchByName(workspaces, parsed.name, {
ambiguousCode: 'AMBIGUOUS_WORKSPACE',
notFoundCode: 'WORKSPACE_NOT_FOUND',
ref,
listHint: 'Run: tdc workspaces to list available workspaces',
})
}
throw new CliError('WORKSPACE_NOT_FOUND', `Workspace "${ref}" not found`, [
'Run: tdc workspaces to list available workspaces',
])
}
export function resolveThreadId(ref: string): string {
const parsed = parseRef(ref)
if (parsed.type === 'id') {
return parsed.id
}
if (parsed.type === 'url' && parsed.parsed.threadId) {
return parsed.parsed.threadId
}
const opaqueId = getOpaqueNameId(parsed)
if (opaqueId) return opaqueId
throw new CliError(
'INVALID_REF',
`Invalid thread reference: ${ref}. Use an id, id:<id>, or a Comms URL.`,
)
}
function assertChannelInWorkspace(channel: Channel, workspaceId: number): void {
if (channel.workspaceId !== workspaceId) {
throw new CliError(
'CHANNEL_NOT_FOUND',
`Channel ${channel.id} does not belong to workspace ${workspaceId}`,
)
}
}
export async function resolveChannelRef(ref: string, workspaceId: number): Promise<Channel> {
const parsed = parseRef(ref)
const client = await getCommsClient()
if (parsed.type === 'id') {
const channel = await client.channels.getChannel(parsed.id)
assertChannelInWorkspace(channel, workspaceId)
return channel
}
if (parsed.type === 'url' && parsed.parsed.channelId) {
if (parsed.parsed.workspaceId && parsed.parsed.workspaceId !== workspaceId) {
throw new CliError(
'CHANNEL_NOT_FOUND',
`Channel URL belongs to workspace ${parsed.parsed.workspaceId}, but the current workspace is ${workspaceId}`,
['Pass the matching workspace-ref or use the default workspace that owns the URL.'],
)
}
const channel = await client.channels.getChannel(parsed.parsed.channelId)
assertChannelInWorkspace(channel, workspaceId)
return channel
}
if (parsed.type === 'name') {
// getChannels is membership-scoped — only channels the current user has joined
// (active + archived). Try an exact match against that list first; the common
// case (user types a channel they're in) returns without the workspace-wide
// getPublicChannels call. Fall through only when we need the unjoined-public
// set — for unjoined-but-public matches or cross-list substring resolution.
const joined = await client.channels.getChannels({ workspaceId })
const lowerName = parsed.name.toLowerCase()
const exactJoined = joined.find((channel) => channel.name.toLowerCase() === lowerName)
if (exactJoined) return exactJoined
// getPublicChannels is workspace-scoped (all public channels regardless of
// membership). Merge and dedupe by id so a joined-and-public channel doesn't
// match twice through matchByName's substring path.
const publicChannels = await client.workspaces.getPublicChannels(workspaceId)
const joinedIds = new Set(joined.map((channel) => channel.id))
const channels = [
...joined,
...publicChannels.filter((channel) => !joinedIds.has(channel.id)),
]
return matchByName(channels, parsed.name, {
ambiguousCode: 'AMBIGUOUS_CHANNEL',
notFoundCode: 'CHANNEL_NOT_FOUND',
ref,
listHint: 'Run: tdc channels to list available channels',
})
}
throw new CliError('CHANNEL_NOT_FOUND', `Channel "${ref}" not found`, [
'Run: tdc channels to list available channels',
])
}
export function resolveChannelId(ref: string): string {
const channelId = getDirectChannelId(ref)
if (channelId) return channelId
throw new CliError(
'INVALID_REF',
`Invalid channel reference: ${ref}. Use an id, id:<id>, or a Comms URL.`,
)
}
export function getDirectChannelId(ref: string): string | null {
const parsed = parseRef(ref)
if (parsed.type === 'id') {
return parsed.id
}
if (parsed.type === 'url') {
if (parsed.parsed.channelId) {
return parsed.parsed.channelId
}
throw new CliError(
'INVALID_REF',
`Invalid channel reference: ${ref}. Use an id, id:<id>, or a Comms URL.`,
)
}
const opaqueId = getOpaqueNameId(parsed)
if (opaqueId) return opaqueId
return null
}
export function resolveCommentId(ref: string): string {
const parsed = parseRef(ref)
if (parsed.type === 'id') {
return parsed.id
}
if (parsed.type === 'url' && parsed.parsed.commentId) {
return parsed.parsed.commentId
}
const opaqueId = getOpaqueNameId(parsed)
if (opaqueId) return opaqueId
throw new CliError(
'INVALID_REF',
`Invalid comment reference: ${ref}. Use an id, id:<id>, or a Comms URL.`,
)
}
export function resolveConversationId(ref: string): string {
const parsed = parseRef(ref)
if (parsed.type === 'id') {
return parsed.id
}
if (parsed.type === 'url' && parsed.parsed.conversationId) {
return parsed.parsed.conversationId
}
const opaqueId = getOpaqueNameId(parsed)
if (opaqueId) return opaqueId
throw new CliError(
'INVALID_REF',
`Invalid conversation reference: ${ref}. Use an id, id:<id>, or a Comms URL.`,
)
}
export function resolveMessageId(ref: string): string {
const parsed = parseRef(ref)
if (parsed.type === 'id') {
return parsed.id
}
if (parsed.type === 'url' && parsed.parsed.messageId) {
return parsed.parsed.messageId
}
const opaqueId = getOpaqueNameId(parsed)
if (opaqueId) return opaqueId
throw new CliError(
'INVALID_REF',
`Invalid message reference: ${ref}. Use an id, id:<id>, or a Comms URL.`,
)
}
export type CommsUrlRoute = {
entityType: 'message' | 'conversation' | 'comment' | 'thread'
url: string
}
export function classifyCommsUrl(url: string): CommsUrlRoute | null {
const parsed = parseCommsUrl(url)
if (!parsed) return null
if (parsed.messageId) return { entityType: 'message', url }
if (parsed.conversationId && !parsed.messageId) return { entityType: 'conversation', url }
if (parsed.commentId) return { entityType: 'comment', url }
if (parsed.threadId && !parsed.commentId) return { entityType: 'thread', url }
return null
}
/**
* Split a list of notify refs into numeric user IDs and base58 group IDs by
* checking each ref against the workspace's known group IDs. Anything not in
* the group set is treated as a user ID and parsed as a number.
*/
export function partitionNotifyIds(
ids: readonly string[],
groupIds: ReadonlySet<string>,
): { userIds: number[]; groupIds: string[] } {
const users: number[] = []
const groups: string[] = []
for (const id of ids) {
if (groupIds.has(id)) {
groups.push(id)
continue
}
const num = Number(id)
if (!Number.isFinite(num) || !/^\d+$/.test(id)) {
throw new CliError(
'INVALID_REF',
`Invalid notify ID "${id}": expected a numeric user ID or a known group ID.`,
)
}
users.push(num)
}
return { userIds: users, groupIds: groups }
}
/**
* Parse a comma-separated list of notify refs into raw IDs (untyped — callers
* use {@link partitionNotifyIds} to split into users vs. groups).
*/
export function parseNotifyIdRefs(refs: string): string[] {
return refs.split(',').map((userRef) => {
const trimmed = userRef.trim()
if (!trimmed) {
throw new CliError('INVALID_REF', 'Invalid notify reference list: found empty value')
}
try {
return extractId(trimmed)
} catch {
throw new CliError(
'INVALID_REF',
`Invalid notify reference: ${trimmed}. Use a user or group id.`,
)
}
})
}
export async function resolveGroupRef(ref: string, workspaceId: number): Promise<Group> {
const parsed = parseRef(ref)
if (parsed.type === 'id') {
try {
const group = await getGroup(parsed.id, workspaceId)
if (group.workspaceId !== workspaceId) {
throw new CliError(
'GROUP_NOT_FOUND',
`Group ${parsed.id} does not belong to workspace ${workspaceId}`,
)
}
return group
} catch (error) {
if (error instanceof CliError) throw error
throw new CliError('GROUP_NOT_FOUND', `Group with ID ${parsed.id} not found`, [
'Run: tdc groups to list available groups',
])
}
}
if (parsed.type === 'name') {
const groups = await getWorkspaceGroups(workspaceId)
return matchByName(groups, parsed.name, {
ambiguousCode: 'AMBIGUOUS_GROUP',
notFoundCode: 'GROUP_NOT_FOUND',
ref,
listHint: 'Run: tdc groups to list available groups',
})
}
throw new CliError('GROUP_NOT_FOUND', `Group "${ref}" not found`, [
'Run: tdc groups to list available groups',
])
}
export type ChannelMemberRefs = {
userIds: number[]
expandedFrom: { groupId: string; groupName: string; userIds: number[] }[]
}
const GROUP_REF_PREFIX = 'group:'
/**
* Resolve a mixed list of user and `group:<ref>` references for channel membership.
*
* Groups are expanded to their current `userIds` at call time. The group itself
* is not persistently linked to the channel — callers should surface that
* caveat in user-facing help text.
*
* Returns deduped userIds in input order, with a parallel `expandedFrom` list
* recording which groups contributed (and which users each group brought in,
* pre-dedup) for reporting purposes.
*/
export async function resolveChannelMemberRefs(
refs: string[],
workspaceId: number,
): Promise<ChannelMemberRefs> {
if (refs.length === 0) {
throw new CliError('MISSING_USERS', 'Provide at least one user or group:<ref> reference.')
}
type Slot =
| { kind: 'user'; ref: string; index: number }
| { kind: 'group'; ref: string; index: number }
const slots: Slot[] = refs.map((ref, index) => {
const trimmed = normalizeRef(ref)
if (trimmed.toLowerCase().startsWith(GROUP_REF_PREFIX)) {
const inner = trimmed.slice(GROUP_REF_PREFIX.length).trim()
if (!inner) {
throw new CliError(
'INVALID_REF',
`Empty group reference: "${ref}". Use group:<id|name>.`,
)
}
return { kind: 'group', ref: inner, index }
}
return { kind: 'user', ref: trimmed, index }
})
const userSlots = slots.filter((s): s is Extract<Slot, { kind: 'user' }> => s.kind === 'user')
const groupSlots = slots.filter(
(s): s is Extract<Slot, { kind: 'group' }> => s.kind === 'group',
)
// A group ref resolves by id (single fetch) or by name (matched against the
// workspace group list). Split here so name refs share one list fetch
// instead of re-fetching the whole list per ref.
const groupIdSlots = groupSlots.filter((s) => parseRef(s.ref).type === 'id')
const groupNameSlots = groupSlots.filter((s) => parseRef(s.ref).type !== 'id')
// Resolve each user slot individually (a single ref may expand to several
// ids, e.g. a comma list or a name match), all groups by id, and the
// workspace group list (once, only when there are name refs) concurrently.
const [userIdsPerSlot, idGroups, workspaceGroups] = await Promise.all([
Promise.all(userSlots.map((s) => resolveUserRefs(s.ref, workspaceId))),
Promise.all(groupIdSlots.map((s) => resolveGroupRef(s.ref, workspaceId))),
groupNameSlots.length > 0
? getWorkspaceGroups(workspaceId)
: Promise.resolve([] as Group[]),
])
const userIdsByIndex = new Map<number, number[]>()
userSlots.forEach((s, i) => {
userIdsByIndex.set(s.index, userIdsPerSlot[i])
})
const groupByIndex = new Map<number, Group>()
groupIdSlots.forEach((s, i) => {
groupByIndex.set(s.index, idGroups[i])
})
for (const s of groupNameSlots) {
groupByIndex.set(
s.index,
matchByName(workspaceGroups, s.ref, {
ambiguousCode: 'AMBIGUOUS_GROUP',
notFoundCode: 'GROUP_NOT_FOUND',
ref: s.ref,
listHint: 'Run: tdc groups to list available groups',
}),
)
}
// Walk the original input order to assemble dedup'd userIds and expandedFrom.
const expandedFrom: ChannelMemberRefs['expandedFrom'] = []
const seen = new Set<number>()
const userIds: number[] = []
const pushId = (id: number) => {
if (!seen.has(id)) {
seen.add(id)
userIds.push(id)
}
}
for (let i = 0; i < refs.length; i++) {
const slotUserIds = userIdsByIndex.get(i)
if (slotUserIds) {
for (const id of slotUserIds) pushId(id)
continue
}
const group = groupByIndex.get(i)
if (!group) continue
expandedFrom.push({
groupId: group.id,
groupName: group.name,
userIds: [...group.userIds],
})
for (const id of group.userIds) pushId(id)
}
return { userIds, expandedFrom }
}
export async function resolveUserRefs(refs: string, workspaceId: number): Promise<number[]> {
const numericIds = parseNumericIdRefs(refs, 'user')
if (numericIds) return numericIds
const { getWorkspaceUsers } = await import('./api.js')
const users = await getWorkspaceUsers(workspaceId)
const parts = refs.split(',').map((r) => r.trim())
const ids: number[] = []
for (const ref of parts) {
const parsed = parseRef(ref)
if (parsed.type === 'id') {
const num = Number(parsed.id)
if (!Number.isFinite(num) || !/^\d+$/.test(parsed.id)) {
throw new CliError('INVALID_REF', `Invalid user ID: ${ref}`)
}
ids.push(num)
continue
}
const query = ref.toLowerCase()
const matches = users.filter(
(u) =>
u.fullName.toLowerCase().includes(query) || u.email?.toLowerCase().includes(query),
)
if (matches.length === 0) {
throw new CliError('USER_NOT_FOUND', `No user found matching "${ref}"`, [
'Run: tdc users to list workspace members',
])
}
if (matches.length > 1) {
const list = matches
.map((u) => ` ${u.id} ${u.fullName} <${u.email ?? ''}>`)
.join('\n')
throw new CliError(
'AMBIGUOUS_USER',
`Multiple users match "${ref}":\n${list}\n\nUse numeric ID to specify.`,
)
}
ids.push(matches[0].id)
}
return ids
}