diff --git a/CODEBASE.md b/CODEBASE.md index 9c089d3..b3731fd 100644 --- a/CODEBASE.md +++ b/CODEBASE.md @@ -185,6 +185,10 @@ don't duplicate it here. `runSearch`, `printSearchResults`). See `docs/comms-search.md`. - **`threads.ts`** — `fetchUnreadThreads`, `unreadFlags`; **`public-channels.ts`** — public-channel id cache + `assertChannelIsPublic`. +- **`read-state.ts`** — `runReadStateMutation`, the loop behind every `mark-read` / + `mark-unread` command (bulk refs, `--stdin`, `--yes`, `--dry-run`, `--json` + rows, the per-workspace unread lookup). An entity plugs in through + `ReadStateEntity` (`THREAD_READ_STATE` in `commands/thread/helpers.ts`). - **`spinner.ts`** — re-exports `LoadingSpinner`, `withSpinner`, `startEarlySpinner`, `stopEarlySpinner` from cli-core. - **`completion.ts`** — Commander tree-walker + `parseCompLine`, `getCompletions`, diff --git a/src/commands/thread/helpers.ts b/src/commands/thread/helpers.ts index fa72386..cefdecf 100644 --- a/src/commands/thread/helpers.ts +++ b/src/commands/thread/helpers.ts @@ -1,23 +1,14 @@ -import { requireConfirmation } from '@todoist/cli-core' -import type { CommsApi, Thread } from '@todoist/comms-sdk' +import type { Thread } from '@todoist/comms-sdk' import chalk from 'chalk' -import { getCommsClient, getWorkspaceGroups, getWorkspaceUsers } from '../../lib/api.js' +import { getWorkspaceGroups, getWorkspaceUsers } from '../../lib/api.js' import { formatRelativeDate } from '../../lib/dates.js' -import { CliError } from '../../lib/errors.js' import { isAccessible } from '../../lib/global-args.js' -import { readStdinLines } from '../../lib/input.js' import { renderMarkdown } from '../../lib/markdown.js' -import type { MutationOptions, StdinOptions } from '../../lib/options.js' -import { - colors, - DELETED_COMMENT_TEXT, - deletedBadge, - formatJson, - pinnedBadge, - pluralize, -} from '../../lib/output.js' +import { colors, DELETED_COMMENT_TEXT, deletedBadge, pinnedBadge } from '../../lib/output.js' import { assertChannelIsPublic } from '../../lib/public-channels.js' +import type { ReadStateEntity } from '../../lib/read-state.js' import { partitionNotifyIds, resolveThreadId } from '../../lib/refs.js' +import { fetchUnreadThreads } from '../../lib/threads.js' export function printSeparator(label: string): void { const totalWidth = 60 @@ -97,183 +88,24 @@ export function formatNotifyLabel(items: NamedEntity[]): string { return items.map((i) => `${i.name} (${i.id})`).join(', ') } -// Shared by `mark-read` and `mark-unread`: the bulk-ref loop, the per-workspace -// unread lookup, confirmation, and output. Each verb supplies a per-thread plan. - -export type ReadStateTextStatus = 'changed' | 'preview' | 'unchanged' - -export type ThreadReadState = { - thread: Thread - /** - * Object index of the last comment the user has read, or `null` when the - * thread is fully read (absent from the workspace's unread list). `-1` - * means nothing has been read, including the thread body. - */ - lastReadObjIndex: number | null -} - -export type ReadStatePlan = { - /** Appended to messages, e.g. `' from comment X'`; empty for the whole thread. */ - scope: string - isUnchanged(state: ThreadReadState): boolean - /** JSON row; `outcome` is `'unchanged'` when nothing needs to move. */ - status(state: ThreadReadState, outcome: 'planned' | 'unchanged'): Status - /** Performs the mutation and returns the thread's new `lastReadObjIndex`. */ - apply(client: CommsApi, state: ThreadReadState): Promise -} - -export type ReadStateMutation = { - verb: 'read' | 'unread' - /** Runs on the full ref list (positional plus `--stdin`) before anything is loaded. */ - validateRefs?(rawRefs: string[]): void - /** - * Builds the per-thread plan. Runs before the unread lookup so an invalid - * option (a bad `--from` ref) fails without a workspace-wide request. - */ - plan(client: CommsApi, threadId: string): Promise> -} - -export async function runThreadReadStateMutation( - refs: string[], - options: MutationOptions & StdinOptions, - mutation: ReadStateMutation, -): Promise { - const rawRefs = await collectThreadRefs(refs, options) - if (rawRefs.length === 0) { - throw new CliError( - 'INVALID_REF', - 'No thread references provided. Pass refs as arguments, or pipe them in with --stdin.', - ) - } - mutation.validateRefs?.(rawRefs) - - // One thread runs without --yes; a bulk run needs it. The dry-run and - // preview output stays per thread, so only the guard is shared. - const needsConfirmation = rawRefs.length > 1 && !options.yes && !options.dryRun - if (needsConfirmation) { - requireConfirmation(options, { command: `tdc thread mark-${mutation.verb}` }) - } - - const client = await getCommsClient() - const unreadCache = new Map>() - const jsonStatuses: Status[] = [] - const textStatuses: ReadStateTextStatus[] = [] - - for (const rawRef of rawRefs) { - const threadId = resolveThreadId(rawRef) - const plan = await mutation.plan(client, threadId) - const state = await loadThreadReadState(client, unreadCache, threadId) - const label = threadLabel(state.thread) - - if (plan.isUnchanged(state)) { - jsonStatuses.push(plan.status(state, 'unchanged')) - textStatuses.push('unchanged') - if (!options.json) { - console.log(`Thread ${label} is already ${mutation.verb}${plan.scope}.`) - } - continue - } - - if (needsConfirmation || options.dryRun) { - jsonStatuses.push(plan.status(state, 'planned')) - textStatuses.push('preview') - if (!options.json) { - const prefix = options.dryRun ? 'Dry run: would' : 'Would' - console.log(`${prefix} mark ${mutation.verb} thread ${label}${plan.scope}.`) - } - continue - } - - const lastReadObjIndex = await plan.apply(client, state) - const unreadByThread = unreadCache.get(state.thread.workspaceId) - if (lastReadObjIndex === null) { - unreadByThread?.delete(threadId) - } else { - unreadByThread?.set(threadId, lastReadObjIndex) - } - - jsonStatuses.push(plan.status(state, 'planned')) - textStatuses.push('changed') - if (!options.json) { - console.log(`Thread ${label} marked ${mutation.verb}${plan.scope}.`) - } - } - - if (options.json) { - console.log( - formatJson( - options.dryRun - ? jsonStatuses.map((status) => ({ ...status, dryRun: true })) - : jsonStatuses, - ), - ) - return - } - - if (rawRefs.length > 1) { - printReadStateSummary(textStatuses) - } - - if (needsConfirmation) { - console.log('Use --yes to confirm.') - } -} - -async function collectThreadRefs(refs: string[], options: StdinOptions): Promise { - const inlineRefs = refs.map((ref) => ref.trim()).filter(Boolean) - if (!options.stdin) return inlineRefs - return [...inlineRefs, ...(await readStdinLines())] -} - -/** - * Loads a thread and its unread position. `unreadCache` maps a workspace id to - * its unread threads (`threadId` -> last read `objIndex`) so bulk runs fetch - * the unread list once per workspace. - */ -async function loadThreadReadState( - client: CommsApi, - unreadCache: Map>, - threadId: string, -): Promise { - const thread = await client.threads.getThread(threadId) - await assertChannelIsPublic(thread.channelId, thread.workspaceId) - - let unreadByThread = unreadCache.get(thread.workspaceId) - if (!unreadByThread) { - const unread = await client.threads.getUnread(thread.workspaceId) - unreadByThread = new Map( - unread.data.map((unreadThread) => [unreadThread.threadId, unreadThread.objIndex]), - ) - unreadCache.set(thread.workspaceId, unreadByThread) - } - - return { thread, lastReadObjIndex: unreadByThread.get(thread.id) ?? null } +/** Threads for the shared `mark-read` / `mark-unread` runner in `src/lib/read-state.ts`. */ +export const THREAD_READ_STATE: ReadStateEntity = { + noun: 'thread', + command: 'thread', + resolveId: resolveThreadId, + load: async (client, threadId) => { + const thread = await client.threads.getThread(threadId) + await assertChannelIsPublic(thread.channelId, thread.workspaceId) + return thread + }, + workspaceId: (thread) => thread.workspaceId, + loadUnread: async (client, workspaceId) => { + const unread = await fetchUnreadThreads(client, workspaceId) + return new Map([...unread].map(([threadId, { objIndex }]) => [threadId, objIndex])) + }, + label: threadLabel, } export function threadLabel(thread: Pick): string { return `${thread.title} (${thread.id})` } - -function printReadStateSummary(statuses: ReadStateTextStatus[]): void { - const summary = [ - summarizeStatus(statuses, 'changed'), - summarizeStatus(statuses, 'unchanged'), - summarizeStatus(statuses, 'preview'), - ].filter(Boolean) - - console.log('') - console.log(`Summary: ${summary.join(', ')}`) -} - -function summarizeStatus( - statuses: ReadStateTextStatus[], - status: ReadStateTextStatus, -): string | null { - const count = statuses.filter((value) => value === status).length - if (count === 0) { - return null - } - - const noun = status === 'preview' ? pluralize(count, 'preview') : pluralize(count, 'thread') - return status === 'preview' ? `${count} ${noun}` : `${count} ${status} ${noun}` -} diff --git a/src/commands/thread/read.ts b/src/commands/thread/read.ts index ba78d67..8470e94 100644 --- a/src/commands/thread/read.ts +++ b/src/commands/thread/read.ts @@ -1,6 +1,7 @@ import type { Thread } from '@todoist/comms-sdk' import type { MutationOptions, StdinOptions } from '../../lib/options.js' -import { runThreadReadStateMutation } from './helpers.js' +import { runReadStateMutation } from '../../lib/read-state.js' +import { THREAD_READ_STATE } from './helpers.js' export type MarkThreadReadOptions = MutationOptions & StdinOptions @@ -13,16 +14,16 @@ export async function markThreadRead( refs: string[], options: MarkThreadReadOptions, ): Promise { - await runThreadReadStateMutation(refs, options, { + await runReadStateMutation(THREAD_READ_STATE, refs, options, { verb: 'read', plan: async (_client, threadId) => ({ scope: '', - isUnchanged: (state) => state.lastReadObjIndex === null, + isUnchanged: (state) => state.unreadObjIndex === null, status: () => ({ id: threadId, isRead: true }), apply: async (client, state) => { await client.threads.markRead({ id: threadId, - objIndex: getLatestObjIndex(state.thread), + objIndex: getLatestObjIndex(state.item), }) return null }, diff --git a/src/commands/thread/unread.ts b/src/commands/thread/unread.ts index d789863..9a6ebb4 100644 --- a/src/commands/thread/unread.ts +++ b/src/commands/thread/unread.ts @@ -1,8 +1,9 @@ -import type { CommsApi } from '@todoist/comms-sdk' +import type { CommsApi, Thread } from '@todoist/comms-sdk' import { CliError } from '../../lib/errors.js' import type { MutationOptions, StdinOptions } from '../../lib/options.js' +import { runReadStateMutation } from '../../lib/read-state.js' import { resolveCommentId } from '../../lib/refs.js' -import { runThreadReadStateMutation } from './helpers.js' +import { THREAD_READ_STATE } from './helpers.js' export type MarkThreadUnreadOptions = MutationOptions & StdinOptions & { from?: string } @@ -22,7 +23,7 @@ export async function markThreadUnread( ): Promise { const from = options.from - await runThreadReadStateMutation(refs, options, { + await runReadStateMutation(THREAD_READ_STATE, refs, options, { verb: 'unread', validateRefs: (rawRefs) => { if (from !== undefined && rawRefs.length > 1) { @@ -41,12 +42,12 @@ export async function markThreadUnread( scope: from === undefined ? '' : ` from comment ${from}`, // Already unread at or before the target: nothing to move. isUnchanged: (state) => - state.lastReadObjIndex !== null && state.lastReadObjIndex <= target, + state.unreadObjIndex !== null && state.unreadObjIndex <= target, status: (state, outcome) => ({ id: threadId, isRead: false, lastReadObjIndex: - outcome === 'unchanged' ? (state.lastReadObjIndex ?? target) : target, + outcome === 'unchanged' ? (state.unreadObjIndex ?? target) : target, }), apply: async (client) => { await client.threads.markUnread({ id: threadId, objIndex: target }) diff --git a/src/lib/read-state.ts b/src/lib/read-state.ts new file mode 100644 index 0000000..59e3f40 --- /dev/null +++ b/src/lib/read-state.ts @@ -0,0 +1,208 @@ +import { requireConfirmation } from '@todoist/cli-core' +import type { CommsApi } from '@todoist/comms-sdk' +import { getCommsClient } from './api.js' +import { CliError } from './errors.js' +import { readStdinLines } from './input.js' +import type { MutationOptions, StdinOptions } from './options.js' +import { formatJson, pluralize } from './output.js' + +// Shared by the `mark-read` and `mark-unread` commands: the bulk-ref loop, the +// per-workspace unread lookup, confirmation, and output. Each entity says how to +// load one item and its workspace's unread list; each verb supplies a per-item plan. + +export type ReadStateTextStatus = 'changed' | 'preview' | 'unchanged' + +/** What the runner needs to know about one kind of item, such as a thread. */ +export type ReadStateEntity = { + /** Lower-case singular noun for messages, e.g. `'thread'`. */ + noun: string + /** The command group, e.g. `'thread'` for `tdc thread mark-read`. */ + command: string + resolveId(ref: string): string + /** Loads the item, refusing one the CLI may not act on. */ + load(client: CommsApi, id: string): Promise + workspaceId(item: Item): number + /** The workspace's unread items, each id mapped to its unread `objIndex`. */ + loadUnread(client: CommsApi, workspaceId: number): Promise> + label(item: Item): string +} + +export type ReadState = { + item: Item + /** + * The item's `objIndex` in the workspace's unread list, or `null` when it is + * fully read (absent from the list). What the index points at is the + * entity's own: each entity's commands read it. + */ + unreadObjIndex: number | null +} + +export type ReadStatePlan = { + /** Appended to messages, e.g. `' from comment X'`; empty for the whole item. */ + scope: string + isUnchanged(state: ReadState): boolean + /** JSON row; `outcome` is `'unchanged'` when nothing needs to move. */ + status(state: ReadState, outcome: 'planned' | 'unchanged'): Status + /** Performs the mutation and returns the item's new `unreadObjIndex`. */ + apply(client: CommsApi, state: ReadState): Promise +} + +export type ReadStateMutation = { + verb: 'read' | 'unread' + /** Runs on the full ref list (positional plus `--stdin`) before anything is loaded. */ + validateRefs?(rawRefs: string[]): void + /** + * Builds the per-item plan. Runs before the unread lookup so an invalid + * option (a bad `--from` ref) fails without a workspace-wide request. + */ + plan(client: CommsApi, id: string): Promise> +} + +export async function runReadStateMutation< + Item extends { id: string }, + Status extends { id: string }, +>( + entity: ReadStateEntity, + refs: string[], + options: MutationOptions & StdinOptions, + mutation: ReadStateMutation, +): Promise { + const rawRefs = await collectRefs(refs, options) + if (rawRefs.length === 0) { + throw new CliError( + 'INVALID_REF', + `No ${entity.noun} references provided. Pass refs as arguments, or pipe them in with --stdin.`, + ) + } + mutation.validateRefs?.(rawRefs) + + // One item runs without --yes; a bulk run needs it. The dry-run and + // preview output stays per item, so only the guard is shared. + const needsConfirmation = rawRefs.length > 1 && !options.yes && !options.dryRun + if (needsConfirmation) { + requireConfirmation(options, { command: `tdc ${entity.command} mark-${mutation.verb}` }) + } + + const client = await getCommsClient() + const unreadCache = new Map>() + const jsonStatuses: Status[] = [] + const textStatuses: ReadStateTextStatus[] = [] + const Noun = capitalize(entity.noun) + + for (const rawRef of rawRefs) { + const id = entity.resolveId(rawRef) + const plan = await mutation.plan(client, id) + const state = await loadReadState(entity, client, unreadCache, id) + const label = entity.label(state.item) + + if (plan.isUnchanged(state)) { + jsonStatuses.push(plan.status(state, 'unchanged')) + textStatuses.push('unchanged') + if (!options.json) { + console.log(`${Noun} ${label} is already ${mutation.verb}${plan.scope}.`) + } + continue + } + + if (needsConfirmation || options.dryRun) { + jsonStatuses.push(plan.status(state, 'planned')) + textStatuses.push('preview') + if (!options.json) { + const prefix = options.dryRun ? 'Dry run: would' : 'Would' + console.log(`${prefix} mark ${mutation.verb} ${entity.noun} ${label}${plan.scope}.`) + } + continue + } + + const unreadObjIndex = await plan.apply(client, state) + const unreadById = unreadCache.get(entity.workspaceId(state.item)) + if (unreadObjIndex === null) { + unreadById?.delete(id) + } else { + unreadById?.set(id, unreadObjIndex) + } + + jsonStatuses.push(plan.status(state, 'planned')) + textStatuses.push('changed') + if (!options.json) { + console.log(`${Noun} ${label} marked ${mutation.verb}${plan.scope}.`) + } + } + + if (options.json) { + console.log( + formatJson( + options.dryRun + ? jsonStatuses.map((status) => ({ ...status, dryRun: true })) + : jsonStatuses, + ), + ) + return + } + + if (rawRefs.length > 1) { + printReadStateSummary(entity.noun, textStatuses) + } + + if (needsConfirmation) { + console.log('Use --yes to confirm.') + } +} + +async function collectRefs(refs: string[], options: StdinOptions): Promise { + const inlineRefs = refs.map((ref) => ref.trim()).filter(Boolean) + if (!options.stdin) return inlineRefs + return [...inlineRefs, ...(await readStdinLines())] +} + +/** + * Loads an item and its unread position. `unreadCache` maps a workspace id to + * its unread items (id -> unread `objIndex`) so bulk runs fetch the unread + * list once per workspace. + */ +async function loadReadState( + entity: ReadStateEntity, + client: CommsApi, + unreadCache: Map>, + id: string, +): Promise> { + const item = await entity.load(client, id) + const workspaceId = entity.workspaceId(item) + + let unreadById = unreadCache.get(workspaceId) + if (!unreadById) { + unreadById = await entity.loadUnread(client, workspaceId) + unreadCache.set(workspaceId, unreadById) + } + + return { item, unreadObjIndex: unreadById.get(item.id) ?? null } +} + +function capitalize(word: string): string { + return word.charAt(0).toUpperCase() + word.slice(1) +} + +function printReadStateSummary(noun: string, statuses: ReadStateTextStatus[]): void { + const summary = [ + summarizeStatus(noun, statuses, 'changed'), + summarizeStatus(noun, statuses, 'unchanged'), + summarizeStatus(noun, statuses, 'preview'), + ].filter(Boolean) + + console.log('') + console.log(`Summary: ${summary.join(', ')}`) +} + +function summarizeStatus( + noun: string, + statuses: ReadStateTextStatus[], + status: ReadStateTextStatus, +): string | null { + const count = statuses.filter((value) => value === status).length + if (count === 0) { + return null + } + + const label = status === 'preview' ? pluralize(count, 'preview') : pluralize(count, noun) + return status === 'preview' ? `${count} ${label}` : `${count} ${status} ${label}` +}