Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update TypeScript config to strict mode #103

Merged
merged 8 commits into from
Aug 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion demo/src/components/CurrentSlide.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ interface Props {
export const CurrentSlide = ({ slides }: Props) => {
const containerRef = useRef<HTMLDivElement>(null);
const { self } = useMembers();
const slide = self?.location?.slide || 0;
const slide = parseInt(self?.location?.slide || '', 10) || 0;

useTrackCursor(containerRef);

Expand Down
2 changes: 1 addition & 1 deletion demo/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"jsx": "react-jsx",

/* Linting */
"strict": false,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
Expand Down
13 changes: 7 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"build": "npm run build:mjs && npm run build:cjs && npm run build:iife",
"build:mjs": "npx tsc --project tsconfig.mjs.json && cp res/package.mjs.json dist/mjs/package.json",
"build:cjs": "npx tsc --project tsconfig.cjs.json && cp res/package.cjs.json dist/cjs/package.json",
"build:iife": "rm -rf dist/iife && npx tsc --project tsconfig.iife.json && rollup dist/iife/index.js --file dist/iife/index.bundle.js --format iife --name Spaces -e ably -g ably:Ably",
"build:iife": "rm -rf dist/iife && npx tsc --project tsconfig.iife.json && rollup -c",
"prepare": "husky install"
},
"exports": {
Expand Down Expand Up @@ -49,6 +49,7 @@
"husky": "^8.0.0",
"mock-socket": "^9.1.5",
"prettier": "^2.8.3",
"rollup": "^3.28.0",
"typescript": "^4.9.5",
"vitest": "^0.29.8"
},
Expand Down
13 changes: 13 additions & 0 deletions rollup.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export default {
input: 'dist/iife/index.js',
output: {
format: 'iife',
name: 'Spaces',
file: 'dist/iife/index.bundle.js',
globals: {
ably: 'Ably',
nanoid: 'nanoid',
},
},
external: ['ably', 'nanoid'],
};
6 changes: 3 additions & 3 deletions src/CursorBatching.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Types } from 'ably';

import { CURSOR_UPDATE } from './Cursors.js';
import { CURSOR_UPDATE } from './CursorConstants.js';
import type { CursorUpdate } from './types.js';
import type { CursorsOptions } from './types.js';

Expand Down Expand Up @@ -44,14 +44,14 @@ export default class CursorBatching {
this.outgoingBuffers.push(value);
}

