@todoist/comms-sdk 0.0.1 → 5.0.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 (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +182 -39
  3. package/dist/esm/authentication.js +247 -0
  4. package/dist/esm/clients/add-comment-helper.js +41 -0
  5. package/dist/esm/clients/attachments-client.js +99 -0
  6. package/dist/esm/clients/base-client.js +30 -0
  7. package/dist/esm/clients/channels-client.js +209 -0
  8. package/dist/esm/clients/comments-client.js +177 -0
  9. package/dist/esm/clients/conversation-messages-client.js +167 -0
  10. package/dist/esm/clients/conversations-client.js +281 -0
  11. package/dist/esm/clients/groups-client.js +170 -0
  12. package/dist/esm/clients/hooks-client.js +50 -0
  13. package/dist/esm/clients/inbox-client.js +186 -0
  14. package/dist/esm/clients/notify-audience.js +43 -0
  15. package/dist/esm/clients/reactions-client.js +96 -0
  16. package/dist/esm/clients/search-client.js +140 -0
  17. package/dist/esm/clients/threads-client.js +363 -0
  18. package/dist/esm/clients/users-client.js +368 -0
  19. package/dist/esm/clients/workspace-users-client.js +299 -0
  20. package/dist/esm/clients/workspaces-client.js +177 -0
  21. package/dist/esm/comms-api.js +67 -0
  22. package/dist/esm/consts/endpoints.js +31 -0
  23. package/dist/esm/index.js +20 -0
  24. package/dist/esm/migration.js +92 -0
  25. package/dist/esm/testUtils/msw-handlers.js +45 -0
  26. package/dist/esm/testUtils/msw-setup.js +32 -0
  27. package/dist/esm/testUtils/obsidian-fetch-adapter.js +50 -0
  28. package/dist/esm/testUtils/test-defaults.js +103 -0
  29. package/dist/esm/transport/fetch-with-retry.js +240 -0
  30. package/dist/esm/transport/http-client.js +53 -0
  31. package/dist/esm/transport/http-dispatcher.js +149 -0
  32. package/dist/esm/types/api-version.js +5 -0
  33. package/dist/esm/types/entities.js +515 -0
  34. package/dist/esm/types/enums.js +34 -0
  35. package/dist/esm/types/errors.js +82 -0
  36. package/dist/esm/types/http.js +1 -0
  37. package/dist/esm/types/index.js +6 -0
  38. package/dist/esm/types/requests.js +184 -0
  39. package/dist/esm/utils/case-conversion.js +47 -0
  40. package/dist/esm/utils/conversation-title.js +110 -0
  41. package/dist/esm/utils/headers.js +29 -0
  42. package/dist/esm/utils/index.js +5 -0
  43. package/dist/esm/utils/multipart-upload.js +198 -0
  44. package/dist/esm/utils/reply-recipients.js +111 -0
  45. package/dist/esm/utils/timestamp-conversion.js +54 -0
  46. package/dist/esm/utils/url-helpers.js +202 -0
  47. package/dist/esm/utils/uuidv7.js +170 -0
  48. package/dist/types/authentication.d.ts +183 -0
  49. package/dist/types/clients/add-comment-helper.d.ts +32 -0
  50. package/dist/types/clients/attachments-client.d.ts +55 -0
  51. package/dist/types/clients/base-client.d.ts +37 -0
  52. package/dist/types/clients/channels-client.d.ts +211 -0
  53. package/dist/types/clients/comments-client.d.ts +228 -0
  54. package/dist/types/clients/conversation-messages-client.d.ts +201 -0
  55. package/dist/types/clients/conversations-client.d.ts +366 -0
  56. package/dist/types/clients/groups-client.d.ts +148 -0
  57. package/dist/types/clients/hooks-client.d.ts +29 -0
  58. package/dist/types/clients/inbox-client.d.ts +478 -0
  59. package/dist/types/clients/notify-audience.d.ts +22 -0
  60. package/dist/types/clients/reactions-client.d.ts +57 -0
  61. package/dist/types/clients/search-client.d.ts +71 -0
  62. package/dist/types/clients/threads-client.d.ts +547 -0
  63. package/dist/types/clients/users-client.d.ts +280 -0
  64. package/dist/types/clients/workspace-users-client.d.ts +172 -0
  65. package/dist/types/clients/workspaces-client.d.ts +154 -0
  66. package/dist/types/comms-api.d.ts +73 -0
  67. package/dist/types/consts/endpoints.d.ts +27 -0
  68. package/dist/types/index.d.ts +21 -0
  69. package/dist/types/migration.d.ts +78 -0
  70. package/dist/types/testUtils/msw-handlers.d.ts +28 -0
  71. package/dist/types/testUtils/msw-setup.d.ts +1 -0
  72. package/dist/types/testUtils/obsidian-fetch-adapter.d.ts +29 -0
  73. package/dist/types/testUtils/test-defaults.d.ts +17 -0
  74. package/dist/types/transport/fetch-with-retry.d.ts +4 -0
  75. package/dist/types/transport/http-client.d.ts +14 -0
  76. package/dist/types/transport/http-dispatcher.d.ts +46 -0
  77. package/dist/types/types/api-version.d.ts +6 -0
  78. package/dist/types/types/entities.d.ts +3081 -0
  79. package/dist/types/types/enums.d.ts +55 -0
  80. package/dist/types/types/errors.d.ts +57 -0
  81. package/dist/types/types/http.d.ts +60 -0
  82. package/dist/types/types/index.d.ts +6 -0
  83. package/dist/types/types/requests.d.ts +604 -0
  84. package/dist/types/utils/case-conversion.d.ts +8 -0
  85. package/dist/types/utils/conversation-title.d.ts +84 -0
  86. package/dist/types/utils/headers.d.ts +13 -0
  87. package/dist/types/utils/index.d.ts +6 -0
  88. package/dist/types/utils/multipart-upload.d.ts +59 -0
  89. package/dist/types/utils/reply-recipients.d.ts +60 -0
  90. package/dist/types/utils/timestamp-conversion.d.ts +13 -0
  91. package/dist/types/utils/url-helpers.d.ts +129 -0
  92. package/dist/types/utils/uuidv7.d.ts +42 -0
  93. package/package.json +80 -8
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Converts a Unix timestamp (in seconds) to a Date object.
3
+ * @param timestamp - Unix timestamp in seconds
4
+ * @returns Date object
5
+ */
6
+ export function timestampToDate(timestamp) {
7
+ return new Date(timestamp * 1000);
8
+ }
9
+ const timestampFieldTargetOverrides = new Map([['pinnedTs', 'pinnedDate']]);
10
+ /**
11
+ * Recursively transforms timestamp fields (ending in 'Ts') in an object to Date objects.
12
+ * Also renames converted fields by removing the 'Ts' suffix.
13
+ * @param obj - The object to transform
14
+ * @returns The transformed object with Date fields
15
+ */
16
+ export function transformTimestamps(obj) {
17
+ if (obj === null || obj === undefined) {
18
+ return obj;
19
+ }
20
+ if (Array.isArray(obj)) {
21
+ return obj.map((item) => transformTimestamps(item));
22
+ }
23
+ if (typeof obj === 'object') {
24
+ const result = {};
25
+ for (const [key, value] of Object.entries(obj)) {
26
+ // Check if the key ends with 'Ts'
27
+ if (key.endsWith('Ts')) {
28
+ const overriddenTargetKey = timestampFieldTargetOverrides.get(key);
29
+ if (typeof value === 'number') {
30
+ // Remove 'Ts' suffix and convert to Date
31
+ const newKey = key.slice(0, -2);
32
+ // If the base key already exists in the original object, use *Date suffix
33
+ // to avoid overwriting it (e.g. posted + postedTs → posted + postedDate)
34
+ const targetKey = overriddenTargetKey ??
35
+ (newKey in obj ? `${newKey}Date` : newKey);
36
+ result[targetKey] = timestampToDate(value);
37
+ continue;
38
+ }
39
+ if (overriddenTargetKey) {
40
+ result[overriddenTargetKey] = value;
41
+ continue;
42
+ }
43
+ }
44
+ if (typeof value === 'object' && value !== null) {
45
+ // Recursively transform nested objects
46
+ result[key] = transformTimestamps(value);
47
+ continue;
48
+ }
49
+ result[key] = value;
50
+ }
51
+ return result;
52
+ }
53
+ return obj;
54
+ }
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Helper functions for creating Comms permalinks (`https://comms.todoist.com/...`).
3
+ *
4
+ * Paths come from `@doist/sdk-kmp`, the shared implementation of Comms link
5
+ * routes, so they stay in step with the other Comms clients. The path builders
6
+ * are used rather than the URL builders so that `getFullCommsURL` can keep
7
+ * serving an arbitrary base URL.
8
+ */
9
+ import { commsChannelPath, commsConversationPath, commsInboxThreadCommentPath, commsInboxThreadPath, commsMessagePath, commsSavedThreadCommentPath, commsSavedThreadPath, commsThreadCommentPath, commsThreadPath, parseCommsLink, } from '@doist/sdk-kmp/comms';
10
+ const COMMS_BASE_URL = 'https://comms.todoist.com';
11
+ /**
12
+ * Builds a path, falling back to a locally built path when the link builder
13
+ * rejects one of the given ids. These helpers run while parsing API responses,
14
+ * so building a path must never fail the parse.
15
+ *
16
+ * Every error is caught, not just id rejection. The link builders expose no
17
+ * error type to narrow on, and a path is never important enough to fail a
18
+ * parse over, so any failure degrades to the locally built path.
19
+ *
20
+ * @param build Builds the path.
21
+ * @param fallback Builds the path without the shared link builder.
22
+ * @returns The built path, or the locally built path if an id was rejected.
23
+ */
24
+ function buildPath(build, fallback) {
25
+ try {
26
+ return build();
27
+ }
28
+ catch {
29
+ return fallback();
30
+ }
31
+ }
32
+ /**
33
+ * Builds a relative Comms URL based on the provided parameters
34
+ * @param params - URL parameters including workspace, channel, conversation, thread, etc.
35
+ * @returns A relative URL path
36
+ * @example
37
+ * getCommsURL({ workspaceId: 1, channelId: '7Yp...', threadId: '7Yq...' })
38
+ * // returns '/1/ch/7Yp.../t/7Yq.../'
39
+ */
40
+ export function getCommsURL(params) {
41
+ const { workspaceId, channelId, conversationId, threadId, commentId, messageId, userId } = params;
42
+ const workspace = String(workspaceId);
43
+ if (channelId) {
44
+ if (threadId && commentId) {
45
+ return buildPath(() => commsThreadCommentPath(workspace, channelId, threadId, commentId), () => `/${workspace}/ch/${channelId}/t/${threadId}/c/${commentId}`);
46
+ }
47
+ if (threadId) {
48
+ return buildPath(() => commsThreadPath(workspace, channelId, threadId), () => `/${workspace}/ch/${channelId}/t/${threadId}/`);
49
+ }
50
+ return buildPath(() => commsChannelPath(workspace, channelId), () => `/${workspace}/ch/${channelId}/`);
51
+ }
52
+ if (threadId) {
53
+ if (commentId) {
54
+ return buildPath(() => commsInboxThreadCommentPath(workspace, threadId, commentId), () => `/${workspace}/inbox/t/${threadId}/c/${commentId}`);
55
+ }
56
+ return buildPath(() => commsInboxThreadPath(workspace, threadId), () => `/${workspace}/inbox/t/${threadId}/`);
57
+ }
58
+ if (conversationId) {
59
+ if (messageId) {
60
+ return buildPath(() => commsMessagePath(workspace, conversationId, messageId), () => `/${workspace}/msg/${conversationId}/m/${messageId}`);
61
+ }
62
+ return buildPath(() => commsConversationPath(workspace, conversationId), () => `/${workspace}/msg/${conversationId}/`);
63
+ }
64
+ // The people view and the bare workspace root have no shared route.
65
+ if (userId) {
66
+ return `/${workspace}/people/u/${userId}`;
67
+ }
68
+ return `/${workspace}/`;
69
+ }
70
+ /**
71
+ * Builds a full Comms URL (with protocol and hostname) based on the provided parameters
72
+ * @param params - URL parameters including workspace, channel, conversation, thread, etc.
73
+ * @param baseUrl - Optional base URL (defaults to 'https://comms.todoist.com')
74
+ */
75
+ export function getFullCommsURL(params, baseUrl = COMMS_BASE_URL) {
76
+ // Strip a trailing slash so links don't double up — `getCommsURL` paths start with '/'.
77
+ const normalizedBase = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
78
+ return `${normalizedBase}${getCommsURL(params)}`;
79
+ }
80
+ /** Returns the URL for a thread in a channel. */
81
+ export function getThreadURL(params) {
82
+ return getCommsURL(params);
83
+ }
84
+ /** Returns the URL for a channel. */
85
+ export function getChannelURL(params) {
86
+ return getCommsURL(params);
87
+ }
88
+ /** Returns the URL for a conversation. */
89
+ export function getConversationURL(params) {
90
+ return getCommsURL(params);
91
+ }
92
+ /** Returns the URL for a specific message in a conversation. */
93
+ export function getMessageURL(params) {
94
+ return getCommsURL(params);
95
+ }
96
+ /** Returns the URL for a comment in a thread. */
97
+ export function getCommentURL(params) {
98
+ return getCommsURL(params);
99
+ }
100
+ /** Returns the URL for the threads root (channels view). */
101
+ export function getThreadsRootURL(workspaceId) {
102
+ return `/${workspaceId}/ch`;
103
+ }
104
+ /** Returns the URL for the inbox. */
105
+ export function getInboxURL(workspaceId, tab) {
106
+ const tabParam = tab ? `/${tab}` : '';
107
+ return `/${workspaceId}/inbox${tabParam}`;
108
+ }
109
+ /** Returns the URL for the messages/conversations root. */
110
+ export function getMessagesRootURL(workspaceId) {
111
+ return `/${workspaceId}/msg`;
112
+ }
113
+ /** Returns the URL for a user profile. */
114
+ export function getUserProfileURL(params) {
115
+ return `/${params.workspaceId}/people/u/${params.userId}`;
116
+ }
117
+ /** Returns the URL for the saved threads view. */
118
+ export function getSavedThreadsRootURL(workspaceId) {
119
+ return `/${workspaceId}/saved`;
120
+ }
121
+ /** Returns the URL for a saved thread. */
122
+ export function getSavedThreadURL(params) {
123
+ const workspace = String(params.workspaceId);
124
+ return buildPath(() => commsSavedThreadPath(workspace, params.threadId), () => `/${workspace}/saved/t/${params.threadId}`);
125
+ }
126
+ /** Returns the URL for a comment on a saved thread. */
127
+ export function getSavedThreadCommentURL(params) {
128
+ const workspace = String(params.workspaceId);
129
+ return buildPath(() => commsSavedThreadCommentPath(workspace, params.threadId, params.commentId), () => `/${workspace}/saved/t/${params.threadId}/c/${params.commentId}`);
130
+ }
131
+ /** Returns the URL for the search root. */
132
+ export function getSearchRootURL(workspaceId) {
133
+ return `/${workspaceId}/search`;
134
+ }
135
+ /** Returns the URL for a search with a query. */
136
+ export function getSearchQueryURL(params) {
137
+ return `/${params.workspaceId}/search?q=${decodeURIComponent(params.query)}`;
138
+ }
139
+ /** Returns the URL for settings. */
140
+ export function getSettingsURL(params) {
141
+ return params.initialLocation
142
+ ? `/${params.workspaceId}/settings/${params.initialLocation}`
143
+ : `/${params.workspaceId}/settings`;
144
+ }
145
+ /** Returns the URL for the team members root. */
146
+ export function getTeamMembersRootURL(workspaceId) {
147
+ return `/${workspaceId}/people/u`;
148
+ }
149
+ /** The kinds of Comms entity a URL can point at. */
150
+ export const COMMS_LINK_TYPES = [
151
+ 'channel',
152
+ 'thread',
153
+ 'thread_comment',
154
+ 'inbox_thread',
155
+ 'inbox_thread_comment',
156
+ 'saved_thread',
157
+ 'saved_thread_comment',
158
+ 'conversation',
159
+ 'message',
160
+ ];
161
+ /**
162
+ * Maps the link parser's type names onto the types this SDK exposes. A name
163
+ * that is missing here is one this SDK does not know about, and is treated as
164
+ * an unrecognised URL rather than surfaced as a value outside the union.
165
+ */
166
+ const LINK_TYPE_BY_PARSED_NAME = {
167
+ Channel: 'channel',
168
+ Thread: 'thread',
169
+ ThreadComment: 'thread_comment',
170
+ InboxThread: 'inbox_thread',
171
+ InboxThreadComment: 'inbox_thread_comment',
172
+ SavedThread: 'saved_thread',
173
+ SavedThreadComment: 'saved_thread_comment',
174
+ Conversation: 'conversation',
175
+ Message: 'message',
176
+ };
177
+ /**
178
+ * Parse a Comms URL into the entity it points at.
179
+ *
180
+ * @param url The URL to parse.
181
+ * @returns The entity the URL points at, or `null` if it is not a Comms URL.
182
+ */
183
+ export function parseCommsURL(url) {
184
+ const link = parseCommsLink(url);
185
+ if (!link) {
186
+ return null;
187
+ }
188
+ const type = LINK_TYPE_BY_PARSED_NAME[link.type.name];
189
+ if (!type) {
190
+ return null;
191
+ }
192
+ return {
193
+ type,
194
+ workspaceId: link.workspaceId,
195
+ channelId: link.channelId ?? null,
196
+ threadId: link.threadId ?? null,
197
+ commentId: link.commentId ?? null,
198
+ conversationId: link.conversationId ?? null,
199
+ messageId: link.messageId ?? null,
200
+ isQuoteReference: link.isQuoteReference,
201
+ };
202
+ }
@@ -0,0 +1,170 @@
1
+ import { v7 as uuidv7 } from 'uuid';
2
+ /**
3
+ * ID utilities for entities that use opaque string identifiers (channels,
4
+ * threads, comments, conversations, messages, groups).
5
+ *
6
+ * Use {@link generateId} to mint a new ID locally and pass it to a creation
7
+ * endpoint. {@link encodeUuidToBase58} / {@link decodeBase58ToUuidBytes}
8
+ * expose the underlying encoding for callers that need to round-trip raw
9
+ * UUID bytes themselves.
10
+ */
11
+ const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
12
+ const BASE58_MAP = (() => {
13
+ const map = {};
14
+ for (let i = 0; i < BASE58_ALPHABET.length; i++) {
15
+ map[BASE58_ALPHABET[i]] = i;
16
+ }
17
+ return map;
18
+ })();
19
+ const UUID_BYTES_LEN = 16;
20
+ const UUID_BASE58_MAX_LEN = 22;
21
+ const HEX_RE = /^[0-9a-f]+$/;
22
+ export class UuidV7Error extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = 'UuidV7Error';
26
+ }
27
+ }
28
+ /** Encode a 16-byte UUID as a base58 string. */
29
+ export function encodeUuidToBase58(bytes) {
30
+ if (bytes.length !== UUID_BYTES_LEN) {
31
+ throw new UuidV7Error(`id must be ${UUID_BYTES_LEN} bytes`);
32
+ }
33
+ let zeros = 0;
34
+ while (zeros < bytes.length && bytes[zeros] === 0) {
35
+ zeros++;
36
+ }
37
+ let n = 0n;
38
+ for (const b of bytes) {
39
+ n = (n << 8n) | BigInt(b);
40
+ }
41
+ let out = '';
42
+ while (n > 0n) {
43
+ const rem = Number(n % 58n);
44
+ out = BASE58_ALPHABET[rem] + out;
45
+ n /= 58n;
46
+ }
47
+ return '1'.repeat(zeros) + out;
48
+ }
49
+ /**
50
+ * Decode a base58 string back into 16 UUID bytes. Throws {@link UuidV7Error}
51
+ * if the input is malformed or doesn't decode to exactly 16 bytes.
52
+ */
53
+ export function decodeBase58ToUuidBytes(value) {
54
+ if (typeof value !== 'string') {
55
+ throw new UuidV7Error('id must be a base58 string');
56
+ }
57
+ if (value.length === 0) {
58
+ throw new UuidV7Error('id is empty');
59
+ }
60
+ if (value.length > UUID_BASE58_MAX_LEN) {
61
+ throw new UuidV7Error('id is too long');
62
+ }
63
+ let zeros = 0;
64
+ while (zeros < value.length && value[zeros] === '1') {
65
+ zeros++;
66
+ }
67
+ let n = 0n;
68
+ for (let i = 0; i < value.length; i++) {
69
+ const ch = value[i];
70
+ const v = BASE58_MAP[ch];
71
+ if (v === undefined) {
72
+ throw new UuidV7Error(`invalid base58 character: '${ch}'`);
73
+ }
74
+ n = n * 58n + BigInt(v);
75
+ }
76
+ const raw = [];
77
+ while (n > 0n) {
78
+ raw.unshift(Number(n & 0xffn));
79
+ n >>= 8n;
80
+ }
81
+ const padded = new Uint8Array(zeros + raw.length);
82
+ padded.set(raw, zeros);
83
+ if (padded.length !== UUID_BYTES_LEN) {
84
+ throw new UuidV7Error(`id must decode to ${UUID_BYTES_LEN} bytes`);
85
+ }
86
+ return padded;
87
+ }
88
+ function hexToBytes(hex) {
89
+ const out = new Uint8Array(hex.length / 2);
90
+ for (let i = 0; i < out.length; i++) {
91
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
92
+ }
93
+ return out;
94
+ }
95
+ /**
96
+ * Mint a fresh ID. Callers should generate one of these locally when
97
+ * creating a new channel / thread / comment / conversation / message /
98
+ * group — the backend requires the client to supply the ID on create.
99
+ */
100
+ export function generateId() {
101
+ const hex = uuidv7().replace(/-/g, '');
102
+ return encodeUuidToBase58(hexToBytes(hex));
103
+ }
104
+ /** Validate an existing entity ID without minting a replacement. */
105
+ export function resolveReferenceId(id, fieldName) {
106
+ if (!isValidUuidV7Base58(id)) {
107
+ throw new UuidV7Error(`invalid ${fieldName} ${JSON.stringify(id)} — use a base58 UUIDv7 value for \`${fieldName}\`.`);
108
+ }
109
+ return id;
110
+ }
111
+ /**
112
+ * Resolve the `id` for a create-style API call: validate the caller-supplied
113
+ * value (throwing {@link UuidV7Error} before the request leaves the SDK) or
114
+ * mint a fresh one via {@link generateId}.
115
+ */
116
+ export function resolveCreateId(id) {
117
+ if (id === undefined)
118
+ return generateId();
119
+ if (!isValidUuidV7Base58(id)) {
120
+ throw new UuidV7Error(`invalid id ${JSON.stringify(id)} — use generateId() or omit \`id\` and let the SDK mint one.`);
121
+ }
122
+ return id;
123
+ }
124
+ /**
125
+ * Validate that a value matches the expected ID format (the decoded bytes
126
+ * have the v7 version nibble + RFC 4122/9562 variant bits). Does NOT
127
+ * validate the embedded timestamp — the backend may still reject a value
128
+ * that is too far in the future or past.
129
+ */
130
+ export function isValidUuidV7Base58(value) {
131
+ if (typeof value !== 'string')
132
+ return false;
133
+ let bytes;
134
+ try {
135
+ bytes = decodeBase58ToUuidBytes(value);
136
+ }
137
+ catch {
138
+ return false;
139
+ }
140
+ const versionNibble = bytes[6] & 0xf0;
141
+ const variantBits = bytes[8] & 0xc0;
142
+ return versionNibble === 0x70 && variantBits === 0x80;
143
+ }
144
+ /**
145
+ * Encode a canonical UUID string (hyphenated or not, any case) as a
146
+ * wire-format ID. Useful when interoperating with systems that hand you
147
+ * UUIDs in canonical form.
148
+ */
149
+ export function base58FromUuidString(uuid) {
150
+ const stripped = uuid.replace(/-/g, '').toLowerCase();
151
+ if (stripped.length !== 32 || !HEX_RE.test(stripped)) {
152
+ throw new UuidV7Error('not a valid UUID string');
153
+ }
154
+ return encodeUuidToBase58(hexToBytes(stripped));
155
+ }
156
+ /**
157
+ * Inverse of {@link base58FromUuidString}: takes a wire-format ID and
158
+ * returns the canonical hyphenated UUID string.
159
+ */
160
+ export function uuidStringFromBase58(value) {
161
+ const bytes = decodeBase58ToUuidBytes(value);
162
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
163
+ return [
164
+ hex.slice(0, 8),
165
+ hex.slice(8, 12),
166
+ hex.slice(12, 16),
167
+ hex.slice(16, 20),
168
+ hex.slice(20, 32),
169
+ ].join('-');
170
+ }
@@ -0,0 +1,183 @@
1
+ import type { CustomFetch } from './types/http.js';
2
+ export type AuthOptions = {
3
+ /** Optional custom base URL for OAuth endpoints */
4
+ baseUrl?: string;
5
+ /** Optional custom fetch implementation for cross-platform compatibility */
6
+ customFetch?: CustomFetch;
7
+ };
8
+ /**
9
+ * OAuth scopes for the Comms API.
10
+ *
11
+ * @remarks
12
+ * Request only the scopes your application needs:
13
+ *
14
+ * **User Scopes:**
15
+ * - `user:read` - Access user's personal settings
16
+ * - `user:write` - Access and update user's personal settings
17
+ *
18
+ * **Workspace Scopes:**
19
+ * - `workspaces:read` - Access teams the user is part of
20
+ * - `workspaces:write` - Access and update teams the user is part of
21
+ *
22
+ * **Channel Scopes:**
23
+ * - `channels:read` - Access channels
24
+ * - `channels:write` - Access and update channels
25
+ * - `channels:remove` - Access, update, and delete channels
26
+ *
27
+ * **Thread Scopes:**
28
+ * - `threads:read` - Access threads
29
+ * - `threads:write` - Access and update threads
30
+ * - `threads:remove` - Access, update, and delete threads
31
+ *
32
+ * **Comment Scopes:**
33
+ * - `comments:read` - Access comments
34
+ * - `comments:write` - Access and update comments
35
+ * - `comments:remove` - Access, update, and delete comments
36
+ *
37
+ * **Group Scopes:**
38
+ * - `groups:read` - Access groups
39
+ * - `groups:write` - Access and update groups
40
+ * - `groups:remove` - Access, update, and delete groups
41
+ *
42
+ * **Message Scopes:**
43
+ * - `messages:read` - Access messages
44
+ * - `messages:write` - Access and update messages
45
+ * - `messages:remove` - Access, update, and delete messages
46
+ *
47
+ * **Reaction Scopes:**
48
+ * - `reactions:read` - Access reactions
49
+ * - `reactions:write` - Access and update reactions
50
+ * - `reactions:remove` - Access, update, and delete reactions
51
+ *
52
+ * **Search Scopes:**
53
+ * - `search:read` - Search
54
+ *
55
+ * **Attachment Scopes:**
56
+ * - `attachments:read` - Access attachments
57
+ * - `attachments:write` - Access and update attachments
58
+ *
59
+ * **Notification Scopes:**
60
+ * - `notifications:read` - Read user's notifications settings
61
+ * - `notifications:write` - Read and update user's notifications settings
62
+ */
63
+ export declare const COMMS_SCOPES: readonly ["user:read", "user:write", "workspaces:read", "workspaces:write", "channels:read", "channels:write", "channels:remove", "threads:read", "threads:write", "threads:remove", "comments:read", "comments:write", "comments:remove", "groups:read", "groups:write", "groups:remove", "messages:read", "messages:write", "messages:remove", "reactions:read", "reactions:write", "reactions:remove", "search:read", "attachments:read", "attachments:write", "notifications:read", "notifications:write"];
64
+ /**
65
+ * Scopes determine what access a token has to the Comms API.
66
+ */
67
+ export type CommsScope = (typeof COMMS_SCOPES)[number];
68
+ export type AuthTokenRequestArgs = {
69
+ clientId: string;
70
+ clientSecret: string;
71
+ code: string;
72
+ redirectUri?: string;
73
+ };
74
+ export type AuthTokenResponse = {
75
+ accessToken: string;
76
+ tokenType: string;
77
+ refreshToken?: string;
78
+ expiresIn?: number;
79
+ scope?: string;
80
+ };
81
+ export type RefreshAuthTokenRequestArgs = {
82
+ clientId: string;
83
+ clientSecret?: string;
84
+ refreshToken: string;
85
+ };
86
+ export type RevokeAuthTokenRequestArgs = {
87
+ clientId: string;
88
+ clientSecret: string;
89
+ accessToken: string;
90
+ };
91
+ /** Supported token endpoint authentication methods for dynamic client registration. */
92
+ export declare const TOKEN_ENDPOINT_AUTH_METHODS: readonly ["client_secret_post", "client_secret_basic", "none"];
93
+ /**
94
+ * Authentication method used at the token endpoint.
95
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc7591#section-2 RFC 7591 Section 2}
96
+ */
97
+ export type TokenEndpointAuthMethod = (typeof TOKEN_ENDPOINT_AUTH_METHODS)[number];
98
+ /**
99
+ * Parameters for registering a new OAuth client via Dynamic Client Registration.
100
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc7591 RFC 7591}
101
+ */
102
+ export type ClientRegistrationRequest = {
103
+ redirectUris: string[];
104
+ clientName?: string;
105
+ clientUri?: string;
106
+ logoUri?: string;
107
+ scope?: readonly CommsScope[];
108
+ grantTypes?: string[];
109
+ responseTypes?: string[];
110
+ tokenEndpointAuthMethod?: TokenEndpointAuthMethod;
111
+ };
112
+ type RawClientRegistrationResponse = {
113
+ clientId: string;
114
+ clientSecret?: string;
115
+ clientName: string;
116
+ redirectUris: string[];
117
+ scope?: string;
118
+ grantTypes: string[];
119
+ responseTypes: string[];
120
+ tokenEndpointAuthMethod: string;
121
+ clientIdIssuedAt?: number;
122
+ clientSecretExpiresAt?: number;
123
+ clientUri?: string;
124
+ logoUri?: string;
125
+ };
126
+ /**
127
+ * Response from a successful dynamic client registration.
128
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc7591#section-3.2.1 RFC 7591 Section 3.2.1}
129
+ */
130
+ export type ClientRegistrationResponse = Omit<RawClientRegistrationResponse, 'clientIdIssuedAt' | 'clientSecretExpiresAt' | 'scope'> & {
131
+ scope?: CommsScope[];
132
+ clientIdIssuedAt?: Date;
133
+ /** `null` indicates the client secret never expires. Absent when no secret is issued. */
134
+ clientSecretExpiresAt?: Date | null;
135
+ };
136
+ export declare function getAuthStateParameter(): string;
137
+ /**
138
+ * Generates the authorization URL for the OAuth2 flow.
139
+ *
140
+ * The `clientId` can be either a traditional client ID string (e.g. from
141
+ * {@link registerClient}) or an HTTPS URL pointing to a client metadata document,
142
+ * as defined in {@link https://drafts.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/ RFC draft-ietf-oauth-client-id-metadata-document}.
143
+ */
144
+ export declare function getAuthorizationUrl(clientId: string, scopes: CommsScope[], state: string, redirectUri?: string, baseUrl?: string): string;
145
+ export declare function getAuthToken(args: AuthTokenRequestArgs, options?: AuthOptions): Promise<AuthTokenResponse>;
146
+ /**
147
+ * Exchanges a refresh token for a new access token using the OAuth2
148
+ * `refresh_token` grant.
149
+ *
150
+ * @example
151
+ * ```typescript
152
+ * const { accessToken, refreshToken } = await refreshAuthToken({
153
+ * clientId: 'client-id',
154
+ * clientSecret: 'client-secret',
155
+ * refreshToken: storedRefreshToken,
156
+ * })
157
+ * ```
158
+ *
159
+ * @returns The refreshed token. The response may include a new `refreshToken`
160
+ * (rotated by the server); persist it in place of the previous one when present.
161
+ * @throws {@link CommsRequestError} If the refresh fails
162
+ */
163
+ export declare function refreshAuthToken(args: RefreshAuthTokenRequestArgs, options?: AuthOptions): Promise<AuthTokenResponse>;
164
+ export declare function revokeAuthToken(args: RevokeAuthTokenRequestArgs, options?: AuthOptions): Promise<boolean>;
165
+ /**
166
+ * Registers a new OAuth client via Dynamic Client Registration (RFC 7591).
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * const client = await registerClient({
171
+ * redirectUris: ['https://example.com/callback'],
172
+ * clientName: 'My App',
173
+ * scope: ['user:read', 'channels:read'],
174
+ * })
175
+ * // Use client.clientId and client.clientSecret for OAuth flows
176
+ * ```
177
+ *
178
+ * @returns The registered client details
179
+ * @throws {@link CommsRequestError} If the registration fails
180
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc7591 RFC 7591}
181
+ */
182
+ export declare function registerClient(args: ClientRegistrationRequest, options?: AuthOptions): Promise<ClientRegistrationResponse>;
183
+ export {};
@@ -0,0 +1,32 @@
1
+ import { type Comment, type createCommentSchema } from '../types/entities.js';
2
+ import type { CustomFetch, CustomHeaders } from '../types/http.js';
3
+ import type { CreateCommentArgs, ThreadAction } from '../types/requests.js';
4
+ type ClientContext = {
5
+ baseUri: string;
6
+ apiToken: string;
7
+ customFetch?: CustomFetch;
8
+ headers?: CustomHeaders;
9
+ /** Per-client Comment schema, base-bound for the returned comment's web `url`. */
10
+ schema: ReturnType<typeof createCommentSchema>;
11
+ };
12
+ /**
13
+ * Internal helper that powers `comments.createComment`,
14
+ * `threads.closeThread`, and `threads.reopenThread`.
15
+ *
16
+ * Normalizes the `notifyAudience` flag into a sentinel `groups` entry,
17
+ * rejects sentinel IDs passed via `groups` / `directGroupMentions`, mints a
18
+ * UUIDv7 `id` when the caller omits one, and posts to `/comments/add`. When
19
+ * `threadAction` is set (`'close'` / `'reopen'`), it is forwarded on the
20
+ * wire so the same request both adds the comment and transitions the
21
+ * parent thread.
22
+ *
23
+ * @param context - Per-call client context (base URI, API token, optional `customFetch`).
24
+ * @param params - The comment payload (`{@link CreateCommentArgs}`).
25
+ * @param options - Optional configuration.
26
+ * @param options.threadAction - When set, also transitions the parent thread (`'close'` or `'reopen'`).
27
+ * @returns The parsed {@link Comment} returned by the API.
28
+ */
29
+ export declare function addCommentRequest(context: ClientContext, params: CreateCommentArgs, options?: {
30
+ threadAction?: ThreadAction;
31
+ }): Promise<Comment>;
32
+ export {};