remove unneeded imports

This commit is contained in:
Gigiaj 2025-04-14 09:49:53 -05:00
parent c413396562
commit e2c97f81a7

View file

@ -1,16 +1,11 @@
import { import {
type Capability, type Capability,
EventDirection, EventDirection,
type IOpenIDCredentials,
type IOpenIDUpdate,
type ISendDelayedEventDetails, type ISendDelayedEventDetails,
type ISendEventDetails, type ISendEventDetails,
type ITurnServer,
type IReadEventRelationsResult, type IReadEventRelationsResult,
type IRoomEvent, type IRoomEvent,
MatrixCapabilities, MatrixCapabilities,
OpenIDRequestState,
type SimpleObservable,
type Widget, type Widget,
WidgetDriver, WidgetDriver,
WidgetEventCapability, WidgetEventCapability,
@ -19,33 +14,22 @@ import {
type ISearchUserDirectoryResult, type ISearchUserDirectoryResult,
type IGetMediaConfigResult, type IGetMediaConfigResult,
type UpdateDelayedEventAction, type UpdateDelayedEventAction,
} from "matrix-widget-api"; } from 'matrix-widget-api';
import { import {
ClientEvent,
type ITurnServer as IClientTurnServer,
EventType, EventType,
type IContent, type IContent,
MatrixError, MatrixError,
type MatrixEvent, type MatrixEvent,
Direction, Direction,
THREAD_RELATION_TYPE,
type SendDelayedEventResponse, type SendDelayedEventResponse,
type StateEvents, type StateEvents,
type TimelineEvents, type TimelineEvents,
MatrixClient, MatrixClient,
Room, // Import Room } from 'matrix-js-sdk';
Timeline, // Import Timeline
} from "matrix-js-sdk"; // Assuming matrix-js-sdk is correctly imported
import {
type ApprovalOpts,
type CapabilitiesOpts,
WidgetLifecycle,
} from "@matrix-org/react-sdk-module-api/lib/lifecycles/WidgetLifecycle"; // Assuming this path is correct
import { logger } from "matrix-js-sdk/lib/logger"; // Assuming logger is correctly imported
export class SmallWidgetDriver extends WidgetDriver { export class SmallWidgetDriver extends WidgetDriver {
private allowedCapabilities: Set<Capability>; private allowedCapabilities: Set<Capability>;
private readonly mxClient: MatrixClient; // Store the client instance private readonly mxClient: MatrixClient; // Store the client instance
public constructor( public constructor(
@ -54,7 +38,7 @@ export class SmallWidgetDriver extends WidgetDriver {
private forWidget: Widget, private forWidget: Widget,
private forWidgetKind: WidgetKind, private forWidgetKind: WidgetKind,
virtual: boolean, // Assuming 'virtual' might be needed later, kept for consistency virtual: boolean, // Assuming 'virtual' might be needed later, kept for consistency
private inRoomId?: string, private inRoomId?: string
) { ) {
super(); super();
this.mxClient = mx; // Store the passed instance this.mxClient = mx; // Store the passed instance
@ -76,19 +60,22 @@ export class SmallWidgetDriver extends WidgetDriver {
// Capability to read room state (MSC2762) // Capability to read room state (MSC2762)
this.allowedCapabilities.add(`org.matrix.msc2762.state:${inRoomId}`); this.allowedCapabilities.add(`org.matrix.msc2762.state:${inRoomId}`);
this.allowedCapabilities.add( this.allowedCapabilities.add(
WidgetEventCapability.forStateEvent(EventDirection.Receive, EventType.RoomMember).raw, WidgetEventCapability.forStateEvent(EventDirection.Receive, EventType.RoomMember).raw
); );
this.allowedCapabilities.add( this.allowedCapabilities.add(
WidgetEventCapability.forStateEvent(EventDirection.Receive, "org.matrix.msc3401.call").raw, WidgetEventCapability.forStateEvent(EventDirection.Receive, 'org.matrix.msc3401.call').raw
); );
this.allowedCapabilities.add( this.allowedCapabilities.add(
WidgetEventCapability.forStateEvent(EventDirection.Receive, EventType.RoomEncryption).raw, WidgetEventCapability.forStateEvent(EventDirection.Receive, EventType.RoomEncryption).raw
); );
const clientUserId = this.mxClient.getSafeUserId(); const clientUserId = this.mxClient.getSafeUserId();
// For the legacy membership type // For the legacy membership type
this.allowedCapabilities.add( this.allowedCapabilities.add(
WidgetEventCapability.forStateEvent(EventDirection.Send, "org.matrix.msc3401.call.member", clientUserId) WidgetEventCapability.forStateEvent(
.raw, EventDirection.Send,
'org.matrix.msc3401.call.member',
clientUserId
).raw
); );
const clientDeviceId = this.mxClient.getDeviceId(); const clientDeviceId = this.mxClient.getDeviceId();
if (clientDeviceId !== null) { if (clientDeviceId !== null) {
@ -96,37 +83,42 @@ export class SmallWidgetDriver extends WidgetDriver {
this.allowedCapabilities.add( this.allowedCapabilities.add(
WidgetEventCapability.forStateEvent( WidgetEventCapability.forStateEvent(
EventDirection.Send, EventDirection.Send,
"org.matrix.msc3401.call.member", 'org.matrix.msc3401.call.member',
`_${clientUserId}_${clientDeviceId}`, `_${clientUserId}_${clientDeviceId}`
).raw, ).raw
); );
// Version with no leading underscore, for room versions whose auth rules allow it // Version with no leading underscore, for room versions whose auth rules allow it
this.allowedCapabilities.add( this.allowedCapabilities.add(
WidgetEventCapability.forStateEvent( WidgetEventCapability.forStateEvent(
EventDirection.Send, EventDirection.Send,
"org.matrix.msc3401.call.member", 'org.matrix.msc3401.call.member',
`${clientUserId}_${clientDeviceId}`, `${clientUserId}_${clientDeviceId}`
).raw, ).raw
); );
} }
this.allowedCapabilities.add( this.allowedCapabilities.add(
WidgetEventCapability.forStateEvent(EventDirection.Receive, "org.matrix.msc3401.call.member").raw, WidgetEventCapability.forStateEvent(EventDirection.Receive, 'org.matrix.msc3401.call.member')
.raw
); );
// for determining auth rules specific to the room version // for determining auth rules specific to the room version
this.allowedCapabilities.add( this.allowedCapabilities.add(
WidgetEventCapability.forStateEvent(EventDirection.Receive, EventType.RoomCreate).raw, WidgetEventCapability.forStateEvent(EventDirection.Receive, EventType.RoomCreate).raw
); );
const sendRecvRoomEvents = [ const sendRecvRoomEvents = [
"io.element.call.encryption_keys", 'io.element.call.encryption_keys',
"org.matrix.rageshake_request", 'org.matrix.rageshake_request',
EventType.Reaction, EventType.Reaction,
EventType.RoomRedaction, EventType.RoomRedaction,
"io.element.call.reaction", 'io.element.call.reaction',
]; ];
for (const eventType of sendRecvRoomEvents) { for (const eventType of sendRecvRoomEvents) {
this.allowedCapabilities.add(WidgetEventCapability.forRoomEvent(EventDirection.Send, eventType).raw); this.allowedCapabilities.add(
this.allowedCapabilities.add(WidgetEventCapability.forRoomEvent(EventDirection.Receive, eventType).raw); WidgetEventCapability.forRoomEvent(EventDirection.Send, eventType).raw
);
this.allowedCapabilities.add(
WidgetEventCapability.forRoomEvent(EventDirection.Receive, eventType).raw
);
} }
const sendRecvToDevice = [ const sendRecvToDevice = [
@ -144,16 +136,14 @@ export class SmallWidgetDriver extends WidgetDriver {
]; ];
for (const eventType of sendRecvToDevice) { for (const eventType of sendRecvToDevice) {
this.allowedCapabilities.add( this.allowedCapabilities.add(
WidgetEventCapability.forToDeviceEvent(EventDirection.Send, eventType).raw, WidgetEventCapability.forToDeviceEvent(EventDirection.Send, eventType).raw
); );
this.allowedCapabilities.add( this.allowedCapabilities.add(
WidgetEventCapability.forToDeviceEvent(EventDirection.Receive, eventType).raw, WidgetEventCapability.forToDeviceEvent(EventDirection.Receive, eventType).raw
); );
} }
} }
public async validateCapabilities(requested: Set<Capability>): Promise<Set<Capability>> { public async validateCapabilities(requested: Set<Capability>): Promise<Set<Capability>> {
// Stubbed under the assumption voice calls will be valid thru element-call // Stubbed under the assumption voice calls will be valid thru element-call
return requested; return requested;
@ -163,24 +153,24 @@ export class SmallWidgetDriver extends WidgetDriver {
eventType: K, eventType: K,
content: StateEvents[K], content: StateEvents[K],
stateKey: string | null, stateKey: string | null,
targetRoomId: string | null, targetRoomId: string | null
): Promise<ISendEventDetails>; ): Promise<ISendEventDetails>;
public async sendEvent<K extends keyof TimelineEvents>( public async sendEvent<K extends keyof TimelineEvents>(
eventType: K, eventType: K,
content: TimelineEvents[K], content: TimelineEvents[K],
stateKey: null, stateKey: null,
targetRoomId: string | null, targetRoomId: string | null
): Promise<ISendEventDetails>; ): Promise<ISendEventDetails>;
public async sendEvent( public async sendEvent(
eventType: string, eventType: string,
content: IContent, content: IContent,
stateKey: string | null = null, stateKey: string | null = null,
targetRoomId: string | null = null, targetRoomId: string | null = null
): Promise<ISendEventDetails> { ): Promise<ISendEventDetails> {
const client = this.mxClient; const client = this.mxClient;
const roomId = targetRoomId || this.inRoomId; const roomId = targetRoomId || this.inRoomId;
if (!client || !roomId) throw new Error("Not in a room or not attached to a client"); if (!client || !roomId) throw new Error('Not in a room or not attached to a client');
let r: { event_id: string } | null; let r: { event_id: string } | null;
if (stateKey !== null) { if (stateKey !== null) {
@ -189,17 +179,17 @@ export class SmallWidgetDriver extends WidgetDriver {
roomId, roomId,
eventType as keyof StateEvents, eventType as keyof StateEvents,
content as StateEvents[keyof StateEvents], content as StateEvents[keyof StateEvents],
stateKey, stateKey
); );
} else if (eventType === EventType.RoomRedaction) { } else if (eventType === EventType.RoomRedaction) {
// special case: extract the `redacts` property and call redact // special case: extract the `redacts` property and call redact
r = await client.redactEvent(roomId, content["redacts"]); r = await client.redactEvent(roomId, content['redacts']);
} else { } else {
// message event // message event
r = await client.sendEvent( r = await client.sendEvent(
roomId, roomId,
eventType as keyof TimelineEvents, eventType as keyof TimelineEvents,
content as TimelineEvents[keyof TimelineEvents], content as TimelineEvents[keyof TimelineEvents]
); );
} }
@ -216,7 +206,7 @@ export class SmallWidgetDriver extends WidgetDriver {
eventType: K, eventType: K,
content: StateEvents[K], content: StateEvents[K],
stateKey: string | null, stateKey: string | null,
targetRoomId: string | null, targetRoomId: string | null
): Promise<ISendDelayedEventDetails>; ): Promise<ISendDelayedEventDetails>;
/** /**
* @experimental Part of MSC4140 & MSC4157 * @experimental Part of MSC4140 & MSC4157
@ -227,7 +217,7 @@ export class SmallWidgetDriver extends WidgetDriver {
eventType: K, eventType: K,
content: TimelineEvents[K], content: TimelineEvents[K],
stateKey: null, stateKey: null,
targetRoomId: string | null, targetRoomId: string | null
): Promise<ISendDelayedEventDetails>; ): Promise<ISendDelayedEventDetails>;
public async sendDelayedEvent( public async sendDelayedEvent(
delay: number | null, delay: number | null,
@ -235,12 +225,12 @@ export class SmallWidgetDriver extends WidgetDriver {
eventType: string, eventType: string,
content: IContent, content: IContent,
stateKey: string | null = null, stateKey: string | null = null,
targetRoomId: string | null = null, targetRoomId: string | null = null
): Promise<ISendDelayedEventDetails> { ): Promise<ISendDelayedEventDetails> {
const client = this.mxClient; const client = this.mxClient;
const roomId = targetRoomId || this.inRoomId; const roomId = targetRoomId || this.inRoomId;
if (!client || !roomId) throw new Error("Not in a room or not attached to a client"); if (!client || !roomId) throw new Error('Not in a room or not attached to a client');
let delayOpts; let delayOpts;
if (delay !== null) { if (delay !== null) {
@ -253,7 +243,7 @@ export class SmallWidgetDriver extends WidgetDriver {
parent_delay_id: parentDelayId, parent_delay_id: parentDelayId,
}; };
} else { } else {
throw new Error("Must provide at least one of delay or parentDelayId"); throw new Error('Must provide at least one of delay or parentDelayId');
} }
let r: SendDelayedEventResponse | null; let r: SendDelayedEventResponse | null;
@ -264,7 +254,7 @@ export class SmallWidgetDriver extends WidgetDriver {
delayOpts, delayOpts,
eventType as keyof StateEvents, eventType as keyof StateEvents,
content as StateEvents[keyof StateEvents], content as StateEvents[keyof StateEvents],
stateKey, stateKey
); );
} else { } else {
// message event // message event
@ -273,7 +263,7 @@ export class SmallWidgetDriver extends WidgetDriver {
delayOpts, delayOpts,
null, null,
eventType as keyof TimelineEvents, eventType as keyof TimelineEvents,
content as TimelineEvents[keyof TimelineEvents], content as TimelineEvents[keyof TimelineEvents]
); );
} }
@ -286,10 +276,13 @@ export class SmallWidgetDriver extends WidgetDriver {
/** /**
* @experimental Part of MSC4140 & MSC4157 * @experimental Part of MSC4140 & MSC4157
*/ */
public async updateDelayedEvent(delayId: string, action: UpdateDelayedEventAction): Promise<void> { public async updateDelayedEvent(
delayId: string,
action: UpdateDelayedEventAction
): Promise<void> {
const client = this.mxClient; const client = this.mxClient;
if (!client) throw new Error("Not in a room or not attached to a client"); if (!client) throw new Error('Not in a room or not attached to a client');
await client._unstable_updateDelayedEvent(delayId, action); await client._unstable_updateDelayedEvent(delayId, action);
} }
@ -300,13 +293,13 @@ export class SmallWidgetDriver extends WidgetDriver {
public async sendToDevice( public async sendToDevice(
eventType: string, eventType: string,
encrypted: boolean, encrypted: boolean,
contentMap: { [userId: string]: { [deviceId: string]: object } }, contentMap: { [userId: string]: { [deviceId: string]: object } }
): Promise<void> { ): Promise<void> {
const client = this.mxClient; const client = this.mxClient;
if (encrypted) { if (encrypted) {
const crypto = client.getCrypto(); const crypto = client.getCrypto();
if (!crypto) throw new Error("E2EE not enabled"); if (!crypto) throw new Error('E2EE not enabled');
// attempt to re-batch these up into a single request // attempt to re-batch these up into a single request
const invertedContentMap: { [content: string]: { userId: string; deviceId: string }[] } = {}; const invertedContentMap: { [content: string]: { userId: string; deviceId: string }[] } = {};
@ -326,11 +319,11 @@ export class SmallWidgetDriver extends WidgetDriver {
const batch = await crypto.encryptToDeviceMessages( const batch = await crypto.encryptToDeviceMessages(
eventType, eventType,
recipients, recipients,
JSON.parse(stringifiedContent), JSON.parse(stringifiedContent)
); );
await client.queueToDevice(batch); await client.queueToDevice(batch);
}), })
); );
} else { } else {
await client.queueToDevice({ await client.queueToDevice({
@ -340,7 +333,7 @@ export class SmallWidgetDriver extends WidgetDriver {
userId, userId,
deviceId, deviceId,
payload: content, payload: content,
})), }))
), ),
}); });
} }
@ -368,7 +361,7 @@ export class SmallWidgetDriver extends WidgetDriver {
msgtype: string | undefined, msgtype: string | undefined,
stateKey: string | undefined, stateKey: string | undefined,
limit: number, limit: number,
since: string | undefined, since: string | undefined
): Promise<IRoomEvent[]> { ): Promise<IRoomEvent[]> {
limit = limit > 0 ? Math.min(limit, Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER; // relatively arbitrary limit = limit > 0 ? Math.min(limit, Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER; // relatively arbitrary
@ -382,8 +375,10 @@ export class SmallWidgetDriver extends WidgetDriver {
if (since !== undefined && ev.getId() === since) break; if (since !== undefined && ev.getId() === since) break;
if (ev.getType() !== eventType || ev.isState()) continue; if (ev.getType() !== eventType || ev.isState()) continue;
if (eventType === EventType.RoomMessage && msgtype && msgtype !== ev.getContent()["msgtype"]) continue; if (eventType === EventType.RoomMessage && msgtype && msgtype !== ev.getContent()['msgtype'])
if (ev.getStateKey() !== undefined && stateKey !== undefined && ev.getStateKey() !== stateKey) continue; continue;
if (ev.getStateKey() !== undefined && stateKey !== undefined && ev.getStateKey() !== stateKey)
continue;
results.push(ev); results.push(ev);
} }
@ -399,7 +394,11 @@ export class SmallWidgetDriver extends WidgetDriver {
* @returns {Promise<IRoomEvent[]>} Resolves to the events representing the * @returns {Promise<IRoomEvent[]>} Resolves to the events representing the
* current values of the room state entries. * current values of the room state entries.
*/ */
public async readRoomState(roomId: string, eventType: string, stateKey: string | undefined): Promise<IRoomEvent[]> { public async readRoomState(
roomId: string,
eventType: string,
stateKey: string | undefined
): Promise<IRoomEvent[]> {
const room = this.mxClient.getRoom(roomId); const room = this.mxClient.getRoom(roomId);
if (room === null) return []; if (room === null) return [];
const state = room.getLiveTimeline().getState(Direction.Forward); const state = room.getLiveTimeline().getState(Direction.Forward);
@ -425,14 +424,14 @@ export class SmallWidgetDriver extends WidgetDriver {
from?: string, from?: string,
to?: string, to?: string,
limit?: number, limit?: number,
direction?: "f" | "b", direction?: 'f' | 'b'
): Promise<IReadEventRelationsResult> { ): Promise<IReadEventRelationsResult> {
const client = this.mxClient; const client = this.mxClient;
const dir = direction as Direction; const dir = direction as Direction;
roomId = roomId ?? this.inRoomId ?? undefined; roomId = roomId ?? this.inRoomId ?? undefined;
if (typeof roomId !== "string") { if (typeof roomId !== 'string') {
throw new Error("Error while reading the current room"); throw new Error('Error while reading the current room');
} }
const { events, nextBatch, prevBatch } = await client.relations( const { events, nextBatch, prevBatch } = await client.relations(
@ -440,7 +439,7 @@ export class SmallWidgetDriver extends WidgetDriver {
eventId, eventId,
relationType ?? null, relationType ?? null,
eventType ?? null, eventType ?? null,
{ from, to, limit, dir }, { from, to, limit, dir }
); );
return { return {
@ -450,7 +449,10 @@ export class SmallWidgetDriver extends WidgetDriver {
}; };
} }
public async searchUserDirectory(searchTerm: string, limit?: number): Promise<ISearchUserDirectoryResult> { public async searchUserDirectory(
searchTerm: string,
limit?: number
): Promise<ISearchUserDirectoryResult> {
const client = this.mxClient; const client = this.mxClient;
const { limited, results } = await client.searchUserDirectory({ term: searchTerm, limit }); const { limited, results } = await client.searchUserDirectory({ term: searchTerm, limit });
@ -501,9 +503,7 @@ export class SmallWidgetDriver extends WidgetDriver {
* @returns The room IDs. * @returns The room IDs.
*/ */
public getKnownRooms(): string[] { public getKnownRooms(): string[] {
return this.mxClient return this.mxClient.getVisibleRooms().map((r) => r.roomId);
.getVisibleRooms()
.map((r) => r.roomId);
} }
/** /**
@ -514,6 +514,8 @@ export class SmallWidgetDriver extends WidgetDriver {
* or undefined if it is not a {@link MatrixError}. * or undefined if it is not a {@link MatrixError}.
*/ */
public processError(error: unknown): IWidgetApiErrorResponseDataDetails | undefined { public processError(error: unknown): IWidgetApiErrorResponseDataDetails | undefined {
return error instanceof MatrixError ? { matrix_api_error: error.asWidgetApiErrorData() } : undefined; return error instanceof MatrixError
? { matrix_api_error: error.asWidgetApiErrorData() }
: undefined;
} }
} }