From b20d3d2e1f0a46d755d5b7a936fa1bc76218e31b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Huan=20=28=E6=9D=8E=E5=8D=93=E6=A1=93=29?= Date: Fri, 28 Feb 2020 13:52:27 +0800 Subject: [PATCH] Create a new package: Matrix JS SDK (matrix-js-sdk) (#42673) * init matrix-js-sdk * make linter happy * pass the tsc testing * add create client * make linter happy * linting * linting --- types/matrix-js-sdk/index.d.ts | 638 +++++++++++++++++++++ types/matrix-js-sdk/matrix-js-sdk-tests.ts | 18 + types/matrix-js-sdk/tsconfig.json | 24 + types/matrix-js-sdk/tslint.json | 3 + 4 files changed, 683 insertions(+) create mode 100644 types/matrix-js-sdk/index.d.ts create mode 100644 types/matrix-js-sdk/matrix-js-sdk-tests.ts create mode 100644 types/matrix-js-sdk/tsconfig.json create mode 100644 types/matrix-js-sdk/tslint.json diff --git a/types/matrix-js-sdk/index.d.ts b/types/matrix-js-sdk/index.d.ts new file mode 100644 index 0000000000..f59be84871 --- /dev/null +++ b/types/matrix-js-sdk/index.d.ts @@ -0,0 +1,638 @@ +// Type definitions for matrix-js-sdk 5.0 +// Project: https://github.com/matrix-org/matrix-js-sdk +// Definitions by: Huan LI (李卓桓) +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +import { EventEmitter } from 'events'; + +export type MatrixCallback = (err: null | object, data: any) => void; + +export class MatrixError { + errcode: string; // The Matrix 'errcode' value, e.g. "M_FORBIDDEN". + name: string; // Same as MatrixError.errcode but with a default unknown string. + message: string; // The Matrix 'error' value, e.g. "Missing token." + data: object; // The raw Matrix error JSON used to construct this object. + httpStatus: number; // The numeric HTTP status code given + + constructor(errorJson: object) +} + +export class Room { + roomId: string; // The ID of this room. + name: string; // The human-readable display name for this room. + timeline: MatrixEvent[]; // The live event timeline for this room, with the oldest event at index 0. Present for backwards compatibility - prefer getLiveTimeline(). + tags: object; // Dict of room tags; the keys are the tag name and the values are any metadata associated with the tag - e.g. { "fav" : { order: 1 } } + accountData: object; // Dict of per-room account_data events; the keys are the event type and the values are the events. + oldState: RoomState; // The state of the room at the time of the oldest event in the live timeline. Present for backwards compatibility - + currentState: RoomState; // The state of the room at the time of the newest event in the timeline. Present for backwards compatibility - + summary: RoomSummary; // The room summary. + storageToken: any; // A token which a data store can use to remember the state of the room. + + constructor(roomId: string, client: MatrixClient, myUserId: string, opts?: { + storageToken?: any // Optional. The token which a data store can use to remember the state of the room. What this means is dependent on the store implementation. + pendingEventOrdering?: string // Controls where pending messages appear in a room's timeline. If "chronological", messages will appear in the timeline + timelineSupport?: boolean // false Set to true to enable improved timeline support. + unstableClientRelationAggregation?: boolean // false Optional. Set to true to enable client-side aggregation of event relations via `EventTimelineSet#getRelationsForEvent`. + }) + + addAccountData(events: MatrixEvent[]): void; + addEventsToTimeline(events: MatrixEvent[], toStartOfTimeline: boolean, timeline: EventTimeline, paginationToken?: string): void; + addLiveEvents(events: MatrixEvent[], duplicateStrategy: string): void; + addPendingEvent(event: MatrixEvent, txnId: string): void; + addReceipt(event: MatrixEvent, fake: boolean): void; + addTags(event: MatrixEvent): void; + addTimeline(): EventTimeline; + clearLoadedMembersIfNeeded(): void; + findEventById(eventId: string): null | MatrixEvent; + getAccountData(type: string): null | MatrixEvent; + getAliases(): string[]; + getAvatarUrl( + baseUrl: string, width: number, height: number, resizeMethod: string, allowDefault: boolean, + ): null | string; + getBlacklistUnverifiedDevices(): boolean; + getCanonicalAlias(): null | string; + getDefaultRoomName(userId: string): string; + getDMInviter(): undefined | string; + getEncryptionTargetMembers(): Promise; + getEventReadUpTo(userId: string, ignoreSynthesized: boolean): string; + getInvitedAndJoinedMemberCount(): number; + getInvitedMemberCount(): number; + getJoinedMemberCount(): number; + getJoinedMembers(): RoomMember[]; + getLiveTimeline(): EventTimeline; + getMember(userId: string): RoomMember; + getMembersWithMembership(membership: string): RoomMember[]; + getMyMembership(myUserId: string): string; + getOrCreateFilteredTimelineSet(filter: Filter): EventTimelineSet; + getPendingEvents(): MatrixEvent[]; + getReceiptsForEvent(event: MatrixEvent): object[]; + getRecommendedVersion(): Promise<{ + version: string, needsUpgrade: boolean, urgent: boolean + }>; + getTimelineForEvent(eventId: string): null | EventTimeline; + getTimelineSets(): EventTimelineSet[]; + getUnfilteredTimelineSet(): EventTimelineSet; + getUnreadNotificationCount(type: string): number; + getUsersReadUpTo(event: MatrixEvent): string[]; + getVersion(): string; + guessDMUserId(): string; + hasMembershipState(userId: string, membership: MembershipType): boolean; + hasUnverifiedDevices(): boolean; + hasUserReadEvent(userId: string, eventId: string): boolean; + loadMembersIfNeeded(): Promise; + maySendMessage(): boolean; + recalculate(): void; + removeEvent(eventId: string): boolean; + removeEvents(event_ids: string[]): void; + removeFilteredTimelineSet(filter: Filter): void; + resetLiveTimeline(backPaginationToken?: string, forwardPaginationToken?: string): void; + setBlacklistUnverifiedDevices(value: boolean): void; + setUnreadNotificationCount(type: string, count: number): void; + shouldEncryptForInvitedMembers(): boolean; + shouldUpgradeToVersion(): null | string; + updateMyMembership(membership: MembershipType): void; + updatePendingEvent(event: MatrixEvent, newStatus: EventStatus, newEventId: string): void; + userMayUpgradeRoom(userId: string): boolean; +} + +export class User { + userId: string; // The ID of the user. + info: object; // The info object supplied in the constructor. + displayName: string; // The 'displayname' of the user if known. + avatarUrl: string; // The 'avatar_url' of the user if known. + presence: string; // The presence enum if known. + presenceStatusMsg: string; // The presence status message if known. + lastActiveAgo: number; // The time elapsed in ms since the user interacted proactively with the server, or we saw a message from the user + lastPresenceTs: number; // Timestamp (ms since the epoch) for when we last received presence data for this user. We can subtract lastActiveAgo + currentlyActive: boolean; // Whether we should consider lastActiveAgo to be an approximation and that the user should be seen as active 'now' + events: { presence: MatrixEvent }; // The events describing this user. + + constructor( + userId: string, + ) + + getLastActiveTs(): number; + getLastModifiedTime(): number; + setAvatarUrl(url: string): void; + setDisplayName(name: string): void; + setPresenceEvent(event: MatrixEvent): void; + setRawDisplayName(name: string): void; +} + +export type EventType = never + |'m.room.canonical_alias' + |'m.room.encryption' + |'m.room.guest_access' + |'m.room.history_visibility' + |'m.room.join_rules' + |'m.room.member' + |'m.room.message' + |'m.room.name' + |'m.room.power_levels' + |'m.room.redaction' + |'m.room.tombstone' + |'m.room.topic' + |'m.sticker'; + +export type MsgType = never + |'m.audio' + |'m.bad.encrypted' + |'m.emote' + |'m.file' + |'m.image' + |'m.notice' + |'m.text' + |'m.video'; + +export type MembershipType = never + |'ban' + |'invite' + |'joined' + |'join' + |'leave'; +/** + * Only part of the MatrixClient methods was put here + * because they are too many. + * @huan 14 June 2019 + */ +export class MatrixClient extends EventEmitter { + acceptGroupInvite(groupId: string, opts: object): Promise; + addPushRule(scope: string, kind: string, ruleId: string, body: object, callback?: () => void): Promise; + addRoomToGroup(groupId: string, roomId: string, isPublic: boolean): Promise; + addRoomToGroupSummary(groupId: string, roomId: string, categoryId?: string): Promise; + addThreePid(creds: object, bind: boolean, callback?: (err: null | object, data: any) => void): Promise; + addUserToGroupSummary(groupId: string, userId: string, roleId?: string): Promise; + backPaginateRoomEventsSearch(searchResults: object): Promise; + ban(roomId: string, userId: string, reason: string, callback: (err: null | object, data: any) => void): Promise; + beginKeyVerification(method: string, userId: string, deviceId: string): Promise; + cancelAndResendEventRoomKeyRequest(event: MatrixEvent): Promise; + cancelPendingEvent(event: MatrixEvent): Promise; + cancelUpload(promise: Promise): boolean; + checkKeyBackup(): object; + claimOneTimeKeys(devices: string[], key_algorithm: string): Promise; + clearStores(): Promise; + createAlias(alias: string, roomId: string, callback: MatrixCallback): Promise; + createFilter(content: object): Promise; + createGroup(content: object): Promise<{ [groupId: string]: string }>; + createKeyBackupVersion(info: object): Promise; + createRoom(options: CreateRoomOptions, callback: MatrixCallback): Promise<{ + room_id: string, + room_alias?: string, + }>; + deactivateAccount(auth: object, erase: boolean): Promise; + deleteAlias(alias: string, callback: MatrixCallback): Promise; + deleteDevice(device_id: string, auth: object): Promise; + deleteMultipleDevices(devices: string, auth: object): Promise; + deletePushRule(scope: string, kind: string, ruleId: string, callback?: MatrixCallback): Promise; + deleteRoomTag(roomId: string, tagName: string, callback?: MatrixCallback): Promise; + deleteThreePid(medium: string, address: string): Promise; + disableKeyBackup(): void; + downloadKeys(userIds: string[], forceDownload: boolean): Promise<{ + [userId: string]: { + [deviceId: string]: string // DeviceInfo + } + }>; + downloadKeysForUsers(userIds: string[], opts?: object): Promise; + dropFromPresenceList(callback: MatrixCallback, userIds: string[]): Promise; + emit(event: string, listener: (...args: any[]) => any): boolean; + enableKeyBackup(info: object): void; + exportRoomKeys(): Promise; + fetchRoomEvent(roomId: string, eventId: string, callback?: MatrixCallback): Promise; + forceDiscardSession(roomId: string): void; + forget(roomId: string, deleteRoom: boolean, callback?: MatrixCallback): Promise; + generateClientSecret(): string; + getAccessToken(): null | string; + getAccountData(eventType: EventType): null | object; + getCanResetTimelineCallback(): null | ((...args: any[]) => any); + getCapabilities(fresh: boolean): Promise; + getCasLoginUrl(redirectUrl: string): string; + getCurrentUploads(): object[]; + getDeviceEd25519Key(): null | string; + getDeviceId(): null | string; + getDevices(): Promise; + getDomain(): null | string; + getEventMapper(): (...args: any[]) => any; + getEventSenderDeviceInfo(event: MatrixEvent): Promise; + getEventTimeline(timelineSet: EventTimelineSet, eventId: string): Promise; + getFallbackAuthUrl(loginType: string, authSessionId: string): string; + getFilter(userId: string, filterId: string, allowCached: boolean): Promise; + getGlobalBlacklistUnverifiedDevices(): boolean; + getGroup(groupId: string): Group; + getGroupInvitedUsers(groupId: string): Promise; + getGroupProfile(groupId: string): Promise; + getGroupRooms(groupId: string): Promise; + getGroups(): Group[]; + getGroupSummary(groupId: string): Promise; + getGroupUsers(groupId: string): Promise; + getHomeserverUrl(): string; + getIdentityServerUrl(stripProto: boolean): string; + getIgnoredUsers(): string[]; + getJoinedGroups(): Promise; + getJoinedRoomMembers(roomId: string): Promise; + getJoinedRooms(): Promise; + getKeyBackupEnabled(): boolean; + getKeyBackupVersion(): Promise; + getKeyChanges(oldToken: string, newToken: string): Promise; + getMediaConfig(callback: MatrixCallback): Promise; + getNotifTimelineSet(): EventTimelineSet; + getOpenIdToken(): Promise; + getOrCreateFilter(filterName: string, filter: Filter): Promise; + getPresenceList(callback: MatrixCallback): Promise; + getProfileInfo(userId: string, info: string, callback?: MatrixCallback): Promise; + getPublicisedGroups(userIds: string[]): Promise; + getPushActionsForEvent(event: MatrixEvent): PushAction; + getPushers(callback: MatrixCallback): Promise; + getPushRules(callback: MatrixCallback): Promise; + getRoom(roomId: string): null | Room; + getRoomDirectoryVisibility(roomId: string, callback?: MatrixCallback): Promise; + getRoomIdForAlias(alias: string, callback?: MatrixCallback): Promise; + getRoomPushRule(scope: string, roomId: string): object; + getRooms(): Room[]; + getRoomTags(roomId: string, callback?: MatrixCallback): Promise; + getRoomUpgradeHistory(roomId: string, verifyLinks: boolean): Room[]; + getScheduler(): null | MatrixScheduler; + getSsoLoginUrl(redirectUrl: string, loginType: string): string; + getStateEvent( + roomId: string, eventType: EventType, stateKey?: string, callback?: MatrixCallback + ): Promise; + getStoredDevice(userId: string, deviceId: string): Promise; + getStoredDevicesForUser(userId: string): Promise; + getSyncState(): null | string; + getSyncStateData(): null | object; + getThirdpartyLocation(protocol: string, params: object): Promise; + getThirdpartyProtocols(): Promise; + getThirdpartyUser(protocol: string, params: object): Promise; + getThreePids(callback: MatrixCallback): Promise; + getTurnServers(): object[]; + getUrlPreview(url: string, ts: number, callback?: MatrixCallback): Promise; + getUser(userId: string): null | User; + getUserId(): null | string; + getUserIdLocalpart(): null | string; + getUsers(): User[]; + getVisibleRooms(): Room[]; + importRoomKeys(keys: object[]): Promise; + initCrypto(): void; + invite(roomId: string, userId: string, callback?: MatrixCallback): Promise; + inviteByEmail(roomId: string, email: string, callback?: MatrixCallback): Promise; + inviteByThreePid(roomId: string, medium: string, address: string, callback?: MatrixCallback): Promise; + inviteToPresenceList(callback: MatrixCallback, userIds: string[]): Promise; + inviteUserToGroup(groupId: string, userId: string): Promise; + isCryptoEnabled(): boolean; + isEventSenderVerified(event: MatrixEvent): boolean; + isGuest(): boolean; + isKeyBackupTrusted(info: object): object; + isLoggedIn(): boolean; + isRoomEncrypted(roomId: string): boolean; + isUserIgnored(userId: string): boolean; + isUsernameAvailable(username: string): Promise; + joinGroup(groupId: string): Promise; + joinRoom(roomIdOrAlias: string, opts: { + syncRoom: boolean // True to do a room initial sync on the resulting room. If false, the returned Room object will have no current state. Default: true. + inviteSignUrl: boolean // If the caller has a keypair 3pid invite, the signing URL is passed in this parameter. + viaServers: string[] // The server names to try and join through in addition to those that are automatically chosen. + }, callback: MatrixCallback): Promise; + kick(roomId: string, userId: string, reason?: string, callback?: MatrixCallback): Promise; + leave(roomId: string, callback?: MatrixCallback): Promise; + leaveGroup(groupId: string): Promise; + leaveRoomChain(roomId: string, includeFuture: boolean): Promise; + login(loginType: string, data: object, callback?: MatrixCallback): Promise; + loginFlows(callback?: MatrixCallback): Promise; + loginWithPassword(user: string, password: string, callback?: MatrixCallback): Promise; + loginWithSAML2(relayState: string, callback?: MatrixCallback): Promise; + loginWithToken(token: string, callback?: MatrixCallback): Promise; + logout(callback?: MatrixCallback): Promise; + lookupThreePid(medium: string, address: string, callback?: MatrixCallback): Promise; + makeTxnId(): string; + members( + roomId: string, includeMembership: string, excludeMembership: string, atEventId: string, callback?: MatrixCallback, + ): Promise; + mxcUrlToHttp(mxcUrl: string, width: number, height: number, resizeMethod: string, allowDirectLinks: boolean): null | string; + paginateEventTimeline(eventTimeline: EventTimeline, opts?: object): Promise; + peekInRoom(roomId: string): Promise; + prepareKeyBackupVersion(password: string): Promise; + publicRooms(options: { + server: string // The remote server to query for the room list. Optional. If unspecified, get the local home server's public room list. + limit: number // Maximum number of entries to return + since: string // Token to paginate from + filter: { // Filter parameters + generic_search_term: string // String to search for + }, + }, callback: (...args: any[]) => any): Promise; + redactEvent(roomId: string, eventId: string, txnIdopt: string, callback?: MatrixCallback): Promise; + register( + username: string, password: string, sessionId: string, + auth: object, bindThreepids: object, guestAccessToken: string, + inhibitLogin: string, callback?: MatrixCallback, + ): Promise; + registerGuest(opts?: object, callback?: MatrixCallback): Promise; + registerRequest(data: object, kind?: string, callback?: MatrixCallback): Promise; + removeRoomFromGroup(groupId: string, roomId: string): Promise; + removeRoomFromGroupSummary(groupId: string, roomId: string): Promise; + removeUserFromGroup(groupId: string, userId: string): Promise; + removeUserFromGroupSummary(groupId: string, userId: string): Promise; + requestAdd3pidEmailToken(email: string, clientSecret: string, sendAttempt: number, nextLink: string): Promise; + requestAdd3pidMsisdnToken( + phoneCountry: string, phoneNumber: string, clientSecret: string, sendAttempt: number, nextLink: string, + ): Promise; + requestEmailToken( + email: string, clientSecret: string, sendAttempt: number, nextLink: string, callback?: MatrixCallback, + ): Promise; + requestPasswordEmailToken( + email: string, clientSecret: string, sendAttempt: number, nextLink: string, callback?: MatrixCallback, + ): Promise; + requestPasswordMsisdnToken( + phoneCountry: string, phoneNumber: string, clientSecret: string, sendAttempt: number, nextLink: string, + ): Promise; + requestRegisterEmailToken( + email: string, clientSecret: string, sendAttempt: number, nextLink: string, + ): Promise; + requestRegisterMsisdnToken( + phoneCountry: string, phoneNumber: string, clientSecret: string, sendAttempt: number, nextLink: string, + ): Promise; + requestVerification( + userId: string, methods: string[], devices: string[], + ): Promise; + resendEvent(event: MatrixEvent, room: Room): Promise; + resetNotifTimelineSet(): void; + resolveRoomAlias(roomAlias: string, callback?: MatrixCallback): Promise; + retryImmediately(): boolean; + roomInitialSync(roomId: string, limit: number, callback?: MatrixCallback): Promise; + roomState(roomId: string, callback?: MatrixCallback): Promise; + scheduleAllGroupSessionsForBackup(): void; + scrollback(room: Room, limit: number, callback?: MatrixCallback): Promise; + search( + opts: { + next_batch: string // the batch token to pass in the query string + body: object // the JSON object to pass to the request body. + }, + callback?: MatrixCallback, + ): Promise; + searchMessageText( + opts: { + query: string // The text to query. + keys: string // The keys to search on. Defaults to all keys. One of "content.body", "content.name", "content.topic". + }, + callback?: MatrixCallback, + ): Promise; + searchRoomEvents(opts: { + term: string // the term to search for + filter: object // a JSON filter object to pass in the request + }): Promise; + searchUserDirectory(opts: { + term: string // the term with which to search. + limit: number // the maximum number of results to return. The server will apply a limit if unspecified. + }): Promise; + sendEmoteMessage( + roomId: string, body: string, txnId: string, callback?: MatrixCallback, + ): Promise; + sendEvent( + roomId: string, eventType: EventType, content: object, txnId: string, callback?: MatrixCallback, + ): Promise; + sendHtmlEmote( + roomId: string, body: string, htmlBody: string, callback?: MatrixCallback, + ): Promise; + sendHtmlMessage( + roomId: string, body: string, htmlBody: string, callback?: MatrixCallback, + ): Promise; + sendHtmlNotice( + roomId: string, body: string, htmlBody: string, callback?: MatrixCallback, + ): Promise; + sendImageMessage( + roomId: string, url: string, info: object, text: string, callback?: MatrixCallback, + ): Promise; + sendKeyBackup( + roomId: string, sessionId: string, version: number, data: object, + ): Promise; + sendMessage( + roomId: string, content: object, txnId: string, callback?: MatrixCallback, + ): Promise; + sendNotice( + roomId: string, body: string, txnId: string, callback?: MatrixCallback, + ): Promise; + sendReadReceipt(event: MatrixEvent, callback?: MatrixCallback): Promise; + sendReceipt(event: MatrixEvent, receiptType: string, callback?: MatrixCallback): Promise; + sendStateEvent( + roomId: string, eventType: EventType, content: object, stateKey?: string, callback?: MatrixCallback, + ): Promise; + sendStickerMessage( + roomId: string, url: string, info: object, text: string, callback?: MatrixCallback, + ): Promise; + sendTextMessage(roomId: string, body: string, txnId: string, callback?: MatrixCallback): Promise; + sendToDevice(eventType: EventType, contentMap: { + [key: string]: { + [key2: string]: object + } + }, txnId?: string): Promise; + sendTyping(roomId: string, isTyping: boolean, timeoutMs: number, callback?: MatrixCallback): Promise; + setAccountData(eventType: EventType, contents: object, callback?: MatrixCallback): Promise; + setAvatarUrl(url: string, callback?: MatrixCallback): Promise; + setDeviceBlocked(userId: string, deviceId: string, blocked?: boolean): Promise; + setDeviceDetails(device_id: string, body: object): Promise; + setDeviceKnown(userId: string, deviceId: string, known?: boolean): Promise; + setDeviceVerified(userId: string, deviceId: string, verified?: boolean): Promise; + setDisplayName(name: string, callback?: MatrixCallback): Promise; + setForceTURN(forceTURN: boolean): void; + setGlobalBlacklistUnverifiedDevices(value: boolean): void; + setGroupJoinPolicy(groupId: string, policy: object): Promise; + setGroupProfile(groupId: string, profile: { + name: string // Name of the group + avatar_url: string // MXC avatar URL + short_description: string // A short description of the room + long_description: string // A longer HTML description of the room + }): Promise; + setGroupPublicity(groupId: string, isPublic: boolean): Promise; + setGuest(isGuest: boolean): void; + setGuestAccess(roomId: string, opts: { + allowJoin: boolean // True to allow guests to join this room. This implicitly gives guests write access. If false or not given, guests are explicitly forbidden from joining the room. + allowRead: boolean // True to set history visibility to be world_readable. This gives guests read access *from this point forward*. If false or not given, history visibility is not modified. + }): Promise; + setIgnoredUsers(userIds: string[], callback?: MatrixCallback): Promise; + setNotifTimelineSet(notifTimelineSet: EventTimelineSet): void; + setPassword(authDict: object, newPassword: string, callback?: MatrixCallback): Promise; + setPowerLevel( + roomId: string, userId: string, powerLevel: number, event: MatrixEvent, callback?: MatrixCallback, + ): Promise; + setPresence(opts: { + presence: string // One of "online", "offline" or "unavailable" + status_msg: string // The status message to attach. + }, callback: (...args: any[]) => any): Promise; + setProfileInfo(info: string, data: object, callback?: MatrixCallback): Promise; + setPusher(pusher: object, callback?: MatrixCallback): Promise; + setPushRuleActions( + scope: string, kind: string, ruleId: string, actions: string[], callback?: MatrixCallback, + ): Promise; + setPushRuleEnabled( + scope: string, kind: string, ruleId: string, enabled: boolean, callback?: MatrixCallback, + ): Promise; + setRoomAccountData( + roomId: string, eventType: EventType, content: object, callback?: MatrixCallback, + ): Promise; + setRoomDirectoryVisibility( + roomId: string, visibility: string, callback?: MatrixCallback, + ): Promise; + setRoomDirectoryVisibilityAppService( + networkId: string, roomId: string, visibility: string, callback?: MatrixCallback, + ): Promise; + setRoomEncryption(roomId: string, config: object): Promise; + setRoomMutePushRule(scope: string, roomId: string, mute: string): Promise; + setRoomName(roomId: string, name: string, callback?: MatrixCallback): Promise; + setRoomReadMarkers(roomId: string, eventId: string, rrEvent: string): Promise; + setRoomReadMarkersHttpRequest(roomId: string, rmEventId: string, rrEventId: string): Promise; + setRoomTag(roomId: string, tagName: string, metadata: object, callback?: MatrixCallback): Promise; + setRoomTopic(roomId: string, topic: string, callback?: MatrixCallback): Promise; + + startClient(opts?: number | { + initialSyncLimit?: number // The event limit= to apply to initial sync. Default: 8. + includeArchivedRooms?: boolean // True to put archived=true on the /initialSync request. Default: false. + resolveInvitesToProfiles?: boolean // True to do /profile requests on every invite event if the displayname/avatar_url is not known for this user ID. Default: false. + pendingEventOrdering?: string // Controls where pending messages appear in a room's timeline. If "chronological", messages will appear in the timeline when the call to sendEvent + pollTimeout?: number // The number of milliseconds to wait on /sync. Default: 30000 (30 seconds). + filter?: Filter // The filter to apply to /sync calls. This will override the opts.initialSyncLimit, which would normally result in a timeline limit filter. + disablePresence?: boolean // True to perform syncing without automatically updating presence. + lazyLoadMembers?: boolean // True to not load all membership events during initial sync but fetch them when needed by calling `loadOutOfBandMembers` This will override the filter + }): void; + stopClient(): void; + stopPeeking(): void; + submitMsisdnToken(sid: string, clientSecret: string, token: string): Promise; + supportsVoip(): boolean; + syncLeftRooms(): Promise; + turnServer(callback?: MatrixCallback): Promise; + unban(roomId: string, userId: string, callback?: MatrixCallback): Promise; + updateGroupRoomVisibility(groupId: string, roomId: string, isPublic: boolean): Promise; + upgradeRoom(roomId: string, newVersion: string): Promise<{ replacement_room: object }>; + uploadContent(file: Buffer, opts: { + includeFilename: boolean // if false will not send the filename, e.g for encrypted file uploads where filename leaks are undesirable. Defaults to true. + type: string // Content-type for the upload. Defaults to file.type, or applicaton/octet-stream. + rawResponse: boolean // Return the raw body, rather than parsing the JSON. Defaults to false (except on node.js, where it defaults to true for backwards compatibility). + onlyContentUri: boolean // Just return the content URI, rather than the whole body. Defaults to false (except on browsers, where it defaults to true for backwards compatibility). + callback: (...args: any[]) => any // Deprecated. Optional. The callback to invoke on success/failure. See the promise return values for more information. + progressHandler: (...args: any[]) => any // Optional. Called when a chunk of data has been uploaded, with an object containing the fields `loaded` (number of bytes transferred) + }): Promise; + uploadKeys(): object; + uploadKeysRequest(content: object, opts?: object, callback?: MatrixCallback): Promise; +} + +/** + * The following types are the classes that To Be Typing: + */ +export type CryptoDeviceInfo = any; +export type EventTimeline = any; +export type EventTimelineSet = any; +export type Group = any; +export type PushAction = any; +export type MatrixScheduler = any; +export type CryptoVerificationBase = any; +export type RoomSummary = any; +export type EventStatus = any; + +export interface CreateRoomOptions { + invite: string[]; // A list of user IDs to invite to this room. + name: string; // The name to give this room. + room_alias_name: string; // The alias localpart to assign to this room. + topic: string; // The topic to give this room. + visibility: string; // Either 'public' or 'private'. +} + +export type FilterComponent = any; + +export class Filter { + static fromJson(userId: string, filterId: string, jsonObj: object): Filter; + + constructor( + userId: string, // The user ID for this filter. + filterId?: string // The filter ID if known. + ) + + filterRoomTimeline(events: MatrixEvent): MatrixEvent[]; + getDefinition(): object; + getFilterId(): null | number; + getRoomTimelineFilterComponent(): FilterComponent; + setDefinition(definition: object): void; + setIncludeLeaveRooms(includeLeave: boolean): void; + setTimelineLimit(limit: number): void; +} + +export class MatrixEvent { + event: object; // The raw (possibly encrypted) event. Do not access this property directly unless you absolutely have to. Prefer the getter methods defined + sender: RoomMember; // The room member who sent this event, or null e.g. this is a presence event. This is only guaranteed to be set for events that appear in + target: RoomMember; // The room member who is the target of this event, e.g. the invitee, the person being banned, etc. + status: EventStatus; // The sending status of the event. + error: Error; // most recent error associated with sending the event, if any + forwardLooking: boolean; // True if this event is 'forward looking', meaning that getDirectionalContent() will return event.content and not event.prev_content. + + constructor(event: object) +} + +export class RoomMember { + roomId: string; // The room ID for this member. + userId: string; // The user ID of this member. + typing: boolean; // True if the room member is currently typing. + name: string; // The human-readable name for this room member. This will be disambiguated with a suffix of " (@user_id:matrix.org)" if another member shares the same displayname. + rawDisplayName: string; // The ambiguous displayname of this room member. + powerLevel: number; // The power level for this room member. + powerLevelNorm: number; // The normalised power level (0-100) for this room member. + user: User; // The User object for this room member, if one exists. + membership: MembershipType; // The membership state for this room member e.g. 'join'. + events: object; // The events describing this RoomMember. + + constructor(roomId: string, userId: string) + + getAvatarUrl( + baseUrl: string, width: number, height: number, resizeMethod: string, allowDefault: boolean, allowDirectLinks: boolean + ): null | string; + getDMInviter(): string; + getLastModifiedTime(): number; + getMxcAvatarUrl(): string; + isOutOfBand(): boolean; + markOutOfBand(): void; + setMembershipEvent(event: MatrixEvent, roomState: RoomState): void; + setPowerLevelEvent(powerLevelEvent: MatrixEvent): void; + setTypingEvent(event: MatrixEvent): void; +} + +export class RoomState { + constructor(roomId?: string, oobMemberFlags?: object) + + clearOutOfBandMembers(): void; + clone(): RoomState; + getInvitedMemberCount(): number; + getInviteForThreePidToken(token: string): undefined | MatrixEvent; + getJoinedMemberCount(): number; + getLastModifiedTime(): number; + getMember(userId: string): RoomMember; + getMembers(): RoomMember[]; + getMembersExcept(excludedIds: string[]): RoomMember[]; + getSentinelMember(userId: string): RoomMember; + getStateEvents(eventType: EventType, stateKey: string): MatrixEvent | MatrixEvent[]; + getUserIdsWithDisplayName(displayName: string): string[]; + markOutOfBandMembersFailed(): void; + markOutOfBandMembersStarted(): void; + mayClientSendStateEvent(stateEventType: EventType, cli: MatrixClient): boolean; + maySendEvent(eventType: EventType, userId: string): boolean; + maySendMessage(userId: string): boolean; + maySendRedactionForEvent(mxEvent: MatrixEvent, userId: string): boolean; + maySendStateEvent(stateEventType: EventType, userId: string): boolean; + mayTriggerNotifOfType(notifLevelKey: string, userId: string): boolean; + needsOutOfBandMembers(): boolean; + setInvitedMemberCount(count: number): void; + setJoinedMemberCount(count: number): void; + setOutOfBandMembers(stateEvents: MatrixEvent): void; + setStateEvents(stateEvents: MatrixEvent): void; + setTypingEvent(event: MatrixEvent): void; + setUnknownStateEvents(events: MatrixEvent): void; +} + +export interface CreateClientOption { + accessToken?: string; + baseUrl?: string; + request?: any; + store?: any; + scheduler?: MatrixScheduler; + cryptoStore?: any; + userId?: string; +} + +export function createClient(ops: string | CreateClientOption): MatrixClient; diff --git a/types/matrix-js-sdk/matrix-js-sdk-tests.ts b/types/matrix-js-sdk/matrix-js-sdk-tests.ts new file mode 100644 index 0000000000..a36666d009 --- /dev/null +++ b/types/matrix-js-sdk/matrix-js-sdk-tests.ts @@ -0,0 +1,18 @@ +/** + * Converted from: + * + * + * Huan Feb 2020 + */ +import sdk from 'matrix-js-sdk'; + +const myUserId = "@example:localhost"; +const myAccessToken = "QGV4YW1wbGU6bG9jYWxob3N0.qPEvLuYfNBjxikiCjP"; + +const matrixClient = sdk.createClient({ + baseUrl: "http://localhost:8008", + accessToken: myAccessToken, + userId: myUserId, +}); + +matrixClient.startClient(10); // messages for each room. diff --git a/types/matrix-js-sdk/tsconfig.json b/types/matrix-js-sdk/tsconfig.json new file mode 100644 index 0000000000..c45451f630 --- /dev/null +++ b/types/matrix-js-sdk/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "esModuleInterop": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "matrix-js-sdk-tests.ts" + ] +} diff --git a/types/matrix-js-sdk/tslint.json b/types/matrix-js-sdk/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/matrix-js-sdk/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +}