140: Fix imports r=D4nte a=D4nte

Resolves #112.

Co-authored-by: Franck Royer <franck@status.im>
This commit is contained in:
bors[bot] 2021-05-10 09:59:18 +00:00 committed by GitHub
commit dcae6c7abf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 126 additions and 108 deletions

View File

@ -11,7 +11,7 @@
"dependencies": { "dependencies": {
"libp2p-tcp": "^0.15.4", "libp2p-tcp": "^0.15.4",
"prompt-sync": "^4.2.0", "prompt-sync": "^4.2.0",
"waku": "../../build/main/lib" "waku": "../../build/main"
}, },
"devDependencies": { "devDependencies": {
"@istanbuljs/nyc-config-typescript": "^1.0.1", "@istanbuljs/nyc-config-typescript": "^1.0.1",
@ -41,7 +41,10 @@
"node": ">=14" "node": ">=14"
} }
}, },
"../../build/main/lib": {}, "../../build/main": {},
"../../build/main/lib": {
"extraneous": true
},
"node_modules/@babel/code-frame": { "node_modules/@babel/code-frame": {
"version": "7.12.11", "version": "7.12.11",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz",
@ -7507,7 +7510,7 @@
"dev": true "dev": true
}, },
"node_modules/waku": { "node_modules/waku": {
"resolved": "../../build/main/lib", "resolved": "../../build/main",
"link": true "link": true
}, },
"node_modules/which": { "node_modules/which": {
@ -13561,7 +13564,7 @@
"dev": true "dev": true
}, },
"waku": { "waku": {
"version": "file:../../build/main/lib" "version": "file:../../build/main"
}, },
"which": { "which": {
"version": "2.0.2", "version": "2.0.2",

View File

@ -33,7 +33,7 @@
"dependencies": { "dependencies": {
"libp2p-tcp": "^0.15.4", "libp2p-tcp": "^0.15.4",
"prompt-sync": "^4.2.0", "prompt-sync": "^4.2.0",
"waku": "../../build/main/lib" "waku": "../../build/main"
}, },
"devDependencies": { "devDependencies": {
"@istanbuljs/nyc-config-typescript": "^1.0.1", "@istanbuljs/nyc-config-typescript": "^1.0.1",

View File

@ -1,12 +1,16 @@
import { expect } from 'chai'; import { expect } from 'chai';
import { ChatMessage } from 'waku/chat_message'; import { ChatMessage } from 'waku';
import { formatMessage } from './chat'; import { formatMessage } from './chat';
describe('CLI Chat app', () => { describe('CLI Chat app', () => {
it('Format message', () => { it('Format message', () => {
const date = new Date(234325324); const date = new Date(234325324);
const chatMessage = new ChatMessage(date, 'alice', 'Hello world!'); const chatMessage = ChatMessage.fromUtf8String(
date,
'alice',
'Hello world!'
);
expect(formatMessage(chatMessage)).to.match(/^<.*> alice: Hello world!$/); expect(formatMessage(chatMessage)).to.match(/^<.*> alice: Hello world!$/);
}); });

View File

@ -3,10 +3,7 @@ import util from 'util';
import TCP from 'libp2p-tcp'; import TCP from 'libp2p-tcp';
import { multiaddr, Multiaddr } from 'multiaddr'; import { multiaddr, Multiaddr } from 'multiaddr';
import { ChatMessage } from 'waku/chat_message'; import { ChatMessage, StoreCodec, Waku, WakuMessage } from 'waku';
import Waku from 'waku/waku';
import { WakuMessage } from 'waku/waku_message';
import { StoreCodec } from 'waku/waku_store';
const ChatContentTopic = 'dingpu'; const ChatContentTopic = 'dingpu';
@ -84,7 +81,7 @@ export default async function startChat(): Promise<void> {
rl.prompt(); rl.prompt();
for await (const line of rl) { for await (const line of rl) {
rl.prompt(); rl.prompt();
const chatMessage = new ChatMessage(new Date(), nick, line); const chatMessage = ChatMessage.fromUtf8String(new Date(), nick, line);
const msg = WakuMessage.fromBytes(chatMessage.encode(), ChatContentTopic); const msg = WakuMessage.fromBytes(chatMessage.encode(), ChatContentTopic);
await waku.relay.send(msg); await waku.relay.send(msg);
@ -129,5 +126,5 @@ export function formatMessage(chatMsg: ChatMessage): string {
minute: '2-digit', minute: '2-digit',
hour12: false, hour12: false,
}); });
return `<${timestamp}> ${chatMsg.nick}: ${chatMsg.message}`; return `<${timestamp}> ${chatMsg.nick}: ${chatMsg.payloadAsUtf8}`;
} }

View File

@ -11,7 +11,7 @@
"react": "^16.14.0", "react": "^16.14.0",
"react-dom": "^16.14.0", "react-dom": "^16.14.0",
"server-name-generator": "^1.0.5", "server-name-generator": "^1.0.5",
"waku": "../../build/main/lib", "waku": "../../build/main",
"web-vitals": "^1.1.1" "web-vitals": "^1.1.1"
}, },
"devDependencies": { "devDependencies": {
@ -30,7 +30,10 @@
"typescript": "^4.2.4" "typescript": "^4.2.4"
} }
}, },
"../../build/main/lib": {}, "../../build/main": {},
"../../build/main/lib": {
"extraneous": true
},
"node_modules/@babel/code-frame": { "node_modules/@babel/code-frame": {
"version": "7.12.13", "version": "7.12.13",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.13.tgz",
@ -22883,7 +22886,7 @@
} }
}, },
"node_modules/waku": { "node_modules/waku": {
"resolved": "../../build/main/lib", "resolved": "../../build/main",
"link": true "link": true
}, },
"node_modules/walker": { "node_modules/walker": {
@ -43268,7 +43271,7 @@
} }
}, },
"waku": { "waku": {
"version": "file:../../build/main/lib" "version": "file:../../build/main"
}, },
"walker": { "walker": {
"version": "1.0.7", "version": "1.0.7",

View File

@ -8,7 +8,7 @@
"react": "^16.14.0", "react": "^16.14.0",
"react-dom": "^16.14.0", "react-dom": "^16.14.0",
"server-name-generator": "^1.0.5", "server-name-generator": "^1.0.5",
"waku": "../../build/main/lib", "waku": "../../build/main",
"web-vitals": "^1.1.1" "web-vitals": "^1.1.1"
}, },
"devDependencies": { "devDependencies": {

View File

@ -2,13 +2,9 @@ import { multiaddr } from 'multiaddr';
import PeerId from 'peer-id'; import PeerId from 'peer-id';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import './App.css'; import './App.css';
import { ChatMessage } from './ChatMessage'; import { ChatMessage, WakuMessage, StoreCodec, Waku } from 'waku';
import { ChatMessage as WakuChatMessage } from 'waku/chat_message';
import { WakuMessage } from 'waku/waku_message';
import { StoreCodec } from 'waku/waku_store';
import handleCommand from './command'; import handleCommand from './command';
import Room from './Room'; import Room from './Room';
import Waku from 'waku/waku';
import { WakuContext } from './WakuContext'; import { WakuContext } from './WakuContext';
import { ThemeProvider } from '@livechat/ui-kit'; import { ThemeProvider } from '@livechat/ui-kit';
import { generate } from 'server-name-generator'; import { generate } from 'server-name-generator';
@ -53,9 +49,7 @@ export default function App() {
useEffect(() => { useEffect(() => {
const handleRelayMessage = (wakuMsg: WakuMessage) => { const handleRelayMessage = (wakuMsg: WakuMessage) => {
if (wakuMsg.payload) { if (wakuMsg.payload) {
const chatMsg = ChatMessage.fromWakuChatMessage( const chatMsg = ChatMessage.decode(wakuMsg.payload);
WakuChatMessage.decode(wakuMsg.payload)
);
if (chatMsg) { if (chatMsg) {
setNewMessages([chatMsg]); setNewMessages([chatMsg]);
} }
@ -77,10 +71,7 @@ export default function App() {
const messages = response const messages = response
.map((wakuMsg) => wakuMsg.payload) .map((wakuMsg) => wakuMsg.payload)
.filter((payload) => !!payload) .filter((payload) => !!payload)
.map((payload) => WakuChatMessage.decode(payload as Uint8Array)) .map((payload) => ChatMessage.decode(payload as Uint8Array));
.map((wakuChatMessage) =>
ChatMessage.fromWakuChatMessage(wakuChatMessage)
);
setArchivedMessages(messages); setArchivedMessages(messages);
} }
} catch (e) { } catch (e) {
@ -132,7 +123,7 @@ export default function App() {
setNick setNick
); );
const commandMessages = response.map((msg) => { const commandMessages = response.map((msg) => {
return new ChatMessage(new Date(), new Date(), command, msg); return ChatMessage.fromUtf8String(new Date(), command, msg);
}); });
setNewMessages(commandMessages); setNewMessages(commandMessages);
}} }}

View File

@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { ChatMessage } from './ChatMessage'; import { ChatMessage } from 'waku';
import { import {
Message, Message,
MessageText, MessageText,
@ -43,14 +43,14 @@ export default function ChatList(props: Props) {
{currentMessageGroup.map((currentMessage) => ( {currentMessageGroup.map((currentMessage) => (
<Message <Message
key={ key={
currentMessage.receivedTimestampMs.valueOf() + currentMessage.timestamp.valueOf() +
currentMessage.nick + currentMessage.nick +
currentMessage.message currentMessage.payloadAsUtf8
} }
authorName={currentMessage.nick} authorName={currentMessage.nick}
date={formatDisplayDate(currentMessage)} date={formatDisplayDate(currentMessage)}
> >
<MessageText>{currentMessage.message}</MessageText> <MessageText>{currentMessage.payloadAsUtf8}</MessageText>
</Message> </Message>
))} ))}
</MessageGroup> </MessageGroup>
@ -84,7 +84,7 @@ function groupMessagesBySender(messageArray: ChatMessage[]): ChatMessage[][] {
} }
function formatDisplayDate(message: ChatMessage): string { function formatDisplayDate(message: ChatMessage): string {
return message.sentTimestamp.toLocaleString([], { return message.timestamp.toLocaleString([], {
month: 'short', month: 'short',
day: 'numeric', day: 'numeric',
hour: 'numeric', hour: 'numeric',
@ -127,14 +127,14 @@ function copyMergeUniqueReplace(
copy.push(msg); copy.push(msg);
} }
}); });
copy.sort((a, b) => a.sentTimestamp.valueOf() - b.sentTimestamp.valueOf()); copy.sort((a, b) => a.timestamp.valueOf() - b.timestamp.valueOf());
return copy; return copy;
} }
function isEqual(lhs: ChatMessage, rhs: ChatMessage): boolean { function isEqual(lhs: ChatMessage, rhs: ChatMessage): boolean {
return ( return (
lhs.nick === rhs.nick && lhs.nick === rhs.nick &&
lhs.message === rhs.message && lhs.payloadAsUtf8 === rhs.payloadAsUtf8 &&
lhs.sentTimestamp.toString() === rhs.sentTimestamp.toString() lhs.timestamp.toString() === rhs.timestamp.toString()
); );
} }

View File

@ -1,19 +0,0 @@
import { ChatMessage as WakuChatMessage } from 'waku/chat_message';
export class ChatMessage {
constructor(
public receivedTimestampMs: Date,
public sentTimestamp: Date,
public nick: string,
public message: string
) {}
static fromWakuChatMessage(wakuChatMessage: WakuChatMessage): ChatMessage {
return new ChatMessage(
new Date(),
wakuChatMessage.timestamp,
wakuChatMessage.nick,
wakuChatMessage.message
);
}
}

View File

@ -1,6 +1,4 @@
import { ChatMessage } from './ChatMessage'; import { ChatMessage, WakuMessage } from 'waku';
import { ChatMessage as WakuChatMessage } from 'waku/chat_message';
import { WakuMessage } from 'waku/waku_message';
import { ChatContentTopic } from './App'; import { ChatContentTopic } from './App';
import ChatList from './ChatList'; import ChatList from './ChatList';
import MessageInput from './MessageInput'; import MessageInput from './MessageInput';
@ -54,7 +52,7 @@ async function handleMessage(
if (message.startsWith('/')) { if (message.startsWith('/')) {
commandHandler(message); commandHandler(message);
} else { } else {
const chatMessage = new WakuChatMessage(new Date(), nick, message); const chatMessage = ChatMessage.fromUtf8String(new Date(), nick, message);
const wakuMsg = WakuMessage.fromBytes( const wakuMsg = WakuMessage.fromBytes(
chatMessage.encode(), chatMessage.encode(),
ChatContentTopic ChatContentTopic

View File

@ -1,5 +1,5 @@
import { createContext, useContext } from 'react'; import { createContext, useContext } from 'react';
import Waku from 'waku/waku'; import { Waku } from 'waku';
export type WakuContextType = { export type WakuContextType = {
waku?: Waku; waku?: Waku;

View File

@ -1,6 +1,6 @@
import { multiaddr } from 'multiaddr'; import { multiaddr } from 'multiaddr';
import PeerId from 'peer-id'; import PeerId from 'peer-id';
import Waku from 'waku/waku'; import { Waku } from 'waku';
function help(): string[] { function help(): string[] {
return [ return [

View File

@ -2,7 +2,7 @@ syntax = "proto3";
package chat.v2; package chat.v2;
message ChatMessageProto { message ChatMessage {
uint64 timestamp = 1; uint64 timestamp = 1;
string nick = 2; string nick = 2;
bytes payload = 3; bytes payload = 3;

10
src/index.ts Normal file
View File

@ -0,0 +1,10 @@
export { Waku } from './lib/waku';
export { WakuMessage } from './lib/waku_message';
export { ChatMessage } from './lib/chat_message';
export { WakuRelay, RelayCodec } from './lib/waku_relay';
export { WakuStore, StoreCodec } from './lib/waku_store';
export * as proto from './proto';

View File

@ -11,14 +11,14 @@ describe('Chat Message', function () {
fc.string(), fc.string(),
fc.string(), fc.string(),
(timestamp, nick, message) => { (timestamp, nick, message) => {
const msg = new ChatMessage(timestamp, nick, message); const msg = ChatMessage.fromUtf8String(timestamp, nick, message);
const buf = msg.encode(); const buf = msg.encode();
const actual = ChatMessage.decode(buf); const actual = ChatMessage.decode(buf);
// Date.toString does not include ms, as we loose this precision by design // Date.toString does not include ms, as we loose this precision by design
expect(actual.timestamp.toString()).to.eq(timestamp.toString()); expect(actual.timestamp.toString()).to.eq(timestamp.toString());
expect(actual.nick).to.eq(nick); expect(actual.nick).to.eq(nick);
expect(actual.message).to.eq(message); expect(actual.payloadAsUtf8).to.eq(message);
} }
) )
); );

View File

@ -1,36 +1,54 @@
import { Reader } from 'protobufjs/minimal'; import { Reader } from 'protobufjs/minimal';
import { ChatMessageProto } from '../../proto/chat/v2/chat_message'; import * as proto from '../../proto/chat/v2/chat_message';
// TODO: Move to waku library?
export class ChatMessage { export class ChatMessage {
public constructor( public constructor(public proto: proto.ChatMessage) {}
public timestamp: Date,
public nick: string, /**
public message: string * Create Chat Message with a utf-8 string as payload.
) {} */
static fromUtf8String(
timestamp: Date,
nick: string,
text: string
): ChatMessage {
const timestampNumber = Math.floor(timestamp.valueOf() / 1000);
const payload = Buffer.from(text, 'utf-8');
return new ChatMessage({
timestamp: timestampNumber,
nick,
payload,
});
}
static decode(bytes: Uint8Array): ChatMessage { static decode(bytes: Uint8Array): ChatMessage {
const protoMsg = ChatMessageProto.decode(Reader.create(bytes)); const protoMsg = proto.ChatMessage.decode(Reader.create(bytes));
const timestamp = new Date(protoMsg.timestamp * 1000); return new ChatMessage(protoMsg);
const message = protoMsg.payload
? Array.from(protoMsg.payload)
.map((char) => {
return String.fromCharCode(char);
})
.join('')
: '';
return new ChatMessage(timestamp, protoMsg.nick, message);
} }
encode(): Uint8Array { encode(): Uint8Array {
const timestamp = Math.floor(this.timestamp.valueOf() / 1000); return proto.ChatMessage.encode(this.proto).finish();
const payload = Buffer.from(this.message, 'utf-8'); }
return ChatMessageProto.encode({ get timestamp(): Date {
timestamp, return new Date(this.proto.timestamp * 1000);
nick: this.nick, }
payload,
}).finish(); get nick(): string {
return this.proto.nick;
}
get payloadAsUtf8(): string {
if (!this.proto.payload) {
return '';
}
return Array.from(this.proto.payload)
.map((char) => {
return String.fromCharCode(char);
})
.join('');
} }
} }

View File

@ -8,7 +8,7 @@ import {
NOISE_KEY_2, NOISE_KEY_2,
} from '../test_utils/'; } from '../test_utils/';
import Waku from './waku'; import { Waku } from './waku';
import { RelayCodec } from './waku_relay'; import { RelayCodec } from './waku_relay';
describe('Waku Dial', function () { describe('Waku Dial', function () {

View File

@ -21,7 +21,7 @@ export type CreateOptions =
} }
| (Libp2pOptions & import('libp2p').CreateOptions); | (Libp2pOptions & import('libp2p').CreateOptions);
export default class Waku { export class Waku {
public libp2p: Libp2p; public libp2p: Libp2p;
public relay: WakuRelay; public relay: WakuRelay;
public store: WakuStore; public store: WakuStore;

View File

@ -8,7 +8,7 @@ import {
NOISE_KEY_2, NOISE_KEY_2,
} from '../../test_utils'; } from '../../test_utils';
import { delay } from '../delay'; import { delay } from '../delay';
import Waku from '../waku'; import { Waku } from '../waku';
import { WakuMessage } from '../waku_message'; import { WakuMessage } from '../waku_message';
import { RelayCodec, RelayDefaultTopic } from './index'; import { RelayCodec, RelayDefaultTopic } from './index';

View File

@ -19,11 +19,11 @@ import PeerId from 'peer-id';
import { WakuMessage } from '../waku_message'; import { WakuMessage } from '../waku_message';
import * as constants from './constants'; import * as constants from './constants';
import { RelayCodec, RelayDefaultTopic } from './constants';
import { getRelayPeers } from './get_relay_peers'; import { getRelayPeers } from './get_relay_peers';
import { RelayHeartbeat } from './relay_heartbeat'; import { RelayHeartbeat } from './relay_heartbeat';
export * from './constants'; export { RelayCodec, RelayDefaultTopic };
export * from './relay_heartbeat';
/** /**
* See {GossipOptions} from libp2p-gossipsub * See {GossipOptions} from libp2p-gossipsub

View File

@ -2,7 +2,7 @@ import { expect } from 'chai';
import TCP from 'libp2p-tcp'; import TCP from 'libp2p-tcp';
import { makeLogFileName, NimWaku, NOISE_KEY_1 } from '../../test_utils'; import { makeLogFileName, NimWaku, NOISE_KEY_1 } from '../../test_utils';
import Waku from '../waku'; import { Waku } from '../waku';
import { WakuMessage } from '../waku_message'; import { WakuMessage } from '../waku_message';
describe('Waku Store', () => { describe('Waku Store', () => {

View File

@ -4,17 +4,17 @@ import _m0 from 'protobufjs/minimal';
export const protobufPackage = 'chat.v2'; export const protobufPackage = 'chat.v2';
export interface ChatMessageProto { export interface ChatMessage {
timestamp: number; timestamp: number;
nick: string; nick: string;
payload: Uint8Array; payload: Uint8Array;
} }
const baseChatMessageProto: object = { timestamp: 0, nick: '' }; const baseChatMessage: object = { timestamp: 0, nick: '' };
export const ChatMessageProto = { export const ChatMessage = {
encode( encode(
message: ChatMessageProto, message: ChatMessage,
writer: _m0.Writer = _m0.Writer.create() writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer { ): _m0.Writer {
if (message.timestamp !== 0) { if (message.timestamp !== 0) {
@ -29,10 +29,10 @@ export const ChatMessageProto = {
return writer; return writer;
}, },
decode(input: _m0.Reader | Uint8Array, length?: number): ChatMessageProto { decode(input: _m0.Reader | Uint8Array, length?: number): ChatMessage {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length; let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseChatMessageProto } as ChatMessageProto; const message = { ...baseChatMessage } as ChatMessage;
message.payload = new Uint8Array(); message.payload = new Uint8Array();
while (reader.pos < end) { while (reader.pos < end) {
const tag = reader.uint32(); const tag = reader.uint32();
@ -54,8 +54,8 @@ export const ChatMessageProto = {
return message; return message;
}, },
fromJSON(object: any): ChatMessageProto { fromJSON(object: any): ChatMessage {
const message = { ...baseChatMessageProto } as ChatMessageProto; const message = { ...baseChatMessage } as ChatMessage;
message.payload = new Uint8Array(); message.payload = new Uint8Array();
if (object.timestamp !== undefined && object.timestamp !== null) { if (object.timestamp !== undefined && object.timestamp !== null) {
message.timestamp = Number(object.timestamp); message.timestamp = Number(object.timestamp);
@ -73,7 +73,7 @@ export const ChatMessageProto = {
return message; return message;
}, },
toJSON(message: ChatMessageProto): unknown { toJSON(message: ChatMessage): unknown {
const obj: any = {}; const obj: any = {};
message.timestamp !== undefined && (obj.timestamp = message.timestamp); message.timestamp !== undefined && (obj.timestamp = message.timestamp);
message.nick !== undefined && (obj.nick = message.nick); message.nick !== undefined && (obj.nick = message.nick);
@ -84,8 +84,8 @@ export const ChatMessageProto = {
return obj; return obj;
}, },
fromPartial(object: DeepPartial<ChatMessageProto>): ChatMessageProto { fromPartial(object: DeepPartial<ChatMessage>): ChatMessage {
const message = { ...baseChatMessageProto } as ChatMessageProto; const message = { ...baseChatMessage } as ChatMessage;
if (object.timestamp !== undefined && object.timestamp !== null) { if (object.timestamp !== undefined && object.timestamp !== null) {
message.timestamp = object.timestamp; message.timestamp = object.timestamp;
} else { } else {

13
src/proto/index.ts Normal file
View File

@ -0,0 +1,13 @@
export { ChatMessage } from './chat/v2/chat_message';
export { WakuMessage } from './waku/v2/message';
export {
Index,
PagingInfo,
PagingInfo_Direction,
ContentFilter,
HistoryQuery,
HistoryResponse,
HistoryRPC,
} from './waku/v2/store';