private async publishFromBuffer(channel, eventName: string) {
private async publishFromBuffer(channel: Types.RealtimeChannelPromise, eventName: string) {
if (!this.isRunning) {
this.isRunning = true;
await this.batchToChannel(channel, eventName);
}
}

private async batchToChannel(channel, eventName: string) {
private async batchToChannel(channel: Types.RealtimeChannelPromise, eventName: string) {
if (!this.hasMovement) {
this.isRunning = false;
return;
Expand Down
1 change: 1 addition & 0 deletions src/CursorConstants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const CURSOR_UPDATE = 'cursorUpdate';
9 changes: 2 additions & 7 deletions src/CursorDispensing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,8 @@ export default class CursorDispensing {
private buffer: Record<string, CursorUpdate[]> = {};
private handlerRunning: boolean = false;
private timerIds: ReturnType<typeof setTimeout>[] = [];
private emitCursorUpdate: (update: CursorUpdate) => void;
private getCurrentBatchTime: () => number;

constructor(emitCursorUpdate, getCurrentBatchTime) {
this.emitCursorUpdate = emitCursorUpdate;
this.getCurrentBatchTime = getCurrentBatchTime;
}
constructor(private emitCursorUpdate: (update: CursorUpdate) => void, private getCurrentBatchTime: () => number) {}

emitFromBatch(batchDispenseInterval: number) {
if (!this.bufferHaveData()) {
Expand Down Expand Up @@ -66,7 +61,7 @@ export default class CursorDispensing {
}

processBatch(message: RealtimeMessage) {
const updates = message.data || [];
const updates: CursorUpdate[] = message.data || [];

updates.forEach((update) => {
const enhancedMsg = {
Expand Down
3 changes: 2 additions & 1 deletion src/Cursors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { it, describe, expect, vi, beforeEach, vitest, afterEach } from 'vitest'
import { Realtime, Types } from 'ably/promises';

import Space from './Space.js';
import Cursors, { CURSOR_UPDATE } from './Cursors.js';
import Cursors from './Cursors.js';
import { CURSOR_UPDATE } from './CursorConstants.js';
import { createPresenceMessage } from './utilities/test/fakes.js';
import CursorBatching from './CursorBatching.js';
import CursorDispensing from './CursorDispensing.js';
Expand Down
41 changes: 23 additions & 18 deletions src/Cursors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import EventEmitter, {
type EventListener,
} from './utilities/EventEmitter.js';
import CursorHistory from './CursorHistory.js';
import { CURSOR_UPDATE } from './CursorConstants.js';

import type { CursorsOptions, CursorUpdate } from './types.js';
import type { RealtimeMessage } from './utilities/types.js';
Expand All @@ -18,22 +19,6 @@ type CursorsEventMap = {
cursorsUpdate: CursorUpdate;
};

export const CURSOR_UPDATE = 'cursorUpdate';

const emitterHasListeners = (emitter) => {
const flattenEvents = (obj) =>
Object.entries(obj)
.map((_, v) => v)
.flat();

return (
emitter.any.length > 0 ||
emitter.anyOnce.length > 0 ||
flattenEvents(emitter.events).length > 0 ||
flattenEvents(emitter.eventsOnce).length > 0
);
};

export default class Cursors extends EventEmitter<CursorsEventMap> {
private readonly cursorBatching: CursorBatching;
private readonly cursorDispensing: CursorDispensing;
Expand Down Expand Up @@ -92,9 +77,29 @@ export default class Cursors extends EventEmitter<CursorsEventMap> {

private isUnsubscribed() {
const channel = this.getChannel();
return !emitterHasListeners(channel['subscriptions']);

interface ChannelWithSubscriptions extends Types.RealtimeChannelPromise {
subscriptions: EventEmitter<{}>;
}

const subscriptions = (channel as ChannelWithSubscriptions).subscriptions;
return !this.emitterHasListeners(subscriptions);
}

private emitterHasListeners = (emitter: EventEmitter<{}>) => {
const flattenEvents = (obj: Record<string, Function[]>) =>
Object.entries(obj)
.map((_, v) => v)
.flat();

return (
emitter.any.length > 0 ||
emitter.anyOnce.length > 0 ||
flattenEvents(emitter.events).length > 0 ||
flattenEvents(emitter.eventsOnce).length > 0
);
};

subscribe<K extends EventKey<CursorsEventMap>>(
listenerOrEvents?: K | K[] | EventListener<CursorsEventMap[K]>,
listener?: EventListener<CursorsEventMap[K]>,
Expand Down Expand Up @@ -136,7 +141,7 @@ export default class Cursors extends EventEmitter<CursorsEventMap> {
}
}

const hasListeners = emitterHasListeners(this);
const hasListeners = this.emitterHasListeners(this);

if (!hasListeners) {
const channel = this.getChannel();
Expand Down
4 changes: 2 additions & 2 deletions src/Locations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,14 +117,14 @@ export default class Locations extends EventEmitter<LocationsEventMap> {
return this.space.members
.getAll()
.filter((member) => member.connectionId !== self?.connectionId)
.reduce((acc, member) => {
.reduce((acc: Record<string, unknown>, member: SpaceMember) => {
acc[member.connectionId] = member.location;
return acc;
}, {});
}

getAll(): Record<string, unknown> {
return this.space.members.getAll().reduce((acc, member) => {
return this.space.members.getAll().reduce((acc: Record<string, unknown>, member: SpaceMember) => {
acc[member.connectionId] = member.location;
return acc;
}, {});
Expand Down
6 changes: 5 additions & 1 deletion src/Space.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,11 @@ class Space extends EventEmitter<SpaceEventsMap> {
return new Promise((resolve) => {
const presence = this.channel.presence;

presence['subscriptions'].once('enter', async () => {
interface PresenceWithSubscriptions extends Types.RealtimePresencePromise {
subscriptions: EventEmitter<{ enter: [unknown] }>;
}

(presence as PresenceWithSubscriptions).subscriptions.once('enter', async () => {
const presenceMessages = await presence.get();
const members = this.members.mapPresenceMembersToSpaceMembers(presenceMessages);

Expand Down
16 changes: 10 additions & 6 deletions src/Spaces.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { it, describe, expect, expectTypeOf, vi, beforeEach } from 'vitest';
import { Realtime, Types } from 'ably/promises';

import Spaces from './Spaces.js';
import Spaces, { type ClientWithOptions } from './Spaces.js';

interface SpacesTestContext {
client: Types.RealtimePromise;
client: ClientWithOptions;
}

vi.mock('ably/promises');

describe('Spaces', () => {
beforeEach<SpacesTestContext>((context) => {
context.client = new Realtime({ key: 'asd' });
context.client = new Realtime({ key: 'asd' }) as ClientWithOptions;
});

it<SpacesTestContext>('expects the injected client to be of the type RealtimePromise', ({ client }) => {
Expand All @@ -32,14 +32,18 @@ describe('Spaces', () => {

it<SpacesTestContext>('applies the agent header to an existing SDK instance', ({ client }) => {
const spaces = new Spaces(client);
expect(client['options'].agents).toEqual({ 'ably-spaces': spaces.version, 'space-custom-client': true });
expect(client.options.agents).toEqual({
'ably-spaces': spaces.version,
'space-custom-client': true,
});
});

it<SpacesTestContext>('extend the agents array when it already exists', ({ client }) => {
client['options']['agents'] = { 'some-client': '1.2.3' };
(client as ClientWithOptions).options.agents = { 'some-client': '1.2.3' };
const spaces = new Spaces(client);
const ablyClient = spaces.ably as ClientWithOptions;

expect(spaces.ably['options'].agents).toEqual({
expect(ablyClient.options.agents).toEqual({
'some-client': '1.2.3',
'ably-spaces': spaces.version,
'space-custom-client': true,
Expand Down
8 changes: 7 additions & 1 deletion src/Spaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ import Space from './Space.js';
import type { SpaceOptions } from './types.js';
import type { Subset } from './utilities/types.js';

export interface ClientWithOptions extends Types.RealtimePromise {
options: {
agents?: Record<string, string | boolean>;
};
}

class Spaces {
private spaces: Record<string, Space> = {};
ably: Types.RealtimePromise;
Expand All @@ -13,7 +19,7 @@ class Spaces {

constructor(client: Types.RealtimePromise) {
this.ably = client;
this.addAgent(this.ably['options']);
this.addAgent((this.ably as ClientWithOptions)['options']);
this.ably.time();
}

Expand Down
Loading
Loading