@linktr.ee/messaging-react 4.2.0-rc-1787325521 → 4.2.0-rc-1787325710
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/dist/AttachmentCard-C-X0jLZ2.cjs +2 -0
- package/dist/AttachmentCard-C-X0jLZ2.cjs.map +1 -0
- package/dist/AttachmentCard-D2IoHdcv.js +410 -0
- package/dist/AttachmentCard-D2IoHdcv.js.map +1 -0
- package/dist/Card-C7uLQbYz.js +105 -0
- package/dist/Card-C7uLQbYz.js.map +1 -0
- package/dist/Card-DENHpLIC.cjs +2 -0
- package/dist/Card-DENHpLIC.cjs.map +1 -0
- package/dist/Card-Ds1FMcUj.cjs +2 -0
- package/dist/Card-Ds1FMcUj.cjs.map +1 -0
- package/dist/Card-EKD9NkTa.js +498 -0
- package/dist/Card-EKD9NkTa.js.map +1 -0
- package/dist/LoadingDots-BSk_UeS0.cjs +2 -0
- package/dist/LoadingDots-BSk_UeS0.cjs.map +1 -0
- package/dist/LoadingDots-B_WiXBeQ.js +73 -0
- package/dist/LoadingDots-B_WiXBeQ.js.map +1 -0
- package/dist/assets/index.css +2 -1
- package/dist/index.cjs +3 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +0 -26
- package/dist/index.js +4071 -41
- package/dist/index.js.map +1 -1
- package/dist/rolldown-runtime-BocRIvOZ.cjs +1 -0
- package/dist/testing.cjs +2 -2
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.js +106 -118
- package/dist/testing.js.map +1 -1
- package/package.json +5 -5
- package/src/components/ChannelView.stories.tsx +0 -4
- package/src/index.ts +0 -3
- package/src/providers/MessagingProvider.test.tsx +1 -127
- package/src/providers/MessagingProvider.tsx +15 -26
- package/src/types.ts +0 -8
- package/dist/Card-BYJyA83X.js +0 -701
- package/dist/Card-BYJyA83X.js.map +0 -1
- package/dist/Card-Be81K6su.cjs +0 -2
- package/dist/Card-Be81K6su.cjs.map +0 -1
- package/dist/Card-BplJtZao.cjs +0 -2
- package/dist/Card-BplJtZao.cjs.map +0 -1
- package/dist/Card-BzvDr-pU.js +0 -112
- package/dist/Card-BzvDr-pU.js.map +0 -1
- package/dist/PurchaseStatusBadge-BmqAQEV9.cjs +0 -2
- package/dist/PurchaseStatusBadge-BmqAQEV9.cjs.map +0 -1
- package/dist/PurchaseStatusBadge-D1RRsubZ.js +0 -59
- package/dist/PurchaseStatusBadge-D1RRsubZ.js.map +0 -1
- package/dist/index-BUC9vqhJ.js +0 -5916
- package/dist/index-BUC9vqhJ.js.map +0 -1
- package/dist/index-BkqyKPJP.cjs +0 -3
- package/dist/index-BkqyKPJP.cjs.map +0 -1
- package/src/logging/index.test.tsx +0 -136
- package/src/logging/index.tsx +0 -48
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
|
package/dist/testing.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
//# sourceMappingURL=testing.cjs.map
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("stream-chat");function t(t,{stubConnection:n=!1}={}){let r=new e.StreamChat(`mock-api-key`,{allowServerSideConnect:!0});return r.userID=t.id,r.user=t,n&&(r.connectUser=async()=>({me:t}),r.disconnectUser=async()=>void 0,r.userMuteStatus=(()=>!1)),r}var n=600;function r({currentUser:e,participant:r,messages:i=[],channelId:a=`mock-dm`,onSend:o}){let s=t(e,{stubConnection:!0}),c=`messaging:${a}`,l=(t,n)=>{let a=t.from===`me`?e:r,o=new Date(Date.now()-(i.length-n)*6e4);return{id:t.id??`mock-msg-${n}`,text:t.text??``,type:`regular`,html:t.text?`<p>${t.text}</p>`:``,user:a,attachments:t.attachments??[],latest_reactions:[],own_reactions:[],reaction_counts:{},reaction_scores:{},reply_count:0,status:`received`,cid:c,created_at:o,updated_at:o,mentioned_users:[],...t.metadata?{metadata:t.metadata}:{}}},u=i.map(l),d={[e.id]:{user:{...e,is_account:!1},user_id:e.id,role:`owner`,is_account:!1},[r.id]:{user:{...r,is_account:!0},user_id:r.id,role:`member`,is_account:!0}},f=s.channel(`messaging`,a,{members:[e.id,r.id]});f.muteStatus=()=>({muted:!1,createdAt:null,expiresAt:null}),f.markRead=(async()=>({})),f.keystroke=(async()=>void 0),f.stopTyping=(async()=>void 0),f.sendReaction=(async()=>({})),f.deleteReaction=(async()=>({})),f.countUnread=(()=>0),f.query=(async()=>({messages:[]})),f.hide=(async()=>({}));let p=!1;f.watch=async()=>(p||=(f.state.messages=u,!0),f.state.members=d,{channel:{members:[e.id,r.id]},members:[],messages:f.state.messages,watchers:[],pinned_messages:[],duration:`0ms`});let m=e=>{f.state.addMessageSorted(e),s.dispatchEvent({type:`message.new`,cid:c,message:e,user:e.user??void 0})},h=0,g=0;return f.sendMessage=async t=>{let r=typeof t==`string`?t:t?.text??``,i={...l({text:r,from:`me`,id:`mock-sent-${h++}`},u.length),...typeof t==`object`?t:{},user:e,cid:c};m(i);let a=o?.(r);if(a){let e=typeof a==`string`?a:a.text,t=typeof a==`string`?void 0:a.attachments,r=`mock-reply-${g++}`;setTimeout(()=>{m(l({text:e,from:`them`,attachments:t,id:r},u.length))},n)}return{message:i}},s.queryChannels=async()=>[f],f.watch(),{client:s,channel:f,participantFilterId:r.id}}exports.createMockMessagingClient=r;
|
|
2
|
+
//# sourceMappingURL=testing.cjs.map
|
package/dist/testing.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.cjs","sources":["../src/testing/createMockStreamChatClient.ts","../src/testing/createMockMessagingClient.ts"],"sourcesContent":["import { StreamChat } from 'stream-chat'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** A participant in the mock conversation. */\nexport interface MockMessagingUser {\n id: string\n name?: string\n image?: string\n}\n\nexport interface CreateMockStreamChatClientOptions {\n /**\n * Also replace the connection-dependent client methods (`connectUser`,\n * `disconnectUser`, `userMuteStatus`) with offline no-ops. Needed when the\n * client drives a flow that would otherwise open a WebSocket or throw\n * \"Make sure to await connectUser() first.\" offline. Direct `<Chat client>`\n * rendering (e.g. component stories) does not need this.\n */\n stubConnection?: boolean\n}\n\n/**\n * Builds an offline `StreamChat` for mocks and stories: a real client on a\n * throwaway api key with `userID`/`user` set so `<Chat>` treats it as\n * connected without a backend. The single place that knows how to construct a\n * connectionless Stream client, so a stream-chat version bump only needs\n * updating here rather than in each mock surface.\n */\nexport function createMockStreamChatClient(\n user: MockMessagingUser,\n { stubConnection = false }: CreateMockStreamChatClientOptions = {}\n): StreamChat {\n const client = new StreamChat('mock-api-key', {\n allowServerSideConnect: true,\n })\n client.userID = user.id\n client.user = user as any\n\n if (stubConnection) {\n client.connectUser = async () => ({ me: user }) as any\n client.disconnectUser = async () => undefined\n client.userMuteStatus = (() => false) as any\n }\n\n return client\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","import type {\n Channel,\n MessageResponse,\n QueryChannelAPIResponse,\n SendMessageAPIResponse,\n} from 'stream-chat'\nimport { StreamChat } from 'stream-chat'\n\nimport {\n createMockStreamChatClient,\n type MockMessagingUser,\n} from './createMockStreamChatClient'\n\n/**\n * A seed message, authored from the viewer's perspective. `from: 'me'` is the\n * connected user (the viewer); `from: 'them'` is the other participant.\n */\nexport interface MockMessage {\n id?: string\n text?: string\n from: 'me' | 'them'\n /** Stream attachment payloads, rendered by the toolkit's attachment gate. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments?: any[]\n /** e.g. `{ custom_type: 'MESSAGE_WELCOME' }`. */\n metadata?: Record<string, unknown>\n}\n\nexport interface CreateMockMessagingClientOptions {\n /** The connected/viewing user. */\n currentUser: MockMessagingUser\n /** The other party in the direct conversation (e.g. the creator/linker). */\n participant: MockMessagingUser\n /** Seed conversation, oldest-first. */\n messages?: MockMessage[]\n /** Channel id; defaults to `mock-dm`. */\n channelId?: string\n /**\n * Optional canned reply. Called after the viewer sends a message; return the\n * reply text (or a partial message) to have `participant` echo a response, or\n * a falsy value for no reply. Drives the \"send echo\" in `dev:mock-messaging`.\n */\n onSend?: (\n text: string\n ) => string | { text?: string; attachments?: unknown[] } | null | undefined\n}\n\nexport interface MockMessagingClient {\n /** Pass to `<MessagingProvider client={...}>`. */\n client: StreamChat\n /** The seeded direct-conversation channel. */\n channel: Channel\n /** Pass to `<MessagingShell initialParticipantFilter={...}>`. */\n participantFilterId: string\n}\n\nconst REPLY_DELAY_MS = 600\n\n/**\n * Builds an offline Stream client seeded with a single direct conversation, so\n * consumers can render the **real** messaging UI (MessagingProvider →\n * MessagingShell → ChannelView) without a Stream backend — for `dev:mock-*`\n * surfaces and Storybook. It is a real `StreamChat` whose network calls\n * (`connectUser`, `queryChannels`, `channel.watch`, `channel.sendMessage`) are\n * replaced with in-memory behaviour driven by Stream's own channel-state\n * machinery, so rendering fidelity matches production.\n *\n * Ships from `@linktr.ee/messaging-react/testing` and must never be imported by\n * production code.\n */\nexport function createMockMessagingClient({\n currentUser,\n participant,\n messages = [],\n channelId = 'mock-dm',\n onSend,\n}: CreateMockMessagingClientOptions): MockMessagingClient {\n // Offline client marked connected without a WebSocket. `stubConnection` also\n // no-ops connectUser/disconnectUser/userMuteStatus: `MessagingProvider`\n // renders `<Chat client={client}>` directly so it never calls connectUser,\n // and handling the `message.new` events dispatched on send + echo below runs\n // Channel._countMessageAsUnread → client.userMuteStatus, which throws offline.\n const client = createMockStreamChatClient(currentUser, {\n stubConnection: true,\n })\n\n const cid = `messaging:${channelId}`\n\n const toStreamMessage = (\n message: MockMessage,\n index: number\n ): MessageResponse => {\n const author = message.from === 'me' ? currentUser : participant\n // Stagger timestamps oldest-first so the list orders naturally. Must be a\n // Date, not an ISO string: we seed `channel.state.messages` directly\n // (bypassing Stream's wire→Date parsing), and stream-chat-react calls\n // `.getTime()` on `created_at` (e.g. useCooldownTimer / addToMessageList).\n const createdAt = new Date(Date.now() - (messages.length - index) * 60_000)\n return {\n id: message.id ?? `mock-msg-${index}`,\n text: message.text ?? '',\n type: 'regular',\n html: message.text ? `<p>${message.text}</p>` : '',\n user: author,\n attachments: message.attachments ?? [],\n latest_reactions: [],\n own_reactions: [],\n reaction_counts: {},\n reaction_scores: {},\n reply_count: 0,\n status: 'received',\n cid,\n created_at: createdAt,\n updated_at: createdAt,\n mentioned_users: [],\n ...(message.metadata ? { metadata: message.metadata } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n const seededMessages = messages.map(toStreamMessage)\n\n const memberState = {\n [currentUser.id]: {\n user: { ...currentUser, is_account: false },\n user_id: currentUser.id,\n role: 'owner',\n is_account: false,\n },\n [participant.id]: {\n user: { ...participant, is_account: true },\n user_id: participant.id,\n role: 'member',\n is_account: true,\n },\n }\n\n const channel = client.channel('messaging', channelId, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: [currentUser.id, participant.id] as any,\n })\n // Read/unread bookkeeping consults channel mute status; without a live\n // connection the real method throws, so report \"not muted\".\n channel.muteStatus = () => ({\n muted: false,\n createdAt: null,\n expiresAt: null,\n })\n\n // Neutralise the rest of the connection-dependent channel API that\n // stream-chat-react calls during the chat lifecycle. Each of these POSTs to\n // Stream or checks for a live WebSocket and would otherwise throw\n // \"Make sure to await connectUser() first.\" offline. They are fire-and-forget\n // (read receipts, typing) or read-only (pagination, unread) so no-ops are safe.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n channel.markRead = (async () => ({}) as any) as any\n channel.keystroke = (async () => undefined) as any\n channel.stopTyping = (async () => undefined) as any\n channel.sendReaction = (async () => ({}) as any) as any\n channel.deleteReaction = (async () => ({}) as any) as any\n channel.countUnread = (() => 0) as any\n // Pagination: report no older pages so \"load more\" resolves to a no-op.\n channel.query = (async () => ({ messages: [] }) as any) as any\n // Leave/Delete Conversation calls channel.hide(); the real method POSTs to\n // Stream, so no-op it to keep the action working offline.\n channel.hide = (async () => ({}) as any) as any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n // Seed state locally instead of fetching. Mirrors the proven ChannelView\n // story mock: override `watch` to populate `state` and return a canned\n // QueryChannelAPIResponse. `stream-chat-react` may call `watch()` again on\n // remount/navigation, so seed only once — otherwise a re-watch would wipe\n // messages added via `sendMessage` + the send-echo reply, resetting the chat.\n let hasSeeded = false\n channel.watch = async () => {\n if (!hasSeeded) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.messages = seededMessages as unknown as any[]\n hasSeeded = true\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.members = memberState as unknown as any\n return {\n channel: { members: [currentUser.id, participant.id] },\n members: [],\n messages: channel.state.messages,\n watchers: [],\n pinned_messages: [],\n duration: '0ms',\n } as unknown as QueryChannelAPIResponse\n }\n\n const appendMessage = (message: MessageResponse) => {\n // addMessageSorted is Stream's own state mutation (dedupes by id), so the\n // toolkit re-renders through the real channel-state path.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.addMessageSorted(message as any)\n client.dispatchEvent({\n type: 'message.new',\n cid,\n message,\n user: message.user ?? undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n }\n\n let sentCount = 0\n let replyCount = 0\n channel.sendMessage = async (message) => {\n const text =\n typeof message === 'string'\n ? message\n : ((message as { text?: string })?.text ?? '')\n const sent = {\n ...toStreamMessage(\n { text, from: 'me', id: `mock-sent-${sentCount++}` },\n seededMessages.length\n ),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...(typeof message === 'object' ? (message as any) : {}),\n user: currentUser,\n cid,\n } as MessageResponse\n\n // stream-chat-react adds the outgoing message optimistically; addMessageSorted\n // dedupes by id, so confirming here is safe and idempotent.\n appendMessage(sent)\n\n const reply = onSend?.(text)\n if (reply) {\n const replyText = typeof reply === 'string' ? reply : reply.text\n const replyAttachments =\n typeof reply === 'string' ? undefined : reply.attachments\n // Capture a unique id before scheduling: two sends within REPLY_DELAY_MS\n // would otherwise both read the same later `sentCount` at fire time and\n // emit colliding reply ids, so Stream's id-based dedupe drops one echo.\n const replyId = `mock-reply-${replyCount++}`\n setTimeout(() => {\n appendMessage(\n toStreamMessage(\n {\n text: replyText,\n from: 'them',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments: replyAttachments as any,\n id: replyId,\n },\n seededMessages.length\n )\n )\n }, REPLY_DELAY_MS)\n }\n\n return { message: sent } as unknown as SendMessageAPIResponse\n }\n\n // MessagingShell finds the direct conversation via queryChannels; always\n // return the one seeded channel regardless of the filter.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client.queryChannels = async () => [channel] as any\n\n // Initialise state up-front so first render already has the conversation.\n void channel.watch()\n\n return { client, channel, participantFilterId: participant.id }\n}\n"],"names":["createMockStreamChatClient","user","stubConnection","client","StreamChat","REPLY_DELAY_MS","createMockMessagingClient","currentUser","participant","messages","channelId","onSend","cid","toStreamMessage","message","index","author","createdAt","seededMessages","memberState","channel","hasSeeded","appendMessage","sentCount","replyCount","text","sent","reply","replyText","replyAttachments","replyId"],"mappings":"+GA6BO,SAASA,EACdC,EACA,CAAE,eAAAC,EAAiB,EAAA,EAA6C,CAAA,EACpD,CACZ,MAAMC,EAAS,IAAIC,EAAAA,WAAW,eAAgB,CAC5C,uBAAwB,EAAA,CACzB,EACD,OAAAD,EAAO,OAASF,EAAK,GACrBE,EAAO,KAAOF,EAEVC,IACFC,EAAO,YAAc,UAAa,CAAE,GAAIF,C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U,SAAWA,EAAQA,EAAM,KACtDE,EACJ,OAAOF,GAAU,SAAW,OAAYA,EAAM,YAI1CG,EAAU,cAAcN,GAAY,GAC1C,WAAW,IAAM,CACfF,EACET,EACE,CACE,KAAMe,EACN,KAAM,OAEN,YAAaC,EACb,GAAIC,CAAA,EAENZ,EAAe,MAAA,CACjB,CAEJ,EAAGb,CAAc,CACnB,CAEA,MAAO,CAAE,QAASqB,CAAA,CACpB,EAKAvB,EAAO,cAAgB,SAAY,CAACiB,CAAO,EAGtCA,EAAQ,MAAA,EAEN,CAAE,OAAAjB,EAAQ,QAAAiB,EAAS,oBAAqBZ,EAAY,EAAA,CAC7D"}
|
|
1
|
+
{"version":3,"file":"testing.cjs","names":[],"sources":["../src/testing/createMockStreamChatClient.ts","../src/testing/createMockMessagingClient.ts"],"sourcesContent":["import { StreamChat } from 'stream-chat'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** A participant in the mock conversation. */\nexport interface MockMessagingUser {\n id: string\n name?: string\n image?: string\n}\n\nexport interface CreateMockStreamChatClientOptions {\n /**\n * Also replace the connection-dependent client methods (`connectUser`,\n * `disconnectUser`, `userMuteStatus`) with offline no-ops. Needed when the\n * client drives a flow that would otherwise open a WebSocket or throw\n * \"Make sure to await connectUser() first.\" offline. Direct `<Chat client>`\n * rendering (e.g. component stories) does not need this.\n */\n stubConnection?: boolean\n}\n\n/**\n * Builds an offline `StreamChat` for mocks and stories: a real client on a\n * throwaway api key with `userID`/`user` set so `<Chat>` treats it as\n * connected without a backend. The single place that knows how to construct a\n * connectionless Stream client, so a stream-chat version bump only needs\n * updating here rather than in each mock surface.\n */\nexport function createMockStreamChatClient(\n user: MockMessagingUser,\n { stubConnection = false }: CreateMockStreamChatClientOptions = {}\n): StreamChat {\n const client = new StreamChat('mock-api-key', {\n allowServerSideConnect: true,\n })\n client.userID = user.id\n client.user = user as any\n\n if (stubConnection) {\n client.connectUser = async () => ({ me: user }) as any\n client.disconnectUser = async () => undefined\n client.userMuteStatus = (() => false) as any\n }\n\n return client\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","import type {\n Channel,\n MessageResponse,\n QueryChannelAPIResponse,\n SendMessageAPIResponse,\n} from 'stream-chat'\nimport { StreamChat } from 'stream-chat'\n\nimport {\n createMockStreamChatClient,\n type MockMessagingUser,\n} from './createMockStreamChatClient'\n\n/**\n * A seed message, authored from the viewer's perspective. `from: 'me'` is the\n * connected user (the viewer); `from: 'them'` is the other participant.\n */\nexport interface MockMessage {\n id?: string\n text?: string\n from: 'me' | 'them'\n /** Stream attachment payloads, rendered by the toolkit's attachment gate. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments?: any[]\n /** e.g. `{ custom_type: 'MESSAGE_WELCOME' }`. */\n metadata?: Record<string, unknown>\n}\n\nexport interface CreateMockMessagingClientOptions {\n /** The connected/viewing user. */\n currentUser: MockMessagingUser\n /** The other party in the direct conversation (e.g. the creator/linker). */\n participant: MockMessagingUser\n /** Seed conversation, oldest-first. */\n messages?: MockMessage[]\n /** Channel id; defaults to `mock-dm`. */\n channelId?: string\n /**\n * Optional canned reply. Called after the viewer sends a message; return the\n * reply text (or a partial message) to have `participant` echo a response, or\n * a falsy value for no reply. Drives the \"send echo\" in `dev:mock-messaging`.\n */\n onSend?: (\n text: string\n ) => string | { text?: string; attachments?: unknown[] } | null | undefined\n}\n\nexport interface MockMessagingClient {\n /** Pass to `<MessagingProvider client={...}>`. */\n client: StreamChat\n /** The seeded direct-conversation channel. */\n channel: Channel\n /** Pass to `<MessagingShell initialParticipantFilter={...}>`. */\n participantFilterId: string\n}\n\nconst REPLY_DELAY_MS = 600\n\n/**\n * Builds an offline Stream client seeded with a single direct conversation, so\n * consumers can render the **real** messaging UI (MessagingProvider →\n * MessagingShell → ChannelView) without a Stream backend — for `dev:mock-*`\n * surfaces and Storybook. It is a real `StreamChat` whose network calls\n * (`connectUser`, `queryChannels`, `channel.watch`, `channel.sendMessage`) are\n * replaced with in-memory behaviour driven by Stream's own channel-state\n * machinery, so rendering fidelity matches production.\n *\n * Ships from `@linktr.ee/messaging-react/testing` and must never be imported by\n * production code.\n */\nexport function createMockMessagingClient({\n currentUser,\n participant,\n messages = [],\n channelId = 'mock-dm',\n onSend,\n}: CreateMockMessagingClientOptions): MockMessagingClient {\n // Offline client marked connected without a WebSocket. `stubConnection` also\n // no-ops connectUser/disconnectUser/userMuteStatus: `MessagingProvider`\n // renders `<Chat client={client}>` directly so it never calls connectUser,\n // and handling the `message.new` events dispatched on send + echo below runs\n // Channel._countMessageAsUnread → client.userMuteStatus, which throws offline.\n const client = createMockStreamChatClient(currentUser, {\n stubConnection: true,\n })\n\n const cid = `messaging:${channelId}`\n\n const toStreamMessage = (\n message: MockMessage,\n index: number\n ): MessageResponse => {\n const author = message.from === 'me' ? currentUser : participant\n // Stagger timestamps oldest-first so the list orders naturally. Must be a\n // Date, not an ISO string: we seed `channel.state.messages` directly\n // (bypassing Stream's wire→Date parsing), and stream-chat-react calls\n // `.getTime()` on `created_at` (e.g. useCooldownTimer / addToMessageList).\n const createdAt = new Date(Date.now() - (messages.length - index) * 60_000)\n return {\n id: message.id ?? `mock-msg-${index}`,\n text: message.text ?? '',\n type: 'regular',\n html: message.text ? `<p>${message.text}</p>` : '',\n user: author,\n attachments: message.attachments ?? [],\n latest_reactions: [],\n own_reactions: [],\n reaction_counts: {},\n reaction_scores: {},\n reply_count: 0,\n status: 'received',\n cid,\n created_at: createdAt,\n updated_at: createdAt,\n mentioned_users: [],\n ...(message.metadata ? { metadata: message.metadata } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n const seededMessages = messages.map(toStreamMessage)\n\n const memberState = {\n [currentUser.id]: {\n user: { ...currentUser, is_account: false },\n user_id: currentUser.id,\n role: 'owner',\n is_account: false,\n },\n [participant.id]: {\n user: { ...participant, is_account: true },\n user_id: participant.id,\n role: 'member',\n is_account: true,\n },\n }\n\n const channel = client.channel('messaging', channelId, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: [currentUser.id, participant.id] as any,\n })\n // Read/unread bookkeeping consults channel mute status; without a live\n // connection the real method throws, so report \"not muted\".\n channel.muteStatus = () => ({\n muted: false,\n createdAt: null,\n expiresAt: null,\n })\n\n // Neutralise the rest of the connection-dependent channel API that\n // stream-chat-react calls during the chat lifecycle. Each of these POSTs to\n // Stream or checks for a live WebSocket and would otherwise throw\n // \"Make sure to await connectUser() first.\" offline. They are fire-and-forget\n // (read receipts, typing) or read-only (pagination, unread) so no-ops are safe.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n channel.markRead = (async () => ({}) as any) as any\n channel.keystroke = (async () => undefined) as any\n channel.stopTyping = (async () => undefined) as any\n channel.sendReaction = (async () => ({}) as any) as any\n channel.deleteReaction = (async () => ({}) as any) as any\n channel.countUnread = (() => 0) as any\n // Pagination: report no older pages so \"load more\" resolves to a no-op.\n channel.query = (async () => ({ messages: [] }) as any) as any\n // Leave/Delete Conversation calls channel.hide(); the real method POSTs to\n // Stream, so no-op it to keep the action working offline.\n channel.hide = (async () => ({}) as any) as any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n // Seed state locally instead of fetching. Mirrors the proven ChannelView\n // story mock: override `watch` to populate `state` and return a canned\n // QueryChannelAPIResponse. `stream-chat-react` may call `watch()` again on\n // remount/navigation, so seed only once — otherwise a re-watch would wipe\n // messages added via `sendMessage` + the send-echo reply, resetting the chat.\n let hasSeeded = false\n channel.watch = async () => {\n if (!hasSeeded) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.messages = seededMessages as unknown as any[]\n hasSeeded = true\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.members = memberState as unknown as any\n return {\n channel: { members: [currentUser.id, participant.id] },\n members: [],\n messages: channel.state.messages,\n watchers: [],\n pinned_messages: [],\n duration: '0ms',\n } as unknown as QueryChannelAPIResponse\n }\n\n const appendMessage = (message: MessageResponse) => {\n // addMessageSorted is Stream's own state mutation (dedupes by id), so the\n // toolkit re-renders through the real channel-state path.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.addMessageSorted(message as any)\n client.dispatchEvent({\n type: 'message.new',\n cid,\n message,\n user: message.user ?? undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n }\n\n let sentCount = 0\n let replyCount = 0\n channel.sendMessage = async (message) => {\n const text =\n typeof message === 'string'\n ? message\n : ((message as { text?: string })?.text ?? '')\n const sent = {\n ...toStreamMessage(\n { text, from: 'me', id: `mock-sent-${sentCount++}` },\n seededMessages.length\n ),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...(typeof message === 'object' ? (message as any) : {}),\n user: currentUser,\n cid,\n } as MessageResponse\n\n // stream-chat-react adds the outgoing message optimistically; addMessageSorted\n // dedupes by id, so confirming here is safe and idempotent.\n appendMessage(sent)\n\n const reply = onSend?.(text)\n if (reply) {\n const replyText = typeof reply === 'string' ? reply : reply.text\n const replyAttachments =\n typeof reply === 'string' ? undefined : reply.attachments\n // Capture a unique id before scheduling: two sends within REPLY_DELAY_MS\n // would otherwise both read the same later `sentCount` at fire time and\n // emit colliding reply ids, so Stream's id-based dedupe drops one echo.\n const replyId = `mock-reply-${replyCount++}`\n setTimeout(() => {\n appendMessage(\n toStreamMessage(\n {\n text: replyText,\n from: 'them',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments: replyAttachments as any,\n id: replyId,\n },\n seededMessages.length\n )\n )\n }, REPLY_DELAY_MS)\n }\n\n return { message: sent } as unknown as SendMessageAPIResponse\n }\n\n // MessagingShell finds the direct conversation via queryChannels; always\n // return the one seeded channel regardless of the filter.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client.queryChannels = async () => [channel] as any\n\n // Initialise state up-front so first render already has the conversation.\n void channel.watch()\n\n return { client, channel, participantFilterId: participant.id }\n}\n"],"mappings":"gGA6BA,SAAgB,EACd,EACA,CAAE,iBAAiB,IAA6C,CAAC,EACrD,CACZ,I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M,YAI1C,EAAU,cAAc,MAC9B,eAAiB,CACf,EACE,EACE,CACE,KAAM,EACN,KAAM,OAEN,YAAa,EACb,GAAI,CACN,EACA,EAAe,MACjB,CACF,CACF,EAAG,CAAc,CACnB,CAEA,MAAO,CAAE,QAAS,CAAK,CACzB,EAKA,EAAO,cAAgB,SAAY,CAAC,CAAO,EAG3C,EAAa,MAAM,EAEZ,CAAE,SAAQ,UAAS,oBAAqB,EAAY,EAAG,CAChE"}
|
package/dist/testing.js
CHANGED
|
@@ -1,120 +1,108 @@
|
|
|
1
|
-
import { StreamChat as
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
return a.userID = s.id, a.user = s, n && (a.connectUser = async () => ({ me: s }), a.disconnectUser = async () => {
|
|
7
|
-
}, a.userMuteStatus = (() => !1)), a;
|
|
1
|
+
import { StreamChat as e } from "stream-chat";
|
|
2
|
+
//#region src/testing/createMockStreamChatClient.ts
|
|
3
|
+
function t(t, { stubConnection: n = !1 } = {}) {
|
|
4
|
+
let r = new e("mock-api-key", { allowServerSideConnect: !0 });
|
|
5
|
+
return r.userID = t.id, r.user = t, n && (r.connectUser = async () => ({ me: t }), r.disconnectUser = async () => void 0, r.userMuteStatus = (() => !1)), r;
|
|
8
6
|
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
attachments: x,
|
|
107
|
-
id: M
|
|
108
|
-
},
|
|
109
|
-
m.length
|
|
110
|
-
)
|
|
111
|
-
);
|
|
112
|
-
}, C);
|
|
113
|
-
}
|
|
114
|
-
return { message: i };
|
|
115
|
-
}, r.queryChannels = async () => [e], e.watch(), { client: r, channel: e, participantFilterId: n.id };
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/testing/createMockMessagingClient.ts
|
|
9
|
+
var n = 600;
|
|
10
|
+
function r({ currentUser: e, participant: r, messages: i = [], channelId: a = "mock-dm", onSend: o }) {
|
|
11
|
+
let s = t(e, { stubConnection: !0 }), c = `messaging:${a}`, l = (t, n) => {
|
|
12
|
+
let a = t.from === "me" ? e : r, o = /* @__PURE__ */ new Date(Date.now() - (i.length - n) * 6e4);
|
|
13
|
+
return {
|
|
14
|
+
id: t.id ?? `mock-msg-${n}`,
|
|
15
|
+
text: t.text ?? "",
|
|
16
|
+
type: "regular",
|
|
17
|
+
html: t.text ? `<p>${t.text}</p>` : "",
|
|
18
|
+
user: a,
|
|
19
|
+
attachments: t.attachments ?? [],
|
|
20
|
+
latest_reactions: [],
|
|
21
|
+
own_reactions: [],
|
|
22
|
+
reaction_counts: {},
|
|
23
|
+
reaction_scores: {},
|
|
24
|
+
reply_count: 0,
|
|
25
|
+
status: "received",
|
|
26
|
+
cid: c,
|
|
27
|
+
created_at: o,
|
|
28
|
+
updated_at: o,
|
|
29
|
+
mentioned_users: [],
|
|
30
|
+
...t.metadata ? { metadata: t.metadata } : {}
|
|
31
|
+
};
|
|
32
|
+
}, u = i.map(l), d = {
|
|
33
|
+
[e.id]: {
|
|
34
|
+
user: {
|
|
35
|
+
...e,
|
|
36
|
+
is_account: !1
|
|
37
|
+
},
|
|
38
|
+
user_id: e.id,
|
|
39
|
+
role: "owner",
|
|
40
|
+
is_account: !1
|
|
41
|
+
},
|
|
42
|
+
[r.id]: {
|
|
43
|
+
user: {
|
|
44
|
+
...r,
|
|
45
|
+
is_account: !0
|
|
46
|
+
},
|
|
47
|
+
user_id: r.id,
|
|
48
|
+
role: "member",
|
|
49
|
+
is_account: !0
|
|
50
|
+
}
|
|
51
|
+
}, f = s.channel("messaging", a, { members: [e.id, r.id] });
|
|
52
|
+
f.muteStatus = () => ({
|
|
53
|
+
muted: !1,
|
|
54
|
+
createdAt: null,
|
|
55
|
+
expiresAt: null
|
|
56
|
+
}), f.markRead = (async () => ({})), f.keystroke = (async () => void 0), f.stopTyping = (async () => void 0), f.sendReaction = (async () => ({})), f.deleteReaction = (async () => ({})), f.countUnread = (() => 0), f.query = (async () => ({ messages: [] })), f.hide = (async () => ({}));
|
|
57
|
+
let p = !1;
|
|
58
|
+
f.watch = async () => (p ||= (f.state.messages = u, !0), f.state.members = d, {
|
|
59
|
+
channel: { members: [e.id, r.id] },
|
|
60
|
+
members: [],
|
|
61
|
+
messages: f.state.messages,
|
|
62
|
+
watchers: [],
|
|
63
|
+
pinned_messages: [],
|
|
64
|
+
duration: "0ms"
|
|
65
|
+
});
|
|
66
|
+
let m = (e) => {
|
|
67
|
+
f.state.addMessageSorted(e), s.dispatchEvent({
|
|
68
|
+
type: "message.new",
|
|
69
|
+
cid: c,
|
|
70
|
+
message: e,
|
|
71
|
+
user: e.user ?? void 0
|
|
72
|
+
});
|
|
73
|
+
}, h = 0, g = 0;
|
|
74
|
+
return f.sendMessage = async (t) => {
|
|
75
|
+
let r = typeof t == "string" ? t : t?.text ?? "", i = {
|
|
76
|
+
...l({
|
|
77
|
+
text: r,
|
|
78
|
+
from: "me",
|
|
79
|
+
id: `mock-sent-${h++}`
|
|
80
|
+
}, u.length),
|
|
81
|
+
...typeof t == "object" ? t : {},
|
|
82
|
+
user: e,
|
|
83
|
+
cid: c
|
|
84
|
+
};
|
|
85
|
+
m(i);
|
|
86
|
+
let a = o?.(r);
|
|
87
|
+
if (a) {
|
|
88
|
+
let e = typeof a == "string" ? a : a.text, t = typeof a == "string" ? void 0 : a.attachments, r = `mock-reply-${g++}`;
|
|
89
|
+
setTimeout(() => {
|
|
90
|
+
m(l({
|
|
91
|
+
text: e,
|
|
92
|
+
from: "them",
|
|
93
|
+
attachments: t,
|
|
94
|
+
id: r
|
|
95
|
+
}, u.length));
|
|
96
|
+
}, n);
|
|
97
|
+
}
|
|
98
|
+
return { message: i };
|
|
99
|
+
}, s.queryChannels = async () => [f], f.watch(), {
|
|
100
|
+
client: s,
|
|
101
|
+
channel: f,
|
|
102
|
+
participantFilterId: r.id
|
|
103
|
+
};
|
|
116
104
|
}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
//# sourceMappingURL=testing.js.map
|
|
105
|
+
//#endregion
|
|
106
|
+
export { r as createMockMessagingClient };
|
|
107
|
+
|
|
108
|
+
//# sourceMappingURL=testing.js.map
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","sources":["../src/testing/createMockStreamChatClient.ts","../src/testing/createMockMessagingClient.ts"],"sourcesContent":["import { StreamChat } from 'stream-chat'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** A participant in the mock conversation. */\nexport interface MockMessagingUser {\n id: string\n name?: string\n image?: string\n}\n\nexport interface CreateMockStreamChatClientOptions {\n /**\n * Also replace the connection-dependent client methods (`connectUser`,\n * `disconnectUser`, `userMuteStatus`) with offline no-ops. Needed when the\n * client drives a flow that would otherwise open a WebSocket or throw\n * \"Make sure to await connectUser() first.\" offline. Direct `<Chat client>`\n * rendering (e.g. component stories) does not need this.\n */\n stubConnection?: boolean\n}\n\n/**\n * Builds an offline `StreamChat` for mocks and stories: a real client on a\n * throwaway api key with `userID`/`user` set so `<Chat>` treats it as\n * connected without a backend. The single place that knows how to construct a\n * connectionless Stream client, so a stream-chat version bump only needs\n * updating here rather than in each mock surface.\n */\nexport function createMockStreamChatClient(\n user: MockMessagingUser,\n { stubConnection = false }: CreateMockStreamChatClientOptions = {}\n): StreamChat {\n const client = new StreamChat('mock-api-key', {\n allowServerSideConnect: true,\n })\n client.userID = user.id\n client.user = user as any\n\n if (stubConnection) {\n client.connectUser = async () => ({ me: user }) as any\n client.disconnectUser = async () => undefined\n client.userMuteStatus = (() => false) as any\n }\n\n return client\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","import type {\n Channel,\n MessageResponse,\n QueryChannelAPIResponse,\n SendMessageAPIResponse,\n} from 'stream-chat'\nimport { StreamChat } from 'stream-chat'\n\nimport {\n createMockStreamChatClient,\n type MockMessagingUser,\n} from './createMockStreamChatClient'\n\n/**\n * A seed message, authored from the viewer's perspective. `from: 'me'` is the\n * connected user (the viewer); `from: 'them'` is the other participant.\n */\nexport interface MockMessage {\n id?: string\n text?: string\n from: 'me' | 'them'\n /** Stream attachment payloads, rendered by the toolkit's attachment gate. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments?: any[]\n /** e.g. `{ custom_type: 'MESSAGE_WELCOME' }`. */\n metadata?: Record<string, unknown>\n}\n\nexport interface CreateMockMessagingClientOptions {\n /** The connected/viewing user. */\n currentUser: MockMessagingUser\n /** The other party in the direct conversation (e.g. the creator/linker). */\n participant: MockMessagingUser\n /** Seed conversation, oldest-first. */\n messages?: MockMessage[]\n /** Channel id; defaults to `mock-dm`. */\n channelId?: string\n /**\n * Optional canned reply. Called after the viewer sends a message; return the\n * reply text (or a partial message) to have `participant` echo a response, or\n * a falsy value for no reply. Drives the \"send echo\" in `dev:mock-messaging`.\n */\n onSend?: (\n text: string\n ) => string | { text?: string; attachments?: unknown[] } | null | undefined\n}\n\nexport interface MockMessagingClient {\n /** Pass to `<MessagingProvider client={...}>`. */\n client: StreamChat\n /** The seeded direct-conversation channel. */\n channel: Channel\n /** Pass to `<MessagingShell initialParticipantFilter={...}>`. */\n participantFilterId: string\n}\n\nconst REPLY_DELAY_MS = 600\n\n/**\n * Builds an offline Stream client seeded with a single direct conversation, so\n * consumers can render the **real** messaging UI (MessagingProvider →\n * MessagingShell → ChannelView) without a Stream backend — for `dev:mock-*`\n * surfaces and Storybook. It is a real `StreamChat` whose network calls\n * (`connectUser`, `queryChannels`, `channel.watch`, `channel.sendMessage`) are\n * replaced with in-memory behaviour driven by Stream's own channel-state\n * machinery, so rendering fidelity matches production.\n *\n * Ships from `@linktr.ee/messaging-react/testing` and must never be imported by\n * production code.\n */\nexport function createMockMessagingClient({\n currentUser,\n participant,\n messages = [],\n channelId = 'mock-dm',\n onSend,\n}: CreateMockMessagingClientOptions): MockMessagingClient {\n // Offline client marked connected without a WebSocket. `stubConnection` also\n // no-ops connectUser/disconnectUser/userMuteStatus: `MessagingProvider`\n // renders `<Chat client={client}>` directly so it never calls connectUser,\n // and handling the `message.new` events dispatched on send + echo below runs\n // Channel._countMessageAsUnread → client.userMuteStatus, which throws offline.\n const client = createMockStreamChatClient(currentUser, {\n stubConnection: true,\n })\n\n const cid = `messaging:${channelId}`\n\n const toStreamMessage = (\n message: MockMessage,\n index: number\n ): MessageResponse => {\n const author = message.from === 'me' ? currentUser : participant\n // Stagger timestamps oldest-first so the list orders naturally. Must be a\n // Date, not an ISO string: we seed `channel.state.messages` directly\n // (bypassing Stream's wire→Date parsing), and stream-chat-react calls\n // `.getTime()` on `created_at` (e.g. useCooldownTimer / addToMessageList).\n const createdAt = new Date(Date.now() - (messages.length - index) * 60_000)\n return {\n id: message.id ?? `mock-msg-${index}`,\n text: message.text ?? '',\n type: 'regular',\n html: message.text ? `<p>${message.text}</p>` : '',\n user: author,\n attachments: message.attachments ?? [],\n latest_reactions: [],\n own_reactions: [],\n reaction_counts: {},\n reaction_scores: {},\n reply_count: 0,\n status: 'received',\n cid,\n created_at: createdAt,\n updated_at: createdAt,\n mentioned_users: [],\n ...(message.metadata ? { metadata: message.metadata } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n const seededMessages = messages.map(toStreamMessage)\n\n const memberState = {\n [currentUser.id]: {\n user: { ...currentUser, is_account: false },\n user_id: currentUser.id,\n role: 'owner',\n is_account: false,\n },\n [participant.id]: {\n user: { ...participant, is_account: true },\n user_id: participant.id,\n role: 'member',\n is_account: true,\n },\n }\n\n const channel = client.channel('messaging', channelId, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: [currentUser.id, participant.id] as any,\n })\n // Read/unread bookkeeping consults channel mute status; without a live\n // connection the real method throws, so report \"not muted\".\n channel.muteStatus = () => ({\n muted: false,\n createdAt: null,\n expiresAt: null,\n })\n\n // Neutralise the rest of the connection-dependent channel API that\n // stream-chat-react calls during the chat lifecycle. Each of these POSTs to\n // Stream or checks for a live WebSocket and would otherwise throw\n // \"Make sure to await connectUser() first.\" offline. They are fire-and-forget\n // (read receipts, typing) or read-only (pagination, unread) so no-ops are safe.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n channel.markRead = (async () => ({}) as any) as any\n channel.keystroke = (async () => undefined) as any\n channel.stopTyping = (async () => undefined) as any\n channel.sendReaction = (async () => ({}) as any) as any\n channel.deleteReaction = (async () => ({}) as any) as any\n channel.countUnread = (() => 0) as any\n // Pagination: report no older pages so \"load more\" resolves to a no-op.\n channel.query = (async () => ({ messages: [] }) as any) as any\n // Leave/Delete Conversation calls channel.hide(); the real method POSTs to\n // Stream, so no-op it to keep the action working offline.\n channel.hide = (async () => ({}) as any) as any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n // Seed state locally instead of fetching. Mirrors the proven ChannelView\n // story mock: override `watch` to populate `state` and return a canned\n // QueryChannelAPIResponse. `stream-chat-react` may call `watch()` again on\n // remount/navigation, so seed only once — otherwise a re-watch would wipe\n // messages added via `sendMessage` + the send-echo reply, resetting the chat.\n let hasSeeded = false\n channel.watch = async () => {\n if (!hasSeeded) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.messages = seededMessages as unknown as any[]\n hasSeeded = true\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.members = memberState as unknown as any\n return {\n channel: { members: [currentUser.id, participant.id] },\n members: [],\n messages: channel.state.messages,\n watchers: [],\n pinned_messages: [],\n duration: '0ms',\n } as unknown as QueryChannelAPIResponse\n }\n\n const appendMessage = (message: MessageResponse) => {\n // addMessageSorted is Stream's own state mutation (dedupes by id), so the\n // toolkit re-renders through the real channel-state path.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.addMessageSorted(message as any)\n client.dispatchEvent({\n type: 'message.new',\n cid,\n message,\n user: message.user ?? undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n }\n\n let sentCount = 0\n let replyCount = 0\n channel.sendMessage = async (message) => {\n const text =\n typeof message === 'string'\n ? message\n : ((message as { text?: string })?.text ?? '')\n const sent = {\n ...toStreamMessage(\n { text, from: 'me', id: `mock-sent-${sentCount++}` },\n seededMessages.length\n ),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...(typeof message === 'object' ? (message as any) : {}),\n user: currentUser,\n cid,\n } as MessageResponse\n\n // stream-chat-react adds the outgoing message optimistically; addMessageSorted\n // dedupes by id, so confirming here is safe and idempotent.\n appendMessage(sent)\n\n const reply = onSend?.(text)\n if (reply) {\n const replyText = typeof reply === 'string' ? reply : reply.text\n const replyAttachments =\n typeof reply === 'string' ? undefined : reply.attachments\n // Capture a unique id before scheduling: two sends within REPLY_DELAY_MS\n // would otherwise both read the same later `sentCount` at fire time and\n // emit colliding reply ids, so Stream's id-based dedupe drops one echo.\n const replyId = `mock-reply-${replyCount++}`\n setTimeout(() => {\n appendMessage(\n toStreamMessage(\n {\n text: replyText,\n from: 'them',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments: replyAttachments as any,\n id: replyId,\n },\n seededMessages.length\n )\n )\n }, REPLY_DELAY_MS)\n }\n\n return { message: sent } as unknown as SendMessageAPIResponse\n }\n\n // MessagingShell finds the direct conversation via queryChannels; always\n // return the one seeded channel regardless of the filter.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client.queryChannels = async () => [channel] as any\n\n // Initialise state up-front so first render already has the conversation.\n void channel.watch()\n\n return { client, channel, participantFilterId: participant.id }\n}\n"],"names":["createMockStreamChatClient","user","stubConnection","client","StreamChat","REPLY_DELAY_MS","createMockMessagingClient","currentUser","participant","messages","channelId","onSend","cid","toStreamMessage","message","index","author","createdAt","seededMessages","memberState","channel","hasSeeded","appendMessage","sentCount","replyCount","text","sent","reply","replyText","replyAttachments","replyId"],"mappings":";AA6BO,SAASA,EACdC,GACA,EAAE,gBAAAC,IAAiB,GAAA,IAA6C,CAAA,GACpD;AACZ,QAAMC,IAAS,IAAIC,EAAW,gBAAgB;AAAA,IAC5C,wBAAwB;AAAA,EAAA,CACzB;AACD,SAAAD,EAAO,SAASF,EAAK,IACrBE,EAAO,OAAOF,GAEVC,MACFC,EAAO,cAAc,aAAa,EAAE,IAAIF,EAAA,IACxCE,EAAO,iBAAiB;K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AAON,MAAY;AACvC,UAAMW,IACJ,OAAOX,KAAY,WACfA,KACEA,KAAA,gBAAAA,EAA+B,SAAQ,IACzCY,IAAO;AAAA,MACX,GAAGb;AAAA,QACD,EAAE,MAAAY,GAAM,MAAM,MAAM,IAAI,aAAaF,GAAW,GAAA;AAAA,QAChDL,EAAe;AAAA,MAAA;AAAA;AAAA,MAGjB,GAAI,OAAOJ,KAAY,WAAYA,IAAkB,CAAA;AAAA,MACrD,MAAMP;AAAA,MACN,KAAAK;AAAA,IAAA;AAKF,IAAAU,EAAcI,CAAI;AAElB,UAAMC,IAAQhB,KAAA,gBAAAA,EAASc;AACvB,QAAIE,GAAO;AACT,YAAMC,IAAY,OAAOD,KAAU,WAAWA,IAAQA,EAAM,MACtDE,IACJ,OAAOF,KAAU,WAAW,SAAYA,EAAM,aAI1CG,IAAU,cAAcN,GAAY;AAC1C,iBAAW,MAAM;AACf,QAAAF;AAAA,UACET;AAAA,YACE;AAAA,cACE,MAAMe;AAAA,cACN,MAAM;AAAA;AAAA,cAEN,aAAaC;AAAA,cACb,IAAIC;AAAA,YAAA;AAAA,YAENZ,EAAe;AAAA,UAAA;AAAA,QACjB;AAAA,MAEJ,GAAGb,CAAc;AAAA,IACnB;AAEA,WAAO,EAAE,SAASqB,EAAA;AAAA,EACpB,GAKAvB,EAAO,gBAAgB,YAAY,CAACiB,CAAO,GAGtCA,EAAQ,MAAA,GAEN,EAAE,QAAAjB,GAAQ,SAAAiB,GAAS,qBAAqBZ,EAAY,GAAA;AAC7D;"}
|
|
1
|
+
{"version":3,"file":"testing.js","names":[],"sources":["../src/testing/createMockStreamChatClient.ts","../src/testing/createMockMessagingClient.ts"],"sourcesContent":["import { StreamChat } from 'stream-chat'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** A participant in the mock conversation. */\nexport interface MockMessagingUser {\n id: string\n name?: string\n image?: string\n}\n\nexport interface CreateMockStreamChatClientOptions {\n /**\n * Also replace the connection-dependent client methods (`connectUser`,\n * `disconnectUser`, `userMuteStatus`) with offline no-ops. Needed when the\n * client drives a flow that would otherwise open a WebSocket or throw\n * \"Make sure to await connectUser() first.\" offline. Direct `<Chat client>`\n * rendering (e.g. component stories) does not need this.\n */\n stubConnection?: boolean\n}\n\n/**\n * Builds an offline `StreamChat` for mocks and stories: a real client on a\n * throwaway api key with `userID`/`user` set so `<Chat>` treats it as\n * connected without a backend. The single place that knows how to construct a\n * connectionless Stream client, so a stream-chat version bump only needs\n * updating here rather than in each mock surface.\n */\nexport function createMockStreamChatClient(\n user: MockMessagingUser,\n { stubConnection = false }: CreateMockStreamChatClientOptions = {}\n): StreamChat {\n const client = new StreamChat('mock-api-key', {\n allowServerSideConnect: true,\n })\n client.userID = user.id\n client.user = user as any\n\n if (stubConnection) {\n client.connectUser = async () => ({ me: user }) as any\n client.disconnectUser = async () => undefined\n client.userMuteStatus = (() => false) as any\n }\n\n return client\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","import type {\n Channel,\n MessageResponse,\n QueryChannelAPIResponse,\n SendMessageAPIResponse,\n} from 'stream-chat'\nimport { StreamChat } from 'stream-chat'\n\nimport {\n createMockStreamChatClient,\n type MockMessagingUser,\n} from './createMockStreamChatClient'\n\n/**\n * A seed message, authored from the viewer's perspective. `from: 'me'` is the\n * connected user (the viewer); `from: 'them'` is the other participant.\n */\nexport interface MockMessage {\n id?: string\n text?: string\n from: 'me' | 'them'\n /** Stream attachment payloads, rendered by the toolkit's attachment gate. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments?: any[]\n /** e.g. `{ custom_type: 'MESSAGE_WELCOME' }`. */\n metadata?: Record<string, unknown>\n}\n\nexport interface CreateMockMessagingClientOptions {\n /** The connected/viewing user. */\n currentUser: MockMessagingUser\n /** The other party in the direct conversation (e.g. the creator/linker). */\n participant: MockMessagingUser\n /** Seed conversation, oldest-first. */\n messages?: MockMessage[]\n /** Channel id; defaults to `mock-dm`. */\n channelId?: string\n /**\n * Optional canned reply. Called after the viewer sends a message; return the\n * reply text (or a partial message) to have `participant` echo a response, or\n * a falsy value for no reply. Drives the \"send echo\" in `dev:mock-messaging`.\n */\n onSend?: (\n text: string\n ) => string | { text?: string; attachments?: unknown[] } | null | undefined\n}\n\nexport interface MockMessagingClient {\n /** Pass to `<MessagingProvider client={...}>`. */\n client: StreamChat\n /** The seeded direct-conversation channel. */\n channel: Channel\n /** Pass to `<MessagingShell initialParticipantFilter={...}>`. */\n participantFilterId: string\n}\n\nconst REPLY_DELAY_MS = 600\n\n/**\n * Builds an offline Stream client seeded with a single direct conversation, so\n * consumers can render the **real** messaging UI (MessagingProvider →\n * MessagingShell → ChannelView) without a Stream backend — for `dev:mock-*`\n * surfaces and Storybook. It is a real `StreamChat` whose network calls\n * (`connectUser`, `queryChannels`, `channel.watch`, `channel.sendMessage`) are\n * replaced with in-memory behaviour driven by Stream's own channel-state\n * machinery, so rendering fidelity matches production.\n *\n * Ships from `@linktr.ee/messaging-react/testing` and must never be imported by\n * production code.\n */\nexport function createMockMessagingClient({\n currentUser,\n participant,\n messages = [],\n channelId = 'mock-dm',\n onSend,\n}: CreateMockMessagingClientOptions): MockMessagingClient {\n // Offline client marked connected without a WebSocket. `stubConnection` also\n // no-ops connectUser/disconnectUser/userMuteStatus: `MessagingProvider`\n // renders `<Chat client={client}>` directly so it never calls connectUser,\n // and handling the `message.new` events dispatched on send + echo below runs\n // Channel._countMessageAsUnread → client.userMuteStatus, which throws offline.\n const client = createMockStreamChatClient(currentUser, {\n stubConnection: true,\n })\n\n const cid = `messaging:${channelId}`\n\n const toStreamMessage = (\n message: MockMessage,\n index: number\n ): MessageResponse => {\n const author = message.from === 'me' ? currentUser : participant\n // Stagger timestamps oldest-first so the list orders naturally. Must be a\n // Date, not an ISO string: we seed `channel.state.messages` directly\n // (bypassing Stream's wire→Date parsing), and stream-chat-react calls\n // `.getTime()` on `created_at` (e.g. useCooldownTimer / addToMessageList).\n const createdAt = new Date(Date.now() - (messages.length - index) * 60_000)\n return {\n id: message.id ?? `mock-msg-${index}`,\n text: message.text ?? '',\n type: 'regular',\n html: message.text ? `<p>${message.text}</p>` : '',\n user: author,\n attachments: message.attachments ?? [],\n latest_reactions: [],\n own_reactions: [],\n reaction_counts: {},\n reaction_scores: {},\n reply_count: 0,\n status: 'received',\n cid,\n created_at: createdAt,\n updated_at: createdAt,\n mentioned_users: [],\n ...(message.metadata ? { metadata: message.metadata } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n const seededMessages = messages.map(toStreamMessage)\n\n const memberState = {\n [currentUser.id]: {\n user: { ...currentUser, is_account: false },\n user_id: currentUser.id,\n role: 'owner',\n is_account: false,\n },\n [participant.id]: {\n user: { ...participant, is_account: true },\n user_id: participant.id,\n role: 'member',\n is_account: true,\n },\n }\n\n const channel = client.channel('messaging', channelId, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: [currentUser.id, participant.id] as any,\n })\n // Read/unread bookkeeping consults channel mute status; without a live\n // connection the real method throws, so report \"not muted\".\n channel.muteStatus = () => ({\n muted: false,\n createdAt: null,\n expiresAt: null,\n })\n\n // Neutralise the rest of the connection-dependent channel API that\n // stream-chat-react calls during the chat lifecycle. Each of these POSTs to\n // Stream or checks for a live WebSocket and would otherwise throw\n // \"Make sure to await connectUser() first.\" offline. They are fire-and-forget\n // (read receipts, typing) or read-only (pagination, unread) so no-ops are safe.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n channel.markRead = (async () => ({}) as any) as any\n channel.keystroke = (async () => undefined) as any\n channel.stopTyping = (async () => undefined) as any\n channel.sendReaction = (async () => ({}) as any) as any\n channel.deleteReaction = (async () => ({}) as any) as any\n channel.countUnread = (() => 0) as any\n // Pagination: report no older pages so \"load more\" resolves to a no-op.\n channel.query = (async () => ({ messages: [] }) as any) as any\n // Leave/Delete Conversation calls channel.hide(); the real method POSTs to\n // Stream, so no-op it to keep the action working offline.\n channel.hide = (async () => ({}) as any) as any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n // Seed state locally instead of fetching. Mirrors the proven ChannelView\n // story mock: override `watch` to populate `state` and return a canned\n // QueryChannelAPIResponse. `stream-chat-react` may call `watch()` again on\n // remount/navigation, so seed only once — otherwise a re-watch would wipe\n // messages added via `sendMessage` + the send-echo reply, resetting the chat.\n let hasSeeded = false\n channel.watch = async () => {\n if (!hasSeeded) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.messages = seededMessages as unknown as any[]\n hasSeeded = true\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.members = memberState as unknown as any\n return {\n channel: { members: [currentUser.id, participant.id] },\n members: [],\n messages: channel.state.messages,\n watchers: [],\n pinned_messages: [],\n duration: '0ms',\n } as unknown as QueryChannelAPIResponse\n }\n\n const appendMessage = (message: MessageResponse) => {\n // addMessageSorted is Stream's own state mutation (dedupes by id), so the\n // toolkit re-renders through the real channel-state path.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.addMessageSorted(message as any)\n client.dispatchEvent({\n type: 'message.new',\n cid,\n message,\n user: message.user ?? undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n }\n\n let sentCount = 0\n let replyCount = 0\n channel.sendMessage = async (message) => {\n const text =\n typeof message === 'string'\n ? message\n : ((message as { text?: string })?.text ?? '')\n const sent = {\n ...toStreamMessage(\n { text, from: 'me', id: `mock-sent-${sentCount++}` },\n seededMessages.length\n ),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...(typeof message === 'object' ? (message as any) : {}),\n user: currentUser,\n cid,\n } as MessageResponse\n\n // stream-chat-react adds the outgoing message optimistically; addMessageSorted\n // dedupes by id, so confirming here is safe and idempotent.\n appendMessage(sent)\n\n const reply = onSend?.(text)\n if (reply) {\n const replyText = typeof reply === 'string' ? reply : reply.text\n const replyAttachments =\n typeof reply === 'string' ? undefined : reply.attachments\n // Capture a unique id before scheduling: two sends within REPLY_DELAY_MS\n // would otherwise both read the same later `sentCount` at fire time and\n // emit colliding reply ids, so Stream's id-based dedupe drops one echo.\n const replyId = `mock-reply-${replyCount++}`\n setTimeout(() => {\n appendMessage(\n toStreamMessage(\n {\n text: replyText,\n from: 'them',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments: replyAttachments as any,\n id: replyId,\n },\n seededMessages.length\n )\n )\n }, REPLY_DELAY_MS)\n }\n\n return { message: sent } as unknown as SendMessageAPIResponse\n }\n\n // MessagingShell finds the direct conversation via queryChannels; always\n // return the one seeded channel regardless of the filter.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client.queryChannels = async () => [channel] as any\n\n // Initialise state up-front so first render already has the conversation.\n void channel.watch()\n\n return { client, channel, participantFilterId: participant.id }\n}\n"],"mappings":";;AA6BA,SAAgB,EACd,GACA,EAAE,oBAAiB,OAA6C,CAAC,GACrD;CACZ,IAAM,IAAS,IAAI,EAAW,gBAAgB,EAC5C,wBAAwB,GAC1B,CAAC;CAUD,OATA,EAAO,SAAS,EAAK,IACrB,EAAO,OAAO,GAEV,MACF,EAAO,cAAc,aAAa,EAAE,IAAI,EAAK,IAC7C,EAAO,iBAAiB,YAAY,KAAA,GACpC,EAAO,wBAAwB,MAG1B;AACT;;;ACUA,IAAM,IAAiB;AAcvB,SAAgB,EAA0B,EACxC,gBACA,gBACA,cAAW,CAAC,GACZ,eAAY,WACZ,aACwD;CAMxD,IAAM,IAAS,EAA2B,GAAa,EACrD,gBAAgB,GAClB,CAAC,GAEK,IAAM,aAAa,KAEnB,KACJ,GACA,MACoB;EACpB,IAAM,IAAS,EAAQ,SAAS,OAAO,IAAc,GAK/C,oBAAY,IAAI,KAAK,KAAK,IAAI,KAAK,EAAS,SAAS,KAAS,GAAM;EAC1E,OAAO;GACL,IAAI,EAAQ,MAAM,YAAY;GAC9B,MAAM,EAAQ,QAAQ;GACtB,MAAM;GACN,MAAM,EAAQ,OAAO,MAAM,EAAQ,KAAK,QAAQ;GAChD,MAAM;GACN,aAAa,EAAQ,eAAe,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AQ,MAAM,iBAAiB,CAAc,GAC7C,EAAO,cAAc;GACnB,MAAM;GACN;GACA;GACA,MAAM,EAAQ,QAAQ,KAAA;EAExB,CAAQ;CACV,GAEI,IAAY,GACZ,IAAa;CAyDjB,OAxDA,EAAQ,cAAc,OAAO,MAAY;EACvC,IAAM,IACJ,OAAO,KAAY,WACf,IACE,GAA+B,QAAQ,IACzC,IAAO;GACX,GAAG,EACD;IAAE;IAAM,MAAM;IAAM,IAAI,aAAa;GAAc,GACnD,EAAe,MACjB;GAEA,GAAI,OAAO,KAAY,WAAY,IAAkB,CAAC;GACtD,MAAM;GACN;EACF;EAIA,EAAc,CAAI;EAElB,IAAM,IAAQ,IAAS,CAAI;EAC3B,IAAI,GAAO;GACT,IAAM,IAAY,OAAO,KAAU,WAAW,IAAQ,EAAM,MACtD,IACJ,OAAO,KAAU,WAAW,KAAA,IAAY,EAAM,aAI1C,IAAU,cAAc;GAC9B,iBAAiB;IACf,EACE,EACE;KACE,MAAM;KACN,MAAM;KAEN,aAAa;KACb,IAAI;IACN,GACA,EAAe,MACjB,CACF;GACF,GAAG,CAAc;EACnB;EAEA,OAAO,EAAE,SAAS,EAAK;CACzB,GAKA,EAAO,gBAAgB,YAAY,CAAC,CAAO,GAG3C,EAAa,MAAM,GAEZ;EAAE;EAAQ;EAAS,qBAAqB,EAAY;CAAG;AAChE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@linktr.ee/messaging-react",
|
|
3
|
-
"version": "4.2.0-rc-
|
|
3
|
+
"version": "4.2.0-rc-1787325710",
|
|
4
4
|
"description": "React messaging components built on messaging-core for web applications",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
@@ -50,8 +50,8 @@
|
|
|
50
50
|
"chromatic:local": "yarn storybook:build && chromatic"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@linktr.ee/messaging-core": "2.
|
|
54
|
-
"@linktr.ee/messaging-taxonomy": "^0.
|
|
53
|
+
"@linktr.ee/messaging-core": "2.6.0-rc-1787325710",
|
|
54
|
+
"@linktr.ee/messaging-taxonomy": "^0.11.0",
|
|
55
55
|
"@phosphor-icons/react": "^2.1.10"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
"@testing-library/user-event": "^14.5.1",
|
|
69
69
|
"@types/react": "^18.3.24",
|
|
70
70
|
"@types/react-dom": "^18.3.7",
|
|
71
|
-
"@vitejs/plugin-react": "^
|
|
71
|
+
"@vitejs/plugin-react": "^5.2.0",
|
|
72
72
|
"@vitest/ui": "^4.1.10",
|
|
73
73
|
"autoprefixer": "^10.4.20",
|
|
74
74
|
"chromatic": "^17.4.0",
|
|
@@ -83,7 +83,7 @@
|
|
|
83
83
|
"tailwindcss": "^3.4.17",
|
|
84
84
|
"tailwindcss-animate": "^1.0.7",
|
|
85
85
|
"typescript": "5.9.2",
|
|
86
|
-
"vite": "^
|
|
86
|
+
"vite": "^8.2.1",
|
|
87
87
|
"vite-plugin-dts": "^3.7.0",
|
|
88
88
|
"vitest": "^4.1.10"
|
|
89
89
|
},
|
|
@@ -682,10 +682,6 @@ WithTypingIndicator.args = {
|
|
|
682
682
|
},
|
|
683
683
|
}
|
|
684
684
|
WithTypingIndicator.parameters = {
|
|
685
|
-
// The typing indicator is animation-dominant, so a snapshot mostly captures
|
|
686
|
-
// whichever frame the animation happened to pause at — a false-positive
|
|
687
|
-
// source. Skip it in Chromatic; the story stays browsable in Storybook.
|
|
688
|
-
chromatic: { disableSnapshot: true },
|
|
689
685
|
docs: {
|
|
690
686
|
description: {
|
|
691
687
|
story:
|
package/src/index.ts
CHANGED
|
@@ -29,13 +29,11 @@ export type {
|
|
|
29
29
|
|
|
30
30
|
// Providers
|
|
31
31
|
export { MessagingProvider } from './providers/MessagingProvider'
|
|
32
|
-
export { MessagingLoggerProvider } from './logging'
|
|
33
32
|
export { CustomMessageProvider } from './components/CustomMessage/context'
|
|
34
33
|
|
|
35
34
|
// Hooks
|
|
36
35
|
export { useComposerLocked } from './components/CustomMessageInput'
|
|
37
36
|
export { useMessaging } from './hooks/useMessaging'
|
|
38
|
-
export { useMessagingLogger } from './logging'
|
|
39
37
|
export { useCustomMessage } from './components/CustomMessage/context'
|
|
40
38
|
|
|
41
39
|
// Utils
|
|
@@ -138,4 +136,3 @@ export type { CustomMessageRegistry } from './components/CustomMessage/context'
|
|
|
138
136
|
export type { AttachmentSourceType } from './components/AttachmentCard/utils/mimeType'
|
|
139
137
|
export type { Faq, FaqListProps } from './components/FaqList'
|
|
140
138
|
export type { FaqListItemProps } from './components/FaqList/FaqListItem'
|
|
141
|
-
export type { Logger } from '@linktr.ee/messaging-core'
|
|
@@ -1,16 +1,10 @@
|
|
|
1
1
|
import { StreamChatService } from '@linktr.ee/messaging-core'
|
|
2
|
-
import type {
|
|
3
|
-
Logger,
|
|
4
|
-
MessagingUser,
|
|
5
|
-
StreamChatServiceConfig,
|
|
6
|
-
} from '@linktr.ee/messaging-core'
|
|
2
|
+
import type { MessagingUser } from '@linktr.ee/messaging-core'
|
|
7
3
|
import { render, waitFor, act } from '@testing-library/react'
|
|
8
4
|
import React from 'react'
|
|
9
5
|
import type { StreamChat } from 'stream-chat'
|
|
10
6
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
11
7
|
|
|
12
|
-
import { useMessagingLogger } from '../logging'
|
|
13
|
-
|
|
14
8
|
import { MessagingProvider, useMessagingContext } from './MessagingProvider'
|
|
15
9
|
|
|
16
10
|
// Stub stream-chat-react's <Chat /> so we don't need a real, fully-wired
|
|
@@ -494,124 +488,4 @@ describe('MessagingProvider', () => {
|
|
|
494
488
|
expect(last.hasClient).toBe(false)
|
|
495
489
|
expect(last.error).toBeNull()
|
|
496
490
|
})
|
|
497
|
-
|
|
498
|
-
describe('logger seam', () => {
|
|
499
|
-
const ServiceProbe: React.FC<{
|
|
500
|
-
onService: (service: StreamChatService | null) => void
|
|
501
|
-
}> = ({ onService }) => {
|
|
502
|
-
const { service } = useMessagingContext()
|
|
503
|
-
React.useEffect(() => {
|
|
504
|
-
onService(service)
|
|
505
|
-
}, [service, onService])
|
|
506
|
-
return null
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
const LoggerProbe: React.FC<{ onLogger: (logger: Logger) => void }> = ({
|
|
510
|
-
onLogger,
|
|
511
|
-
}) => {
|
|
512
|
-
const logger = useMessagingLogger()
|
|
513
|
-
React.useEffect(() => {
|
|
514
|
-
onLogger(logger)
|
|
515
|
-
}, [logger, onLogger])
|
|
516
|
-
return null
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
// The service stores its resolved sink privately; read it to prove which
|
|
520
|
-
// logger the provider handed to the constructor.
|
|
521
|
-
const serviceLogger = (service: StreamChatService) =>
|
|
522
|
-
(service as unknown as { logger: Logger }).logger
|
|
523
|
-
|
|
524
|
-
const renderWithLogger = async (
|
|
525
|
-
props: Partial<React.ComponentProps<typeof MessagingProvider>> & {
|
|
526
|
-
serviceConfig: Omit<StreamChatServiceConfig, 'apiKey'>
|
|
527
|
-
}
|
|
528
|
-
) => {
|
|
529
|
-
setupServiceMock()
|
|
530
|
-
const services: (StreamChatService | null)[] = []
|
|
531
|
-
const loggers: Logger[] = []
|
|
532
|
-
|
|
533
|
-
render(
|
|
534
|
-
<MessagingProvider
|
|
535
|
-
apiKey="mock-api-key"
|
|
536
|
-
user={
|
|
537
|
-
{ type: 'guest', id: 'guest-1', name: 'Guest' } as MessagingUser
|
|
538
|
-
}
|
|
539
|
-
{...props}
|
|
540
|
-
>
|
|
541
|
-
<ServiceProbe onService={(s) => services.push(s)} />
|
|
542
|
-
<LoggerProbe onLogger={(l) => loggers.push(l)} />
|
|
543
|
-
</MessagingProvider>
|
|
544
|
-
)
|
|
545
|
-
|
|
546
|
-
await waitFor(() => expect(services.filter(Boolean).length).toBe(1))
|
|
547
|
-
return {
|
|
548
|
-
service: services.filter(Boolean).pop() as StreamChatService,
|
|
549
|
-
logger: loggers[loggers.length - 1],
|
|
550
|
-
}
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
const baseServiceConfig: Omit<StreamChatServiceConfig, 'apiKey'> = {
|
|
554
|
-
fetchToken: async () => 'token',
|
|
555
|
-
createChannel: async () => ({ channelId: 'ch-1' }),
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
it('forwards the logger prop into the service and to the subtree', async () => {
|
|
559
|
-
const sink: Logger = { error: vi.fn() }
|
|
560
|
-
const { service, logger } = await renderWithLogger({
|
|
561
|
-
serviceConfig: baseServiceConfig,
|
|
562
|
-
logger: sink,
|
|
563
|
-
})
|
|
564
|
-
|
|
565
|
-
expect(serviceLogger(service).error).toBe(sink.error)
|
|
566
|
-
|
|
567
|
-
const error = new Error('boom')
|
|
568
|
-
logger.error?.('[MessagingShell] Failed:', error)
|
|
569
|
-
expect(sink.error).toHaveBeenCalledWith('[MessagingShell] Failed:', error)
|
|
570
|
-
})
|
|
571
|
-
|
|
572
|
-
it('resolves a partial prop sink before handing it to the service', async () => {
|
|
573
|
-
const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
574
|
-
const sink: Logger = { error: vi.fn() }
|
|
575
|
-
const { service } = await renderWithLogger({
|
|
576
|
-
serviceConfig: baseServiceConfig,
|
|
577
|
-
logger: sink,
|
|
578
|
-
})
|
|
579
|
-
|
|
580
|
-
// The service swaps its own console defaults out wholesale, so an
|
|
581
|
-
// unresolved partial sink would silence the levels it omits.
|
|
582
|
-
serviceLogger(service).warn?.('[StreamChatService] Slow:', 1)
|
|
583
|
-
expect(consoleWarn).toHaveBeenCalledWith('[StreamChatService] Slow:', 1)
|
|
584
|
-
})
|
|
585
|
-
|
|
586
|
-
it('lets an explicit serviceConfig.logger win over the logger prop', async () => {
|
|
587
|
-
const configSink: Logger = { error: vi.fn() }
|
|
588
|
-
const propSink: Logger = { error: vi.fn() }
|
|
589
|
-
const { service } = await renderWithLogger({
|
|
590
|
-
serviceConfig: { ...baseServiceConfig, logger: configSink },
|
|
591
|
-
logger: propSink,
|
|
592
|
-
})
|
|
593
|
-
|
|
594
|
-
expect(serviceLogger(service)).toBe(configSink)
|
|
595
|
-
})
|
|
596
|
-
|
|
597
|
-
it('leaves the service on its console defaults when no logger is given', async () => {
|
|
598
|
-
const consoleError = vi
|
|
599
|
-
.spyOn(console, 'error')
|
|
600
|
-
.mockImplementation(() => {})
|
|
601
|
-
const { service, logger } = await renderWithLogger({
|
|
602
|
-
serviceConfig: baseServiceConfig,
|
|
603
|
-
})
|
|
604
|
-
|
|
605
|
-
// Not the react seam object: the service fell back to its own defaults.
|
|
606
|
-
expect(serviceLogger(service)).not.toBe(logger)
|
|
607
|
-
|
|
608
|
-
const error = new Error('boom')
|
|
609
|
-
logger.error?.('[MessagingShell] Failed:', error)
|
|
610
|
-
serviceLogger(service).error?.('[StreamChatService] Failed:', error)
|
|
611
|
-
expect(consoleError.mock.calls).toEqual([
|
|
612
|
-
['[MessagingShell] Failed:', error],
|
|
613
|
-
['[StreamChatService] Failed:', error],
|
|
614
|
-
])
|
|
615
|
-
})
|
|
616
|
-
})
|
|
617
491
|
})
|