Take client creating functionality out of MatrixClientPeg (#34092)

* Take client creating functionality out of MatrixClientPeg

Because all sorts of things import MatrixClientPeg and this means
they pull in all manner of things related to creating a client, when
all they need is to get the current one (and specifically it fixes
the import cycle that means I can't add my test).

* Remove fake indexeddb

as it seems like the tests didn't actually see the fake indexeddb before
(somehow) but now do, and are failing because they have that but no postmessage.
It feels like the right solution is for these tests to not need indexeddb.

* Don't mock a refresh token

The tests don't mock out enough for the token refreshing setup to work,
it wa somehow always ending up as null previously and now wasn't, at which
point it broke, so just make it actually unset.

* Move formatter instatiation to lazy

rather than eagerly at parse time, as this apparently shifted one
test to hit this import cycle instead.

* Tests for room name generator
This commit is contained in:
David Baker
2026-07-03 16:21:59 +01:00
committed by GitHub
parent 0c0cb5df3d
commit ff8329be09
17 changed files with 359 additions and 191 deletions
+138 -1
View File
@@ -1,4 +1,5 @@
/*
Copyright 2026 Element Creations Ltd.
Copyright 2024 New Vector Ltd.
Copyright 2017-2021 The Matrix.org Foundation C.I.C.
@@ -14,9 +15,20 @@ import {
IndexedDBCryptoStore,
IndexedDBStore,
LocalStorageCryptoStore,
RoomNameType,
type RoomNameState,
type TokenRefreshFunction,
EventTimelineSet,
EventTimeline,
} from "matrix-js-sdk/src/matrix";
import { VerificationMethod } from "matrix-js-sdk/src/types";
import indexeddbWorkerFactory from "../workers/indexeddbWorkerFactory";
import SettingsStore from "../settings/SettingsStore";
import { crossSigningCallbacks } from "../SecurityManager";
import IdentityAuthClient from "../IdentityAuthClient";
import { _t } from "../languageHandler";
import { formatList } from "./FormattingUtils";
const localStorage = window.localStorage;
@@ -27,6 +39,131 @@ try {
indexedDB = window.indexedDB;
} catch {}
/**
* Credentials used to create a MatrixClient with `createClientWithCreds`.
*/
export interface IMatrixClientCreds {
homeserverUrl: string;
identityServerUrl?: string;
userId: string;
deviceId?: string;
accessToken: string;
refreshToken?: string;
guest?: boolean;
pickleKey?: string;
freshLogin?: boolean;
}
function namesToRoomName(names: string[], count: number): string | undefined {
const countWithoutMe = count - 1;
if (!names.length) {
return _t("empty_room");
}
if (names.length === 1 && countWithoutMe <= 1) {
return names[0];
}
}
function memberNamesToRoomName(names: string[], count: number): string {
const name = namesToRoomName(names, count);
if (name) return name;
if (names.length === 2 && count === 2) {
return formatList(names);
}
return formatList(names, 1);
}
function inviteeNamesToRoomName(names: string[], count: number): string {
const name = namesToRoomName(names, count);
if (name) return name;
if (names.length === 2 && count === 2) {
return _t("inviting_user1_and_user2", {
user1: names[0],
user2: names[1],
});
}
return _t("inviting_user_and_n_others", {
user: names[0],
count: count - 1,
});
}
function roomNameGenerator(_: string, state: RoomNameState): string | null {
switch (state.type) {
case RoomNameType.Generated:
switch (state.subtype) {
case "Inviting":
return inviteeNamesToRoomName(state.names, state.count);
default:
return memberNamesToRoomName(state.names, state.count);
}
case RoomNameType.EmptyRoom:
if (state.oldName) {
return _t("empty_room_was_name", {
oldName: state.oldName,
});
} else {
return _t("empty_room");
}
default:
return null;
}
}
/**
* Create a new matrix client from credentials with all the options needed.
*
* @param creds The credentials to create the client with
* @param tokenRefreshFunction Optional function to call when the access token is expired
*
* @returns {MatrixClient} the newly-created MatrixClient
*/
export function createClientWithCreds(
creds: IMatrixClientCreds,
tokenRefreshFunction?: TokenRefreshFunction,
): MatrixClient {
const opts: ICreateClientOpts = {
baseUrl: creds.homeserverUrl,
idBaseUrl: creds.identityServerUrl,
accessToken: creds.accessToken,
refreshToken: creds.refreshToken,
tokenRefreshFunction,
userId: creds.userId,
deviceId: creds.deviceId,
pickleKey: creds.pickleKey,
timelineSupport: true,
forceTURN: !SettingsStore.getValue("webRtcAllowPeerToPeer"),
fallbackICEServerAllowed: !!SettingsStore.getValue("fallbackICEServerAllowed"),
// Gather up to 20 ICE candidates when a call arrives: this should be more than we'd
// ever normally need, so effectively this should make all the gathering happen when
// the call arrives.
iceCandidatePoolSize: 20,
verificationMethods: [VerificationMethod.Sas, VerificationMethod.ShowQrCode, VerificationMethod.Reciprocate],
identityServer: new IdentityAuthClient(),
// These are always installed regardless of the labs flag so that cross-signing features
// can toggle on without reloading and also be accessed immediately after login.
cryptoCallbacks: { ...crossSigningCallbacks },
enableEncryptedStateEvents: SettingsStore.getValue("feature_msc4362_encrypted_state_events"),
unstableMSC1763Retention: SettingsStore.getValue("feature_retention"),
roomNameGenerator,
};
const newCli = createMatrixClient(opts);
newCli.setGuest(Boolean(creds.guest));
const notifTimelineSet = new EventTimelineSet(undefined, {
timelineSupport: true,
pendingEvents: false,
});
// XXX: what is our initial pagination token?! it somehow needs to be synchronised with /sync.
notifTimelineSet.getLiveTimeline().setPaginationToken("", EventTimeline.BACKWARDS);
newCli.setNotifTimelineSet(notifTimelineSet);
return newCli;
}
/**
* Create a new matrix client, with the persistent stores set up appropriately
* (using localstorage/indexeddb, etc)
@@ -36,7 +173,7 @@ try {
*
* @returns {MatrixClient} the newly-created MatrixClient
*/
export default function createMatrixClient(opts: ICreateClientOpts): MatrixClient {
export function createMatrixClient(opts: ICreateClientOpts): MatrixClient {
const storeOpts: Partial<ICreateClientOpts> = {
useAuthorizationHeader: true,
};