@todoist/comms-sdk 0.0.0-stage → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +187 -2
- package/dist/esm/authentication.js +247 -0
- package/dist/esm/clients/add-comment-helper.js +41 -0
- package/dist/esm/clients/attachments-client.js +99 -0
- package/dist/esm/clients/base-client.js +30 -0
- package/dist/esm/clients/channels-client.js +209 -0
- package/dist/esm/clients/comments-client.js +177 -0
- package/dist/esm/clients/conversation-messages-client.js +167 -0
- package/dist/esm/clients/conversations-client.js +281 -0
- package/dist/esm/clients/groups-client.js +170 -0
- package/dist/esm/clients/hooks-client.js +50 -0
- package/dist/esm/clients/inbox-client.js +186 -0
- package/dist/esm/clients/notify-audience.js +43 -0
- package/dist/esm/clients/reactions-client.js +96 -0
- package/dist/esm/clients/search-client.js +140 -0
- package/dist/esm/clients/threads-client.js +363 -0
- package/dist/esm/clients/users-client.js +368 -0
- package/dist/esm/clients/workspace-users-client.js +299 -0
- package/dist/esm/clients/workspaces-client.js +177 -0
- package/dist/esm/comms-api.js +67 -0
- package/dist/esm/consts/endpoints.js +31 -0
- package/dist/esm/index.js +20 -0
- package/dist/esm/migration.js +92 -0
- package/dist/esm/testUtils/msw-handlers.js +45 -0
- package/dist/esm/testUtils/msw-setup.js +32 -0
- package/dist/esm/testUtils/obsidian-fetch-adapter.js +50 -0
- package/dist/esm/testUtils/test-defaults.js +103 -0
- package/dist/esm/transport/fetch-with-retry.js +240 -0
- package/dist/esm/transport/http-client.js +53 -0
- package/dist/esm/transport/http-dispatcher.js +149 -0
- package/dist/esm/types/api-version.js +5 -0
- package/dist/esm/types/entities.js +508 -0
- package/dist/esm/types/enums.js +34 -0
- package/dist/esm/types/errors.js +82 -0
- package/dist/esm/types/http.js +1 -0
- package/dist/esm/types/index.js +6 -0
- package/dist/esm/types/requests.js +184 -0
- package/dist/esm/utils/case-conversion.js +47 -0
- package/dist/esm/utils/conversation-title.js +110 -0
- package/dist/esm/utils/headers.js +29 -0
- package/dist/esm/utils/index.js +5 -0
- package/dist/esm/utils/multipart-upload.js +198 -0
- package/dist/esm/utils/reply-recipients.js +111 -0
- package/dist/esm/utils/timestamp-conversion.js +54 -0
- package/dist/esm/utils/url-helpers.js +202 -0
- package/dist/esm/utils/uuidv7.js +170 -0
- package/dist/types/authentication.d.ts +183 -0
- package/dist/types/clients/add-comment-helper.d.ts +32 -0
- package/dist/types/clients/attachments-client.d.ts +55 -0
- package/dist/types/clients/base-client.d.ts +37 -0
- package/dist/types/clients/channels-client.d.ts +211 -0
- package/dist/types/clients/comments-client.d.ts +228 -0
- package/dist/types/clients/conversation-messages-client.d.ts +201 -0
- package/dist/types/clients/conversations-client.d.ts +366 -0
- package/dist/types/clients/groups-client.d.ts +148 -0
- package/dist/types/clients/hooks-client.d.ts +29 -0
- package/dist/types/clients/inbox-client.d.ts +478 -0
- package/dist/types/clients/notify-audience.d.ts +22 -0
- package/dist/types/clients/reactions-client.d.ts +57 -0
- package/dist/types/clients/search-client.d.ts +71 -0
- package/dist/types/clients/threads-client.d.ts +547 -0
- package/dist/types/clients/users-client.d.ts +280 -0
- package/dist/types/clients/workspace-users-client.d.ts +172 -0
- package/dist/types/clients/workspaces-client.d.ts +154 -0
- package/dist/types/comms-api.d.ts +73 -0
- package/dist/types/consts/endpoints.d.ts +27 -0
- package/dist/types/index.d.ts +21 -0
- package/dist/types/migration.d.ts +78 -0
- package/dist/types/testUtils/msw-handlers.d.ts +28 -0
- package/dist/types/testUtils/msw-setup.d.ts +1 -0
- package/dist/types/testUtils/obsidian-fetch-adapter.d.ts +29 -0
- package/dist/types/testUtils/test-defaults.d.ts +17 -0
- package/dist/types/transport/fetch-with-retry.d.ts +4 -0
- package/dist/types/transport/http-client.d.ts +14 -0
- package/dist/types/transport/http-dispatcher.d.ts +46 -0
- package/dist/types/types/api-version.d.ts +6 -0
- package/dist/types/types/entities.d.ts +3081 -0
- package/dist/types/types/enums.d.ts +55 -0
- package/dist/types/types/errors.d.ts +57 -0
- package/dist/types/types/http.d.ts +60 -0
- package/dist/types/types/index.d.ts +6 -0
- package/dist/types/types/requests.d.ts +604 -0
- package/dist/types/utils/case-conversion.d.ts +8 -0
- package/dist/types/utils/conversation-title.d.ts +84 -0
- package/dist/types/utils/headers.d.ts +13 -0
- package/dist/types/utils/index.d.ts +6 -0
- package/dist/types/utils/multipart-upload.d.ts +59 -0
- package/dist/types/utils/reply-recipients.d.ts +60 -0
- package/dist/types/utils/timestamp-conversion.d.ts +13 -0
- package/dist/types/utils/url-helpers.d.ts +129 -0
- package/dist/types/utils/uuidv7.d.ts +42 -0
- package/package.json +81 -5
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { RequestAttachmentSchema } from './entities.js';
|
|
3
|
+
import { NOTIFY_AUDIENCES } from './enums.js';
|
|
4
|
+
/**
|
|
5
|
+
* Create-side requests require an `id` on the wire. The SDK clients accept
|
|
6
|
+
* `id` as optional and auto-generate one via
|
|
7
|
+
* {@link import('../utils/uuidv7').generateId} when the caller doesn't pass
|
|
8
|
+
* one — callers can still mint their own ID locally (e.g. for optimistic
|
|
9
|
+
* UI) and have it stick.
|
|
10
|
+
*/
|
|
11
|
+
export const CreateChannelArgsSchema = z.object({
|
|
12
|
+
workspaceId: z.number(),
|
|
13
|
+
name: z.string(),
|
|
14
|
+
id: z.string().optional(),
|
|
15
|
+
userIds: z.array(z.number()).nullable().optional(),
|
|
16
|
+
color: z.number().nullable().optional(),
|
|
17
|
+
public: z.boolean().nullable().optional(),
|
|
18
|
+
description: z.string().nullable().optional(),
|
|
19
|
+
useDefaultRecipients: z.boolean().nullable().optional(),
|
|
20
|
+
defaultGroups: z.array(z.string()).nullable().optional(),
|
|
21
|
+
defaultRecipients: z.array(z.number()).nullable().optional(),
|
|
22
|
+
isFavorited: z.boolean().nullable().optional(),
|
|
23
|
+
icon: z.number().nullable().optional(),
|
|
24
|
+
});
|
|
25
|
+
export const UpdateChannelArgsSchema = z.object({
|
|
26
|
+
id: z.string(),
|
|
27
|
+
name: z.string(),
|
|
28
|
+
color: z.number().nullable().optional(),
|
|
29
|
+
public: z.boolean().nullable().optional(),
|
|
30
|
+
description: z.string().nullable().optional(),
|
|
31
|
+
useDefaultRecipients: z.boolean().nullable().optional(),
|
|
32
|
+
defaultGroups: z.array(z.string()).nullable().optional(),
|
|
33
|
+
defaultRecipients: z.array(z.number()).nullable().optional(),
|
|
34
|
+
isFavorited: z.boolean().nullable().optional(),
|
|
35
|
+
icon: z.number().nullable().optional(),
|
|
36
|
+
});
|
|
37
|
+
export const CreateThreadArgsSchema = z.object({
|
|
38
|
+
channelId: z.string(),
|
|
39
|
+
content: z.string(),
|
|
40
|
+
title: z.string().nullable().optional(),
|
|
41
|
+
id: z.string().optional(),
|
|
42
|
+
recipients: z.array(z.number()).nullable().optional(),
|
|
43
|
+
groups: z.array(z.string()).nullable().optional(),
|
|
44
|
+
notifyAudience: z.enum(NOTIFY_AUDIENCES).nullable().optional(),
|
|
45
|
+
attachments: z.array(RequestAttachmentSchema).nullable().optional(),
|
|
46
|
+
});
|
|
47
|
+
export const UpdateThreadArgsSchema = z.object({
|
|
48
|
+
id: z.string(),
|
|
49
|
+
title: z.string().nullable().optional(),
|
|
50
|
+
content: z.string().nullable().optional(),
|
|
51
|
+
});
|
|
52
|
+
export const CreateCommentArgsSchema = z.object({
|
|
53
|
+
threadId: z.string(),
|
|
54
|
+
content: z.string(),
|
|
55
|
+
id: z.string().optional(),
|
|
56
|
+
attachments: z.array(RequestAttachmentSchema).nullable().optional(),
|
|
57
|
+
actions: z.unknown().nullable().optional(),
|
|
58
|
+
recipients: z.array(z.number()).nullable().optional(),
|
|
59
|
+
groups: z.array(z.string()).nullable().optional(),
|
|
60
|
+
directMentions: z.array(z.number()).nullable().optional(),
|
|
61
|
+
directGroupMentions: z.array(z.string()).nullable().optional(),
|
|
62
|
+
notifyAudience: z.enum(NOTIFY_AUDIENCES).nullable().optional(),
|
|
63
|
+
});
|
|
64
|
+
export const UpdateCommentArgsSchema = z.object({
|
|
65
|
+
id: z.string(),
|
|
66
|
+
content: z.string(),
|
|
67
|
+
});
|
|
68
|
+
export const CreateConversationArgsSchema = z.object({
|
|
69
|
+
workspaceId: z.number(),
|
|
70
|
+
recipients: z.array(z.number()),
|
|
71
|
+
id: z.string().optional(),
|
|
72
|
+
title: z.string().nullable().optional(),
|
|
73
|
+
});
|
|
74
|
+
export const CreateMessageArgsSchema = z
|
|
75
|
+
.object({
|
|
76
|
+
conversationId: z.string().nullable().optional(),
|
|
77
|
+
threadId: z.string().nullable().optional(),
|
|
78
|
+
content: z.string(),
|
|
79
|
+
id: z.string().optional(),
|
|
80
|
+
attachments: z.array(RequestAttachmentSchema).nullable().optional(),
|
|
81
|
+
})
|
|
82
|
+
.refine((data) => {
|
|
83
|
+
return ((data.conversationId && !data.threadId) || (!data.conversationId && data.threadId));
|
|
84
|
+
}, {
|
|
85
|
+
message: 'Exactly one of conversationId or threadId must be provided',
|
|
86
|
+
});
|
|
87
|
+
export const GetChannelsArgsSchema = z.object({
|
|
88
|
+
workspaceId: z.number(),
|
|
89
|
+
archived: z.boolean().nullable().optional(),
|
|
90
|
+
});
|
|
91
|
+
export const GetThreadsArgsSchema = z.object({
|
|
92
|
+
workspaceId: z.number(),
|
|
93
|
+
channelId: z.string().nullable().optional(),
|
|
94
|
+
archived: z.boolean().nullable().optional(),
|
|
95
|
+
newerThan: z.date().nullable().optional(),
|
|
96
|
+
olderThan: z.date().nullable().optional(),
|
|
97
|
+
limit: z.number().nullable().optional(),
|
|
98
|
+
});
|
|
99
|
+
export const GetCommentsArgsSchema = z.object({
|
|
100
|
+
threadId: z.string(),
|
|
101
|
+
newerThan: z.date().nullable().optional(),
|
|
102
|
+
olderThan: z.date().nullable().optional(),
|
|
103
|
+
limit: z.number().nullable().optional(),
|
|
104
|
+
});
|
|
105
|
+
export const GetConversationsArgsSchema = z.object({
|
|
106
|
+
workspaceId: z.number(),
|
|
107
|
+
archived: z.boolean().nullable().optional(),
|
|
108
|
+
olderThan: z.date().nullable().optional(),
|
|
109
|
+
beforeId: z.string().nullable().optional(),
|
|
110
|
+
limit: z.number().nullable().optional(),
|
|
111
|
+
});
|
|
112
|
+
export const GetOrCreateConversationArgsSchema = z.object({
|
|
113
|
+
workspaceId: z.number(),
|
|
114
|
+
userIds: z.array(z.number()),
|
|
115
|
+
id: z.string().optional(),
|
|
116
|
+
});
|
|
117
|
+
// Search
|
|
118
|
+
export const SEARCH_TYPES = ['threads', 'messages', 'conversations', 'all'];
|
|
119
|
+
// Inbox
|
|
120
|
+
export const ARCHIVE_FILTER_VALUES = ['active', 'archived', 'all'];
|
|
121
|
+
// Hooks
|
|
122
|
+
export const NON_MESSAGE_HOOK_EVENTS = [
|
|
123
|
+
'workspace_added',
|
|
124
|
+
'workspace_updated',
|
|
125
|
+
'workspace_deleted',
|
|
126
|
+
'workspace_user_added',
|
|
127
|
+
'workspace_user_updated',
|
|
128
|
+
'workspace_user_removed',
|
|
129
|
+
'channel_added',
|
|
130
|
+
'channel_updated',
|
|
131
|
+
'channel_deleted',
|
|
132
|
+
'channel_user_added',
|
|
133
|
+
'channel_user_removed',
|
|
134
|
+
'thread_added',
|
|
135
|
+
'thread_updated',
|
|
136
|
+
'thread_deleted',
|
|
137
|
+
'comment_added',
|
|
138
|
+
'comment_updated',
|
|
139
|
+
'comment_deleted',
|
|
140
|
+
'group_added',
|
|
141
|
+
'group_updated',
|
|
142
|
+
'group_deleted',
|
|
143
|
+
'group_user_added',
|
|
144
|
+
'group_user_removed',
|
|
145
|
+
];
|
|
146
|
+
export const MESSAGE_HOOK_EVENTS = ['message_added', 'message_updated'];
|
|
147
|
+
export const HOOK_EVENTS = [...NON_MESSAGE_HOOK_EVENTS, ...MESSAGE_HOOK_EVENTS];
|
|
148
|
+
export const NonMessageHookEventSchema = z.enum(NON_MESSAGE_HOOK_EVENTS);
|
|
149
|
+
export const MessageHookEventSchema = z.enum(MESSAGE_HOOK_EVENTS);
|
|
150
|
+
export const HookEventSchema = z.enum(HOOK_EVENTS);
|
|
151
|
+
export const HookTargetUrlSchema = z
|
|
152
|
+
.url()
|
|
153
|
+
.max(150)
|
|
154
|
+
.refine((value) => {
|
|
155
|
+
try {
|
|
156
|
+
return new URL(value).protocol === 'https:';
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
}, { message: 'URL must use HTTPS' });
|
|
162
|
+
export const SubscribeHookArgsBaseSchema = z.object({
|
|
163
|
+
targetUrl: HookTargetUrlSchema,
|
|
164
|
+
workspaceId: z.number().nullable().optional(),
|
|
165
|
+
channelId: z.string().nullable().optional(),
|
|
166
|
+
threadId: z.string().nullable().optional(),
|
|
167
|
+
});
|
|
168
|
+
export const SubscribeNonMessageHookArgsSchema = SubscribeHookArgsBaseSchema.extend({
|
|
169
|
+
event: NonMessageHookEventSchema,
|
|
170
|
+
conversationId: z.never().optional(),
|
|
171
|
+
});
|
|
172
|
+
export const SubscribeMessageHookArgsSchema = SubscribeHookArgsBaseSchema.extend({
|
|
173
|
+
event: MessageHookEventSchema,
|
|
174
|
+
conversationId: z.string().nullable().optional(),
|
|
175
|
+
});
|
|
176
|
+
export const SubscribeHookArgsSchema = z.union([
|
|
177
|
+
SubscribeNonMessageHookArgsSchema,
|
|
178
|
+
SubscribeMessageHookArgsSchema,
|
|
179
|
+
]);
|
|
180
|
+
export const UnsubscribeHookArgsSchema = z.object({
|
|
181
|
+
targetUrl: HookTargetUrlSchema,
|
|
182
|
+
});
|
|
183
|
+
// Threads
|
|
184
|
+
export const THREAD_ACTIONS = ['close', 'reopen'];
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import camelcase from 'camelcase';
|
|
2
|
+
function isObject(value) {
|
|
3
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
4
|
+
}
|
|
5
|
+
function isArray(value) {
|
|
6
|
+
return Array.isArray(value);
|
|
7
|
+
}
|
|
8
|
+
function toSnakeCase(str) {
|
|
9
|
+
return str
|
|
10
|
+
.replace(/([A-Z])/g, '_$1')
|
|
11
|
+
.toLowerCase()
|
|
12
|
+
.replace(/^_/, '');
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* @internal
|
|
16
|
+
*/
|
|
17
|
+
export function camelCaseKeys(obj) {
|
|
18
|
+
if (isArray(obj)) {
|
|
19
|
+
return obj.map(camelCaseKeys);
|
|
20
|
+
}
|
|
21
|
+
if (isObject(obj)) {
|
|
22
|
+
const result = {};
|
|
23
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
24
|
+
const camelKey = camelcase(key);
|
|
25
|
+
result[camelKey] = camelCaseKeys(value);
|
|
26
|
+
}
|
|
27
|
+
return result;
|
|
28
|
+
}
|
|
29
|
+
return obj;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* @internal
|
|
33
|
+
*/
|
|
34
|
+
export function snakeCaseKeys(obj) {
|
|
35
|
+
if (isArray(obj)) {
|
|
36
|
+
return obj.map(snakeCaseKeys);
|
|
37
|
+
}
|
|
38
|
+
if (isObject(obj)) {
|
|
39
|
+
const result = {};
|
|
40
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
41
|
+
const snakeKey = toSnakeCase(key);
|
|
42
|
+
result[snakeKey] = snakeCaseKeys(value);
|
|
43
|
+
}
|
|
44
|
+
return result;
|
|
45
|
+
}
|
|
46
|
+
return obj;
|
|
47
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The title a conversation shows when nobody has named it.
|
|
3
|
+
*
|
|
4
|
+
* The rules come from `@doist/sdk-kmp`, the shared implementation of Comms
|
|
5
|
+
* logic, so titles match the other Comms clients. The wording stays with each
|
|
6
|
+
* caller, which joins the names in the user's language.
|
|
7
|
+
*/
|
|
8
|
+
import { ConversationKind, ConversationMemberProvidable, getConversationTitle as getSharedConversationTitle, } from '@doist/sdk-kmp/shared-comms-all';
|
|
9
|
+
/** The ways a conversation's title can be shown. */
|
|
10
|
+
export const CONVERSATION_TITLE_TYPES = [
|
|
11
|
+
'custom',
|
|
12
|
+
'yourself',
|
|
13
|
+
'one_to_one',
|
|
14
|
+
'group',
|
|
15
|
+
'untitled',
|
|
16
|
+
];
|
|
17
|
+
/**
|
|
18
|
+
* Maps the shared title types onto the types this SDK exposes. It's keyed by
|
|
19
|
+
* every name the library can return, so a type the library adds fails the
|
|
20
|
+
* type check until it's mapped here.
|
|
21
|
+
*/
|
|
22
|
+
const TITLE_TYPE_BY_SHARED_NAME = {
|
|
23
|
+
Custom: 'custom',
|
|
24
|
+
Yourself: 'yourself',
|
|
25
|
+
OneToOne: 'one_to_one',
|
|
26
|
+
Group: 'group',
|
|
27
|
+
Untitled: 'untitled',
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Returns the shared conversation kind for the API's `private` flag. Callers
|
|
31
|
+
* never pass one in, since Kotlin compares enum entries by identity.
|
|
32
|
+
*/
|
|
33
|
+
function getConversationKind(isPrivate) {
|
|
34
|
+
if (isPrivate == null) {
|
|
35
|
+
return ConversationKind.Unknown;
|
|
36
|
+
}
|
|
37
|
+
return isPrivate ? ConversationKind.Private : ConversationKind.Group;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Works out the title a conversation shows, as the current user sees it.
|
|
41
|
+
*
|
|
42
|
+
* - A `title` with something visible in it wins: `custom`.
|
|
43
|
+
* - A 1:1 shows the other person's full name: `one_to_one`.
|
|
44
|
+
* - A group shows the others' short names in alphabetical order, ignoring case
|
|
45
|
+
* and accents: `group`. Past `maxNames`, it counts the rest in `othersCount`,
|
|
46
|
+
* though a single person over is named instead.
|
|
47
|
+
* - People removed from the workspace drop out of a group but stay in a 1:1.
|
|
48
|
+
* - A group down to you and one other person sets `includesYou`. Down to you
|
|
49
|
+
* alone, it shows your full name: `yourself`.
|
|
50
|
+
* - With no name to show, the type is `untitled`.
|
|
51
|
+
*
|
|
52
|
+
* `private` only tells a 1:1 from a group of two. Without it, as on a search
|
|
53
|
+
* result, two people read as a 1:1. Past two people the count decides, since
|
|
54
|
+
* chats imported from Twist can be private with three people in them.
|
|
55
|
+
*
|
|
56
|
+
* Someone in `userIds` who isn't in `users` reads as a name that hasn't loaded,
|
|
57
|
+
* so a group counts them rather than naming them.
|
|
58
|
+
*
|
|
59
|
+
* The wording stays with the caller: join `names`, "N more" for `othersCount`
|
|
60
|
+
* and "you" for `includesYou` with a list formatter in the user's language.
|
|
61
|
+
*
|
|
62
|
+
* @param args - The arguments for working out the title.
|
|
63
|
+
* @param args.conversation - The conversation's `title`, `userIds` and `private` flag.
|
|
64
|
+
* @param args.users - The users to take names from. Include people removed from the
|
|
65
|
+
* workspace, so a group can leave them out rather than count them.
|
|
66
|
+
* @param args.currentUserId - The ID of the user viewing the conversation.
|
|
67
|
+
* @param args.maxNames - How many names a group shows before it counts the rest.
|
|
68
|
+
* Defaults to 3, as the Comms apps show. Anything below 1 counts as 1.
|
|
69
|
+
* @returns A new title on every call.
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* ```typescript
|
|
73
|
+
* const users = await api.workspaceUsers.getWorkspaceUsers({
|
|
74
|
+
* workspaceId: 123,
|
|
75
|
+
* includeRemoved: true,
|
|
76
|
+
* })
|
|
77
|
+
* const title = getConversationTitle({ conversation, users, currentUserId: me.id })
|
|
78
|
+
* // { type: 'group', names: ['Bob J.', 'Cara S.', 'Dan B.'], othersCount: 2, includesYou: false }
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
export function getConversationTitle(args) {
|
|
82
|
+
const { conversation, users, currentUserId, maxNames = 3 } = args;
|
|
83
|
+
const usersById = new Map(users.map((user) => [user.id, user]));
|
|
84
|
+
const members = conversation.userIds.map((id) => {
|
|
85
|
+
// Someone missing from `users` reads as blank, which the shared rules
|
|
86
|
+
// count as a name that hasn't loaded.
|
|
87
|
+
const user = usersById.get(id);
|
|
88
|
+
return {
|
|
89
|
+
fullName: user?.fullName ?? '',
|
|
90
|
+
shortName: user?.shortName ?? '',
|
|
91
|
+
isYou: id === currentUserId,
|
|
92
|
+
isRemoved: user?.removed ?? false,
|
|
93
|
+
};
|
|
94
|
+
});
|
|
95
|
+
const title = getSharedConversationTitle({
|
|
96
|
+
[ConversationMemberProvidable.Symbol]: true,
|
|
97
|
+
getMemberCount: () => members.length,
|
|
98
|
+
getMemberFullName: (index) => members[index].fullName,
|
|
99
|
+
getMemberShortName: (index) => members[index].shortName,
|
|
100
|
+
isMemberYou: (index) => members[index].isYou,
|
|
101
|
+
isMemberRemoved: (index) => members[index].isRemoved,
|
|
102
|
+
}, getConversationKind(conversation.private), conversation.title, maxNames);
|
|
103
|
+
return {
|
|
104
|
+
type: TITLE_TYPE_BY_SHARED_NAME[title.type.name],
|
|
105
|
+
// The library asks for its array to be treated as read-only, so callers get a copy.
|
|
106
|
+
names: [...title.names],
|
|
107
|
+
othersCount: title.othersCount,
|
|
108
|
+
includesYou: title.includesYou,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Merges header records left to right. HTTP header names are case-insensitive,
|
|
3
|
+
* so a later record replaces any earlier header with the same name whatever
|
|
4
|
+
* its case. Without this, a caller's `authorization` would sit alongside the
|
|
5
|
+
* SDK's `Authorization` and `fetch` would join the two into one value.
|
|
6
|
+
*/
|
|
7
|
+
export function mergeHeaders(...sources) {
|
|
8
|
+
const merged = {};
|
|
9
|
+
for (const source of sources) {
|
|
10
|
+
if (!source)
|
|
11
|
+
continue;
|
|
12
|
+
for (const [name, value] of Object.entries(source)) {
|
|
13
|
+
const lowerName = name.toLowerCase();
|
|
14
|
+
for (const existingName of Object.keys(merged)) {
|
|
15
|
+
if (existingName.toLowerCase() === lowerName)
|
|
16
|
+
delete merged[existingName];
|
|
17
|
+
}
|
|
18
|
+
merged[name] = value;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return merged;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Turns the `headers` option into the record to send with one request, calling
|
|
25
|
+
* it when it is a function so per-request values are fresh.
|
|
26
|
+
*/
|
|
27
|
+
export function resolveCustomHeaders(headers) {
|
|
28
|
+
return typeof headers === 'function' ? headers() : headers;
|
|
29
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { v4 as uuid } from 'uuid';
|
|
2
|
+
import { fetchWithRetry } from '../transport/fetch-with-retry.js';
|
|
3
|
+
import { mergeHeaders, resolveCustomHeaders } from './headers.js';
|
|
4
|
+
/**
|
|
5
|
+
* Determine a content-type from a filename extension. Falls back to
|
|
6
|
+
* `application/octet-stream` for unknown extensions.
|
|
7
|
+
*/
|
|
8
|
+
export function getContentTypeFromFileName(fileName) {
|
|
9
|
+
const extension = fileName.toLowerCase().split('.').pop();
|
|
10
|
+
return extension ? (MIME_BY_EXTENSION[extension] ?? DEFAULT_MIME_TYPE) : DEFAULT_MIME_TYPE;
|
|
11
|
+
}
|
|
12
|
+
const DEFAULT_MIME_TYPE = 'application/octet-stream';
|
|
13
|
+
/**
|
|
14
|
+
* Extension → MIME map covering the formats commonly attached to messages.
|
|
15
|
+
* Anything not listed falls back to {@link DEFAULT_MIME_TYPE}; callers can
|
|
16
|
+
* always override via the `contentType` argument.
|
|
17
|
+
*/
|
|
18
|
+
const MIME_BY_EXTENSION = {
|
|
19
|
+
// Images
|
|
20
|
+
png: 'image/png',
|
|
21
|
+
jpg: 'image/jpeg',
|
|
22
|
+
jpeg: 'image/jpeg',
|
|
23
|
+
gif: 'image/gif',
|
|
24
|
+
webp: 'image/webp',
|
|
25
|
+
svg: 'image/svg+xml',
|
|
26
|
+
bmp: 'image/bmp',
|
|
27
|
+
ico: 'image/x-icon',
|
|
28
|
+
tif: 'image/tiff',
|
|
29
|
+
tiff: 'image/tiff',
|
|
30
|
+
heic: 'image/heic',
|
|
31
|
+
heif: 'image/heif',
|
|
32
|
+
avif: 'image/avif',
|
|
33
|
+
// Documents / text
|
|
34
|
+
pdf: 'application/pdf',
|
|
35
|
+
txt: 'text/plain',
|
|
36
|
+
md: 'text/markdown',
|
|
37
|
+
csv: 'text/csv',
|
|
38
|
+
json: 'application/json',
|
|
39
|
+
xml: 'application/xml',
|
|
40
|
+
html: 'text/html',
|
|
41
|
+
htm: 'text/html',
|
|
42
|
+
rtf: 'application/rtf',
|
|
43
|
+
doc: 'application/msword',
|
|
44
|
+
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
45
|
+
xls: 'application/vnd.ms-excel',
|
|
46
|
+
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
47
|
+
ppt: 'application/vnd.ms-powerpoint',
|
|
48
|
+
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
49
|
+
// Archives
|
|
50
|
+
zip: 'application/zip',
|
|
51
|
+
gz: 'application/gzip',
|
|
52
|
+
tar: 'application/x-tar',
|
|
53
|
+
'7z': 'application/x-7z-compressed',
|
|
54
|
+
rar: 'application/vnd.rar',
|
|
55
|
+
// Audio
|
|
56
|
+
mp3: 'audio/mpeg',
|
|
57
|
+
wav: 'audio/wav',
|
|
58
|
+
ogg: 'audio/ogg',
|
|
59
|
+
m4a: 'audio/mp4',
|
|
60
|
+
flac: 'audio/flac',
|
|
61
|
+
aac: 'audio/aac',
|
|
62
|
+
// Video
|
|
63
|
+
mp4: 'video/mp4',
|
|
64
|
+
m4v: 'video/mp4',
|
|
65
|
+
mov: 'video/quicktime',
|
|
66
|
+
avi: 'video/x-msvideo',
|
|
67
|
+
webm: 'video/webm',
|
|
68
|
+
mkv: 'video/x-matroska',
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Normalise a supported {@link UploadFile} into a `Blob` plus a resolved file name and
|
|
72
|
+
* content type, ready to be encoded into the multipart body.
|
|
73
|
+
*/
|
|
74
|
+
function toBlob(file, fileName, contentType) {
|
|
75
|
+
if (file instanceof Blob) {
|
|
76
|
+
// Duck-type the name rather than `instanceof File`: `File` isn't a global in
|
|
77
|
+
// Node 18, so a `node:buffer` `File` (which carries a real `name`) would
|
|
78
|
+
// otherwise fall back to `'upload'` and lose its inferred file name.
|
|
79
|
+
const blobName = file.name;
|
|
80
|
+
const name = fileName || (typeof blobName === 'string' ? blobName : undefined) || 'upload';
|
|
81
|
+
const type = contentType || file.type || getContentTypeFromFileName(name);
|
|
82
|
+
// Re-wrap only when stamping a type the Blob doesn't already carry.
|
|
83
|
+
const blob = file.type === type ? file : new Blob([file], { type });
|
|
84
|
+
return { blob, fileName: name, contentType: type };
|
|
85
|
+
}
|
|
86
|
+
if (file instanceof Uint8Array) {
|
|
87
|
+
if (!fileName) {
|
|
88
|
+
throw new Error('fileName is required when uploading raw bytes');
|
|
89
|
+
}
|
|
90
|
+
const type = contentType || getContentTypeFromFileName(fileName);
|
|
91
|
+
// `Blob` accepts any `ArrayBufferView`; the cast satisfies the stricter lib
|
|
92
|
+
// `BlobPart` type (which pins the backing buffer to `ArrayBuffer`).
|
|
93
|
+
return { blob: new Blob([file], { type }), fileName, contentType: type };
|
|
94
|
+
}
|
|
95
|
+
throw new Error('Unsupported file type for upload: expected a Blob or Uint8Array');
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Escapes a value for use inside a quoted `Content-Disposition` parameter, where a raw
|
|
99
|
+
* quote would end the value early and a raw CR or LF would end the header. A lone CR
|
|
100
|
+
* needs escaping too, not just CRLF pairs.
|
|
101
|
+
*
|
|
102
|
+
* This is the same escaping the platform's own `FormData` encoder applies, so servers
|
|
103
|
+
* see exactly what they would from any browser.
|
|
104
|
+
*/
|
|
105
|
+
function escapeDispositionValue(value) {
|
|
106
|
+
return value.replace(/"/g, '%22').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Rejects a media type that could not be safely written into a part header.
|
|
110
|
+
*
|
|
111
|
+
* `contentType` is public caller input and reaches the header verbatim. A value
|
|
112
|
+
* carrying a CR or LF would end the header early and let the caller forge one
|
|
113
|
+
* of its own — `Blob` normalises the `type` it stores, but the supplied value
|
|
114
|
+
* is what gets interpolated. Reject rather than silently rewrite, so a caller
|
|
115
|
+
* passing something unusable finds out instead of having it altered.
|
|
116
|
+
*/
|
|
117
|
+
function assertHeaderSafeContentType(contentType) {
|
|
118
|
+
if (!/^[\x20-\x7e]*$/.test(contentType)) {
|
|
119
|
+
throw new Error('contentType must contain only printable ASCII characters, without CR or LF');
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Encodes a `multipart/form-data` body as a `Blob`, together with the `Content-Type`
|
|
124
|
+
* that describes it.
|
|
125
|
+
*
|
|
126
|
+
* Deliberately avoids `FormData`. A `FormData` body is only encoded by the `fetch` that
|
|
127
|
+
* owns that `FormData` class — undici brands its own and checks it with a plain
|
|
128
|
+
* `instanceof` — and the SDK dispatches through undici's own `fetch` to keep the request
|
|
129
|
+
* client on the same undici as the dispatcher. A global `FormData` handed to it is
|
|
130
|
+
* stringified to the literal `"[object FormData]"`, so the upload silently carries no
|
|
131
|
+
* file. `Blob` has no such brand and works with whichever `fetch` sends the request,
|
|
132
|
+
* including a caller-supplied `customFetch`.
|
|
133
|
+
*/
|
|
134
|
+
function buildMultipartBody(args) {
|
|
135
|
+
const { blob, fileName, contentType, fields } = args;
|
|
136
|
+
assertHeaderSafeContentType(contentType);
|
|
137
|
+
const boundary = `----comms-sdk-${uuid()}`;
|
|
138
|
+
const parts = [
|
|
139
|
+
`--${boundary}\r\n` +
|
|
140
|
+
`Content-Disposition: form-data; name="file"; filename="${escapeDispositionValue(fileName)}"\r\n` +
|
|
141
|
+
`Content-Type: ${contentType}\r\n\r\n`,
|
|
142
|
+
blob,
|
|
143
|
+
'\r\n',
|
|
144
|
+
];
|
|
145
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
146
|
+
if (value !== undefined && value !== null) {
|
|
147
|
+
parts.push(`--${boundary}\r\n` +
|
|
148
|
+
`Content-Disposition: form-data; name="${escapeDispositionValue(key)}"\r\n\r\n` +
|
|
149
|
+
`${String(value)}\r\n`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
parts.push(`--${boundary}--\r\n`);
|
|
153
|
+
return { body: new Blob(parts), contentType: `multipart/form-data; boundary=${boundary}` };
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Upload a file using `multipart/form-data`.
|
|
157
|
+
*
|
|
158
|
+
* Encodes the request body as a `Blob` so it works unchanged in the browser and in
|
|
159
|
+
* Node.js, whichever `fetch` ends up sending it. The `file` part is sent alongside `file_name`,
|
|
160
|
+
* `file_size`, and `underlying_type` fields (the canonical Comms upload shape); any
|
|
161
|
+
* `additionalFields` are merged in and override the derived values. Authentication uses
|
|
162
|
+
* `Authorization: Bearer`, matching every other Comms SDK client.
|
|
163
|
+
*
|
|
164
|
+
* The response is JSON-parsed and camel-cased by {@link fetchWithRetry}; callers validate
|
|
165
|
+
* the returned shape with the appropriate schema.
|
|
166
|
+
*/
|
|
167
|
+
export async function uploadMultipartFile(args) {
|
|
168
|
+
const { baseUrl, authToken, endpoint, file, fileName, contentType, additionalFields, maxRetries = 0, requestId, headers: customHeaders, customFetch, } = args;
|
|
169
|
+
const { blob, fileName: resolvedFileName, contentType: resolvedType, } = toBlob(file, fileName, contentType);
|
|
170
|
+
const fields = {
|
|
171
|
+
file_name: resolvedFileName,
|
|
172
|
+
file_size: blob.size,
|
|
173
|
+
underlying_type: resolvedType,
|
|
174
|
+
...additionalFields,
|
|
175
|
+
};
|
|
176
|
+
const multipart = buildMultipartBody({
|
|
177
|
+
blob,
|
|
178
|
+
fileName: resolvedFileName,
|
|
179
|
+
contentType: resolvedType,
|
|
180
|
+
fields,
|
|
181
|
+
});
|
|
182
|
+
// Custom headers come first so they can never replace the SDK's own.
|
|
183
|
+
const headers = mergeHeaders(resolveCustomHeaders(customHeaders), {
|
|
184
|
+
Authorization: `Bearer ${authToken}`,
|
|
185
|
+
// The boundary is ours, so this has to be declared explicitly — `fetch`
|
|
186
|
+
// only fills it in for a `FormData` body.
|
|
187
|
+
'Content-Type': multipart.contentType,
|
|
188
|
+
...(requestId ? { 'X-Request-Id': requestId } : {}),
|
|
189
|
+
});
|
|
190
|
+
const url = new URL(endpoint, baseUrl).toString();
|
|
191
|
+
const response = await fetchWithRetry(url, {
|
|
192
|
+
method: 'POST',
|
|
193
|
+
headers,
|
|
194
|
+
body: multipart.body,
|
|
195
|
+
timeout: 30000,
|
|
196
|
+
}, maxRetries, customFetch);
|
|
197
|
+
return response.data;
|
|
198
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who a new reply in a thread notifies by default.
|
|
3
|
+
*
|
|
4
|
+
* The rule comes from `@doist/sdk-kmp`, the shared implementation of Comms
|
|
5
|
+
* logic, so replies default to the same people as in the other Comms clients.
|
|
6
|
+
*/
|
|
7
|
+
import { getDefaultReplyRecipients as getSharedDefaultReplyRecipients, ReplyRecipientsProvidable, } from '@doist/sdk-kmp/shared-comms-clients';
|
|
8
|
+
import { EVERYONE, EVERYONE_IN_THREAD, GROUP_ID_MARKERS } from '../types/enums.js';
|
|
9
|
+
/**
|
|
10
|
+
* Whether a system message marks a masked post: an integration's post, or an
|
|
11
|
+
* imported comment, shown under someone else's name.
|
|
12
|
+
*/
|
|
13
|
+
function isMasked(systemMessage) {
|
|
14
|
+
return (typeof systemMessage === 'object' &&
|
|
15
|
+
systemMessage !== null &&
|
|
16
|
+
'type' in systemMessage &&
|
|
17
|
+
systemMessage.type === 'USER_MASK');
|
|
18
|
+
}
|
|
19
|
+
function recipientsOf(post) {
|
|
20
|
+
return post.recipients ?? [];
|
|
21
|
+
}
|
|
22
|
+
function groupsOf(post) {
|
|
23
|
+
return post.groups ?? [];
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Returns the audience the special groups stand for. A comment that notified
|
|
27
|
+
* both reached the whole channel, so the channel wins.
|
|
28
|
+
*/
|
|
29
|
+
function getNotifyAudience(groupIds) {
|
|
30
|
+
if (groupIds.includes(EVERYONE)) {
|
|
31
|
+
return 'channel';
|
|
32
|
+
}
|
|
33
|
+
if (groupIds.includes(EVERYONE_IN_THREAD)) {
|
|
34
|
+
return 'thread';
|
|
35
|
+
}
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
function isSpecialGroup(groupId) {
|
|
39
|
+
return GROUP_ID_MARKERS.includes(groupId);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Works out who a new reply in a thread notifies by default, as the current
|
|
43
|
+
* user writes it.
|
|
44
|
+
*
|
|
45
|
+
* - The newest comment that counts sets the default: its author, and the
|
|
46
|
+
* people and groups it notified. Deleted comments, system messages (such as
|
|
47
|
+
* closing, reopening or moving the thread) and masked posts from
|
|
48
|
+
* integrations or imports don't count. A comment that notified one person
|
|
49
|
+
* does.
|
|
50
|
+
* - With no comment that counts, the thread sets it the same way, except that
|
|
51
|
+
* a thread to everyone in the channel defaults to everyone who interacted.
|
|
52
|
+
* - Closing a thread, or replying in a closed one, defaults to everyone who
|
|
53
|
+
* interacted, and nobody else.
|
|
54
|
+
* - The current user is never one of the people.
|
|
55
|
+
*
|
|
56
|
+
* Everyone in the channel and everyone who interacted come back as
|
|
57
|
+
* `notifyAudience` rather than in `groups`. If a comment notified both, the
|
|
58
|
+
* channel wins. The lists are always there, empty or not, so the result can be
|
|
59
|
+
* spread straight into `createComment` or `closeThread`.
|
|
60
|
+
*
|
|
61
|
+
* @param args - The arguments for working out the recipients.
|
|
62
|
+
* @param args.thread - The thread's `creator`, `recipients`, `groups` and `closed` flag.
|
|
63
|
+
* @param args.comments - The thread's comments, oldest first, as `getComments` returns them.
|
|
64
|
+
* @param args.currentUserId - The ID of the user writing the reply.
|
|
65
|
+
* @param args.isClosingThread - Whether the reply closes the thread. Defaults to `false`.
|
|
66
|
+
* @returns A new object on every call.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```typescript
|
|
70
|
+
* const comments = await api.comments.getComments({ threadId: thread.id })
|
|
71
|
+
* await api.comments.createComment({
|
|
72
|
+
* threadId: thread.id,
|
|
73
|
+
* content: 'On it',
|
|
74
|
+
* ...getDefaultReplyRecipients({ thread, comments, currentUserId: me.id }),
|
|
75
|
+
* })
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export function getDefaultReplyRecipients(args) {
|
|
79
|
+
const { thread, comments, currentUserId, isClosingThread = false } = args;
|
|
80
|
+
// The shared rule reads comments newest first.
|
|
81
|
+
const comment = (index) => comments[comments.length - 1 - index];
|
|
82
|
+
// The library takes IDs as strings, and these come back as numbers below.
|
|
83
|
+
const result = getSharedDefaultReplyRecipients({
|
|
84
|
+
[ReplyRecipientsProvidable.Symbol]: true,
|
|
85
|
+
getThreadAuthorId: () => String(thread.creator),
|
|
86
|
+
getThreadRecipientCount: () => recipientsOf(thread).length,
|
|
87
|
+
getThreadRecipientId: (index) => String(recipientsOf(thread)[index]),
|
|
88
|
+
getThreadGroupCount: () => groupsOf(thread).length,
|
|
89
|
+
getThreadGroupId: (index) => groupsOf(thread)[index],
|
|
90
|
+
isThreadClosed: () => thread.closed === true,
|
|
91
|
+
getCommentCount: () => comments.length,
|
|
92
|
+
getCommentAuthorId: (index) => String(comment(index).creator),
|
|
93
|
+
getCommentRecipientCount: (index) => recipientsOf(comment(index)).length,
|
|
94
|
+
getCommentRecipientId: (index, recipientIndex) => String(recipientsOf(comment(index))[recipientIndex]),
|
|
95
|
+
getCommentGroupCount: (index) => groupsOf(comment(index)).length,
|
|
96
|
+
getCommentGroupId: (index, groupIndex) => groupsOf(comment(index))[groupIndex],
|
|
97
|
+
isCommentDeleted: (index) => comment(index).deleted === true,
|
|
98
|
+
// Comments from the API have all been posted.
|
|
99
|
+
isCommentDraft: () => false,
|
|
100
|
+
isCommentSystemMessage: (index) => {
|
|
101
|
+
const { systemMessage } = comment(index);
|
|
102
|
+
return systemMessage != null && !isMasked(systemMessage);
|
|
103
|
+
},
|
|
104
|
+
isCommentMasked: (index) => isMasked(comment(index).systemMessage),
|
|
105
|
+
}, String(currentUserId), isClosingThread);
|
|
106
|
+
return {
|
|
107
|
+
recipients: result.recipientIds.map(Number),
|
|
108
|
+
groups: result.groupIds.filter((groupId) => !isSpecialGroup(groupId)),
|
|
109
|
+
notifyAudience: getNotifyAudience(result.groupIds),
|
|
110
|
+
};
|
|
111
|
+
}
|