@wtfalch/chat 0.1.0 → 0.2.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.
@@ -29,6 +29,17 @@ export type FakeMessageSeed = {
29
29
  /** The id of the message this replies to, making it a `m.thread` reply.
30
30
  * Matrix threads are one level, so this is always the root's id. */
31
31
  threadRootId?: string;
32
+ /** Seeds an `m.file`/`m.image` in one step, without a real upload round
33
+ * trip -- what `roomFiles` (#9) reads `content.url`/`content.info` off
34
+ * of. `body` is still the file's name, matching what a real client
35
+ * sends. Cheap enough to seed the hundreds of messages a pagination
36
+ * test needs. */
37
+ attachment?: {
38
+ mxcUri: string;
39
+ mimeType: string;
40
+ size: number;
41
+ isImage?: boolean;
42
+ };
32
43
  };
33
44
  export type FakeMember = {
34
45
  userId: string;
@@ -69,6 +80,11 @@ export declare class FakeChatServer {
69
80
  /** Controls for upload failure and in-flight UI scenarios. */
70
81
  uploadBarrier: Promise<void> | null;
71
82
  uploadStatus: number;
83
+ /** What `PUT .../state/m.room.pinned_events/` answers with -- 403 models
84
+ * the power-level refusal a room whose power levels predate ticket #8
85
+ * gives a member, which `pinMessage`/`unpinMessage` must reject on
86
+ * rather than resolve quietly. */
87
+ pinStatus: number;
72
88
  readonly userId: string;
73
89
  /** The Matrix server name, as `userId` gives it -- what an `mxc://`
74
90
  * reference from this homeserver names. */
@@ -112,6 +128,35 @@ export declare class FakeChatServer {
112
128
  path: string;
113
129
  authorised: boolean;
114
130
  }>;
131
+ /** Every `PUT .../typing/...` this server has answered, in order -- for a
132
+ * test that asserts `sendTyping` actually reached the wire, with what
133
+ * it sent. */
134
+ readonly sentTyping: Array<{
135
+ roomId: string;
136
+ userId: string;
137
+ typing: boolean;
138
+ timeoutMs?: number;
139
+ }>;
140
+ /** Every `PUT .../presence/{userId}/status` this server has answered, in
141
+ * order -- the immediate half of `announcePresence`. */
142
+ readonly sentPresence: Array<{
143
+ userId: string;
144
+ presence: string;
145
+ }>;
146
+ /** Set to refuse the next presence `PUT` with `M_LIMIT_EXCEEDED`, the
147
+ * way a real Synapse refuses a second presence change inside ten
148
+ * seconds (`rc_presence.per_user`). Clears itself after one refusal. */
149
+ refuseNextPresence: boolean;
150
+ /** The `set_presence` query parameter every `/sync` has carried, in
151
+ * order, `undefined` where the client omitted it. This is the half that
152
+ * actually makes an announcement survive, so a test that only checked
153
+ * `sentPresence` would pass against a client that cannot hold anybody
154
+ * away for longer than one poll. */
155
+ readonly syncPresence: Array<string | undefined>;
156
+ /** Rooms currently carrying the room-scoped `dont_notify` push rule, for
157
+ * a test that wants to assert on the server's own state rather than
158
+ * only through the client's `rooms()`. */
159
+ get mutedRoomIds(): string[];
115
160
  constructor(options?: FakeChatServerOptions);
116
161
  dispose(): void;
117
162
  /** Resolves once a `/sync` request is parked waiting for a test to drive
@@ -147,6 +192,22 @@ export declare class FakeChatServer {
147
192
  * `rooms.leave` block, the way a real incremental `/sync` reports a kick
148
193
  * or a self-leave. Throws if nothing is parked. */
149
194
  leaveRoom(roomId: string): void;
195
+ /** Delivers a parked poll as `m.typing` for `roomId` -- Matrix's own
196
+ * shape: an EDU with no sender of its own, always the room's complete
197
+ * current set of typing user ids, never a diff against the last one.
198
+ * Pass an empty list for what Matrix does on its own once a typing
199
+ * state's timeout elapses server-side; this fake never does that by
200
+ * itself, so a test drives both halves explicitly. Throws if nothing is
201
+ * parked. */
202
+ receiveTyping(roomId: string, userIds: string[]): void;
203
+ /** Delivers a parked poll as an `m.presence` EDU for somebody else --
204
+ * Matrix's own three states (`online`/`unavailable`/`offline`), or
205
+ * MSC3026's unstable `org.matrix.msc3026.busy` -- for a test that drives
206
+ * `presence()`/`onPresenceChanged` without a live homeserver. Presence
207
+ * EDUs are account-wide, not room-scoped, so this carries no room id --
208
+ * see `#answerParked`'s own `presence.events`. Throws if nothing is
209
+ * parked. */
210
+ receivePresence(userId: string, presence: string): void;
150
211
  /** Delivers a parked poll as somebody else reacting to a message.
151
212
  * Returns the minted event id, so a test can then redact it. Throws if
152
213
  * nothing is parked. */
@@ -31,6 +31,11 @@ export class FakeChatServer {
31
31
  /** Controls for upload failure and in-flight UI scenarios. */
32
32
  uploadBarrier = null;
33
33
  uploadStatus = 200;
34
+ /** What `PUT .../state/m.room.pinned_events/` answers with -- 403 models
35
+ * the power-level refusal a room whose power levels predate ticket #8
36
+ * gives a member, which `pinMessage`/`unpinMessage` must reject on
37
+ * rather than resolve quietly. */
38
+ pinStatus = 200;
34
39
  userId;
35
40
  /** The Matrix server name, as `userId` gives it -- what an `mxc://`
36
41
  * reference from this homeserver names. */
@@ -57,6 +62,29 @@ export class FakeChatServer {
57
62
  * request carried -- for a test that asserts nothing reaches the
58
63
  * legacy unauthenticated endpoints, and that the token was sent. */
59
64
  mediaRequests = [];
65
+ /** Every `PUT .../typing/...` this server has answered, in order -- for a
66
+ * test that asserts `sendTyping` actually reached the wire, with what
67
+ * it sent. */
68
+ sentTyping = [];
69
+ /** Every `PUT .../presence/{userId}/status` this server has answered, in
70
+ * order -- the immediate half of `announcePresence`. */
71
+ sentPresence = [];
72
+ /** Set to refuse the next presence `PUT` with `M_LIMIT_EXCEEDED`, the
73
+ * way a real Synapse refuses a second presence change inside ten
74
+ * seconds (`rc_presence.per_user`). Clears itself after one refusal. */
75
+ refuseNextPresence = false;
76
+ /** The `set_presence` query parameter every `/sync` has carried, in
77
+ * order, `undefined` where the client omitted it. This is the half that
78
+ * actually makes an announcement survive, so a test that only checked
79
+ * `sentPresence` would pass against a client that cannot hold anybody
80
+ * away for longer than one poll. */
81
+ syncPresence = [];
82
+ /** Rooms currently carrying the room-scoped `dont_notify` push rule, for
83
+ * a test that wants to assert on the server's own state rather than
84
+ * only through the client's `rooms()`. */
85
+ get mutedRoomIds() {
86
+ return [...this.#mutedRooms];
87
+ }
60
88
  #dispose;
61
89
  #rooms;
62
90
  #tokenLifetimeMs;
@@ -74,6 +102,12 @@ export class FakeChatServer {
74
102
  * of it -- matrix-js-sdk asks for both while it builds a thread. */
75
103
  #events = new Map();
76
104
  #tags = new Map();
105
+ /** Rooms carrying the account's room-scoped `dont_notify` push rule --
106
+ * what `muteRoom` writes and takes away, and the only rule kind this
107
+ * fake bothers to model. Read back through `/pushrules/`, exactly as
108
+ * Synapse would answer it, so a test never has to reach past the
109
+ * client's own `rooms()` to know a mute landed. */
110
+ #mutedRooms = new Set();
77
111
  #roomSeq = 0;
78
112
  #mediaSeq = 0;
79
113
  /** Deliveries made while no poll was parked, waiting for the next one --
@@ -339,18 +373,34 @@ export class FakeChatServer {
339
373
  * does against Synapse. */
340
374
  #messageEvent(seed) {
341
375
  this.#eventSeq += 1;
376
+ const { attachment } = seed;
377
+ // `threadRootId` applies to either shape: a file shared inside a
378
+ // thread is exactly as real as a text reply inside one, and a seed
379
+ // that silently dropped it on the attachment branch would make it
380
+ // impossible to test `roomFiles`' own thread-spanning behaviour
381
+ // against this fixture at all (confirmed the hard way -- see the
382
+ // refuter report this fixed).
383
+ const threaded = seed.threadRootId
384
+ ? { 'm.relates_to': { rel_type: 'm.thread', event_id: seed.threadRootId } }
385
+ : {};
342
386
  return {
343
387
  type: 'm.room.message',
344
388
  event_id: seed.id ?? `$seeded-${this.#eventSeq}`,
345
389
  sender: seed.sender ?? PEER_USER_ID,
346
390
  origin_server_ts: this.#now(),
347
- content: {
348
- msgtype: 'm.text',
349
- body: seed.body,
350
- ...(seed.threadRootId
351
- ? { 'm.relates_to': { rel_type: 'm.thread', event_id: seed.threadRootId } }
352
- : {}),
353
- },
391
+ content: attachment
392
+ ? {
393
+ msgtype: attachment.isImage ? 'm.image' : 'm.file',
394
+ body: seed.body,
395
+ url: attachment.mxcUri,
396
+ info: { mimetype: attachment.mimeType, size: attachment.size },
397
+ ...threaded,
398
+ }
399
+ : {
400
+ msgtype: 'm.text',
401
+ body: seed.body,
402
+ ...threaded,
403
+ },
354
404
  };
355
405
  }
356
406
  /** Mints a seed's messages once and remembers them. Minting them inside
@@ -364,17 +414,41 @@ export class FakeChatServer {
364
414
  #record(roomId, event) {
365
415
  this.#events.set(roomId, [...(this.#events.get(roomId) ?? []), event]);
366
416
  }
367
- /** One room's incremental entry, carrying just these events. */
368
- #timelineEntry(roomId, events) {
417
+ /** One room's incremental entry, carrying just these events -- and,
418
+ * given some, ephemeral ones (`m.typing`) alongside them, the way a real
419
+ * incremental `/sync` carries both together. */
420
+ #timelineEntry(roomId, events, ephemeralEvents = []) {
369
421
  return {
370
422
  summary: {},
371
423
  state: { events: [] },
372
424
  timeline: { events, limited: false, prev_batch: `t-${roomId}` },
373
- ephemeral: { events: [] },
425
+ ephemeral: { events: ephemeralEvents },
374
426
  account_data: { events: this.#roomAccountDataEvents(roomId) },
375
427
  unread_notifications: { highlight_count: 0, notification_count: 0 },
376
428
  };
377
429
  }
430
+ /** Delivers a parked poll as `m.typing` for `roomId` -- Matrix's own
431
+ * shape: an EDU with no sender of its own, always the room's complete
432
+ * current set of typing user ids, never a diff against the last one.
433
+ * Pass an empty list for what Matrix does on its own once a typing
434
+ * state's timeout elapses server-side; this fake never does that by
435
+ * itself, so a test drives both halves explicitly. Throws if nothing is
436
+ * parked. */
437
+ receiveTyping(roomId, userIds) {
438
+ this.#deliverParked({
439
+ [roomId]: this.#timelineEntry(roomId, [], [{ type: 'm.typing', content: { user_ids: userIds } }]),
440
+ });
441
+ }
442
+ /** Delivers a parked poll as an `m.presence` EDU for somebody else --
443
+ * Matrix's own three states (`online`/`unavailable`/`offline`), or
444
+ * MSC3026's unstable `org.matrix.msc3026.busy` -- for a test that drives
445
+ * `presence()`/`onPresenceChanged` without a live homeserver. Presence
446
+ * EDUs are account-wide, not room-scoped, so this carries no room id --
447
+ * see `#answerParked`'s own `presence.events`. Throws if nothing is
448
+ * parked. */
449
+ receivePresence(userId, presence) {
450
+ this.#deliverParked({}, {}, [{ type: 'm.presence', sender: userId, content: { presence } }]);
451
+ }
378
452
  /** Delivers a parked poll as somebody else reacting to a message.
379
453
  * Returns the minted event id, so a test can then redact it. Throws if
380
454
  * nothing is parked. */
@@ -462,11 +536,11 @@ export class FakeChatServer {
462
536
  to_device: { events: [] },
463
537
  };
464
538
  }
465
- #deliverParked(join, leave = {}) {
539
+ #deliverParked(join, leave = {}, presenceEvents = []) {
466
540
  if (!this.#pending) {
467
541
  throw new Error('fake chat: addRoom called with no /sync request parked');
468
542
  }
469
- this.#answerParked(join, leave);
543
+ this.#answerParked(join, leave, presenceEvents);
470
544
  }
471
545
  /** Delivers now if a poll is parked, and otherwise holds the payload for
472
546
  * the next one. What `#deliverParked` refuses to do: a test driving the
@@ -481,7 +555,7 @@ export class FakeChatServer {
481
555
  }
482
556
  this.#queued.push({ join, leave });
483
557
  }
484
- #answerParked(join, leave) {
558
+ #answerParked(join, leave, presenceEvents = []) {
485
559
  const pending = this.#pending;
486
560
  if (!pending)
487
561
  return;
@@ -491,7 +565,7 @@ export class FakeChatServer {
491
565
  next_batch: this.#nextBatch(),
492
566
  rooms: { join, leave },
493
567
  account_data: { events: this.#accountDataEvents() },
494
- presence: { events: [] },
568
+ presence: { events: presenceEvents },
495
569
  to_device: { events: [] },
496
570
  }));
497
571
  }
@@ -561,6 +635,7 @@ export class FakeChatServer {
561
635
  if (!token || !this.#validTokens.has(token)) {
562
636
  return Promise.resolve(jsonResponse(401, { errcode: 'M_UNKNOWN_TOKEN', error: 'Invalid access token' }));
563
637
  }
638
+ this.syncPresence.push(url.searchParams.get('set_presence') ?? undefined);
564
639
  if (url.searchParams.get('since') === null) {
565
640
  return Promise.resolve(jsonResponse(200, this.#fullSyncBody()));
566
641
  }
@@ -608,9 +683,38 @@ export class FakeChatServer {
608
683
  }
609
684
  if (url.pathname === '/_matrix/client/v3/pushrules/') {
610
685
  return Promise.resolve(jsonResponse(200, {
611
- global: { content: [], override: [], room: [], sender: [], underride: [] },
686
+ global: {
687
+ content: [],
688
+ override: [],
689
+ room: [...this.#mutedRooms].map((roomId) => ({
690
+ rule_id: roomId,
691
+ default: false,
692
+ enabled: true,
693
+ actions: ['dont_notify'],
694
+ })),
695
+ sender: [],
696
+ underride: [],
697
+ },
612
698
  }));
613
699
  }
700
+ // What `setRoomMutePushRule` PUTs and DELETEs -- see `ChatClient.muteRoom`.
701
+ // This fake only ever sees `'global'`, the one scope the client uses, but
702
+ // matches on it anyway rather than any scope: a client that started
703
+ // writing device-scoped rules should fail here, not be quietly muted.
704
+ const roomPushRule = url.pathname.match(/^\/_matrix\/client\/v3\/pushrules\/global\/room\/([^/]+)$/);
705
+ if (roomPushRule && this.#authorised(init)) {
706
+ const roomId = decodeURIComponent(roomPushRule[1]);
707
+ if (init?.method === 'DELETE') {
708
+ if (!this.#mutedRooms.has(roomId)) {
709
+ return Promise.resolve(jsonResponse(404, { errcode: 'M_NOT_FOUND', error: 'Push rule does not exist' }));
710
+ }
711
+ this.#mutedRooms.delete(roomId);
712
+ }
713
+ else {
714
+ this.#mutedRooms.add(roomId);
715
+ }
716
+ return Promise.resolve(jsonResponse(200, {}));
717
+ }
614
718
  if (url.pathname.startsWith('/_matrix/client/v3/user/') && url.pathname.endsWith('/filter')) {
615
719
  return Promise.resolve(jsonResponse(200, { filter_id: 'fake-filter' }));
616
720
  }
@@ -662,6 +766,55 @@ export class FakeChatServer {
662
766
  // reads false -- which is what a fully-loaded thread should say.
663
767
  return Promise.resolve(jsonResponse(200, { chunk: chunk.map((entry) => ({ ...entry, room_id: roomId })) }));
664
768
  }
769
+ // `roomFiles`' own backward walk, and `paginate`'s plain scrollback:
770
+ // both are `GET .../messages`, and the only thing that tells them
771
+ // apart on the wire is whether a `contains_url` filter came along.
772
+ // `#events` is oldest first, so this reverses it once and paginates
773
+ // with a plain numeric cursor -- there is no real Matrix stream token
774
+ // to imitate here, only "how far back has this walk gone".
775
+ const messages = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/messages$/);
776
+ if (messages && this.#authorised(init)) {
777
+ const roomId = decodeURIComponent(messages[1]);
778
+ let filter = {};
779
+ try {
780
+ const raw = url.searchParams.get('filter');
781
+ if (raw)
782
+ filter = JSON.parse(raw);
783
+ }
784
+ catch {
785
+ // Same tolerance as every other body/param this fake parses.
786
+ }
787
+ const newestFirst = [...(this.#events.get(roomId) ?? [])].reverse();
788
+ // Not what real Synapse does. `entry.content.url` is read live, here,
789
+ // on every call -- so a redacted event (`#record`'s content already
790
+ // emptied, see the `redact` route above) simply has no `url` left to
791
+ // match by the time this runs. Real Synapse computes `contains_url`
792
+ // once, at persist time, and never revisits it on redaction (checked
793
+ // against the installed v1.161.0 source), so a redacted file-bearing
794
+ // event still *matches* the filter there and still comes back from
795
+ // `/messages` -- pruned, but present. `roomFiles`' own
796
+ // `event.isRedacted()` guard is what excludes it in production. A
797
+ // unit test built on this fake exercises that a redacted file is
798
+ // excluded, but not *why* -- `test/integration/roomfiles.test.ts`'s
799
+ // real-Synapse redaction case is what actually proves the guard.
800
+ const matching = newestFirst.filter((entry) => {
801
+ if (filter.types && !filter.types.includes(entry.type))
802
+ return false;
803
+ if (filter.contains_url && entry.content.url === undefined)
804
+ return false;
805
+ return true;
806
+ });
807
+ const limit = Number(url.searchParams.get('limit') ?? '30');
808
+ const from = url.searchParams.get('from');
809
+ const start = from?.startsWith('idx-') ? Number(from.slice('idx-'.length)) : 0;
810
+ const chunk = matching.slice(start, start + limit);
811
+ const nextIndex = start + chunk.length;
812
+ const end = nextIndex < matching.length ? `idx-${nextIndex}` : undefined;
813
+ return Promise.resolve(jsonResponse(200, {
814
+ chunk: chunk.map((entry) => ({ ...entry, room_id: roomId })),
815
+ ...(end ? { end } : {}),
816
+ }));
817
+ }
665
818
  const send = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/send\/([^/]+)\/([^/]+)$/);
666
819
  if (send && this.#authorised(init)) {
667
820
  let content = {};
@@ -717,6 +870,35 @@ export class FakeChatServer {
717
870
  this.#deliverOrQueue({ [roomId]: this.#timelineEntry(roomId, [event]) });
718
871
  return Promise.resolve(jsonResponse(200, { event_id: event.event_id }));
719
872
  }
873
+ // `sendStateEvent`'s own default state key is `''`, never `undefined`
874
+ // (see matrix-js-sdk's `client.js`), so the path this mints always
875
+ // carries the trailing, empty state-key segment.
876
+ const pinnedEvents = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/state\/m\.room\.pinned_events\/?$/);
877
+ if (pinnedEvents && this.#authorised(init)) {
878
+ if (this.pinStatus !== 200) {
879
+ return Promise.resolve(jsonResponse(this.pinStatus, { errcode: 'M_FORBIDDEN', error: 'pinning refused' }));
880
+ }
881
+ let content = {};
882
+ try {
883
+ content = JSON.parse(String(init?.body ?? '{}'));
884
+ }
885
+ catch {
886
+ // Same tolerance as every other route here.
887
+ }
888
+ const roomId = decodeURIComponent(pinnedEvents[1]);
889
+ this.#eventSeq += 1;
890
+ const event = {
891
+ type: 'm.room.pinned_events',
892
+ state_key: '',
893
+ event_id: `$pinned-${this.#eventSeq}`,
894
+ sender: this.userId,
895
+ origin_server_ts: this.#now(),
896
+ content,
897
+ };
898
+ this.#record(roomId, event);
899
+ this.#deliverOrQueue({ [roomId]: this.#timelineEntry(roomId, [event]) });
900
+ return Promise.resolve(jsonResponse(200, { event_id: event.event_id }));
901
+ }
720
902
  // Uploads go to `/_matrix/media/v3/upload`, which is still the
721
903
  // upload endpoint under authenticated media -- only *downloads* moved
722
904
  // to `/_matrix/client/v1/media`.
@@ -789,6 +971,58 @@ export class FakeChatServer {
789
971
  this.#setTag(decodeURIComponent(tag[2]), decodeURIComponent(tag[3]), init?.method !== 'DELETE');
790
972
  return Promise.resolve(jsonResponse(200, {}));
791
973
  }
974
+ // What `client.sendTyping` PUTs -- see `ChatClient.sendTyping`. Recorded
975
+ // rather than echoed back through sync on its own: a real homeserver's
976
+ // own typing timer is what turns this into the `m.typing` EDU other
977
+ // members see, and a test drives that side explicitly with
978
+ // `receiveTyping` instead of this fake modelling a timer.
979
+ const typing = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/typing\/([^/]+)$/);
980
+ if (typing && this.#authorised(init)) {
981
+ let body = {};
982
+ try {
983
+ body = JSON.parse(String(init?.body ?? '{}'));
984
+ }
985
+ catch {
986
+ // Same tolerance as every other write here: a malformed body is
987
+ // recorded as sent rather than failing the test for a reason it
988
+ // did not choose.
989
+ }
990
+ this.sentTyping.push({
991
+ roomId: decodeURIComponent(typing[1]),
992
+ userId: decodeURIComponent(typing[2]),
993
+ typing: Boolean(body.typing),
994
+ timeoutMs: body.timeout,
995
+ });
996
+ return Promise.resolve(jsonResponse(200, {}));
997
+ }
998
+ // The immediate half of `announcePresence`. Recorded rather than fed
999
+ // back as an `m.presence` event: on a real homeserver this sets the
1000
+ // *signed-in person's own* presence, which is read by everybody else's
1001
+ // client, not by this one -- `presence()` here is driven by
1002
+ // `receivePresence` instead, the same way typing is.
1003
+ const presence = url.pathname.match(/^\/_matrix\/client\/v3\/presence\/([^/]+)\/status$/);
1004
+ if (presence && this.#authorised(init)) {
1005
+ if (this.refuseNextPresence) {
1006
+ this.refuseNextPresence = false;
1007
+ return Promise.resolve(jsonResponse(429, {
1008
+ errcode: 'M_LIMIT_EXCEEDED',
1009
+ error: 'Too many requests',
1010
+ retry_after_ms: 10_000,
1011
+ }));
1012
+ }
1013
+ let body = {};
1014
+ try {
1015
+ body = JSON.parse(String(init?.body ?? '{}'));
1016
+ }
1017
+ catch {
1018
+ // Same tolerance as every other write here.
1019
+ }
1020
+ this.sentPresence.push({
1021
+ userId: decodeURIComponent(presence[1]),
1022
+ presence: String(body.presence),
1023
+ });
1024
+ return Promise.resolve(jsonResponse(200, {}));
1025
+ }
792
1026
  const receipt = url.pathname.match(/^\/_matrix\/client\/v3\/rooms\/([^/]+)\/receipt\/m\.read\/([^/]+)$/);
793
1027
  if (receipt) {
794
1028
  const token = bearerToken(init);