@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,177 @@
1
+ import { z } from 'zod';
2
+ import { ENDPOINT_WORKSPACES } from '../consts/endpoints.js';
3
+ import { request } from '../transport/http-client.js';
4
+ import { ChannelSchema, createChannelSchema, WorkspaceSchema, } from '../types/entities.js';
5
+ import { BaseClient } from './base-client.js';
6
+ export const ChannelListSchema = z.array(ChannelSchema);
7
+ /**
8
+ * Client for `/api/v1.0/workspaces/`. Workspace IDs are integers. The backend
9
+ * currently rejects any `color` other than `1` on add/update.
10
+ */
11
+ export class WorkspacesClient extends BaseClient {
12
+ constructor() {
13
+ super(...arguments);
14
+ this.linkBaseUrl = this.getLinkBaseUrl();
15
+ // Reuse the shared singleton when no custom base is configured.
16
+ this.channelListSchema = this.linkBaseUrl
17
+ ? z.array(createChannelSchema(this.linkBaseUrl))
18
+ : ChannelListSchema;
19
+ }
20
+ /**
21
+ * Gets all the user's workspaces.
22
+ *
23
+ * @returns An array of all workspaces the user belongs to.
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * const workspaces = await api.workspaces.getWorkspaces()
28
+ * workspaces.forEach(ws => console.log(ws.name))
29
+ * ```
30
+ */
31
+ getWorkspaces() {
32
+ return request({
33
+ httpMethod: 'GET',
34
+ baseUri: this.getBaseUri(),
35
+ relativePath: `${ENDPOINT_WORKSPACES}/get`,
36
+ apiToken: this.apiToken,
37
+ payload: undefined,
38
+ headers: this.headers,
39
+ customFetch: this.customFetch,
40
+ }).then((response) => response.data.map((workspace) => WorkspaceSchema.parse(workspace)));
41
+ }
42
+ /**
43
+ * Gets a single workspace object by id.
44
+ *
45
+ * @param id - The workspace ID.
46
+ * @returns The workspace object.
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * const workspace = await api.workspaces.getWorkspace(123)
51
+ * console.log(workspace.name)
52
+ * ```
53
+ */
54
+ getWorkspace(id) {
55
+ return request({
56
+ httpMethod: 'GET',
57
+ baseUri: this.getBaseUri(),
58
+ relativePath: `${ENDPOINT_WORKSPACES}/getone`,
59
+ apiToken: this.apiToken,
60
+ payload: { id },
61
+ headers: this.headers,
62
+ customFetch: this.customFetch,
63
+ }).then((response) => WorkspaceSchema.parse(response.data));
64
+ }
65
+ /**
66
+ * Gets the user's default workspace.
67
+ *
68
+ * @returns The default workspace object.
69
+ *
70
+ * @example
71
+ * ```typescript
72
+ * const workspace = await api.workspaces.getDefaultWorkspace()
73
+ * console.log(workspace.name)
74
+ * ```
75
+ */
76
+ getDefaultWorkspace() {
77
+ return request({
78
+ httpMethod: 'GET',
79
+ baseUri: this.getBaseUri(),
80
+ relativePath: `${ENDPOINT_WORKSPACES}/get_default`,
81
+ apiToken: this.apiToken,
82
+ payload: undefined,
83
+ headers: this.headers,
84
+ customFetch: this.customFetch,
85
+ }).then((response) => WorkspaceSchema.parse(response.data));
86
+ }
87
+ /**
88
+ * Creates a new workspace.
89
+ *
90
+ * @param name - The name of the new workspace.
91
+ * @returns The created workspace object.
92
+ *
93
+ * @example
94
+ * ```typescript
95
+ * const workspace = await api.workspaces.createWorkspace('My Team')
96
+ * console.log('Created:', workspace.name)
97
+ * ```
98
+ */
99
+ createWorkspace(name) {
100
+ return request({
101
+ httpMethod: 'POST',
102
+ baseUri: this.getBaseUri(),
103
+ relativePath: `${ENDPOINT_WORKSPACES}/add`,
104
+ apiToken: this.apiToken,
105
+ payload: { name },
106
+ headers: this.headers,
107
+ customFetch: this.customFetch,
108
+ }).then((response) => WorkspaceSchema.parse(response.data));
109
+ }
110
+ /**
111
+ * Updates an existing workspace.
112
+ *
113
+ * @param id - The workspace ID.
114
+ * @param name - The new name for the workspace.
115
+ * @returns The updated workspace object.
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * const workspace = await api.workspaces.updateWorkspace(123, 'New Team Name')
120
+ * ```
121
+ */
122
+ updateWorkspace(id, name) {
123
+ return request({
124
+ httpMethod: 'POST',
125
+ baseUri: this.getBaseUri(),
126
+ relativePath: `${ENDPOINT_WORKSPACES}/update`,
127
+ apiToken: this.apiToken,
128
+ payload: { id, name },
129
+ headers: this.headers,
130
+ customFetch: this.customFetch,
131
+ }).then((response) => WorkspaceSchema.parse(response.data));
132
+ }
133
+ /**
134
+ * Removes a workspace and all its data (not recoverable).
135
+ *
136
+ * @param id - The workspace ID.
137
+ *
138
+ * @example
139
+ * ```typescript
140
+ * await api.workspaces.removeWorkspace(123)
141
+ * ```
142
+ */
143
+ removeWorkspace(id) {
144
+ return request({
145
+ httpMethod: 'POST',
146
+ baseUri: this.getBaseUri(),
147
+ relativePath: `${ENDPOINT_WORKSPACES}/remove`,
148
+ apiToken: this.apiToken,
149
+ payload: { id },
150
+ headers: this.headers,
151
+ customFetch: this.customFetch,
152
+ }).then(() => undefined);
153
+ }
154
+ /**
155
+ * Gets the public channels of a workspace.
156
+ *
157
+ * @param id - The workspace ID.
158
+ * @returns An array of public channel objects.
159
+ *
160
+ * @example
161
+ * ```typescript
162
+ * const channels = await api.workspaces.getPublicChannels(123)
163
+ * channels.forEach(ch => console.log(ch.name))
164
+ * ```
165
+ */
166
+ getPublicChannels(id) {
167
+ return request({
168
+ httpMethod: 'GET',
169
+ baseUri: this.getBaseUri(),
170
+ relativePath: `${ENDPOINT_WORKSPACES}/get_public_channels`,
171
+ apiToken: this.apiToken,
172
+ payload: { id },
173
+ headers: this.headers,
174
+ customFetch: this.customFetch,
175
+ }).then((response) => this.channelListSchema.parse(response.data));
176
+ }
177
+ }
@@ -0,0 +1,67 @@
1
+ import { AttachmentsClient } from './clients/attachments-client.js';
2
+ import { ChannelsClient } from './clients/channels-client.js';
3
+ import { CommentsClient } from './clients/comments-client.js';
4
+ import { ConversationMessagesClient } from './clients/conversation-messages-client.js';
5
+ import { ConversationsClient } from './clients/conversations-client.js';
6
+ import { GroupsClient } from './clients/groups-client.js';
7
+ import { HooksClient } from './clients/hooks-client.js';
8
+ import { InboxClient } from './clients/inbox-client.js';
9
+ import { ReactionsClient } from './clients/reactions-client.js';
10
+ import { SearchClient } from './clients/search-client.js';
11
+ import { ThreadsClient } from './clients/threads-client.js';
12
+ import { UsersClient } from './clients/users-client.js';
13
+ import { WorkspaceUsersClient } from './clients/workspace-users-client.js';
14
+ import { WorkspacesClient } from './clients/workspaces-client.js';
15
+ import { closeDefaultDispatcher } from './transport/http-dispatcher.js';
16
+ /**
17
+ * The main API client for interacting with the Comms REST API.
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * import { CommsApi } from '@todoist/comms-sdk'
22
+ *
23
+ * const api = new CommsApi('your-api-token')
24
+ * const user = await api.users.getSessionUser()
25
+ * ```
26
+ */
27
+ export class CommsApi {
28
+ /**
29
+ * Creates a new Comms API client.
30
+ *
31
+ * @param authToken - Your Comms API token.
32
+ * @param options - Optional configuration options.
33
+ */
34
+ constructor(authToken, options) {
35
+ const clientConfig = {
36
+ apiToken: authToken,
37
+ baseUrl: options?.baseUrl,
38
+ version: options?.version,
39
+ customFetch: options?.customFetch,
40
+ headers: options?.headers,
41
+ };
42
+ this.users = new UsersClient(clientConfig);
43
+ this.workspaces = new WorkspacesClient(clientConfig);
44
+ this.workspaceUsers = new WorkspaceUsersClient(clientConfig);
45
+ this.channels = new ChannelsClient(clientConfig);
46
+ this.threads = new ThreadsClient(clientConfig);
47
+ this.groups = new GroupsClient(clientConfig);
48
+ this.conversations = new ConversationsClient(clientConfig);
49
+ this.comments = new CommentsClient(clientConfig);
50
+ this.conversationMessages = new ConversationMessagesClient(clientConfig);
51
+ this.inbox = new InboxClient(clientConfig);
52
+ this.reactions = new ReactionsClient(clientConfig);
53
+ this.search = new SearchClient(clientConfig);
54
+ this.attachments = new AttachmentsClient(clientConfig);
55
+ this.hooks = new HooksClient(clientConfig);
56
+ }
57
+ /**
58
+ * Drains the SDK's process-global connection pool. CLIs and scripts
59
+ * should `await api.close()` before exit so Node's event loop empties
60
+ * immediately instead of waiting ~4s on keep-alive. Affects every
61
+ * `CommsApi` and OAuth helper in the same process — it's a
62
+ * process-shutdown gesture, not an instance teardown. Browser-safe.
63
+ */
64
+ async close() {
65
+ await closeDefaultDispatcher();
66
+ }
67
+ }
@@ -0,0 +1,31 @@
1
+ import { DEFAULT_API_VERSION } from '../types/api-version.js';
2
+ const BASE_URI = 'https://comms.todoist.com';
3
+ /**
4
+ * Gets the base URI for Comms API requests.
5
+ *
6
+ * Preserves any path component on `domainBase` so callers can route through
7
+ * a proxy (e.g. `https://proxy.example.com/comms` → `.../comms/api/v1.0/`).
8
+ *
9
+ * @param version - API version. Defaults to 'v1.0'.
10
+ * @param domainBase - Custom domain base URL. Defaults to Comms' API domain.
11
+ * @returns Complete base URI with trailing slash (e.g., 'https://comms.todoist.com/api/v1.0/')
12
+ */
13
+ export function getCommsBaseUri(version = DEFAULT_API_VERSION, domainBase = BASE_URI) {
14
+ const base = domainBase.endsWith('/') ? domainBase : `${domainBase}/`;
15
+ return new URL(`api/${version}/`, base).toString();
16
+ }
17
+ export const ENDPOINT_USERS = 'users';
18
+ export const ENDPOINT_WORKSPACES = 'workspaces';
19
+ export const ENDPOINT_CHANNELS = 'channels';
20
+ export const ENDPOINT_THREADS = 'threads';
21
+ export const ENDPOINT_GROUPS = 'groups';
22
+ export const ENDPOINT_CONVERSATIONS = 'conversations';
23
+ export const ENDPOINT_COMMENTS = 'comments';
24
+ export const ENDPOINT_NOTIFICATIONS = 'notifications';
25
+ export const ENDPOINT_INBOX = 'inbox';
26
+ export const ENDPOINT_REACTIONS = 'reactions';
27
+ export const ENDPOINT_SEARCH = 'search';
28
+ export const ENDPOINT_CONVERSATION_MESSAGES = 'conversation_messages';
29
+ export const ENDPOINT_ATTACHMENTS = 'attachments';
30
+ export const ENDPOINT_FILES = 'files';
31
+ export const ENDPOINT_HOOKS = 'hooks';
@@ -0,0 +1,20 @@
1
+ export * from './authentication.js';
2
+ export * from './migration.js';
3
+ export { AttachmentsClient, IMAGE_READ_MIME_TYPES, ImageReadResultSchema, } from './clients/attachments-client.js';
4
+ export { ChannelsClient } from './clients/channels-client.js';
5
+ export { CommentsClient } from './clients/comments-client.js';
6
+ export { ConversationMessagesClient } from './clients/conversation-messages-client.js';
7
+ export { ConversationsClient } from './clients/conversations-client.js';
8
+ export { GroupsClient } from './clients/groups-client.js';
9
+ export { HooksClient } from './clients/hooks-client.js';
10
+ export { InboxClient } from './clients/inbox-client.js';
11
+ export { ReactionsClient } from './clients/reactions-client.js';
12
+ export { SearchClient } from './clients/search-client.js';
13
+ export { ThreadsClient } from './clients/threads-client.js';
14
+ export { UsersClient } from './clients/users-client.js';
15
+ export { WorkspaceUsersClient } from './clients/workspace-users-client.js';
16
+ export { WorkspacesClient } from './clients/workspaces-client.js';
17
+ export { CommsApi } from './comms-api.js';
18
+ export { closeDefaultDispatcher } from './transport/http-dispatcher.js';
19
+ export * from './types/index.js';
20
+ export * from './utils/index.js';
@@ -0,0 +1,92 @@
1
+ import { request } from './transport/http-client.js';
2
+ import { CommsRequestError } from './types/errors.js';
3
+ /**
4
+ * Default origin of the Twist migration backend.
5
+ *
6
+ * The `fetch_new_url` endpoint lives on Twist (`twist.com`) and authenticates
7
+ * with a **Twist** token, not a Comms one. This is why the migration helpers are
8
+ * standalone functions rather than methods on {@link CommsApi} (which is
9
+ * constructed with a Comms token).
10
+ */
11
+ const DEFAULT_TWIST_BASE_URL = 'https://twist.com';
12
+ function getTwistMigrationUrl(baseUrl) {
13
+ const base = baseUrl ?? DEFAULT_TWIST_BASE_URL;
14
+ const trimmed = base.endsWith('/') ? base.slice(0, -1) : base;
15
+ return `${trimmed}/api/comms_migration/fetch_new_url`;
16
+ }
17
+ /**
18
+ * Translates a Twist URL to its equivalent Comms URL using Twist's
19
+ * `comms_migration/fetch_new_url` endpoint.
20
+ *
21
+ * Authenticates with a **Twist** token (external to the Comms SDK), so this is a
22
+ * standalone helper rather than a method on {@link CommsApi}.
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * const newUrl = await fetchNewCommsUrl({
27
+ * oldUrl: 'https://twist.com/a/123/ch/456/t/789',
28
+ * twistToken: process.env.TWIST_AUTH_TOKEN,
29
+ * })
30
+ * ```
31
+ *
32
+ * @returns The equivalent Comms URL.
33
+ * @throws {@link CommsRequestError} If the request fails. URLs that cannot be
34
+ * migrated surface as a thrown error too: `400` with `responseData.error.code`
35
+ * of `'invalid_url'`, or `404` with `'not_imported'`.
36
+ */
37
+ export async function fetchNewCommsUrl(args, options) {
38
+ const response = await request({
39
+ httpMethod: 'POST',
40
+ baseUri: getTwistMigrationUrl(options?.baseUrl),
41
+ relativePath: '',
42
+ apiToken: args.twistToken,
43
+ payload: { oldUrl: args.oldUrl },
44
+ customFetch: options?.customFetch,
45
+ });
46
+ const newUrl = response.data?.newUrl;
47
+ if (!newUrl) {
48
+ throw new CommsRequestError('Migration response did not contain a new URL.', response.status, response.data);
49
+ }
50
+ return newUrl;
51
+ }
52
+ /**
53
+ * Translates multiple Twist URLs to their equivalent Comms URLs.
54
+ *
55
+ * URLs are processed **sequentially** to stay friendly to the rate-sensitive
56
+ * migration endpoint. A failure on one URL does not abort the run: each result
57
+ * carries either a `newUrl` (success) or a `CommsRequestError` (failure), in the
58
+ * same order as the input.
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * const results = await fetchNewCommsUrls({
63
+ * oldUrls: ['https://twist.com/a/1/ch/2/t/3', 'https://twist.com/bad'],
64
+ * twistToken: process.env.TWIST_AUTH_TOKEN,
65
+ * })
66
+ * for (const result of results) {
67
+ * if (result.newUrl) console.log(`${result.oldUrl} -> ${result.newUrl}`)
68
+ * else console.warn(`${result.oldUrl} failed`, result.error)
69
+ * }
70
+ * ```
71
+ *
72
+ * @returns One {@link MigrationResult} per input URL, in input order.
73
+ * @throws Re-throws any error that is not a {@link CommsRequestError}.
74
+ */
75
+ export async function fetchNewCommsUrls(args, options) {
76
+ const results = [];
77
+ for (const oldUrl of args.oldUrls) {
78
+ try {
79
+ const newUrl = await fetchNewCommsUrl({ oldUrl, twistToken: args.twistToken }, options);
80
+ results.push({ oldUrl, newUrl });
81
+ }
82
+ catch (error) {
83
+ if (error instanceof CommsRequestError) {
84
+ results.push({ oldUrl, error });
85
+ }
86
+ else {
87
+ throw error;
88
+ }
89
+ }
90
+ }
91
+ return results;
92
+ }
@@ -0,0 +1,45 @@
1
+ import { HttpResponse, http } from 'msw';
2
+ const BASE_URL = 'https://comms.todoist.com';
3
+ /**
4
+ * Creates a successful API response with the given data
5
+ */
6
+ export function createSuccessResponse(data) {
7
+ return HttpResponse.json(data, { status: 200 });
8
+ }
9
+ /**
10
+ * Creates an error API response
11
+ */
12
+ export function createErrorResponse(errorCode, errorMessage, status = 400) {
13
+ return HttpResponse.json({
14
+ error_code: errorCode,
15
+ error_string: errorMessage,
16
+ }, { status });
17
+ }
18
+ /**
19
+ * Helper to create API endpoint URL
20
+ */
21
+ export function apiUrl(path) {
22
+ // Remove leading slash if present
23
+ const cleanPath = path.startsWith('/') ? path.slice(1) : path;
24
+ return `${BASE_URL}/${cleanPath}`;
25
+ }
26
+ /**
27
+ * Creates a handler for a GET endpoint
28
+ */
29
+ export function createGetHandler(endpoint, responseData) {
30
+ return http.get(apiUrl(endpoint), () => {
31
+ return createSuccessResponse(responseData);
32
+ });
33
+ }
34
+ /**
35
+ * Creates a handler for a POST endpoint
36
+ */
37
+ export function createPostHandler(endpoint, responseData) {
38
+ return http.post(apiUrl(endpoint), () => {
39
+ return createSuccessResponse(responseData);
40
+ });
41
+ }
42
+ /**
43
+ * Export http from msw for custom handlers
44
+ */
45
+ export { http, HttpResponse };
@@ -0,0 +1,32 @@
1
+ import { setupServer } from 'msw/node';
2
+ import { afterAll, afterEach, beforeAll, vi } from 'vitest';
3
+ // In production the transport uses undici's own `fetch` (paired with the
4
+ // dispatcher) so the request client and dispatcher stay on one undici version.
5
+ // MSW intercepts the *global* `fetch`, not that separate undici instance, so
6
+ // force the transport onto the global `fetch` for every test in the suite;
7
+ // MSW then intercepts requests as usual. The real undici transport is covered
8
+ // directly by `http-dispatcher.test.ts` and `fetch-with-retry.test.ts`, which
9
+ // opt out of this seam.
10
+ vi.mock('../transport/http-dispatcher', async (importOriginal) => {
11
+ const actual = await importOriginal();
12
+ return {
13
+ ...actual,
14
+ getDefaultTransport: vi.fn(async () => undefined),
15
+ };
16
+ });
17
+ // Create MSW server instance
18
+ export const server = setupServer();
19
+ // Start server before all tests
20
+ beforeAll(() => {
21
+ // Only warn on unhandled requests instead of error, since transport/http-client.test.ts
22
+ // uses direct fetch mocking which bypasses MSW
23
+ server.listen({ onUnhandledRequest: 'warn' });
24
+ });
25
+ // Reset handlers after each test
26
+ afterEach(() => {
27
+ server.resetHandlers();
28
+ });
29
+ // Clean up after all tests
30
+ afterAll(() => {
31
+ server.close();
32
+ });
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Creates a CustomFetch adapter for Obsidian's requestUrl API.
3
+ *
4
+ * This adapter bridges the gap between Obsidian's requestUrl interface and the
5
+ * standard fetch-like interface expected by the Comms API SDK.
6
+ *
7
+ * Key differences handled by this adapter:
8
+ * - Obsidian returns response data as properties (response.json, response.text)
9
+ * while the SDK expects methods (response.json(), response.text())
10
+ * - Obsidian's requestUrl bypasses CORS restrictions that would block standard fetch
11
+ * - Obsidian throws on HTTP errors by default; we set throw: false to handle manually
12
+ * - Obsidian doesn't provide statusText; we default to empty string
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * import { requestUrl } from 'obsidian'
17
+ * import { createObsidianFetchAdapter } from './obsidian-fetch-adapter.js'
18
+ *
19
+ * const api = new CommsApi('your-token', {
20
+ * customFetch: createObsidianFetchAdapter(requestUrl)
21
+ * })
22
+ * ```
23
+ *
24
+ * @param requestUrl - The Obsidian requestUrl function
25
+ * @returns A CustomFetch function compatible with the Comms API SDK
26
+ */
27
+ export function createObsidianFetchAdapter(requestUrl) {
28
+ return async (url, options) => {
29
+ // Build the request parameters in Obsidian's format
30
+ const requestParams = {
31
+ url,
32
+ method: options?.method || 'GET',
33
+ headers: options?.headers,
34
+ body: options?.body,
35
+ throw: false, // Don't throw on HTTP errors; let the SDK handle status codes
36
+ };
37
+ // Make the request using Obsidian's requestUrl
38
+ const response = await requestUrl(requestParams);
39
+ // Transform Obsidian's response format to match CustomFetchResponse interface
40
+ return {
41
+ ok: response.status >= 200 && response.status < 300,
42
+ status: response.status,
43
+ statusText: '', // Obsidian doesn't provide statusText
44
+ headers: response.headers,
45
+ // Wrap Obsidian's direct properties as methods returning promises
46
+ text: () => Promise.resolve(response.text),
47
+ json: () => Promise.resolve(response.json),
48
+ };
49
+ };
50
+ }
@@ -0,0 +1,103 @@
1
+ import { getCommsBaseUri } from '../consts/endpoints.js';
2
+ export const TEST_API_TOKEN = 'test-api-token';
3
+ export const TEST_API_BASE_URL = getCommsBaseUri().replace(/\/$/, '');
4
+ // Stable test IDs. TEST_CHANNEL_ID and TEST_THREAD_ID are base58
5
+ // UUIDv7-shaped because create-thread and add-comment paths validate them
6
+ // SDK-side.
7
+ export const TEST_CHANNEL_ID = 'CQ7yksHFbYFrSPVTaHVCs';
8
+ export const TEST_THREAD_ID = 'CQ7yksHFbYFrSPVTaHVCt';
9
+ export const TEST_COMMENT_ID = '7YpL3oZ4kZ9vP7Q1tR2sX41';
10
+ export const TEST_CONVERSATION_ID = '7YpL3oZ4kZ9vP7Q1tR2sX42';
11
+ export const TEST_MESSAGE_ID = '7YpL3oZ4kZ9vP7Q1tR2sX43';
12
+ export const TEST_GROUP_ID = '7YpL3oZ4kZ9vP7Q1tR2sX44';
13
+ export const mockUser = {
14
+ id: 1,
15
+ email: 'test@example.com',
16
+ fullName: 'Test User',
17
+ shortName: 'TU',
18
+ timezone: 'America/New_York',
19
+ removed: false,
20
+ lang: 'en',
21
+ };
22
+ export const mockWorkspace = {
23
+ id: 1,
24
+ name: 'Test Workspace',
25
+ creator: 1,
26
+ created: new Date('2021-01-01T00:00:00Z'),
27
+ };
28
+ export const mockChannel = {
29
+ id: TEST_CHANNEL_ID,
30
+ name: 'general',
31
+ creator: 1,
32
+ public: true,
33
+ workspaceId: 1,
34
+ archived: false,
35
+ created: new Date('2021-01-01T00:00:00Z'),
36
+ version: 0,
37
+ url: `https://comms.todoist.com/1/ch/${TEST_CHANNEL_ID}/`,
38
+ };
39
+ export const mockThread = {
40
+ id: TEST_THREAD_ID,
41
+ title: 'Test Thread',
42
+ content: 'This is a test thread',
43
+ creator: 1,
44
+ channelId: TEST_CHANNEL_ID,
45
+ workspaceId: 1,
46
+ commentCount: 0,
47
+ lastUpdated: new Date('2021-01-01T00:00:00Z'),
48
+ pinned: false,
49
+ posted: new Date('2021-01-01T00:00:00Z'),
50
+ snippet: 'This is a test thread',
51
+ snippetCreator: 1,
52
+ isArchived: false,
53
+ url: `https://comms.todoist.com/1/ch/${TEST_CHANNEL_ID}/t/${TEST_THREAD_ID}/`,
54
+ };
55
+ export const mockGroup = {
56
+ id: TEST_GROUP_ID,
57
+ name: 'Test Group',
58
+ workspaceId: 1,
59
+ userIds: [1, 2, 3],
60
+ version: 0,
61
+ };
62
+ export const mockConversation = {
63
+ id: TEST_CONVERSATION_ID,
64
+ workspaceId: 1,
65
+ userIds: [1, 2],
66
+ messageCount: 1,
67
+ lastObjIndex: 0,
68
+ snippet: 'Hello there',
69
+ snippetCreators: [1],
70
+ lastActive: new Date('2021-01-01T00:00:00Z'),
71
+ archived: false,
72
+ created: new Date('2021-01-01T00:00:00Z'),
73
+ creator: 1,
74
+ url: `https://comms.todoist.com/1/msg/${TEST_CONVERSATION_ID}/`,
75
+ };
76
+ export const mockComment = {
77
+ id: TEST_COMMENT_ID,
78
+ content: 'This is a comment',
79
+ creator: 1,
80
+ threadId: TEST_THREAD_ID,
81
+ workspaceId: 1,
82
+ channelId: TEST_CHANNEL_ID,
83
+ posted: new Date('2021-01-01T00:00:00Z'),
84
+ url: `https://comms.todoist.com/1/ch/${TEST_CHANNEL_ID}/t/${TEST_THREAD_ID}/c/${TEST_COMMENT_ID}`,
85
+ };
86
+ export const mockWorkspaceUser = {
87
+ id: 1,
88
+ fullName: 'Test User',
89
+ email: 'test@example.com',
90
+ userType: 'USER',
91
+ shortName: 'TU',
92
+ firstName: 'Test',
93
+ imageId: null,
94
+ avatarUrls: null,
95
+ dateFormat: null,
96
+ removed: false,
97
+ restricted: null,
98
+ setupPending: null,
99
+ theme: null,
100
+ timeFormat: null,
101
+ timezone: 'America/New_York',
102
+ version: 1,
103
+ };