Skip to content

Commit

Permalink
Enable better tree shaking (#3356)
Browse files Browse the repository at this point in the history
  • Loading branch information
t3chguy committed May 15, 2023
1 parent e6a3b0e commit 6ef9f6c
Show file tree
Hide file tree
Showing 14 changed files with 69 additions and 70 deletions.
4 changes: 2 additions & 2 deletions src/content-repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import * as utils from "./utils";
import { encodeParams } from "./utils";

/**
* Get the HTTP URL for an MXC URI.
Expand Down Expand Up @@ -74,6 +74,6 @@ export function getHttpUriForMxc(
serverAndMediaId = serverAndMediaId.slice(0, fragmentOffset);
}

const urlParams = Object.keys(params).length === 0 ? "" : "?" + utils.encodeParams(params);
const urlParams = Object.keys(params).length === 0 ? "" : "?" + encodeParams(params);
return baseUrl + prefix + serverAndMediaId + urlParams + fragment;
}
4 changes: 2 additions & 2 deletions src/crypto/store/indexeddb-crypto-store-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ limitations under the License.
*/

import { logger, PrefixedLogger } from "../../logger";
import * as utils from "../../utils";
import { deepCompare } from "../../utils";
import {
CryptoStore,
IDeviceData,
Expand Down Expand Up @@ -158,7 +158,7 @@ export class Backend implements CryptoStore {

const existing = cursor.value;

if (utils.deepCompare(existing.requestBody, requestBody)) {
if (deepCompare(existing.requestBody, requestBody)) {
// got a match
callback(existing);
return;
Expand Down
6 changes: 3 additions & 3 deletions src/crypto/store/memory-crypto-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ limitations under the License.
*/

import { logger } from "../../logger";
import * as utils from "../../utils";
import { deepCompare, promiseTry } from "../../utils";
import {
CryptoStore,
IDeviceData,
Expand Down Expand Up @@ -90,7 +90,7 @@ export class MemoryCryptoStore implements CryptoStore {
public getOrAddOutgoingRoomKeyRequest(request: OutgoingRoomKeyRequest): Promise<OutgoingRoomKeyRequest> {
const requestBody = request.requestBody;

return utils.promiseTry(() => {
return promiseTry(() => {
// first see if we already have an entry for this request.
const existing = this._getOutgoingRoomKeyRequest(requestBody);

Expand Down Expand Up @@ -138,7 +138,7 @@ export class MemoryCryptoStore implements CryptoStore {
// eslint-disable-next-line @typescript-eslint/naming-convention
private _getOutgoingRoomKeyRequest(requestBody: IRoomKeyRequestBody): OutgoingRoomKeyRequest | null {
for (const existing of this.outgoingRoomKeyRequests) {
if (utils.deepCompare(existing.requestBody, requestBody)) {
if (deepCompare(existing.requestBody, requestBody)) {
return existing;
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/http-api/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ limitations under the License.
* This is an internal module. See {@link MatrixHttpApi} for the public class.
*/

import * as utils from "../utils";
import { checkObjectHasKeys, encodeParams } from "../utils";
import { TypedEventEmitter } from "../models/typed-event-emitter";
import { Method } from "./method";
import { ConnectionError, MatrixError } from "./errors";
Expand All @@ -45,7 +45,7 @@ export class FetchHttpApi<O extends IHttpOpts> {
private eventEmitter: TypedEventEmitter<HttpApiEvent, HttpApiEventHandlerMap>,
public readonly opts: O,
) {
utils.checkObjectHasKeys(opts, ["baseUrl", "prefix"]);
checkObjectHasKeys(opts, ["baseUrl", "prefix"]);
opts.onlyData = !!opts.onlyData;
opts.useAuthorizationHeader = opts.useAuthorizationHeader ?? true;
}
Expand Down Expand Up @@ -304,7 +304,7 @@ export class FetchHttpApi<O extends IHttpOpts> {
public getUrl(path: string, queryParams?: QueryDict, prefix?: string, baseUrl?: string): URL {
const url = new URL((baseUrl ?? this.opts.baseUrl) + (prefix ?? this.opts.prefix) + path);
if (queryParams) {
utils.encodeParams(queryParams, url.searchParams);
encodeParams(queryParams, url.searchParams);
}
return url;
}
Expand Down
26 changes: 13 additions & 13 deletions src/http-api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ limitations under the License.
import { FetchHttpApi } from "./fetch";
import { FileType, IContentUri, IHttpOpts, Upload, UploadOpts, UploadResponse } from "./interface";
import { MediaPrefix } from "./prefix";
import * as utils from "../utils";
import { defer, QueryDict, removeElement } from "../utils";
import * as callbacks from "../realtime-callbacks";
import { Method } from "./method";
import { ConnectionError } from "./errors";
Expand Down Expand Up @@ -58,14 +58,14 @@ export class MatrixHttpApi<O extends IHttpOpts> extends FetchHttpApi<O> {
total: 0,
abortController,
} as Upload;
const defer = utils.defer<UploadResponse>();
const deferred = defer<UploadResponse>();

if (global.XMLHttpRequest) {
const xhr = new global.XMLHttpRequest();

const timeoutFn = function (): void {
xhr.abort();
defer.reject(new Error("Timeout"));
deferred.reject(new Error("Timeout"));
};

// set an initial timeout of 30s; we'll advance it each time we get a progress notification
Expand All @@ -84,16 +84,16 @@ export class MatrixHttpApi<O extends IHttpOpts> extends FetchHttpApi<O> {
}

if (xhr.status >= 400) {
defer.reject(parseErrorResponse(xhr, xhr.responseText));
deferred.reject(parseErrorResponse(xhr, xhr.responseText));
} else {
defer.resolve(JSON.parse(xhr.responseText));
deferred.resolve(JSON.parse(xhr.responseText));
}
} catch (err) {
if ((<Error>err).name === "AbortError") {
defer.reject(err);
deferred.reject(err);
return;
}
defer.reject(new ConnectionError("request failed", <Error>err));
deferred.reject(new ConnectionError("request failed", <Error>err));
}
break;
}
Expand Down Expand Up @@ -131,7 +131,7 @@ export class MatrixHttpApi<O extends IHttpOpts> extends FetchHttpApi<O> {
xhr.abort();
});
} else {
const queryParams: utils.QueryDict = {};
const queryParams: QueryDict = {};
if (includeFilename && fileName) {
queryParams.filename = fileName;
}
Expand All @@ -146,16 +146,16 @@ export class MatrixHttpApi<O extends IHttpOpts> extends FetchHttpApi<O> {
.then((response) => {
return this.opts.onlyData ? <UploadResponse>response : response.json();
})
.then(defer.resolve, defer.reject);
.then(deferred.resolve, deferred.reject);
}

// remove the upload from the list on completion
upload.promise = defer.promise.finally(() => {
utils.removeElement(this.uploads, (elem) => elem === upload);
upload.promise = deferred.promise.finally(() => {
removeElement(this.uploads, (elem) => elem === upload);
});
abortController.signal.addEventListener("abort", () => {
utils.removeElement(this.uploads, (elem) => elem === upload);
defer.reject(new DOMException("Aborted", "AbortError"));
removeElement(this.uploads, (elem) => elem === upload);
deferred.reject(new DOMException("Aborted", "AbortError"));
});
this.uploads.push(upload);
return upload.promise;
Expand Down
4 changes: 2 additions & 2 deletions src/models/read-receipt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
WrappedReceipt,
} from "../@types/read_receipts";
import { ListenerMap, TypedEventEmitter } from "./typed-event-emitter";
import * as utils from "../utils";
import { isSupportedReceiptType } from "../utils";
import { MatrixEvent } from "./event";
import { EventType } from "../@types/event";
import { EventTimelineSet } from "./event-timeline-set";
Expand Down Expand Up @@ -267,7 +267,7 @@ export abstract class ReadReceipt<
public getUsersReadUpTo(event: MatrixEvent): string[] {
return this.getReceiptsForEvent(event)
.filter(function (receipt) {
return utils.isSupportedReceiptType(receipt.type);
return isSupportedReceiptType(receipt.type);
})
.map(function (receipt) {
return receipt.userId;
Expand Down
14 changes: 7 additions & 7 deletions src/models/room-member.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ limitations under the License.
*/

import { getHttpUriForMxc } from "../content-repo";
import * as utils from "../utils";
import { removeDirectionOverrideChars, removeHiddenChars } from "../utils";
import { User } from "./user";
import { MatrixEvent } from "./event";
import { RoomState } from "./room-state";
Expand Down Expand Up @@ -206,8 +206,8 @@ export class RoomMember extends TypedEventEmitter<RoomMemberEvent, RoomMemberEve

// not quite raw: we strip direction override chars so it can safely be inserted into
// blocks of text without breaking the text direction
this.rawDisplayName = utils.removeDirectionOverrideChars(event.getDirectionalContent().displayname ?? "");
if (!this.rawDisplayName || !utils.removeHiddenChars(this.rawDisplayName)) {
this.rawDisplayName = removeDirectionOverrideChars(event.getDirectionalContent().displayname ?? "");
if (!this.rawDisplayName || !removeHiddenChars(this.rawDisplayName)) {
this.rawDisplayName = this.userId;
}

Expand Down Expand Up @@ -407,7 +407,7 @@ function shouldDisambiguate(selfUserId: string, displayName?: string, roomState?

// First check if the displayname is something we consider truthy
// after stripping it of zero width characters and padding spaces
if (!utils.removeHiddenChars(displayName)) return false;
if (!removeHiddenChars(displayName)) return false;

if (!roomState) return false;

Expand All @@ -432,11 +432,11 @@ function shouldDisambiguate(selfUserId: string, displayName?: string, roomState?
function calculateDisplayName(selfUserId: string, displayName: string | undefined, disambiguate: boolean): string {
if (!displayName || displayName === selfUserId) return selfUserId;

if (disambiguate) return utils.removeDirectionOverrideChars(displayName) + " (" + selfUserId + ")";
if (disambiguate) return removeDirectionOverrideChars(displayName) + " (" + selfUserId + ")";

// First check if the displayname is something we consider truthy
// after stripping it of zero width characters and padding spaces
if (!utils.removeHiddenChars(displayName)) return selfUserId;
if (!removeHiddenChars(displayName)) return selfUserId;

// We always strip the direction override characters (LRO and RLO).
// These override the text direction for all subsequent characters
Expand All @@ -449,5 +449,5 @@ function calculateDisplayName(selfUserId: string, displayName: string | undefine
// names should flip into the correct direction automatically based on
// the characters, and you can still embed rtl in ltr or vice versa
// with the embed chars or marker chars.
return utils.removeDirectionOverrideChars(displayName);
return removeDirectionOverrideChars(displayName);
}
12 changes: 6 additions & 6 deletions src/models/room-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ limitations under the License.

import { RoomMember } from "./room-member";
import { logger } from "../logger";
import * as utils from "../utils";
import { isNumber, removeHiddenChars } from "../utils";
import { EventType, UNSTABLE_MSC2716_MARKER } from "../@types/event";
import { IEvent, MatrixEvent, MatrixEventEvent } from "./event";
import { MatrixClient } from "../client";
Expand Down Expand Up @@ -759,7 +759,7 @@ export class RoomState extends TypedEventEmitter<EmittedEvents, EventHandlerMap>
* @returns An array of user IDs or an empty array.
*/
public getUserIdsWithDisplayName(displayName: string): string[] {
return this.displayNameToUserIds.get(utils.removeHiddenChars(displayName)) ?? [];
return this.displayNameToUserIds.get(removeHiddenChars(displayName)) ?? [];
}

/**
Expand Down Expand Up @@ -798,7 +798,7 @@ export class RoomState extends TypedEventEmitter<EmittedEvents, EventHandlerMap>
}

let requiredLevel = 50;
if (utils.isNumber(powerLevels[action])) {
if (isNumber(powerLevels[action])) {
requiredLevel = powerLevels[action]!;
}

Expand Down Expand Up @@ -928,7 +928,7 @@ export class RoomState extends TypedEventEmitter<EmittedEvents, EventHandlerMap>
powerLevelsEvent &&
powerLevelsEvent.getContent() &&
powerLevelsEvent.getContent().notifications &&
utils.isNumber(powerLevelsEvent.getContent().notifications[notifLevelKey])
isNumber(powerLevelsEvent.getContent().notifications[notifLevelKey])
) {
notifLevel = powerLevelsEvent.getContent().notifications[notifLevelKey];
}
Expand Down Expand Up @@ -1058,7 +1058,7 @@ export class RoomState extends TypedEventEmitter<EmittedEvents, EventHandlerMap>
// We clobber the user_id > name lookup but the name -> [user_id] lookup
// means we need to remove that user ID from that array rather than nuking
// the lot.
const strippedOldName = utils.removeHiddenChars(oldName);
const strippedOldName = removeHiddenChars(oldName);

const existingUserIds = this.displayNameToUserIds.get(strippedOldName);
if (existingUserIds) {
Expand All @@ -1070,7 +1070,7 @@ export class RoomState extends TypedEventEmitter<EmittedEvents, EventHandlerMap>

this.userIdsToDisplayNames[userId] = displayName;

const strippedDisplayname = displayName && utils.removeHiddenChars(displayName);
const strippedDisplayname = displayName && removeHiddenChars(displayName);
// an empty stripped displayname (undefined/'') will be set to MXID in room-member.js
if (strippedDisplayname) {
const arr = this.displayNameToUserIds.get(strippedDisplayname) ?? [];
Expand Down
6 changes: 3 additions & 3 deletions src/models/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
} from "./event-timeline-set";
import { Direction, EventTimeline } from "./event-timeline";
import { getHttpUriForMxc } from "../content-repo";
import * as utils from "../utils";
import { compare, removeElement } from "../utils";
import { normalize, noUnsafeEventProps } from "../utils";
import { IEvent, IThreadBundledRelationship, MatrixEvent, MatrixEventEvent, MatrixEventHandlerMap } from "./event";
import { EventStatus } from "./event-status";
Expand Down Expand Up @@ -733,7 +733,7 @@ export class Room extends ReadReceipt<RoomEmittedEvents, RoomEventHandlerMap> {
);
}

const removed = utils.removeElement(
const removed = removeElement(
this.pendingEventList,
function (ev) {
return ev.getId() == eventId;
Expand Down Expand Up @@ -3267,7 +3267,7 @@ export class Room extends ReadReceipt<RoomEmittedEvents, RoomEventHandlerMap> {
return true;
});
// make sure members have stable order
otherMembers.sort((a, b) => utils.compare(a.userId, b.userId));
otherMembers.sort((a, b) => compare(a.userId, b.userId));
// only 5 first members, immitate summaryHeroes
otherMembers = otherMembers.slice(0, 5);
otherNames = otherMembers.map((m) => m.name);
Expand Down
11 changes: 5 additions & 6 deletions src/scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,10 @@ limitations under the License.
* This is an internal module which manages queuing, scheduling and retrying
* of requests.
*/
import * as utils from "./utils";
import { logger } from "./logger";
import { MatrixEvent } from "./models/event";
import { EventType } from "./@types/event";
import { IDeferred } from "./utils";
import { defer, IDeferred, removeElement } from "./utils";
import { ConnectionError, MatrixError } from "./http-api";
import { ISendEventResponse } from "./@types/requests";

Expand Down Expand Up @@ -175,7 +174,7 @@ export class MatrixScheduler<T = ISendEventResponse> {
return false;
}
let removed = false;
utils.removeElement(this.queues[name], (element) => {
removeElement(this.queues[name], (element) => {
if (element.event.getId() === event.getId()) {
// XXX we should probably reject the promise?
// https://github.com/matrix-org/matrix-js-sdk/issues/496
Expand Down Expand Up @@ -214,15 +213,15 @@ export class MatrixScheduler<T = ISendEventResponse> {
if (!this.queues[queueName]) {
this.queues[queueName] = [];
}
const defer = utils.defer<T>();
const deferred = defer<T>();
this.queues[queueName].push({
event: event,
defer: defer,
defer: deferred,
attempts: 0,
});
debuglog("Queue algorithm dumped event %s into queue '%s'", event.getId(), queueName);
this.startProcessingQueues();
return defer.promise;
return deferred.promise;
}

private startProcessingQueues(): void {
Expand Down
6 changes: 3 additions & 3 deletions src/sliding-sync-sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ limitations under the License.
import type { SyncCryptoCallbacks } from "./common-crypto/CryptoBackend";
import { NotificationCountType, Room, RoomEvent } from "./models/room";
import { logger } from "./logger";
import * as utils from "./utils";
import { promiseMapSeries } from "./utils";
import { EventTimeline } from "./models/event-timeline";
import { ClientEvent, IStoredClientOpts, MatrixClient } from "./client";
import {
Expand Down Expand Up @@ -726,8 +726,8 @@ export class SlidingSyncSdk {
}
};

await utils.promiseMapSeries(stateEvents, processRoomEvent);
await utils.promiseMapSeries(timelineEvents, processRoomEvent);
await promiseMapSeries(stateEvents, processRoomEvent);
await promiseMapSeries(timelineEvents, processRoomEvent);
ephemeralEvents.forEach(function (e) {
client.emit(ClientEvent.Event, e);
});
Expand Down
Loading

0 comments on commit 6ef9f6c

Please sign in to comment.