@sendbird/uikit-utils 3.1.2 → 3.3.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.
Files changed (38) hide show
  1. package/lib/commonjs/hooks/index.js.map +1 -1
  2. package/lib/commonjs/hooks/react-native.js +25 -1
  3. package/lib/commonjs/hooks/react-native.js.map +1 -1
  4. package/lib/commonjs/sendbird/message.js +28 -0
  5. package/lib/commonjs/sendbird/message.js.map +1 -1
  6. package/lib/commonjs/shared/file.js +1 -0
  7. package/lib/commonjs/shared/file.js.map +1 -1
  8. package/lib/commonjs/shared/index.js +8 -0
  9. package/lib/commonjs/shared/index.js.map +1 -1
  10. package/lib/commonjs/types.js.map +1 -1
  11. package/lib/commonjs/ui-format/common.js +26 -1
  12. package/lib/commonjs/ui-format/common.js.map +1 -1
  13. package/lib/module/hooks/index.js.map +1 -1
  14. package/lib/module/hooks/react-native.js +24 -1
  15. package/lib/module/hooks/react-native.js.map +1 -1
  16. package/lib/module/sendbird/message.js +26 -1
  17. package/lib/module/sendbird/message.js.map +1 -1
  18. package/lib/module/shared/file.js +1 -0
  19. package/lib/module/shared/file.js.map +1 -1
  20. package/lib/module/shared/index.js +6 -0
  21. package/lib/module/shared/index.js.map +1 -1
  22. package/lib/module/types.js.map +1 -1
  23. package/lib/module/ui-format/common.js +23 -0
  24. package/lib/module/ui-format/common.js.map +1 -1
  25. package/lib/typescript/src/hooks/index.d.ts +1 -1
  26. package/lib/typescript/src/hooks/react-native.d.ts +11 -0
  27. package/lib/typescript/src/sendbird/message.d.ts +9 -1
  28. package/lib/typescript/src/shared/index.d.ts +2 -0
  29. package/lib/typescript/src/types.d.ts +1 -1
  30. package/lib/typescript/src/ui-format/common.d.ts +8 -0
  31. package/package.json +5 -9
  32. package/src/hooks/index.ts +2 -2
  33. package/src/hooks/react-native.ts +24 -1
  34. package/src/sendbird/message.ts +29 -2
  35. package/src/shared/file.ts +1 -0
  36. package/src/shared/index.ts +8 -0
  37. package/src/types.ts +3 -1
  38. package/src/ui-format/common.ts +27 -0
@@ -1,5 +1,5 @@
1
1
  import { MessageSearchOrder } from '@sendbird/chat/message';
2
- import { getFileExtension, getFileType } from '../shared/file';
2
+ import { getFileExtension, getFileType, parseMimeType } from '../shared/file';
3
3
  import { getMessageTimeFormat } from '../ui-format/common';
4
4
  export function isNewMessage(msg, currentUserId) {
5
5
  const myMessage = isMyMessage(msg, currentUserId);
@@ -158,6 +158,9 @@ export function getMessageType(message) {
158
158
  return 'user';
159
159
  }
160
160
  if (message.isFileMessage()) {
161
+ if (isVoiceMessage(message)) {
162
+ return 'file.voice';
163
+ }
161
164
  const fileType = getFileTypeFromMessage(message);
162
165
  switch (fileType) {
163
166
  case 'image':
@@ -185,4 +188,26 @@ export function getDefaultMessageSearchQueryParams(channel, keyword) {
185
188
  order: MessageSearchOrder.TIMESTAMP
186
189
  };
187
190
  }
191
+ const SBU_MIME_PARAM_KEY = 'sbu_type';
192
+ const SBU_MIME_PARAM_VOICE_MESSAGE_VALUE = 'voice';
193
+ export function isVoiceMessage(message) {
194
+ if (!message.isFileMessage()) return false;
195
+ const {
196
+ parameters
197
+ } = parseMimeType(message.type);
198
+ return !!parameters[SBU_MIME_PARAM_KEY] && parameters[SBU_MIME_PARAM_KEY] === SBU_MIME_PARAM_VOICE_MESSAGE_VALUE;
199
+ }
200
+ export function getVoiceMessageFileObject(uri) {
201
+ let extension = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'm4a';
202
+ return {
203
+ uri,
204
+ type: getVoiceMessageMimeType(extension),
205
+ name: `Voice_message.${extension}`,
206
+ size: 0
207
+ };
208
+ }
209
+ export function getVoiceMessageMimeType() {
210
+ let extension = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'm4a';
211
+ return `audio/${extension};${SBU_MIME_PARAM_KEY}=${SBU_MIME_PARAM_VOICE_MESSAGE_VALUE}`;
212
+ }
188
213
  //# sourceMappingURL=message.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["MessageSearchOrder","getFileExtension","getFileType","getMessageTimeFormat","isNewMessage","msg","currentUserId","myMessage","isMyMessage","isAdminMessage","updatedAt","isSendableMessage","undefined","_msg$sender","arguments","length","sender","userId","messageKeyExtractor","message","getMessageUniqId","messageComparator","a","b","aStatusOffset","bStatusOffset","sendingStatus","Number","MAX_SAFE_INTEGER","createdAt","hasSameSender","_a$sender","_b$sender","calcMessageGrouping","groupEnabled","curr","prev","next","getPrev","Date","getNext","groupWithPrev","groupWithNext","isUserMessage","isFileMessage","String","messageId","reqId","getThumbnailUriFromFileMessage","thumbnails","url","getAvailableUriFromFileMessage","_message$messageParam","messageParams","file","uri","isSendbirdNotification","dataPayload","Boolean","parseSendbirdNotification","sendbird","JSON","parse","shouldRenderParentMessage","_message$parentMessag","_message$parentMessag2","parentMessage","shouldRenderReaction","channel","reactionEnabled","isOpenChannel","isGroupChannel","isBroadcast","isSuper","isEphemeral","getReactionCount","reaction","userIds","fileIconMapper","getFileTypeFromMessage","type","name","convertFileTypeToMessageType","fileType","getFileIconFromMessageType","messageType","getFileIconFromMessage","getMessageType","ogMetaData","getDefaultMessageSearchQueryParams","keyword","channelUrl","messageTimestampFrom","Math","max","joinedAt","invitedAt","order","TIMESTAMP"],"sources":["message.ts"],"sourcesContent":["import { MessageSearchOrder } from '@sendbird/chat/message';\n\nimport { getFileExtension, getFileType } from '../shared/file';\nimport type {\n SendbirdBaseChannel,\n SendbirdBaseMessage,\n SendbirdDataPayload,\n SendbirdFileMessage,\n SendbirdGroupChannel,\n SendbirdMessage,\n SendbirdReaction,\n SendbirdSendableMessage,\n SendbirdUserMessage,\n} from '../types';\nimport { getMessageTimeFormat } from '../ui-format/common';\n\nexport function isNewMessage(msg: SendbirdMessage, currentUserId?: string) {\n const myMessage = isMyMessage(msg, currentUserId);\n if (myMessage) return false;\n if (msg.isAdminMessage()) return false;\n return msg.updatedAt === 0;\n}\n\nexport function isSendableMessage(msg?: SendbirdMessage | null): msg is SendbirdSendableMessage {\n return msg !== undefined && msg !== null && 'sendingStatus' in msg;\n}\n\nexport function isMyMessage(\n msg?: SendbirdMessage | null,\n currentUserId = '##__USER_ID_IS_NOT_PROVIDED__##',\n): msg is SendbirdSendableMessage {\n if (!isSendableMessage(msg)) return false;\n return msg.sender?.userId === currentUserId;\n}\n\nexport function messageKeyExtractor(message: SendbirdMessage): string {\n return getMessageUniqId(message);\n}\n\n// |-------------------|-------------------|-----------------|-------------------|\n// | sending status | reqId | messageId | createdAt |\n// |-------------------|-------------------|-----------------|-------------------|\n// | pending | timestamp(A) | 0 | timestamp(B) |\n// | canceled | timestamp(A) | 0 | ? |\n// | failed | timestamp(A) | 0 | ? |\n// | succeeded | timestamp(A) / '' | id from DB | timestamp(C) |\n// |-------------------|-------------------|-----------------|-------------------|\nexport function messageComparator(a: SendbirdMessage, b: SendbirdMessage) {\n let aStatusOffset = 0;\n let bStatusOffset = 0;\n\n if (isSendableMessage(a) && a.sendingStatus !== 'succeeded') aStatusOffset = Number.MAX_SAFE_INTEGER;\n if (isSendableMessage(b) && b.sendingStatus !== 'succeeded') bStatusOffset = Number.MAX_SAFE_INTEGER;\n\n return b.createdAt + bStatusOffset - (a.createdAt + aStatusOffset);\n}\n\nexport function hasSameSender(a?: SendbirdMessage, b?: SendbirdMessage) {\n if (!a || !b) return false;\n if ('sender' in a && 'sender' in b) return a.sender?.userId === b.sender?.userId;\n return false;\n}\n\nexport function calcMessageGrouping(\n groupEnabled: boolean,\n curr: SendbirdMessage,\n prev?: SendbirdMessage,\n next?: SendbirdMessage,\n) {\n const getPrev = () => {\n if (!groupEnabled) return false;\n if (!prev) return false;\n if (curr.isAdminMessage()) return false;\n if (!hasSameSender(curr, prev)) return false;\n if (getMessageTimeFormat(new Date(curr.createdAt)) !== getMessageTimeFormat(new Date(prev.createdAt))) return false;\n return true;\n };\n\n const getNext = () => {\n if (!groupEnabled) return false;\n if (!next) return false;\n if (curr.isAdminMessage()) return false;\n if (!hasSameSender(curr, next)) return false;\n if (getMessageTimeFormat(new Date(curr.createdAt)) !== getMessageTimeFormat(new Date(next.createdAt))) return false;\n return true;\n };\n\n return { groupWithPrev: getPrev(), groupWithNext: getNext() };\n}\n\nexport function getMessageUniqId(msg: SendbirdBaseMessage) {\n if (msg.isUserMessage() || msg.isFileMessage()) {\n if (msg.sendingStatus === 'succeeded') return String(msg.messageId);\n return msg.reqId;\n }\n\n return String(msg.messageId);\n}\n\nexport function getThumbnailUriFromFileMessage(message: SendbirdFileMessage) {\n if (message.thumbnails && message.thumbnails.length > 0) {\n return message.thumbnails[0].url;\n }\n\n return getAvailableUriFromFileMessage(message);\n}\n\nexport function getAvailableUriFromFileMessage(message: SendbirdFileMessage) {\n if (!message.url && message.messageParams?.file && 'uri' in message.messageParams.file) {\n return message.messageParams.file.uri;\n }\n\n return message.url;\n}\n\ntype RawSendbirdDataPayload = { sendbird: string | object };\nexport function isSendbirdNotification(dataPayload?: {\n [key: string]: string | object;\n}): dataPayload is RawSendbirdDataPayload {\n if (!dataPayload) return false;\n return Boolean(dataPayload['sendbird']);\n}\n\nexport function parseSendbirdNotification(dataPayload: RawSendbirdDataPayload): SendbirdDataPayload {\n return typeof dataPayload.sendbird === 'string' ? JSON.parse(dataPayload.sendbird) : dataPayload.sendbird;\n}\n\nexport function shouldRenderParentMessage(message: SendbirdMessage): message is (\n | SendbirdUserMessage\n | SendbirdFileMessage\n) & {\n parentMessage: SendbirdUserMessage | SendbirdFileMessage;\n} {\n return !!(\n (message.isFileMessage() || message.isUserMessage()) &&\n (message.parentMessage?.isFileMessage() || message.parentMessage?.isUserMessage())\n );\n}\n\nexport function shouldRenderReaction(channel: SendbirdBaseChannel, reactionEnabled: boolean) {\n if (channel.isOpenChannel()) {\n return false;\n }\n\n if (channel.isGroupChannel()) {\n if (channel.isBroadcast) return false;\n if (channel.isSuper) return false;\n if (channel.isEphemeral) return false;\n }\n\n return reactionEnabled;\n}\n\nexport function getReactionCount(reaction: SendbirdReaction) {\n return reaction.userIds.length;\n}\n\nexport type MessageType =\n | 'user'\n | 'admin'\n | 'file'\n | 'unknown'\n | `user.${'opengraph'}`\n | `file.${'image' | 'video' | 'audio'}`;\n\nexport type FileType = 'file' | 'image' | 'audio' | 'video';\n\nconst fileIconMapper = {\n 'audio': 'file-audio',\n 'image': 'photo',\n 'video': 'play',\n 'file': 'file-document',\n} as const;\n\ntype ValueOf<T> = T[keyof T];\nexport type FileIcon = ValueOf<typeof fileIconMapper>;\n\nexport function getFileTypeFromMessage(message: SendbirdFileMessage): FileType {\n return getFileType(message.type || getFileExtension(message.name));\n}\nexport const convertFileTypeToMessageType = (fileType: FileType = 'file'): MessageType => {\n switch (fileType) {\n case 'audio':\n case 'image':\n case 'video':\n return `file.${fileType}`;\n case 'file':\n return fileType;\n }\n};\nexport const getFileIconFromMessageType = (messageType: MessageType): FileIcon => {\n switch (messageType) {\n case 'file':\n return fileIconMapper['file'];\n case 'file.image':\n return fileIconMapper['image'];\n case 'file.video':\n return fileIconMapper['video'];\n case 'file.audio':\n return fileIconMapper['audio'];\n default:\n return fileIconMapper['file'];\n }\n};\nexport const getFileIconFromMessage = (message: SendbirdFileMessage): FileIcon => {\n const fileType = getFileTypeFromMessage(message);\n const messageType = convertFileTypeToMessageType(fileType);\n return getFileIconFromMessageType(messageType);\n};\n\nexport function getMessageType(message: SendbirdMessage): MessageType {\n if (message.isAdminMessage()) {\n return 'admin';\n }\n\n if (message.isUserMessage()) {\n if (message.ogMetaData) {\n return 'user.opengraph';\n }\n return 'user';\n }\n\n if (message.isFileMessage()) {\n const fileType = getFileTypeFromMessage(message);\n switch (fileType) {\n case 'image':\n case 'video': {\n return `file.${fileType}`;\n }\n case 'audio': {\n return `file.${fileType}`;\n }\n default: {\n return 'file';\n }\n }\n }\n\n return 'unknown';\n}\n\nexport function getDefaultMessageSearchQueryParams(channel: SendbirdGroupChannel, keyword: string) {\n return {\n keyword,\n channelUrl: channel.url,\n messageTimestampFrom: Math.max(channel.joinedAt, channel.invitedAt),\n order: MessageSearchOrder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AsB,CAAC5D,OAAO,CAAC;EAChD,MAAMkE,WAAW,GAAGH,4BAA4B,CAACC,QAAQ,CAAC;EAC1D,OAAOC,0BAA0B,CAACC,WAAW,CAAC;AAChD,CAAC;AAED,OAAO,SAASE,cAAcA,CAACpE,OAAwB,EAAe;EACpE,IAAIA,OAAO,CAACV,cAAc,EAAE,EAAE;IAC5B,OAAO,OAAO;EAChB;EAEA,IAAIU,OAAO,CAACwB,aAAa,EAAE,EAAE;IAC3B,IAAIxB,OAAO,CAACqE,UAAU,EAAE;MACtB,OAAO,gBAAgB;IACzB;IACA,OAAO,MAAM;EACf;EAEA,IAAIrE,OAAO,CAACyB,aAAa,EAAE,EAAE;IAC3B,MAAMuC,QAAQ,GAAGJ,sBAAsB,CAAC5D,OAAO,CAAC;IAChD,QAAQgE,QAAQ;MACd,KAAK,OAAO;MACZ,KAAK,OAAO;QAAE;UACZ,OAAQ,QAAOA,QAAS,EAAC;QAC3B;MACA,KAAK,OAAO;QAAE;UACZ,OAAQ,QAAOA,QAAS,EAAC;QAC3B;MACA;QAAS;UACP,OAAO,MAAM;QACf;IAAC;EAEL;EAEA,OAAO,SAAS;AAClB;AAEA,OAAO,SAASM,kCAAkCA,CAACrB,OAA6B,EAAEsB,OAAe,EAAE;EACjG,OAAO;IACLA,OAAO;IACPC,UAAU,EAAEvB,OAAO,CAAClB,GAAG;IACvB0C,oBAAoB,EAAEC,IAAI,CAACC,GAAG,CAAC1B,OAAO,CAAC2B,QAAQ,EAAE3B,OAAO,CAAC4B,SAAS,CAAC;IACnEC,KAAK,EAAEjG,kBAAkB,CAACkG;EAC5B,CAAC;AACH"}
1
+ {"version":3,"names":["MessageSearchOrder","getFileExtension","getFileType","parseMimeType","getMessageTimeFormat","isNewMessage","msg","currentUserId","myMessage","isMyMessage","isAdminMessage","updatedAt","isSendableMessage","undefined","_msg$sender","arguments","length","sender","userId","messageKeyExtractor","message","getMessageUniqId","messageComparator","a","b","aStatusOffset","bStatusOffset","sendingStatus","Number","MAX_SAFE_INTEGER","createdAt","hasSameSender","_a$sender","_b$sender","calcMessageGrouping","groupEnabled","curr","prev","next","getPrev","Date","getNext","groupWithPrev","groupWithNext","isUserMessage","isFileMessage","String","messageId","reqId","getThumbnailUriFromFileMessage","thumbnails","url","getAvailableUriFromFileMessage","_message$messageParam","messageParams","file","uri","isSendbirdNotification","dataPayload","Boolean","parseSendbirdNotification","sendbird","JSON","parse","shouldRenderParentMessage","_message$parentMessag","_message$parentMessag2","parentMessage","shouldRenderReaction","channel","reactionEnabled","isOpenChannel","isGroupChannel","isBroadcast","isSuper","isEphemeral","getReactionCount","reaction","userIds","fileIconMapper","getFileTypeFromMessage","type","name","convertFileTypeToMessageType","fileType","getFileIconFromMessageType","messageType","getFileIconFromMessage","getMessageType","ogMetaData","isVoiceMessage","getDefaultMessageSearchQueryParams","keyword","channelUrl","messageTimestampFrom","Math","max","joinedAt","invitedAt","order","TIMESTAMP","SBU_MIME_PARAM_KEY","SBU_MIME_PARAM_VOICE_MESSAGE_VALUE","parameters","getVoiceMessageFileObject","extension","getVoiceMessageMimeType","size"],"sources":["message.ts"],"sourcesContent":["import { MessageSearchOrder } from '@sendbird/chat/message';\n\nimport { getFileExtension, getFileType, parseMimeType } from '../shared/file';\nimport type {\n SendbirdBaseChannel,\n SendbirdBaseMessage,\n SendbirdDataPayload,\n SendbirdFileMessage,\n SendbirdGroupChannel,\n SendbirdMessage,\n SendbirdReaction,\n SendbirdSendableMessage,\n SendbirdUserMessage,\n} from '../types';\nimport { getMessageTimeFormat } from '../ui-format/common';\n\nexport function isNewMessage(msg: SendbirdMessage, currentUserId?: string) {\n const myMessage = isMyMessage(msg, currentUserId);\n if (myMessage) return false;\n if (msg.isAdminMessage()) return false;\n return msg.updatedAt === 0;\n}\n\nexport function isSendableMessage(msg?: SendbirdMessage | null): msg is SendbirdSendableMessage {\n return msg !== undefined && msg !== null && 'sendingStatus' in msg;\n}\n\nexport function isMyMessage(\n msg?: SendbirdMessage | null,\n currentUserId = '##__USER_ID_IS_NOT_PROVIDED__##',\n): msg is SendbirdSendableMessage {\n if (!isSendableMessage(msg)) return false;\n return msg.sender?.userId === currentUserId;\n}\n\nexport function messageKeyExtractor(message: SendbirdMessage): string {\n return getMessageUniqId(message);\n}\n\n// |-------------------|-------------------|-----------------|-------------------|\n// | sending status | reqId | messageId | createdAt |\n// |-------------------|-------------------|-----------------|-------------------|\n// | pending | timestamp(A) | 0 | timestamp(B) |\n// | canceled | timestamp(A) | 0 | ? |\n// | failed | timestamp(A) | 0 | ? |\n// | succeeded | timestamp(A) / '' | id from DB | timestamp(C) |\n// |-------------------|-------------------|-----------------|-------------------|\nexport function messageComparator(a: SendbirdMessage, b: SendbirdMessage) {\n let aStatusOffset = 0;\n let bStatusOffset = 0;\n\n if (isSendableMessage(a) && a.sendingStatus !== 'succeeded') aStatusOffset = Number.MAX_SAFE_INTEGER;\n if (isSendableMessage(b) && b.sendingStatus !== 'succeeded') bStatusOffset = Number.MAX_SAFE_INTEGER;\n\n return b.createdAt + bStatusOffset - (a.createdAt + aStatusOffset);\n}\n\nexport function hasSameSender(a?: SendbirdMessage, b?: SendbirdMessage) {\n if (!a || !b) return false;\n if ('sender' in a && 'sender' in b) return a.sender?.userId === b.sender?.userId;\n return false;\n}\n\nexport function calcMessageGrouping(\n groupEnabled: boolean,\n curr: SendbirdMessage,\n prev?: SendbirdMessage,\n next?: SendbirdMessage,\n) {\n const getPrev = () => {\n if (!groupEnabled) return false;\n if (!prev) return false;\n if (curr.isAdminMessage()) return false;\n if (!hasSameSender(curr, prev)) return false;\n if (getMessageTimeFormat(new Date(curr.createdAt)) !== getMessageTimeFormat(new Date(prev.createdAt))) return false;\n return true;\n };\n\n const getNext = () => {\n if (!groupEnabled) return false;\n if (!next) return false;\n if (curr.isAdminMessage()) return false;\n if (!hasSameSender(curr, next)) return false;\n if (getMessageTimeFormat(new Date(curr.createdAt)) !== getMessageTimeFormat(new Date(next.createdAt))) return false;\n return true;\n };\n\n return { groupWithPrev: getPrev(), groupWithNext: getNext() };\n}\n\nexport function getMessageUniqId(msg: SendbirdBaseMessage) {\n if (msg.isUserMessage() || msg.isFileMessage()) {\n if (msg.sendingStatus === 'succeeded') return String(msg.messageId);\n return msg.reqId;\n }\n\n return String(msg.messageId);\n}\n\nexport function getThumbnailUriFromFileMessage(message: SendbirdFileMessage) {\n if (message.thumbnails && message.thumbnails.length > 0) {\n return message.thumbnails[0].url;\n }\n\n return getAvailableUriFromFileMessage(message);\n}\n\nexport function getAvailableUriFromFileMessage(message: SendbirdFileMessage) {\n if (!message.url && message.messageParams?.file && 'uri' in message.messageParams.file) {\n return message.messageParams.file.uri;\n }\n\n return message.url;\n}\n\ntype RawSendbirdDataPayload = { sendbird: string | object };\nexport function isSendbirdNotification(dataPayload?: {\n [key: string]: string | object;\n}): dataPayload is RawSendbirdDataPayload {\n if (!dataPayload) return false;\n return Boolean(dataPayload['sendbird']);\n}\n\nexport function parseSendbirdNotification(dataPayload: RawSendbirdDataPayload): SendbirdDataPayload {\n return typeof dataPayload.sendbird === 'string' ? JSON.parse(dataPayload.sendbird) : dataPayload.sendbird;\n}\n\nexport function shouldRenderParentMessage(message: SendbirdMessage): message is (\n | SendbirdUserMessage\n | SendbirdFileMessage\n) & {\n parentMessage: SendbirdUserMessage | SendbirdFileMessage;\n} {\n return !!(\n (message.isFileMessage() || message.isUserMessage()) &&\n (message.parentMessage?.isFileMessage() || message.parentMessage?.isUserMessage())\n );\n}\n\nexport function shouldRenderReaction(channel: SendbirdBaseChannel, reactionEnabled: boolean) {\n if (channel.isOpenChannel()) {\n return false;\n }\n\n if (channel.isGroupChannel()) {\n if (channel.isBroadcast) return false;\n if (channel.isSuper) return false;\n if (channel.isEphemeral) return false;\n }\n\n return reactionEnabled;\n}\n\nexport function getReactionCount(reaction: SendbirdReaction) {\n return reaction.userIds.length;\n}\n\nexport type MessageType =\n | 'user'\n | 'admin'\n | 'file'\n | 'unknown'\n | `user.${'opengraph'}`\n | `file.${'image' | 'video' | 'audio' | 'voice'}`;\n\nexport type FileType = 'file' | 'image' | 'audio' | 'video';\n\nconst fileIconMapper = {\n 'audio': 'file-audio',\n 'image': 'photo',\n 'video': 'play',\n 'file': 'file-document',\n} as const;\n\ntype ValueOf<T> = T[keyof T];\nexport type FileIcon = ValueOf<typeof fileIconMapper>;\n\nexport function getFileTypeFromMessage(message: SendbirdFileMessage): FileType {\n return getFileType(message.type || getFileExtension(message.name));\n}\nexport const convertFileTypeToMessageType = (fileType: FileType = 'file'): MessageType => {\n switch (fileType) {\n case 'audio':\n case 'image':\n case 'video':\n return `file.${fileType}`;\n case 'file':\n return fileType;\n }\n};\nexport const getFileIconFromMessageType = (messageType: MessageType): FileIcon => {\n switch (messageType) {\n case 'file':\n return fileIconMapper['file'];\n case 'file.image':\n return fileIconMapper['image'];\n case 'file.video':\n return fileIconMapper['video'];\n case 'file.audio':\n return fileIconMapper['audio'];\n default:\n return fileIconMapper['file'];\n }\n};\nexport const getFileIconFromMessage = (message: SendbirdFileMessage): FileIcon => {\n const fileType = getFileTypeFromMessage(message);\n const messageType = convertFileTypeToMessageType(fileType);\n return getFileIconFromMessageType(messageType);\n};\n\nexport function getMessageType(message: SendbirdMessage): MessageType {\n if (message.isAdminMessage()) {\n return 'admin';\n }\n\n if (message.isUserMessage()) {\n if (message.ogMetaData) {\n return 'user.opengraph';\n }\n return 'user';\n }\n\n if (message.isFileMessage()) {\n if (isVoiceMessage(message)) {\n return 'file.voice';\n }\n\n const fileType = getFileTypeFromMessage(message);\n switch (fileType) {\n case 'image':\n case 'video': {\n return `file.${fileType}`;\n }\n case 'audio': {\n return `file.${fileType}`;\n }\n default: {\n return 'file';\n }\n }\n }\n\n return 'unknown';\n}\n\nexport function getDefaultMessageSearchQueryParams(channel: SendbirdGroupChannel, keyword: string) {\n return {\n keyword,\n channelUrl: channel.url,\n messageTimestampFrom: Math.max(channel.joinedAt, channel.invitedAt),\n order: MessageSearchOrder.TIMESTAMP,\n };\n}\n\nconst SBU_MIME_PARAM_KEY = 'sbu_type';\nconst SBU_MIME_PARAM_VOICE_MESSAGE_VALUE = 'voice';\n\nexport function isVoiceMessage(message: SendbirdMessage): message is SendbirdFileMessage {\n if (!message.isFileMessage()) return false;\n\n const { parameters } = parseMimeType(message.type);\n return !!parameters[SBU_MIME_PARAM_KEY] && parameters[SBU_MIME_PARAM_KEY] === SBU_MIME_PARAM_VOICE_MESSAGE_VALUE;\n}\n\nexport function getVoiceMessageFileObject(uri: string, extension = 'm4a') {\n return {\n uri,\n type: getVoiceMessageMimeType(extension),\n name: `Voice_message.${extension}`,\n size: 0,\n };\n}\n\nexport function getVoiceMessageMimeType(extension = 'm4a') {\n return `audio/${extension};${SBU_MIME_PARAM_KEY}=${SBU_MIME_PARAM_VOICE_MESSAGE_VALUE}`;\n}\n"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,wBAAwB;AAE3D,SAASC,gBAAgB,EAAEC,WAAW,EAAEC,aAAa,QAAQ,gBAAgB;AAY7E,SAASC,oBAAoB,QAAQ,qBAAqB;AAE1D,OAAO,SAASC,YAAYA,CAACC,GAAoB,EAAEC,aAAsB,EAAE;EACzE,MAAMC,SAAS,GAAGC,WAAW,CAACH,GAAG,EAAEC,aAAa,CAAC;EACjD,IAAIC,SAAS,EAAE,OAAO,KAAK;EAC3B,IAAIF,GAAG,CAACI,cAAc,EAAE,EAAE,OAAO,KAAK;EACtC,OAAOJ,GAAG,CAACK,SAAS,KAAK,CAAC;AAC5B;AAEA,OAAO,SAASC,iBAAiBA,CAACN,GAA4B,EAAkC;EAC9F,OAAOA,GAAG,KAAKO,SAAS,IAAIP,GAAG,KAAK,IAAI,IAAI,eAAe,IAAIA,GAAG;AACpE;AAEA,OAAO,SAASG,WAAWA,CACzBH,GAA4B,EAEI;EAAA,IAAAQ,WAAA;EAAA,IADhCP,aAAa,GAAAQ,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAF,SAAA,GAAAE,SAAA,MAAG,iCAAiC;EAEjD,IAAI,CAACH,i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XTENSION_MIME_MAP = {
16
16
  'avi': 'video/x-msvideo',
17
17
  // Audio
18
18
  'aac': 'audio/aac',
19
+ 'm4a': 'audio/m4a',
19
20
  'mid': 'audio/midi',
20
21
  'mp3': 'audio/mpeg',
21
22
  'ogg': 'audio/ogg',
@@ -1 +1 @@
1
- {"version":3,"names":["EXTENSION_MIME_MAP","imageExtRegex","audioExtRegex","videoExtRegex","getFileType","extensionOrType","lowerCased","toLowerCase","indexOf","type","split","match","startsWith","getDownscaleSize","origin","resizing","ratio","maxWidth","width","maxHeight","height","Math","min","normalizeFileName","fileName","extension","_extension","_filename","hasExtension","lastIndexOf","length","parseMimeType","mimeType","fullType","parts","subtype","parameters","part","name","value","trim","getFileExtensionFromMime","MIME_EXTENSION_MAP","Object","entries","reduce","acc","_ref","key","getMimeFromFileExtension","ext","sliceIdx","extWithoutDot","slice","getFileExtension","filePath","pathWithoutParams","idx","result","getFileExtensionFromUri","uri","fetch","then","response","headers","get","isImage","shouldCompressImage","mime","compressionEnabled","arguments","undefined","Boolean"],"sources":["file.ts"],"sourcesContent":["const EXTENSION_MIME_MAP = {\n // Image\n 'jpeg': 'image/jpeg',\n 'jpg': 'image/jpeg',\n 'png': 'image/png',\n 'gif': 'image/gif',\n 'webp': 'image/webp',\n 'svg': 'image/svg+xml',\n\n // Video\n '3gp': 'video/3gpp',\n 'mp4': 'video/mp4',\n 'mpeg': 'video/mpeg',\n 'ogv': 'video/ogg',\n 'video/quicktime': 'mov',\n 'webm': 'video/webm',\n 'avi': 'video/x-msvideo',\n\n // Audio\n 'aac': 'audio/aac',\n 'mid': 'audio/midi',\n 'mp3': 'audio/mpeg',\n 'ogg': 'audio/ogg',\n 'wav': 'audio/wav',\n 'weba': 'audio/webm',\n\n // Files\n 'txt': 'text/plain',\n 'pdf': 'application/pdf',\n 'doc': 'application/msword',\n 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'xls': 'application/vnd.ms-excel',\n 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'ppt': 'application/vnd.ms-powerpoint',\n 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'zip': 'application/zip',\n 'json': 'application/json',\n 'gzip': 'application/x-gzip',\n} as Record<string, string>;\n\nexport const imageExtRegex = /jpeg|jpg|png|webp|gif/i;\nexport const audioExtRegex = /3gp|aac|aax|act|aiff|flac|gsm|m4a|m4b|m4p|tta|wma|mp3|webm|wav|ogg/i;\nexport const videoExtRegex = /mov|vod|mp4|avi|mpeg|ogv/i;\nexport const getFileType = (extensionOrType: string) => {\n const lowerCased = extensionOrType.toLowerCase();\n\n // mime type\n if (lowerCased.indexOf('/') > -1) {\n const type = lowerCased.split('/')[0];\n if (type === 'video') return 'video';\n if (type === 'audio') return 'audio';\n if (type === 'image') return 'image';\n return 'file';\n }\n\n // extensions\n if (lowerCased.match(imageExtRegex)) return 'image';\n if (lowerCased.match(audioExtRegex)) return 'audio';\n if (lowerCased.match(videoExtRegex)) return 'video';\n\n // others\n if (lowerCased.startsWith('image')) return 'image';\n if (lowerCased.startsWith('audio')) return 'audio';\n if (lowerCased.startsWith('video')) return 'video';\n\n return 'file';\n};\n\n/**\n * Calculates the downscaled size of an image while preserving its aspect ratio.\n *\n * @param {Object} origin - The original size object with `width` and `height` properties.\n * @param {Object} resizing - The resizing object with optional `width` and `height` properties.\n * @returns {Object} - A new size object with the downscaled `width` and `height` properties.\n * @example\n * ```ts\n * getDownscaleSize({ width: 1200, height: 800 }, { width: 600 }); // returns { width: 600, height: 400 }\n * ```\n */\ntype Size = { width: number; height: number };\nexport function getDownscaleSize(origin: Size, resizing: Partial<Size>) {\n let ratio: number;\n\n const maxWidth = resizing.width || origin.width,\n maxHeight = resizing.height || origin.height;\n\n if (origin.width <= maxWidth && origin.height <= maxHeight) {\n ratio = 1;\n } else if (origin.width > maxWidth && origin.height <= maxHeight) {\n ratio = maxWidth / origin.width;\n } else if (origin.width <= maxWidth && origin.height > maxHeight) {\n ratio = maxHeight / origin.height;\n } else {\n ratio = Math.min(maxWidth / origin.width, maxHeight / origin.height);\n }\n\n return { width: origin.width * ratio, height: origin.height * ratio };\n}\n\n/**\n * Normalize a file name by ensuring it has the given extension, if it doesn't already.\n *\n * @param {string} fileName - The file name to normalize.\n * @param {string} extension - The desired extension, without a leading period.\n * @returns {string} - The normalized file name, with the extension.\n */\nexport function normalizeFileName(fileName: string, extension: string) {\n if (!extension) return fileName;\n\n // .extension\n let _extension = extension.toLowerCase();\n if (_extension.indexOf('.') !== 0) {\n _extension = '.' + _extension;\n }\n\n // filename.extension | filename\n const _filename = fileName.toLowerCase();\n const hasExtension = _filename.lastIndexOf(_extension) === _filename.length - _extension.length;\n if (!hasExtension) {\n // filename.extension\n return fileName + _extension;\n } else {\n // filename.extension\n return fileName;\n }\n}\n\n/**\n * Parses a MIME type string into its components.\n *\n * @param mimeType - The MIME type string to parse.\n * @returns An object containing the type, subtype, and parameters of the MIME type.\n */\ntype MimeType = { type: string; subtype: string; parameters: Record<string, string> };\nexport function parseMimeType(mimeType: string): MimeType {\n const [fullType, ...parts] = mimeType.split(';');\n const [type, subtype] = fullType.split('/');\n const parameters: MimeType['parameters'] = {};\n\n for (const part of parts) {\n const [name, value] = part.trim().split('=');\n parameters[name] = value;\n }\n\n return { type, subtype, parameters };\n}\n\n/**\n * Returns the file extension based on the MIME type.\n *\n * @param {string | null | undefined} mimeType - The MIME type to look up.\n * @returns {string} - The file extension for the given MIME type, or an empty string if no matching file extension was found.\n */\nexport function getFileExtensionFromMime(mimeType?: string | null): string {\n if (!mimeType) return '';\n const MIME_EXTENSION_MAP = Object.entries(EXTENSION_MIME_MAP).reduce((acc, [key, value]) => {\n acc[value] = key;\n return acc;\n }, {} as Record<string, string>);\n\n const extension = MIME_EXTENSION_MAP[mimeType.toLowerCase()];\n if (extension) return '.' + extension;\n return '';\n}\n\n/**\n * Returns the MIME type based on the file extension.\n *\n * @param {string | null | undefined} ext - The file extension to look up.\n * @returns {string} - The MIME type for the given file extension, or an empty string if no matching MIME type was found.\n */\nexport function getMimeFromFileExtension(ext?: string | null) {\n if (!ext) return '';\n\n const sliceIdx = ext.lastIndexOf('.');\n const extWithoutDot = sliceIdx === -1 ? ext : ext.slice(sliceIdx + 1);\n\n return EXTENSION_MIME_MAP[extWithoutDot.toLowerCase()] || '';\n}\n\n/**\n * Returns the file extension of a file path.\n *\n * @param {string} filePath - The file path to extract the extension from.\n * @returns {string} - The file extension, or an empty string if the file path does not have an extension.\n */\nexport function getFileExtension(filePath: string) {\n const pathWithoutParams = filePath.split('?')[0];\n\n const idx = pathWithoutParams.lastIndexOf('.');\n if (idx === -1) return '';\n\n const result = pathWithoutParams.slice(idx - pathWithoutParams.length).toLowerCase();\n if (result === '.') return '';\n else return result;\n}\n\nexport async function getFileExtensionFromUri(uri: string) {\n const type = await fetch(uri).then((response) => response.headers.get('content-type'));\n return getFileExtensionFromMime(type);\n}\n\nexport function isImage(filePath: string, mimeType?: string) {\n const type = getFileType(mimeType || getFileExtension(filePath));\n return type === 'image';\n}\n\nexport function shouldCompressImage(mime: string, compressionEnabled = true) {\n const extension = getFileExtensionFromMime(mime);\n return Boolean(extension.match(/jpg|jpeg|png/i) && compressionEnabled);\n}\n"],"mappings":"AAAA,MAAMA,kBAAkB,GAAG;EACzB;EACA,MAAM,EAAE,YAAY;EACpB,KAAK,EAAE,YAAY;EACnB,KAAK,EAAE,WAAW;EAClB,KAAK,EAAE,WAAW;EAClB,MAAM,EAAE,YAAY;EACpB,KAAK,EAAE,eAAe;EAEtB;EACA,KAAK,EAAE,YAAY;EACnB,KAAK,EAAE,WAAW;EAClB,MAAM,EAAE,YAAY;EACpB,KAAK,EAAE,WAAW;EAClB,iBAAiB,EAAE,KAAK;EACxB,MAAM,EAAE,YAAY;EACpB,KAAK,EAAE,iBAAiB;EAExB;EACA,KAAK,EAAE,WAAW;EAClB,KAAK,EAAE,YAAY;EACnB,KAAK,EAAE,YAAY;EACnB,KAAK,EAAE,WAAW;EAClB,KA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M;AACpB;AAEA,OAAO,eAAeC,uBAAuBA,CAACC,GAAW,EAAE;EACzD,MAAMnD,IAAI,GAAG,MAAMoD,KAAK,CAACD,GAAG,CAAC,CAACE,IAAI,CAAEC,QAAQ,IAAKA,QAAQ,CAACC,OAAO,CAACC,GAAG,CAAC,cAAc,CAAC,CAAC;EACtF,OAAOxB,wBAAwB,CAAChC,IAAI,CAAC;AACvC;AAEA,OAAO,SAASyD,OAAOA,CAACX,QAAgB,EAAEvB,QAAiB,EAAE;EAC3D,MAAMvB,IAAI,GAAGL,WAAW,CAAC4B,QAAQ,IAAIsB,gBAAgB,CAACC,QAAQ,CAAC,CAAC;EAChE,OAAO9C,IAAI,KAAK,OAAO;AACzB;AAEA,OAAO,SAAS0D,mBAAmBA,CAACC,IAAY,EAA6B;EAAA,IAA3BC,kBAAkB,GAAAC,SAAA,CAAAxC,MAAA,QAAAwC,SAAA,QAAAC,SAAA,GAAAD,SAAA,MAAG,IAAI;EACzE,MAAM7C,SAAS,GAAGgB,wBAAwB,CAAC2B,IAAI,CAAC;EAChD,OAAOI,OAAO,CAAC/C,SAAS,CAACd,KAAK,CAAC,eAAe,CAAC,IAAI0D,kBAAkB,CAAC;AACxE"}
1
+ {"version":3,"names":["EXTENSION_MIME_MAP","imageExtRegex","audioExtRegex","videoExtRegex","getFileType","extensionOrType","lowerCased","toLowerCase","indexOf","type","split","match","startsWith","getDownscaleSize","origin","resizing","ratio","maxWidth","width","maxHeight","height","Math","min","normalizeFileName","fileName","extension","_extension","_filename","hasExtension","lastIndexOf","length","parseMimeType","mimeType","fullType","parts","subtype","parameters","part","name","value","trim","getFileExtensionFromMime","MIME_EXTENSION_MAP","Object","entries","reduce","acc","_ref","key","getMimeFromFileExtension","ext","sliceIdx","extWithoutDot","slice","getFileExtension","filePath","pathWithoutParams","idx","result","getFileExtensionFromUri","uri","fetch","then","response","headers","get","isImage","shouldCompressImage","mime","compressionEnabled","arguments","undefined","Boolean"],"sources":["file.ts"],"sourcesContent":["const EXTENSION_MIME_MAP = {\n // Image\n 'jpeg': 'image/jpeg',\n 'jpg': 'image/jpeg',\n 'png': 'image/png',\n 'gif': 'image/gif',\n 'webp': 'image/webp',\n 'svg': 'image/svg+xml',\n\n // Video\n '3gp': 'video/3gpp',\n 'mp4': 'video/mp4',\n 'mpeg': 'video/mpeg',\n 'ogv': 'video/ogg',\n 'video/quicktime': 'mov',\n 'webm': 'video/webm',\n 'avi': 'video/x-msvideo',\n\n // Audio\n 'aac': 'audio/aac',\n 'm4a': 'audio/m4a',\n 'mid': 'audio/midi',\n 'mp3': 'audio/mpeg',\n 'ogg': 'audio/ogg',\n 'wav': 'audio/wav',\n 'weba': 'audio/webm',\n\n // Files\n 'txt': 'text/plain',\n 'pdf': 'application/pdf',\n 'doc': 'application/msword',\n 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'xls': 'application/vnd.ms-excel',\n 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'ppt': 'application/vnd.ms-powerpoint',\n 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'zip': 'application/zip',\n 'json': 'application/json',\n 'gzip': 'application/x-gzip',\n} as Record<string, string>;\n\nexport const imageExtRegex = /jpeg|jpg|png|webp|gif/i;\nexport const audioExtRegex = /3gp|aac|aax|act|aiff|flac|gsm|m4a|m4b|m4p|tta|wma|mp3|webm|wav|ogg/i;\nexport const videoExtRegex = /mov|vod|mp4|avi|mpeg|ogv/i;\nexport const getFileType = (extensionOrType: string) => {\n const lowerCased = extensionOrType.toLowerCase();\n\n // mime type\n if (lowerCased.indexOf('/') > -1) {\n const type = lowerCased.split('/')[0];\n if (type === 'video') return 'video';\n if (type === 'audio') return 'audio';\n if (type === 'image') return 'image';\n return 'file';\n }\n\n // extensions\n if (lowerCased.match(imageExtRegex)) return 'image';\n if (lowerCased.match(audioExtRegex)) return 'audio';\n if (lowerCased.match(videoExtRegex)) return 'video';\n\n // others\n if (lowerCased.startsWith('image')) return 'image';\n if (lowerCased.startsWith('audio')) return 'audio';\n if (lowerCased.startsWith('video')) return 'video';\n\n return 'file';\n};\n\n/**\n * Calculates the downscaled size of an image while preserving its aspect ratio.\n *\n * @param {Object} origin - The original size object with `width` and `height` properties.\n * @param {Object} resizing - The resizing object with optional `width` and `height` properties.\n * @returns {Object} - A new size object with the downscaled `width` and `height` properties.\n * @example\n * ```ts\n * getDownscaleSize({ width: 1200, height: 800 }, { width: 600 }); // returns { width: 600, height: 400 }\n * ```\n */\ntype Size = { width: number; height: number };\nexport function getDownscaleSize(origin: Size, resizing: Partial<Size>) {\n let ratio: number;\n\n const maxWidth = resizing.width || origin.width,\n maxHeight = resizing.height || origin.height;\n\n if (origin.width <= maxWidth && origin.height <= maxHeight) {\n ratio = 1;\n } else if (origin.width > maxWidth && origin.height <= maxHeight) {\n ratio = maxWidth / origin.width;\n } else if (origin.width <= maxWidth && origin.height > maxHeight) {\n ratio = maxHeight / origin.height;\n } else {\n ratio = Math.min(maxWidth / origin.width, maxHeight / origin.height);\n }\n\n return { width: origin.width * ratio, height: origin.height * ratio };\n}\n\n/**\n * Normalize a file name by ensuring it has the given extension, if it doesn't already.\n *\n * @param {string} fileName - The file name to normalize.\n * @param {string} extension - The desired extension, without a leading period.\n * @returns {string} - The normalized file name, with the extension.\n */\nexport function normalizeFileName(fileName: string, extension: string) {\n if (!extension) return fileName;\n\n // .extension\n let _extension = extension.toLowerCase();\n if (_extension.indexOf('.') !== 0) {\n _extension = '.' + _extension;\n }\n\n // filename.extension | filename\n const _filename = fileName.toLowerCase();\n const hasExtension = _filename.lastIndexOf(_extension) === _filename.length - _extension.length;\n if (!hasExtension) {\n // filename.extension\n return fileName + _extension;\n } else {\n // filename.extension\n return fileName;\n }\n}\n\n/**\n * Parses a MIME type string into its components.\n *\n * @param mimeType - The MIME type string to parse.\n * @returns An object containing the type, subtype, and parameters of the MIME type.\n */\ntype MimeType = { type: string; subtype: string; parameters: Record<string, string> };\nexport function parseMimeType(mimeType: string): MimeType {\n const [fullType, ...parts] = mimeType.split(';');\n const [type, subtype] = fullType.split('/');\n const parameters: MimeType['parameters'] = {};\n\n for (const part of parts) {\n const [name, value] = part.trim().split('=');\n parameters[name] = value;\n }\n\n return { type, subtype, parameters };\n}\n\n/**\n * Returns the file extension based on the MIME type.\n *\n * @param {string | null | undefined} mimeType - The MIME type to look up.\n * @returns {string} - The file extension for the given MIME type, or an empty string if no matching file extension was found.\n */\nexport function getFileExtensionFromMime(mimeType?: string | null): string {\n if (!mimeType) return '';\n const MIME_EXTENSION_MAP = Object.entries(EXTENSION_MIME_MAP).reduce((acc, [key, value]) => {\n acc[value] = key;\n return acc;\n }, {} as Record<string, string>);\n\n const extension = MIME_EXTENSION_MAP[mimeType.toLowerCase()];\n if (extension) return '.' + extension;\n return '';\n}\n\n/**\n * Returns the MIME type based on the file extension.\n *\n * @param {string | null | undefined} ext - The file extension to look up.\n * @returns {string} - The MIME type for the given file extension, or an empty string if no matching MIME type was found.\n */\nexport function getMimeFromFileExtension(ext?: string | null) {\n if (!ext) return '';\n\n const sliceIdx = ext.lastIndexOf('.');\n const extWithoutDot = sliceIdx === -1 ? ext : ext.slice(sliceIdx + 1);\n\n return EXTENSION_MIME_MAP[extWithoutDot.toLowerCase()] || '';\n}\n\n/**\n * Returns the file extension of a file path.\n *\n * @param {string} filePath - The file path to extract the extension from.\n * @returns {string} - The file extension, or an empty string if the file path does not have an extension.\n */\nexport function getFileExtension(filePath: string) {\n const pathWithoutParams = filePath.split('?')[0];\n\n const idx = pathWithoutParams.lastIndexOf('.');\n if (idx === -1) return '';\n\n const result = pathWithoutParams.slice(idx - pathWithoutParams.length).toLowerCase();\n if (result === '.') return '';\n else return result;\n}\n\nexport async function getFileExtensionFromUri(uri: string) {\n const type = await fetch(uri).then((response) => response.headers.get('content-type'));\n return getFileExtensionFromMime(type);\n}\n\nexport function isImage(filePath: string, mimeType?: string) {\n const type = getFileType(mimeType || getFileExtension(filePath));\n return type === 'image';\n}\n\nexport function shouldCompressImage(mime: string, compressionEnabled = true) {\n const extension = getFileExtensionFromMime(mime);\n return Boolean(extension.match(/jpg|jpeg|png/i) && compressionEnabled);\n}\n"],"mappings":"AAAA,MAAMA,kBAAkB,GAAG;EACzB;EACA,MAAM,EAAE,YAAY;EACpB,KAAK,EAAE,YAAY;EACnB,KAAK,EAAE,WAAW;EAClB,KAAK,EAAE,WAAW;EAClB,MAAM,EAAE,YAAY;EACpB,KAAK,EAAE,eAAe;EAEtB;EACA,KAAK,EAAE,YAAY;EACnB,KAAK,EAAE,WAAW;EAClB,MAAM,EAAE,YAAY;EACpB,KAAK,EAAE,WAAW;EAClB,iBAAiB,EAAE,KAAK;EACxB,MAAM,EAAE,YAAY;EACpB,KAAK,EAAE,iBAAiB;EAExB;EACA,KAAK,EAAE,WAAW;EAClB,KAAK,EAAE,WAAW;EAClB,KAAK,EAAE,YAAY;EACnB,KAAK,EAAE,YAAY;EACnB,KAAK,EAAE,WAAW;EAClB,KAAK,EAAE,WAAW;EAClB,MAAM,EAAE,YAAY;EAEpB;EACA,KAAK,EAAE,YAAY;EACnB,KAAK,EAAE,iBAAiB;EACxB,KAAK,EAAE,oBAAoB;EAC3B,MAAM,EAAE,yEAAyE;EACjF,KAAK,EAAE,0BAA0B;EACjC,MAAM,EAAE,mEAAmE;EAC3E,KAAK,EAAE,+BAA+B;EACtC,MAAM,EAAE,2EAA2E;EACnF,KAAK,EAAE,iBAAiB;EACxB,MAAM,EAAE,kBAAkB;EAC1B,MAAM,EAAE;AACV,CAA2B;AAE3B,OAAO,MAAMC,aAAa,GAAG,wBAAwB;AACrD,OAAO,MAAMC,aAAa,GAAG,qEAAqE;AAClG,OAAO,MAAMC,aAAa,GAAG,2BAA2B;AACxD,OAAO,MAAMC,WAAW,GAAIC,eAAuB,IAAK;EACtD,MAAMC,UAAU,GAAGD,eAAe,CAACE,WAAW,EAAE;;EAEhD;EACA,IAAID,UAAU,CAACE,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC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,wBAAwB,CAAC2B,IAAI,CAAC;EAChD,OAAOI,OAAO,CAAC/C,SAAS,CAACd,KAAK,CAAC,eAAe,CAAC,IAAI0D,kBAAkB,CAAC;AACxE"}
@@ -48,4 +48,10 @@ export function mergeObjectArrays(A, B, key) {
48
48
  }
49
49
  return newArr;
50
50
  }
51
+ export function sleep(ms) {
52
+ return new Promise(resolve => setTimeout(resolve, ms));
53
+ }
54
+ export function matchesOneOf(value, candidates) {
55
+ return candidates.includes(value);
56
+ }
51
57
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["hash","str","String","Math","abs","split","reduce","a","c","charCodeAt","replace","start","end","text","slice","conditionChaining","conditions","values","idx","findIndex","state","Boolean","length","pick","obj","keys","pickedObj","key","mergeObjectArrays","A","B","uniqueValues","Set","map","newArr","i","has","push","add"],"sources":["index.ts"],"sourcesContent":["/**\n * Converts a given string to a hashed string.\n * */\nexport function hash(str: string) {\n return String(Math.abs(str.split('').reduce((a, c) => ((a << 5) - a + c.charCodeAt(0)) | 0, 0)));\n}\n\n/**\n * Replace a specific range of text in the string with another text.\n * */\nexport function replace(str: string, start: number, end: number, text: string) {\n return str.slice(0, start) + text + str.slice(end);\n}\n\n/**\n * Returns the value corresponding to the first true index of a given condition array.\n * */\nexport function conditionChaining<T, V>(conditions: T[], values: V[]) {\n const idx = conditions.findIndex((state) => Boolean(state));\n return idx > -1 ? values[idx] : values[values.length - 1];\n}\n\n/**\n * Returns a new object with only the specified keys from the input object.\n *\n * @param {Object} obj - The input object to pick keys from.\n * @param {Array<string>} keys - An array of keys to pick from the input object.\n * @returns {Object} - A new object containing only the specified keys from the input object.\n * @example\n * ```ts\n * pick({ a: 1, b: '2', c: true }, ['a', 'c']); // returns { a: 1, c: true }\n * ```\n */\nexport function pick<T extends { [key: string]: unknown }, Keys extends keyof T>(obj: T, keys: Keys[]) {\n return keys.reduce((pickedObj, key) => {\n pickedObj[key] = obj[key];\n return pickedObj;\n }, {} as { [key in Keys]: T[key] });\n}\n\nexport function mergeObjectArrays<T>(A: T[], B: T[], key: keyof T): T[] {\n const uniqueValues = new Set(A.map((obj) => obj[key]));\n const newArr = [...A];\n\n for (let i = 0; i < B.length; i++) {\n if (!uniqueValues.has(B[i][key])) {\n newArr.push(B[i]);\n uniqueValues.add(B[i][key]);\n }\n }\n\n return newArr;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAO,SAASA,IAAIA,CAACC,GAAW,EAAE;EAChC,OAAOC,MAAM,CAACC,IAAI,CAACC,GAAG,CAACH,GAAG,CAACI,KAAK,CAAC,EAAE,CAAC,CAACC,MAAM,CAAC,CAACC,CAAC,EAAEC,CAAC,KAAM,CAACD,CAAC,IAAI,CAAC,IAAIA,CAAC,GAAGC,CAAC,CAACC,UAAU,CAAC,CAAC,CAAC,GAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAClG;;AAEA;AACA;AACA;AACA,OAAO,SAASC,OAAOA,CAACT,GAAW,EAAEU,KAAa,EAAEC,GAAW,EAAEC,IAAY,EAAE;EAC7E,OAAOZ,GAAG,CAACa,KAAK,CAAC,CAAC,EAAEH,KAAK,CAAC,GAAGE,IAAI,GAAGZ,GAAG,CAACa,KAAK,CAACF,GAAG,CAAC;AACpD;;AAEA;AACA;AACA;AACA,OAAO,SAASG,iBAAiBA,CAAOC,UAAe,EAAEC,MAAW,EAAE;EACpE,MAAMC,GAAG,GAAGF,UAAU,CAACG,SAAS,CAAEC,KAAK,IAAKC,OAAO,CAACD,KAAK,CAAC,CAAC;EAC3D,OAAOF,GAAG,GAAG,CAAC,CAAC,GAAGD,MAAM,CAACC,GAAG,CAAC,GAAGD,MAAM,CAACA,MAAM,CAACK,MAAM,GAAG,CAAC,CAAC;AAC3D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,IAAIA,CAA6DC,GAAM,EAAEC,IAAY,EAAE;EACrG,OAAOA,IAAI,CAACnB,MAAM,CAAC,CAACoB,SAAS,EAAEC,GAAG,KAAK;IACrCD,SAAS,CAACC,GAAG,CAAC,GAAGH,GAAG,CAACG,GAAG,CAAC;IACzB,OAAOD,SAAS;EAClB,CAAC,EAAE,CAAC,CAAC,CAA8B;AACrC;AAEA,OAAO,SAASE,iBAAiBA,CAAIC,CAAM,EAAEC,CAAM,EAAEH,GAAY,EAAO;EACtE,MAAMI,YAAY,GAAG,IAAIC,GAAG,CAACH,CAAC,CAACI,GAAG,CAAET,GAAG,IAAKA,GAAG,CAACG,GAAG,CAAC,CAAC,CAAC;EACtD,MAAMO,MAAM,GAAG,CAAC,GAAGL,CAAC,CAAC;EAErB,KAAK,IAAIM,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGL,CAAC,CAACR,MAAM,EAAEa,CAAC,EAAE,EAAE;IACjC,IAAI,CAACJ,YAAY,CAACK,GAAG,CAACN,CAAC,CAACK,CAAC,CAAC,CAACR,GAAG,CAAC,CAAC,EAAE;MAChCO,MAAM,CAACG,IAAI,CAACP,CAAC,CAACK,CAAC,CAAC,CAAC;MACjBJ,YAAY,CAACO,GAAG,CAACR,CAAC,CAACK,CAAC,CAAC,CAACR,GAAG,CAAC,CAAC;IAC7B;EACF;EAEA,OAAOO,MAAM;AACf"}
1
+ {"version":3,"names":["hash","str","String","Math","abs","split","reduce","a","c","charCodeAt","replace","start","end","text","slice","conditionChaining","conditions","values","idx","findIndex","state","Boolean","length","pick","obj","keys","pickedObj","key","mergeObjectArrays","A","B","uniqueValues","Set","map","newArr","i","has","push","add","sleep","ms","Promise","resolve","setTimeout","matchesOneOf","value","candidates","includes"],"sources":["index.ts"],"sourcesContent":["/**\n * Converts a given string to a hashed string.\n * */\nexport function hash(str: string) {\n return String(Math.abs(str.split('').reduce((a, c) => ((a << 5) - a + c.charCodeAt(0)) | 0, 0)));\n}\n\n/**\n * Replace a specific range of text in the string with another text.\n * */\nexport function replace(str: string, start: number, end: number, text: string) {\n return str.slice(0, start) + text + str.slice(end);\n}\n\n/**\n * Returns the value corresponding to the first true index of a given condition array.\n * */\nexport function conditionChaining<T, V>(conditions: T[], values: V[]) {\n const idx = conditions.findIndex((state) => Boolean(state));\n return idx > -1 ? values[idx] : values[values.length - 1];\n}\n\n/**\n * Returns a new object with only the specified keys from the input object.\n *\n * @param {Object} obj - The input object to pick keys from.\n * @param {Array<string>} keys - An array of keys to pick from the input object.\n * @returns {Object} - A new object containing only the specified keys from the input object.\n * @example\n * ```ts\n * pick({ a: 1, b: '2', c: true }, ['a', 'c']); // returns { a: 1, c: true }\n * ```\n */\nexport function pick<T extends { [key: string]: unknown }, Keys extends keyof T>(obj: T, keys: Keys[]) {\n return keys.reduce((pickedObj, key) => {\n pickedObj[key] = obj[key];\n return pickedObj;\n }, {} as { [key in Keys]: T[key] });\n}\n\nexport function mergeObjectArrays<T>(A: T[], B: T[], key: keyof T): T[] {\n const uniqueValues = new Set(A.map((obj) => obj[key]));\n const newArr = [...A];\n\n for (let i = 0; i < B.length; i++) {\n if (!uniqueValues.has(B[i][key])) {\n newArr.push(B[i]);\n uniqueValues.add(B[i][key]);\n }\n }\n\n return newArr;\n}\n\nexport function sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function matchesOneOf<V, C extends V[]>(value: V, candidates: C) {\n return candidates.includes(value);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAO,SAASA,IAAIA,CAACC,GAAW,EAAE;EAChC,OAAOC,MAAM,CAACC,IAAI,CAACC,GAAG,CAACH,GAAG,CAACI,KAAK,CAAC,EAAE,CAAC,CAACC,MAAM,CAAC,CAACC,CAAC,EAAEC,CAAC,KAAM,CAACD,CAAC,IAAI,CAAC,IAAIA,CAAC,GAAGC,CAAC,CAACC,UAAU,CAAC,CAAC,CAAC,GAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAClG;;AAEA;AACA;AACA;AACA,OAAO,SAASC,OAAOA,CAACT,GAAW,EAAEU,KAAa,EAAEC,GAAW,EAAEC,I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ACK,CAAC,CAAC,CAAC;MACjBJ,YAAY,CAACO,GAAG,CAACR,CAAC,CAACK,CAAC,CAAC,CAACR,GAAG,CAAC,CAAC;IAC7B;EACF;EAEA,OAAOO,MAAM;AACf;AAEA,OAAO,SAASK,KAAKA,CAACC,EAAU,EAAE;EAChC,OAAO,IAAIC,OAAO,CAAEC,OAAO,IAAKC,UAAU,CAACD,OAAO,EAAEF,EAAE,CAAC,CAAC;AAC1D;AAEA,OAAO,SAASI,YAAYA,CAAmBC,KAAQ,EAAEC,UAAa,EAAE;EACtE,OAAOA,UAAU,CAACC,QAAQ,CAACF,KAAK,CAAC;AACnC"}
@@ -1 +1 @@
1
- {"version":3,"names":[],"sources":["types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport type React from 'react';\n\nimport type SendbirdChat from '@sendbird/chat';\nimport type {\n BaseChannel,\n Emoji,\n EmojiCategory,\n EmojiContainer,\n Encryption,\n Participant,\n RestrictedUser,\n SendbirdError as SBError,\n User,\n UserUpdateParams,\n} from '@sendbird/chat';\nimport type { FeedChannel } from '@sendbird/chat/feedChannel';\nimport type {\n GroupChannel,\n GroupChannelCollection,\n GroupChannelCreateParams,\n GroupChannelListQuery,\n GroupChannelModule,\n GroupChannelUpdateParams,\n Member,\n MessageCollection,\n} from '@sendbird/chat/groupChannel';\nimport type {\n ModuleNamespaces,\n OpenChannelCreateParams,\n OpenChannelUpdateParams,\n SendableMessage,\n} from '@sendbird/chat/lib/__definition';\nimport type {\n AdminMessage,\n BaseMessage,\n FileMessage,\n FileMessageCreateParams,\n FileMessageUpdateParams,\n MessageSearchQuery,\n MultipleFilesMessage,\n PreviousMessageListQuery,\n Reaction,\n UserMessage,\n UserMessageCreateParams,\n UserMessageUpdateParams,\n} from '@sendbird/chat/message';\nimport type { OpenChannel, OpenChannelListQuery, OpenChannelModule } from '@sendbird/chat/openChannel';\n\nexport type FilterByValueType<T extends object, Type> = {\n [K in keyof T as T[K] extends Type ? K : never]: T[K];\n};\n\nexport type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void\n ? I\n : never;\n\nexport type OmittedValues<T, K extends keyof T> = Omit<T, K>[keyof Omit<T, K>];\n\nexport type PartialDeep<T> = T extends object\n ? T extends Function\n ? T\n : {\n [P in keyof T]?: PartialDeep<T[P]>;\n }\n : T;\n\nexport type PartialNullable<T> = {\n [P in keyof T]?: T[P] | null;\n};\n\nexport type Optional<T> = T | undefined;\n\nexport type ContextValue<T extends React.Context<any>> = T extends React.Context<infer V> ? V : never;\n\nexport type OnBeforeHandler<T> = (params: T) => T | Promise<T>;\n\nexport interface UserStruct {\n userId: string;\n}\nexport type SendbirdChatSDK = SendbirdChat & ModuleNamespaces<[GroupChannelModule, OpenChannelModule]>;\nexport type SendbirdMessage = BaseMessage | FileMessage | UserMessage | AdminMessage | SendableMessage;\nexport type SendbirdChannel = BaseChannel | GroupChannel | OpenChannel;\nexport type SendbirdUserMessage = UserMessage;\nexport type SendbirdFileMessage = FileMessage;\nexport type SendbirdMultipleFilesMessage = MultipleFilesMessage;\nexport type SendbirdAdminMessage = AdminMessage;\nexport type SendbirdBaseMessage = BaseMessage;\nexport type SendbirdSendableMessage = SendableMessage;\nexport type SendbirdFileMessageCreateParams = FileMessageCreateParams;\nexport type SendbirdFileMessageUpdateParams = FileMessageUpdateParams;\nexport type SendbirdUserMessageCreateParams = UserMessageCreateParams;\nexport type SendbirdUserMessageUpdateParams = UserMessageUpdateParams;\n\nexport type SendbirdGroupChannelCreateParams = GroupChannelCreateParams;\nexport type SendbirdGroupChannelUpdateParams = GroupChannelUpdateParams;\nexport type SendbirdOpenChannelCreateParams = OpenChannelCreateParams;\nexport type SendbirdOpenChannelUpdateParams = OpenChannelUpdateParams;\n\nexport type SendbirdUserUpdateParams = UserUpdateParams;\nexport type SendbirdUser = User;\nexport type SendbirdRestrictedUser = RestrictedUser;\nexport type SendbirdMember = Member;\nexport type SendbirdParticipant = Participant;\n\nexport type SendbirdGroupChannel = GroupChannel;\nexport type SendbirdBaseChannel = BaseChannel;\nexport type SendbirdOpenChannel = OpenChannel;\nexport type SendbirdFeedChannel = FeedChannel;\n\nexport type SendbirdReaction = Reaction;\nexport type SendbirdEmoji = Emoji;\nexport type SendbirdEmojiCategory = EmojiCategory;\nexport type SendbirdEmojiContainer = EmojiContainer;\n\nexport type SendbirdGroupChannelCollection = GroupChannelCollection;\nexport type SendbirdGroupChannelListQuery = GroupChannelListQuery;\nexport type SendbirdOpenChannelListQuery = OpenChannelListQuery;\nexport type SendbirdMessageCollection = MessageCollection;\nexport type SendbirdPreviousMessageListQuery = PreviousMessageListQuery;\nexport type SendbirdMessageSearchQuery = MessageSearchQuery;\n\nexport type SendbirdError = SBError;\nexport type SendbirdEncryption = Encryption;\n\nexport interface SendbirdDataPayload {\n app_id: string;\n audience_type: string;\n category: string;\n channel: {\n channel_unread_message_count: number;\n channel_url: string;\n custom_type: string;\n name: string;\n };\n channel_type: string;\n created_at: number;\n custom_type: string;\n files: NotificationFiles[];\n mentioned_users: NotificationMentionedUsers[];\n message: string;\n message_id: number;\n push_sound: string;\n push_title: null;\n recipient: {\n id: string;\n name: string;\n push_template: string;\n };\n sender?: {\n id: string;\n name: string;\n profile_url: string;\n require_auth_for_profile_image: boolean;\n };\n sqs_ts: number;\n translations: NotificationTranslations;\n type: 'ADMM' | 'MESG' | 'FILE' | string;\n unread_message_count: number;\n}\nexport interface NotificationFiles {\n type: string;\n url: string;\n name: string;\n size: number;\n require_auth: boolean;\n}\n\nexport interface NotificationTranslations {}\nexport interface NotificationMentionedUsers {}\n"],"mappings":""}
1
+ {"version":3,"names":[],"sources":["types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport type React from 'react';\n\nimport type SendbirdChat from '@sendbird/chat';\nimport type {\n BaseChannel,\n Emoji,\n EmojiCategory,\n EmojiContainer,\n Encryption,\n Participant,\n RestrictedUser,\n SendbirdError as SBError,\n User,\n UserUpdateParams,\n} from '@sendbird/chat';\nimport type { FeedChannel } from '@sendbird/chat/feedChannel';\nimport type {\n GroupChannel,\n GroupChannelCollection,\n GroupChannelCreateParams,\n GroupChannelListQuery,\n GroupChannelModule,\n GroupChannelUpdateParams,\n Member,\n MessageCollection,\n} from '@sendbird/chat/groupChannel';\nimport type {\n ModuleNamespaces,\n OpenChannelCreateParams,\n OpenChannelUpdateParams,\n SendableMessage,\n} from '@sendbird/chat/lib/__definition';\nimport type {\n AdminMessage,\n BaseMessage,\n FileMessage,\n FileMessageCreateParams,\n FileMessageUpdateParams,\n MessageSearchQuery,\n MultipleFilesMessage,\n PreviousMessageListQuery,\n Reaction,\n UserMessage,\n UserMessageCreateParams,\n UserMessageUpdateParams,\n} from '@sendbird/chat/message';\nimport type { OpenChannel, OpenChannelListQuery, OpenChannelModule } from '@sendbird/chat/openChannel';\n\nexport type FilterByValueType<T extends object, Type> = {\n [K in keyof T as T[K] extends Type ? K : never]: T[K];\n};\n\nexport type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void\n ? I\n : never;\n\nexport type OmittedValues<T, K extends keyof T> = Omit<T, K>[keyof Omit<T, K>];\n\nexport type PartialDeep<T> = T extends object\n ? T extends Set<unknown>\n ? T\n : T extends Function\n ? T\n : {\n [P in keyof T]?: PartialDeep<T[P]>;\n }\n : T;\n\nexport type PartialNullable<T> = {\n [P in keyof T]?: T[P] | null;\n};\n\nexport type Optional<T> = T | undefined;\n\nexport type ContextValue<T extends React.Context<any>> = T extends React.Context<infer V> ? V : never;\n\nexport type OnBeforeHandler<T> = (params: T) => T | Promise<T>;\n\nexport interface UserStruct {\n userId: string;\n}\nexport type SendbirdChatSDK = SendbirdChat & ModuleNamespaces<[GroupChannelModule, OpenChannelModule]>;\nexport type SendbirdMessage = BaseMessage | FileMessage | UserMessage | AdminMessage | SendableMessage;\nexport type SendbirdChannel = BaseChannel | GroupChannel | OpenChannel;\nexport type SendbirdUserMessage = UserMessage;\nexport type SendbirdFileMessage = FileMessage;\nexport type SendbirdMultipleFilesMessage = MultipleFilesMessage;\nexport type SendbirdAdminMessage = AdminMessage;\nexport type SendbirdBaseMessage = BaseMessage;\nexport type SendbirdSendableMessage = SendableMessage;\nexport type SendbirdFileMessageCreateParams = FileMessageCreateParams;\nexport type SendbirdFileMessageUpdateParams = FileMessageUpdateParams;\nexport type SendbirdUserMessageCreateParams = UserMessageCreateParams;\nexport type SendbirdUserMessageUpdateParams = UserMessageUpdateParams;\n\nexport type SendbirdGroupChannelCreateParams = GroupChannelCreateParams;\nexport type SendbirdGroupChannelUpdateParams = GroupChannelUpdateParams;\nexport type SendbirdOpenChannelCreateParams = OpenChannelCreateParams;\nexport type SendbirdOpenChannelUpdateParams = OpenChannelUpdateParams;\n\nexport type SendbirdUserUpdateParams = UserUpdateParams;\nexport type SendbirdUser = User;\nexport type SendbirdRestrictedUser = RestrictedUser;\nexport type SendbirdMember = Member;\nexport type SendbirdParticipant = Participant;\n\nexport type SendbirdGroupChannel = GroupChannel;\nexport type SendbirdBaseChannel = BaseChannel;\nexport type SendbirdOpenChannel = OpenChannel;\nexport type SendbirdFeedChannel = FeedChannel;\n\nexport type SendbirdReaction = Reaction;\nexport type SendbirdEmoji = Emoji;\nexport type SendbirdEmojiCategory = EmojiCategory;\nexport type SendbirdEmojiContainer = EmojiContainer;\n\nexport type SendbirdGroupChannelCollection = GroupChannelCollection;\nexport type SendbirdGroupChannelListQuery = GroupChannelListQuery;\nexport type SendbirdOpenChannelListQuery = OpenChannelListQuery;\nexport type SendbirdMessageCollection = MessageCollection;\nexport type SendbirdPreviousMessageListQuery = PreviousMessageListQuery;\nexport type SendbirdMessageSearchQuery = MessageSearchQuery;\n\nexport type SendbirdError = SBError;\nexport type SendbirdEncryption = Encryption;\n\nexport interface SendbirdDataPayload {\n app_id: string;\n audience_type: string;\n category: string;\n channel: {\n channel_unread_message_count: number;\n channel_url: string;\n custom_type: string;\n name: string;\n };\n channel_type: string;\n created_at: number;\n custom_type: string;\n files: NotificationFiles[];\n mentioned_users: NotificationMentionedUsers[];\n message: string;\n message_id: number;\n push_sound: string;\n push_title: null;\n recipient: {\n id: string;\n name: string;\n push_template: string;\n };\n sender?: {\n id: string;\n name: string;\n profile_url: string;\n require_auth_for_profile_image: boolean;\n };\n sqs_ts: number;\n translations: NotificationTranslations;\n type: 'ADMM' | 'MESG' | 'FILE' | string;\n unread_message_count: number;\n}\nexport interface NotificationFiles {\n type: string;\n url: string;\n name: string;\n size: number;\n require_auth: boolean;\n}\n\nexport interface NotificationTranslations {}\nexport interface NotificationMentionedUsers {}\n"],"mappings":""}
@@ -137,4 +137,27 @@ export const getMessagePreviewTime = (timestamp, locale) => {
137
137
  locale
138
138
  });
139
139
  };
140
+
141
+ /**
142
+ * milliseconds to 00:00 format
143
+ * */
144
+ export const millsToMMSS = mills => {
145
+ let seconds = Math.floor(Math.max(0, mills) / 1000);
146
+ const minutes = Math.floor(seconds / 60);
147
+ seconds = seconds % 60;
148
+ const mm = String(minutes).padStart(2, '0');
149
+ const ss = String(seconds).padStart(2, '0');
150
+ return `${mm}:${ss}`;
151
+ };
152
+
153
+ /**
154
+ * milliseconds to 0:00 format
155
+ * */
156
+ export const millsToMSS = mills => {
157
+ let seconds = Math.floor(Math.max(0, mills) / 1000);
158
+ const minutes = Math.floor(seconds / 60);
159
+ seconds = seconds % 60;
160
+ const ss = String(seconds).padStart(2, '0');
161
+ return `${minutes}:${ss}`;
162
+ };
140
163
  //# sourceMappingURL=common.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["format","isThisYear","isToday","isYesterday","defaultOpts","mode","maxLen","separator","truncate","str","opts","arguments","length","undefined","options","slice","lead","Math","ceil","trail","floor","Error","truncatedCount","count","MAX","MAX_SUFFIX","getDateSeparatorFormat","date","locale","getMessageTimeFormat","getMessagePreviewTitle","message","EMPTY_USERNAME","isFileMessage","isUserMessage","sender","nickname","isAdminMessage","getMessagePreviewBody","EMPTY_MESSAGE","extIdx","name","lastIndexOf","file","ext","getMessagePreviewTime","timestamp"],"sources":["common.ts"],"sourcesContent":["import type { Locale } from 'date-fns';\nimport { format, isThisYear, isToday, isYesterday } from 'date-fns';\n\nimport type { SendbirdBaseMessage } from '../types';\n\ntype TruncateMode = 'head' | 'mid' | 'tail';\ntype TruncateOption = { mode: TruncateMode; maxLen: number; separator: string };\nconst defaultOpts: TruncateOption = { mode: 'mid', maxLen: 40, separator: '...' };\n\n/**\n * String truncate util\n * @param {string} str\n * @param {Object} opts Options for truncate\n * @param {'head' | 'mid' | 'tail'} opts.mode default \"mid\"\n * @param {number} opts.maxLen default 40\n * @param {string} opts.separator default \"...\"\n * @returns {string}\n * */\nexport const truncate = (str: string, opts: Partial<TruncateOption> = defaultOpts): string => {\n const options = { ...defaultOpts, ...opts };\n const { maxLen, mode, separator } = options;\n\n if (str.length <= maxLen) return str;\n\n if (mode === 'head') {\n return separator + str.slice(-maxLen);\n }\n\n if (mode === 'mid') {\n const lead = Math.ceil(maxLen / 2);\n const trail = Math.floor(maxLen / 2);\n return str.slice(0, lead) + separator + str.slice(-trail);\n }\n\n if (mode === 'tail') {\n return str.slice(0, maxLen) + separator;\n }\n\n throw new Error('Invalid truncate mode: ' + mode);\n};\n\n/**\n * Count truncate util\n * If count exceed the limit, it comes in the form of \"MAX+\"\n *\n * @param {number} count\n * @param {number} MAX default 99\n * @param {string} MAX_SUFFIX default +\n * @returns {string}\n * */\nexport const truncatedCount = (count: number, MAX = 99, MAX_SUFFIX = '+') => {\n if (count >= MAX) return `${MAX}${MAX_SUFFIX}`;\n return `${count}`;\n};\n\n/**\n * Messages date separator format\n *\n * @param {Date} date\n * @param {Locale} [locale]\n * @returns {string}\n * */\nexport const getDateSeparatorFormat = (date: Date, locale?: Locale): string => {\n if (isThisYear(date)) return format(date, 'MMM dd, yyyy', { locale });\n return format(date, 'E, MMM dd', { locale });\n};\n\n/**\n * Message time format\n *\n * @param {Date} date\n * @param {Locale} [locale]\n * @returns {string}\n * */\nexport const getMessageTimeFormat = (date: Date, locale?: Locale): string => {\n return format(date, 'p', { locale });\n};\n\n/**\n * Message preview title text\n * */\nexport const getMessagePreviewTitle = (message: SendbirdBaseMessage, EMPTY_USERNAME = '(No name)') => {\n if (message.isFileMessage() || message.isUserMessage()) {\n return message.sender.nickname || EMPTY_USERNAME;\n }\n if (message.isAdminMessage()) {\n return 'Admin';\n }\n return EMPTY_USERNAME;\n};\n\n/**\n * Message preview body text\n * */\nexport const getMessagePreviewBody = (message: SendbirdBaseMessage, EMPTY_MESSAGE = '') => {\n if (message.isFileMessage()) {\n const extIdx = message.name.lastIndexOf('.');\n if (extIdx > -1) {\n const file = message.name.slice(0, extIdx);\n const ext = message.name.slice(extIdx);\n return file + ext;\n }\n\n return message.name;\n }\n\n if (message.isUserMessage()) {\n return message.message ?? EMPTY_MESSAGE;\n }\n\n if (message.isAdminMessage()) {\n return message.message ?? EMPTY_MESSAGE;\n }\n\n return EMPTY_MESSAGE;\n};\n\n/**\n * Message preview time format\n * */\nexport const getMessagePreviewTime = (timestamp: number, locale?: Locale) => {\n if (isToday(timestamp)) return format(timestamp, 'p', { locale });\n if (isYesterday(timestamp)) return 'Yesterday';\n if (isThisYear(timestamp)) return format(timestamp, 'MMM dd', { locale });\n\n return format(timestamp, 'yyyy/MM/dd', { locale });\n};\n"],"mappings":"AACA,SAASA,MAAM,EAAEC,UAAU,EAAEC,OAAO,EAAEC,WAAW,QAAQ,UAAU;AAMnE,MAAMC,WAA2B,GAAG;EAAEC,IAAI,EAAE,KAAK;EAAEC,MAAM,EAAE,EAAE;EAAEC,SAAS,EAAE;AAAM,CAAC;;AAEjF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,QAAQ,GAAG,SAAAA,CAACC,GAAW,EAA0D;EAAA,IAAxDC,IAA6B,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,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,GAAG,CAAC;IAC5C,IAAIF,MAAM,GAAG,CAAC,CAAC,EAAE;MACf,MAAMG,IAAI,GAAGZ,OAAO,CAACU,IAAI,CAAC1B,KAAK,CAAC,CAAC,EAAEyB,MAAM,CAAC;MAC1C,MAAMI,GAAG,GAAGb,OAAO,CAACU,IAAI,CAAC1B,KAAK,CAACyB,MAAM,CAAC;MACtC,OAAOG,IAAI,GAAGC,GAAG;IACnB;IAEA,OAAOb,OAAO,CAACU,IAAI;EACrB;EAEA,IAAIV,OAAO,CAACG,aAAa,EAAE,EAAE;IAC3B,OAAOH,OAAO,CAACA,OAAO,IAAIQ,aAAa;EACzC;EAEA,IAAIR,OAAO,CAACM,cAAc,EAAE,EAAE;IAC5B,OAAON,OAAO,CAACA,OAAO,IAAIQ,aAAa;EACzC;EAEA,OAAOA,aAAa;AACtB,CAAC;;AAED;AACA;AACA;AACA,OAAO,MAAMM,qBAAqB,GAAGA,CAACC,SAAiB,EAAElB,MAAe,KAAK;EAC3E,IAAI1B,OAAO,CAAC4C,SAAS,CAAC,EAAE,OAAO9C,MAAM,CAAC8C,SAAS,EAAE,GAAG,EAAE;IAAElB;EAAO,CAAC,CAAC;EACjE,IAAIzB,WAAW,CAAC2C,SAAS,CAAC,EAAE,OAAO,WAAW;EAC9C,IAAI7C,UAAU,CAAC6C,SAAS,CAAC,EAAE,OAAO9C,MAAM,CAAC8C,SAAS,EAAE,QAAQ,EAAE;IAAElB;EAAO,CAAC,CAAC;EAEzE,OAAO5B,MAAM,CAAC8C,SAAS,EAAE,YAAY,EAAE;IAAElB;EAAO,CAAC,CAAC;AACpD,CAAC"}
1
+ {"version":3,"names":["format","isThisYear","isToday","isYesterday","defaultOpts","mode","maxLen","separator","truncate","str","opts","arguments","length","undefined","options","slice","lead","Math","ceil","trail","floor","Error","truncatedCount","count","MAX","MAX_SUFFIX","getDateSeparatorFormat","date","locale","getMessageTimeFormat","getMessagePreviewTitle","message","EMPTY_USERNAME","isFileMessage","isUserMessage","sender","nickname","isAdminMessage","getMessagePreviewBody","EMPTY_MESSAGE","extIdx","name","lastIndexOf","file","ext","getMessagePreviewTime","timestamp","millsToMMSS","mills","seconds","max","minutes","mm","String","padStart","ss","millsToMSS"],"sources":["common.ts"],"sourcesContent":["import type { Locale } from 'date-fns';\nimport { format, isThisYear, isToday, isYesterday } from 'date-fns';\n\nimport type { SendbirdBaseMessage } from '../types';\n\ntype TruncateMode = 'head' | 'mid' | 'tail';\ntype TruncateOption = { mode: TruncateMode; maxLen: number; separator: string };\nconst defaultOpts: TruncateOption = { mode: 'mid', maxLen: 40, separator: '...' };\n\n/**\n * String truncate util\n * @param {string} str\n * @param {Object} opts Options for truncate\n * @param {'head' | 'mid' | 'tail'} opts.mode default \"mid\"\n * @param {number} opts.maxLen default 40\n * @param {string} opts.separator default \"...\"\n * @returns {string}\n * */\nexport const truncate = (str: string, opts: Partial<TruncateOption> = defaultOpts): string => {\n const options = { ...defaultOpts, ...opts };\n const { maxLen, mode, separator } = options;\n\n if (str.length <= maxLen) return str;\n\n if (mode === 'head') {\n return separator + str.slice(-maxLen);\n }\n\n if (mode === 'mid') {\n const lead = Math.ceil(maxLen / 2);\n const trail = Math.floor(maxLen / 2);\n return str.slice(0, lead) + separator + str.slice(-trail);\n }\n\n if (mode === 'tail') {\n return str.slice(0, maxLen) + separator;\n }\n\n throw new Error('Invalid truncate mode: ' + mode);\n};\n\n/**\n * Count truncate util\n * If count exceed the limit, it comes in the form of \"MAX+\"\n *\n * @param {number} count\n * @param {number} MAX default 99\n * @param {string} MAX_SUFFIX default +\n * @returns {string}\n * */\nexport const truncatedCount = (count: number, MAX = 99, MAX_SUFFIX = '+') => {\n if (count >= MAX) return `${MAX}${MAX_SUFFIX}`;\n return `${count}`;\n};\n\n/**\n * Messages date separator format\n *\n * @param {Date} date\n * @param {Locale} [locale]\n * @returns {string}\n * */\nexport const getDateSeparatorFormat = (date: Date, locale?: Locale): string => {\n if (isThisYear(date)) return format(date, 'MMM dd, yyyy', { locale });\n return format(date, 'E, MMM dd', { locale });\n};\n\n/**\n * Message time format\n *\n * @param {Date} date\n * @param {Locale} [locale]\n * @returns {string}\n * */\nexport const getMessageTimeFormat = (date: Date, locale?: Locale): string => {\n return format(date, 'p', { locale });\n};\n\n/**\n * Message preview title text\n * */\nexport const getMessagePreviewTitle = (message: SendbirdBaseMessage, EMPTY_USERNAME = '(No name)') => {\n if (message.isFileMessage() || message.isUserMessage()) {\n return message.sender.nickname || EMPTY_USERNAME;\n }\n if (message.isAdminMessage()) {\n return 'Admin';\n }\n return EMPTY_USERNAME;\n};\n\n/**\n * Message preview body text\n * */\nexport const getMessagePreviewBody = (message: SendbirdBaseMessage, EMPTY_MESSAGE = '') => {\n if (message.isFileMessage()) {\n const extIdx = message.name.lastIndexOf('.');\n if (extIdx > -1) {\n const file = message.name.slice(0, extIdx);\n const ext = message.name.slice(extIdx);\n return file + ext;\n }\n\n return message.name;\n }\n\n if (message.isUserMessage()) {\n return message.message ?? EMPTY_MESSAGE;\n }\n\n if (message.isAdminMessage()) {\n return message.message ?? EMPTY_MESSAGE;\n }\n\n return EMPTY_MESSAGE;\n};\n\n/**\n * Message preview time format\n * */\nexport const getMessagePreviewTime = (timestamp: number, locale?: Locale) => {\n if (isToday(timestamp)) return format(timestamp, 'p', { locale });\n if (isYesterday(timestamp)) return 'Yesterday';\n if (isThisYear(timestamp)) return format(timestamp, 'MMM dd', { locale });\n\n return format(timestamp, 'yyyy/MM/dd', { locale });\n};\n\n/**\n * milliseconds to 00:00 format\n * */\nexport const millsToMMSS = (mills: number) => {\n let seconds = Math.floor(Math.max(0, mills) / 1000);\n const minutes = Math.floor(seconds / 60);\n seconds = seconds % 60;\n\n const mm = String(minutes).padStart(2, '0');\n const ss = String(seconds).padStart(2, '0');\n\n return `${mm}:${ss}`;\n};\n\n/**\n * milliseconds to 0:00 format\n * */\nexport const millsToMSS = (mills: number) => {\n let seconds = Math.floor(Math.max(0, mills) / 1000);\n const minutes = Math.floor(seconds / 60);\n seconds =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,7 @@ export declare const useAsyncLayoutEffect: (asyncEffect: AsyncEffectCallback, de
9
9
  export declare const useIIFE: <T>(callback: () => T) => T;
10
10
  export declare const useIsMountedRef: () => import("react").MutableRefObject<boolean>;
11
11
  export declare const useIsFirstMount: () => boolean;
12
- export declare const useFreshCallback: <T extends (...args: any[]) => any>(callback: T) => T;
12
+ export declare const useFreshCallback: <T extends Function>(callback: T) => T;
13
13
  export declare const useDebounceEffect: (action: () => void, delay: number, deps?: DependencyList) => void;
14
14
  export declare const usePartialState: <S>(initialState: S) => [S & Partial<S>, import("react").Dispatch<Partial<S>>];
15
15
  export declare const useRefTracker: <T>(target: T) => import("react").MutableRefObject<T>;
@@ -1,3 +1,4 @@
1
+ /// <reference types="react" />
1
2
  import { AppStateEvent, AppStateStatus } from 'react-native';
2
3
  import { EdgeInsets } from 'react-native-safe-area-context';
3
4
  type EdgePaddingMap = {
@@ -9,4 +10,14 @@ type EdgePaddingMap = {
9
10
  export declare const useSafeAreaPadding: <T extends keyof EdgeInsets, Result extends { [key in EdgePaddingMap[T]]: EdgeInsets[T]; }>(edges: T[]) => Result;
10
11
  type AppStateListener = (status: AppStateStatus) => void;
11
12
  export declare const useAppState: (type: AppStateEvent, listener: AppStateListener) => void;
13
+ /**
14
+ * To display a new modal in React-Native, you should ensure that a new modal is opened only after the existing modal has been dismissed to avoid conflicts.
15
+ * To achieve this, you can use a deferred onClose that can be awaited until the onDismiss is called.
16
+ * */
17
+ export declare const useDeferredModalState: () => {
18
+ onClose: () => Promise<void>;
19
+ onDismiss: () => void;
20
+ visible: boolean;
21
+ setVisible: import("react").Dispatch<import("react").SetStateAction<boolean>>;
22
+ };
12
23
  export {};
@@ -25,7 +25,7 @@ export declare function shouldRenderParentMessage(message: SendbirdMessage): mes
25
25
  };
26
26
  export declare function shouldRenderReaction(channel: SendbirdBaseChannel, reactionEnabled: boolean): boolean;
27
27
  export declare function getReactionCount(reaction: SendbirdReaction): number;
28
- export type MessageType = 'user' | 'admin' | 'file' | 'unknown' | `user.${'opengraph'}` | `file.${'image' | 'video' | 'audio'}`;
28
+ export type MessageType = 'user' | 'admin' | 'file' | 'unknown' | `user.${'opengraph'}` | `file.${'image' | 'video' | 'audio' | 'voice'}`;
29
29
  export type FileType = 'file' | 'image' | 'audio' | 'video';
30
30
  declare const fileIconMapper: {
31
31
  readonly audio: "file-audio";
@@ -46,4 +46,12 @@ export declare function getDefaultMessageSearchQueryParams(channel: SendbirdGrou
46
46
  messageTimestampFrom: number;
47
47
  order: MessageSearchOrder;
48
48
  };
49
+ export declare function isVoiceMessage(message: SendbirdMessage): message is SendbirdFileMessage;
50
+ export declare function getVoiceMessageFileObject(uri: string, extension?: string): {
51
+ uri: string;
52
+ type: string;
53
+ name: string;
54
+ size: number;
55
+ };
56
+ export declare function getVoiceMessageMimeType(extension?: string): string;
49
57
  export {};
@@ -25,3 +25,5 @@ export declare function pick<T extends {
25
25
  [key: string]: unknown;
26
26
  }, Keys extends keyof T>(obj: T, keys: Keys[]): { [key in Keys]: T[key]; };
27
27
  export declare function mergeObjectArrays<T>(A: T[], B: T[], key: keyof T): T[];
28
+ export declare function sleep(ms: number): Promise<unknown>;
29
+ export declare function matchesOneOf<V, C extends V[]>(value: V, candidates: C): boolean;
@@ -11,7 +11,7 @@ export type FilterByValueType<T extends object, Type> = {
11
11
  };
12
12
  export type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
13
13
  export type OmittedValues<T, K extends keyof T> = Omit<T, K>[keyof Omit<T, K>];
14
- export type PartialDeep<T> = T extends object ? T extends Function ? T : {
14
+ export type PartialDeep<T> = T extends object ? T extends Set<unknown> ? T : T extends Function ? T : {
15
15
  [P in keyof T]?: PartialDeep<T[P]>;
16
16
  } : T;
17
17
  export type PartialNullable<T> = {
@@ -54,4 +54,12 @@ export declare const getMessagePreviewBody: (message: SendbirdBaseMessage, EMPTY
54
54
  * Message preview time format
55
55
  * */
56
56
  export declare const getMessagePreviewTime: (timestamp: number, locale?: Locale) => string;
57
+ /**
58
+ * milliseconds to 00:00 format
59
+ * */
60
+ export declare const millsToMMSS: (mills: number) => string;
61
+ /**
62
+ * milliseconds to 0:00 format
63
+ * */
64
+ export declare const millsToMSS: (mills: number) => string;
57
65
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sendbird/uikit-utils",
3
- "version": "3.1.2",
3
+ "version": "3.3.0",
4
4
  "description": "A collection of utility functions and constants for building chat UI components with Sendbird UIKit.",
5
5
  "keywords": [
6
6
  "sendbird",
@@ -25,7 +25,8 @@
25
25
  "test": "jest",
26
26
  "build": "bob build",
27
27
  "clean": "del lib",
28
- "publish:next": "npm publish --tag next"
28
+ "publish:next": "npm publish --tag next",
29
+ "publish:local": "yalc publish"
29
30
  },
30
31
  "repository": {
31
32
  "type": "git",
@@ -52,7 +53,7 @@
52
53
  "react": "17.0.2",
53
54
  "react-native": "0.67.5",
54
55
  "react-native-builder-bob": "^0.18.0",
55
- "typescript": "4.9.4"
56
+ "typescript": "5.2.2"
56
57
  },
57
58
  "peerDependencies": {
58
59
  "@sendbird/chat": "^4.9.8",
@@ -81,10 +82,5 @@
81
82
  ]
82
83
  ]
83
84
  },
84
- "typedoc": {
85
- "entryPoint": "./src/index.ts",
86
- "readmeFile": "./README.md",
87
- "displayName": "@sendbird/uikit-utils"
88
- },
89
- "gitHead": "49d482105f9e2bc0643916682126935747a84011"
85
+ "gitHead": "51adda5f33a7bb450b51ce30f505dcc9884e9586"
90
86
  }
@@ -72,10 +72,10 @@ export const useIsFirstMount = () => {
72
72
  return isFirstMount.current;
73
73
  };
74
74
 
75
- export const useFreshCallback = <T extends (...args: any[]) => any>(callback: T): T => {
75
+ export const useFreshCallback = <T extends Function>(callback: T): T => {
76
76
  const ref = useRef<T>(callback);
77
77
  ref.current = callback;
78
- return useCallback(((...args) => ref.current(...args)) as T, []);
78
+ return useCallback(((...args: any[]) => ref.current(...args)) as unknown as T, []);
79
79
  };
80
80
 
81
81
  export const useDebounceEffect = (action: () => void, delay: number, deps: DependencyList = []) => {
@@ -1,4 +1,4 @@
1
- import { useEffect, useRef } from 'react';
1
+ import { useEffect, useRef, useState } from 'react';
2
2
  import { AppState, AppStateEvent, AppStateStatus } from 'react-native';
3
3
  import { EdgeInsets, useSafeAreaInsets } from 'react-native-safe-area-context';
4
4
 
@@ -44,3 +44,26 @@ export const useAppState = (type: AppStateEvent, listener: AppStateListener) =>
44
44
  };
45
45
  }, []);
46
46
  };
47
+
48
+ /**
49
+ * To display a new modal in React-Native, you should ensure that a new modal is opened only after the existing modal has been dismissed to avoid conflicts.
50
+ * To achieve this, you can use a deferred onClose that can be awaited until the onDismiss is called.
51
+ * */
52
+ export const useDeferredModalState = () => {
53
+ const resolveRef = useRef<(value: void) => void>();
54
+ const [visible, setVisible] = useState(false);
55
+
56
+ return {
57
+ onClose: () => {
58
+ return new Promise<void>((resolve) => {
59
+ resolveRef.current = resolve;
60
+ setVisible(false);
61
+ });
62
+ },
63
+ onDismiss: () => {
64
+ resolveRef.current?.();
65
+ },
66
+ visible,
67
+ setVisible,
68
+ };
69
+ };
@@ -1,6 +1,6 @@
1
1
  import { MessageSearchOrder } from '@sendbird/chat/message';
2
2
 
3
- import { getFileExtension, getFileType } from '../shared/file';
3
+ import { getFileExtension, getFileType, parseMimeType } from '../shared/file';
4
4
  import type {
5
5
  SendbirdBaseChannel,
6
6
  SendbirdBaseMessage,
@@ -161,7 +161,7 @@ export type MessageType =
161
161
  | 'file'
162
162
  | 'unknown'
163
163
  | `user.${'opengraph'}`
164
- | `file.${'image' | 'video' | 'audio'}`;
164
+ | `file.${'image' | 'video' | 'audio' | 'voice'}`;
165
165
 
166
166
  export type FileType = 'file' | 'image' | 'audio' | 'video';
167
167
 
@@ -221,6 +221,10 @@ export function getMessageType(message: SendbirdMessage): MessageType {
221
221
  }
222
222
 
223
223
  if (message.isFileMessage()) {
224
+ if (isVoiceMessage(message)) {
225
+ return 'file.voice';
226
+ }
227
+
224
228
  const fileType = getFileTypeFromMessage(message);
225
229
  switch (fileType) {
226
230
  case 'image':
@@ -247,3 +251,26 @@ export function getDefaultMessageSearchQueryParams(channel: SendbirdGroupChannel
247
251
  order: MessageSearchOrder.TIMESTAMP,
248
252
  };
249
253
  }
254
+
255
+ const SBU_MIME_PARAM_KEY = 'sbu_type';
256
+ const SBU_MIME_PARAM_VOICE_MESSAGE_VALUE = 'voice';
257
+
258
+ export function isVoiceMessage(message: SendbirdMessage): message is SendbirdFileMessage {
259
+ if (!message.isFileMessage()) return false;
260
+
261
+ const { parameters } = parseMimeType(message.type);
262
+ return !!parameters[SBU_MIME_PARAM_KEY] && parameters[SBU_MIME_PARAM_KEY] === SBU_MIME_PARAM_VOICE_MESSAGE_VALUE;
263
+ }
264
+
265
+ export function getVoiceMessageFileObject(uri: string, extension = 'm4a') {
266
+ return {
267
+ uri,
268
+ type: getVoiceMessageMimeType(extension),
269
+ name: `Voice_message.${extension}`,
270
+ size: 0,
271
+ };
272
+ }
273
+
274
+ export function getVoiceMessageMimeType(extension = 'm4a') {
275
+ return `audio/${extension};${SBU_MIME_PARAM_KEY}=${SBU_MIME_PARAM_VOICE_MESSAGE_VALUE}`;
276
+ }
@@ -18,6 +18,7 @@ const EXTENSION_MIME_MAP = {
18
18
 
19
19
  // Audio
20
20
  'aac': 'audio/aac',
21
+ 'm4a': 'audio/m4a',
21
22
  'mid': 'audio/midi',
22
23
  'mp3': 'audio/mpeg',
23
24
  'ogg': 'audio/ogg',
@@ -51,3 +51,11 @@ export function mergeObjectArrays<T>(A: T[], B: T[], key: keyof T): T[] {
51
51
 
52
52
  return newArr;
53
53
  }
54
+
55
+ export function sleep(ms: number) {
56
+ return new Promise((resolve) => setTimeout(resolve, ms));
57
+ }
58
+
59
+ export function matchesOneOf<V, C extends V[]>(value: V, candidates: C) {
60
+ return candidates.includes(value);
61
+ }
package/src/types.ts CHANGED
@@ -60,7 +60,9 @@ export type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never
60
60
  export type OmittedValues<T, K extends keyof T> = Omit<T, K>[keyof Omit<T, K>];
61
61
 
62
62
  export type PartialDeep<T> = T extends object
63
- ? T extends Function
63
+ ? T extends Set<unknown>
64
+ ? T
65
+ : T extends Function
64
66
  ? T
65
67
  : {
66
68
  [P in keyof T]?: PartialDeep<T[P]>;