@solarpunkltd/swarm-chat-js 6.1.5 → 6.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.esm.js +2 -16
- package/dist/index.js +1 -1
- package/dist/lib/core.d.ts +2 -3
- package/dist/lib/core.d.ts.map +1 -1
- package/dist/swarm-chat-umd.js +1 -1
- package/package.json +2 -2
package/dist/index.esm.js
CHANGED
|
@@ -37056,7 +37056,7 @@ class Waku {
|
|
|
37056
37056
|
}
|
|
37057
37057
|
class SwarmChat {
|
|
37058
37058
|
constructor(u) {
|
|
37059
|
-
this.waku = null, this.logger = Logger$1.getInstance(), this.errorHandler = ErrorHandler.getInstance(), this.gsocIndex = null, this.fetchProcessRunning = !1, this.stopFetch = !1
|
|
37059
|
+
this.waku = null, this.isStarted = !1, this.startPromise = null, this.logger = Logger$1.getInstance(), this.errorHandler = ErrorHandler.getInstance(), this.gsocIndex = null, this.fetchProcessRunning = !1, this.stopFetch = !1;
|
|
37060
37060
|
const h = new PrivateKey(remove0x(u.user.privateKey));
|
|
37061
37061
|
this.userDetails = {
|
|
37062
37062
|
privateKey: u.user.privateKey,
|
|
@@ -37077,20 +37077,6 @@ class SwarmChat {
|
|
|
37077
37077
|
}, this.emitter = new EventEmitter$2(), this.utils = new SwarmChatUtils(this.userDetails, this.swarmSettings), this.history = new SwarmHistory(this.utils, this.emitter);
|
|
37078
37078
|
}
|
|
37079
37079
|
async start() {
|
|
37080
|
-
if (this.isStarted) {
|
|
37081
|
-
this.logger.debug("SwarmChat is already started, ignoring duplicate start() call");
|
|
37082
|
-
return;
|
|
37083
|
-
}
|
|
37084
|
-
if (this.startPromise)
|
|
37085
|
-
return this.logger.debug("SwarmChat start is already in progress, waiting for completion"), this.startPromise;
|
|
37086
|
-
this.startPromise = this.performStart();
|
|
37087
|
-
try {
|
|
37088
|
-
await this.startPromise, this.isStarted = !0;
|
|
37089
|
-
} finally {
|
|
37090
|
-
this.startPromise = null;
|
|
37091
|
-
}
|
|
37092
|
-
}
|
|
37093
|
-
async performStart() {
|
|
37094
37080
|
await this.init(), await this.startMessageFetchProcess();
|
|
37095
37081
|
}
|
|
37096
37082
|
async startMessageFetchProcess() {
|
|
@@ -37098,7 +37084,7 @@ class SwarmChat {
|
|
|
37098
37084
|
u ? await this.startWakuMessageFetch(u) : await this.startPollingMessageFetch();
|
|
37099
37085
|
}
|
|
37100
37086
|
async stop() {
|
|
37101
|
-
this.
|
|
37087
|
+
this.emitter.cleanAll(), this.stopPollingMessageFetch(), this.history.cleanup(), this.waku && (await this.waku.stop(), this.waku = null);
|
|
37102
37088
|
}
|
|
37103
37089
|
async startWakuMessageFetch(u) {
|
|
37104
37090
|
this.logger.info("Waku is enabled");
|
package/dist/index.js
CHANGED
|
@@ -64,4 +64,4 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
64
64
|
`;)Me++;return Me}function fe(){if($.length>0)return $.shift();if(M)return C();var pe,Me,$e,Pe,Be,Re=h===0;do{if(h===v)return null;for(pe=!1;whitespaceRe.test($e=B(h));)if($e===`
|
|
65
65
|
`&&(Re=!0,++w),++h===v)return null;if(B(h)==="/"){if(++h===v)throw T("comment");if(B(h)==="/")if(u){if(Pe=h,Be=!1,H(h-1)){Be=!0;do if(h=te(h),h===v||(h++,!Re))break;while(H(h))}else h=Math.min(v,te(h)+1);Be&&(N(Pe,h,Re),Re=!0),w++,pe=!0}else{for(Be=B(Pe=h+1)==="/";B(++h)!==`
|
|
66
66
|
`;)if(h===v)return null;++h,Be&&(N(Pe,h-1,Re),Re=!0),++w,pe=!0}else if(($e=B(h))==="*"){Pe=h+1,Be=u||B(Pe)==="*";do{if($e===`
|
|
67
|
-
`&&++w,++h===v)throw T("comment");Me=$e,$e=B(h)}while(Me!=="*"||$e!=="/");++h,Be&&(N(Pe,h-2,Re),Re=!0),pe=!0}else return"/"}}while(pe);var je=h;delimRe.lastIndex=0;var we=delimRe.test(B(je++));if(!we)for(;je<v&&!delimRe.test(B(je));)++je;var D=y.substring(h,h=je);return(D==='"'||D==="'")&&(M=D),D}function ce(pe){$.push(pe)}function le(){if(!$.length){var pe=fe();if(pe===null)return null;ce(pe)}return $[0]}function ie(pe,Me){var $e=le(),Pe=$e===pe;if(Pe)return fe(),!0;if(!Me)throw T("token '"+$e+"', '"+pe+"' expected");return!1}function ge(pe){var Me=null,$e;return pe===void 0?($e=E[w-1],delete E[w-1],$e&&(u||$e.type==="*"||$e.lineEmpty)&&(Me=$e.leading?$e.text:null)):(b<pe&&le(),$e=E[pe],delete E[pe],$e&&!$e.lineEmpty&&(u||$e.type==="/")&&(Me=$e.leading?null:$e.text)),Me}return Object.defineProperty({next:fe,peek:le,push:ce,skip:ie,cmnt:ge},"line",{get:function(){return w}})}var parse_1=parse;parse.filename=null;parse.defaults={keepCase:!1};var tokenize=tokenize_1,Root=requireRoot(),Type=requireType(),Field=requireField(),MapField=requireMapfield(),OneOf=requireOneof(),Enum=require_enum(),Service=requireService(),Method=requireMethod(),ReflectionObject=requireObject(),types=requireTypes(),util=requireUtil(),base10Re=/^[1-9][0-9]*$/,base10NegRe=/^-?[1-9][0-9]*$/,base16Re=/^0[x][0-9a-fA-F]+$/,base16NegRe=/^-?0[x][0-9a-fA-F]+$/,base8Re=/^0[0-7]+$/,base8NegRe=/^-?0[0-7]+$/,numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,nameRe=/^[a-zA-Z_][a-zA-Z_0-9]*$/,typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function parse(y,u,h){u instanceof Root||(h=u,u=new Root),h||(h=parse.defaults);var v=h.preferTrailingComment||!1,w=tokenize(y,h.alternateCommentMode||!1),b=w.next,E=w.push,$=w.peek,M=w.skip,T=w.cmnt,C=!0,B,N,H,te="proto2",fe=u,ce=[],le={},ie=h.keepCase?function(ne){return ne}:util.camelCase;function ge(){ce.forEach(ne=>{ne._edition=te,Object.keys(le).forEach(be=>{ne.getOption(be)===void 0&&ne.setOption(be,le[be],!0)})})}function pe(ne,be,Ie){var Le=parse.filename;return Ie||(parse.filename=null),Error("illegal "+(be||"token")+" '"+ne+"' ("+(Le?Le+", ":"")+"line "+w.line+")")}function Me(){var ne=[],be;do{if((be=b())!=='"'&&be!=="'")throw pe(be);ne.push(b()),M(be),be=$()}while(be==='"'||be==="'");return ne.join("")}function $e(ne){var be=b();switch(be){case"'":case'"':return E(be),Me();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return Be(be,!0)}catch{if(typeRefRe.test(be))return be;throw pe(be,"value")}}function Pe(ne,be){var Ie,Le;do if(be&&((Ie=$())==='"'||Ie==="'")){var Fe=Me();if(ne.push(Fe),te>=2023)throw pe(Fe,"id")}else try{ne.push([Le=Re(b()),M("to",!0)?Re(b()):Le])}catch(tt){if(be&&typeRefRe.test(Ie)&&te>=2023)ne.push(Ie);else throw tt}while(M(",",!0));var He={options:void 0};He.setOption=function(tt,Ne){this.options===void 0&&(this.options={}),this.options[tt]=Ne},L(He,function(Ne){if(Ne==="option")he(He,Ne),M(";");else throw pe(Ne)},function(){oe(He)})}function Be(ne,be){var Ie=1;switch(ne.charAt(0)==="-"&&(Ie=-1,ne=ne.substring(1)),ne){case"inf":case"INF":case"Inf":return Ie*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(base10Re.test(ne))return Ie*parseInt(ne,10);if(base16Re.test(ne))return Ie*parseInt(ne,16);if(base8Re.test(ne))return Ie*parseInt(ne,8);if(numberRe.test(ne))return Ie*parseFloat(ne);throw pe(ne,"number",be)}function Re(ne,be){switch(ne){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!be&&ne.charAt(0)==="-")throw pe(ne,"id");if(base10NegRe.test(ne))return parseInt(ne,10);if(base16NegRe.test(ne))return parseInt(ne,16);if(base8NegRe.test(ne))return parseInt(ne,8);throw pe(ne,"id")}function je(){if(B!==void 0)throw pe("package");if(B=b(),!typeRefRe.test(B))throw pe(B,"name");fe=fe.define(B),M(";")}function we(){var ne=$(),be;switch(ne){case"weak":be=H||(H=[]),b();break;case"public":b();default:be=N||(N=[]);break}ne=Me(),M(";"),be.push(ne)}function D(){if(M("="),te=Me(),te<2023)throw pe(te,"syntax");M(";")}function q(){if(M("="),te=Me(),!["2023"].includes(te))throw pe(te,"edition");M(";")}function O(ne,be){switch(be){case"option":return he(ne,be),M(";"),!0;case"message":return X(ne,be),!0;case"enum":return Q(ne,be),!0;case"service":return ye(ne,be),!0;case"extend":return ae(ne,be),!0}return!1}function L(ne,be,Ie){var Le=w.line;if(ne&&(typeof ne.comment!="string"&&(ne.comment=T()),ne.filename=parse.filename),M("{",!0)){for(var Fe;(Fe=b())!=="}";)be(Fe);M(";",!0)}else Ie&&Ie(),M(";"),ne&&(typeof ne.comment!="string"||v)&&(ne.comment=T(Le)||ne.comment)}function X(ne,be){if(!nameRe.test(be=b()))throw pe(be,"type name");var Ie=new Type(be);L(Ie,function(Fe){if(!O(Ie,Fe))switch(Fe){case"map":ee(Ie);break;case"required":if(te!=="proto2")throw pe(Fe);case"repeated":j(Ie,Fe);break;case"optional":if(te==="proto3")j(Ie,"proto3_optional");else{if(te!=="proto2")throw pe(Fe);j(Ie,"optional")}break;case"oneof":F(Ie,Fe);break;case"extensions":Pe(Ie.extensions||(Ie.extensions=[]));break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0);break;default:if(te==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(Ie,"optional");break}}),ne.add(Ie),ne===fe&&ce.push(Ie)}function j(ne,be,Ie){var Le=b();if(Le==="group"){re(ne,be);return}for(;Le.endsWith(".")||$().startsWith(".");)Le+=b();if(!typeRefRe.test(Le))throw pe(Le,"type");var Fe=b();if(!nameRe.test(Fe))throw pe(Fe,"name");Fe=ie(Fe),M("=");var He=new Field(Fe,Re(b()),Le,be,Ie);if(L(He,function(nt){if(nt==="option")he(He,nt),M(";");else throw pe(nt)},function(){oe(He)}),be==="proto3_optional"){var tt=new OneOf("_"+Fe);He.setOption("proto3_optional",!0),tt.add(He),ne.add(tt)}else ne.add(He);ne===fe&&ce.push(He)}function re(ne,be){if(te>=2023)throw pe("group");var Ie=b();if(!nameRe.test(Ie))throw pe(Ie,"name");var Le=util.lcFirst(Ie);Ie===Le&&(Ie=util.ucFirst(Ie)),M("=");var Fe=Re(b()),He=new Type(Ie);He.group=!0;var tt=new Field(Le,Fe,Ie,be);tt.filename=parse.filename,L(He,function(nt){switch(nt){case"option":he(He,nt),M(";");break;case"required":case"repeated":j(He,nt);break;case"optional":te==="proto3"?j(He,"proto3_optional"):j(He,"optional");break;case"message":X(He,nt);break;case"enum":Q(He,nt);break;case"reserved":Pe(He.reserved||(He.reserved=[]),!0);break;default:throw pe(nt)}}),ne.add(He).add(tt)}function ee(ne){M("<");var be=b();if(types.mapKey[be]===void 0)throw pe(be,"type");M(",");var Ie=b();if(!typeRefRe.test(Ie))throw pe(Ie,"type");M(">");var Le=b();if(!nameRe.test(Le))throw pe(Le,"name");M("=");var Fe=new MapField(ie(Le),Re(b()),be,Ie);L(Fe,function(tt){if(tt==="option")he(Fe,tt),M(";");else throw pe(tt)},function(){oe(Fe)}),ne.add(Fe)}function F(ne,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new OneOf(ie(be));L(Ie,function(Fe){Fe==="option"?(he(Ie,Fe),M(";")):(E(Fe),j(Ie,"optional"))}),ne.add(Ie)}function Q(ne,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new Enum(be);L(Ie,function(Fe){switch(Fe){case"option":he(Ie,Fe),M(";");break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0),Ie.reserved===void 0&&(Ie.reserved=[]);break;default:U(Ie,Fe)}}),ne.add(Ie),ne===fe&&ce.push(Ie)}function U(ne,be){if(!nameRe.test(be))throw pe(be,"name");M("=");var Ie=Re(b(),!0),Le={options:void 0};Le.getOption=function(Fe){return this.options[Fe]},Le.setOption=function(Fe,He){ReflectionObject.prototype.setOption.call(Le,Fe,He)},Le.setParsedOption=function(){},L(Le,function(He){if(He==="option")he(Le,He),M(";");else throw pe(He)},function(){oe(Le)}),ne.add(be,Ie,Le.comment,Le.parsedOptions||Le.options)}function he(ne,be){var Ie,Le,Fe=!0;for(be==="option"&&(be=b());be!=="=";){if(be==="("){var He=b();M(")"),be="("+He+")"}if(Fe){if(Fe=!1,be.includes(".")&&!be.includes("(")){var tt=be.split(".");Ie=tt[0]+".",be=tt[1];continue}Ie=be}else Le=Le?Le+=be:be;be=b()}var Ne=Le?Ie.concat(Le):Ie,nt=Oe(ne,Ne);Le=Le&&Le[0]==="."?Le.slice(1):Le,Ie=Ie&&Ie[Ie.length-1]==="."?Ie.slice(0,-1):Ie,Ae(ne,Ie,nt,Le)}function Oe(ne,be){if(M("{",!0)){for(var Ie={};!M("}",!0);){if(!nameRe.test(de=b()))throw pe(de,"name");if(de===null)throw pe(de,"end of input");var Le,Fe=de;if(M(":",!0),$()==="{")Le=Oe(ne,be+"."+de);else if($()==="["){Le=[];var He;if(M("[",!0)){do He=$e(),Le.push(He);while(M(",",!0));M("]"),typeof He<"u"&&Ve(ne,be+"."+de,He)}}else Le=$e(),Ve(ne,be+"."+de,Le);var tt=Ie[Fe];tt&&(Le=[].concat(tt).concat(Le)),Ie[Fe]=Le,M(",",!0),M(";",!0)}return Ie}var Ne=$e();return Ve(ne,be,Ne),Ne}function Ve(ne,be,Ie){if(fe===ne&&/^features\./.test(be)){le[be]=Ie;return}ne.setOption&&ne.setOption(be,Ie)}function Ae(ne,be,Ie,Le){ne.setParsedOption&&ne.setParsedOption(be,Ie,Le)}function oe(ne){if(M("[",!0)){do he(ne,"option");while(M(",",!0));M("]")}return ne}function ye(ne,be){if(!nameRe.test(be=b()))throw pe(be,"service name");var Ie=new Service(be);L(Ie,function(Fe){if(!O(Ie,Fe))if(Fe==="rpc")Ce(Ie,Fe);else throw pe(Fe)}),ne.add(Ie),ne===fe&&ce.push(Ie)}function Ce(ne,be){var Ie=T(),Le=be;if(!nameRe.test(be=b()))throw pe(be,"name");var Fe=be,He,tt,Ne,nt;if(M("("),M("stream",!0)&&(tt=!0),!typeRefRe.test(be=b())||(He=be,M(")"),M("returns"),M("("),M("stream",!0)&&(nt=!0),!typeRefRe.test(be=b())))throw pe(be);Ne=be,M(")");var it=new Method(Fe,Le,He,Ne,tt,nt);it.comment=Ie,L(it,function(ut){if(ut==="option")he(it,ut),M(";");else throw pe(ut)}),ne.add(it)}function ae(ne,be){if(!typeRefRe.test(be=b()))throw pe(be,"reference");var Ie=be;L(null,function(Fe){switch(Fe){case"required":case"repeated":j(ne,Fe,Ie);break;case"optional":te==="proto3"?j(ne,"proto3_optional",Ie):j(ne,"optional",Ie);break;default:if(te==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(ne,"optional",Ie);break}})}for(var de;(de=b())!==null;)switch(de){case"package":if(!C)throw pe(de);je();break;case"import":if(!C)throw pe(de);we();break;case"syntax":if(!C)throw pe(de);D();break;case"edition":if(!C)throw pe(de);q();break;case"option":he(fe,de),M(";",!0);break;default:if(O(fe,de)){C=!1;continue}throw pe(de)}return ge(),parse.filename=null,{package:B,imports:N,weakImports:H,root:u}}var common_1=common,commonRe=/\/|\./;function common(y,u){commonRe.test(y)||(y="google/protobuf/"+y+".proto",u={nested:{google:{nested:{protobuf:{nested:u}}}}}),common[y]=u}common("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var timeType;common("duration",{Duration:timeType={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}});common("timestamp",{Timestamp:timeType});common("empty",{Empty:{fields:{}}});common("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}});common("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}});common("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}});common.get=function y(u){return common[u]||null};var protobuf$1=src.exports=indexLightExports;protobuf$1.build="full";protobuf$1.tokenize=tokenize_1;protobuf$1.parse=parse_1;protobuf$1.common=common_1;protobuf$1.Root._configure(protobuf$1.Type,protobuf$1.parse,protobuf$1.common);var srcExports=src.exports,protobufjs=srcExports;const protobuf=getDefaultExportFromCjs$1(protobufjs);class Waku{constructor(u,h,v){this.node=u,this.chatTopic=h,this.onMessage=v,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.reliableChannel=null,this.decoder=null,this.messagePayloadType=null,this.messageReceivedListener=null,this.senderId=crypto$1.randomBytes(8).toString("hex"),this.handleMessageReceived=async({payload:w})=>{try{if(!w){this.logger.warn("Received Waku message without payload");return}if(!this.messagePayloadType)throw new Error("Protobuf schema not initialized");const b=this.messagePayloadType.decode(w),E=this.messagePayloadType.toObject(b,{longs:String,enums:String,defaults:!0});if(!E.message){this.logger.warn("Decoded object has no message field");return}let $=E.message.additionalProps;if($&&typeof $=="string")try{$=JSON.parse($)}catch{this.logger.warn("Failed to parse additionalProps as JSON:",$)}const M={...E.message,timestamp:Number(E.message.timestamp),additionalProps:$};if(!(M!=null&&M.id)){this.logger.warn("Received invalid message structure via Waku");return}this.onMessage(M)}catch(b){this.errorHandler.handleError(b,"Waku2.handleMessageReceived")}}}async start(){this.createProtobufSchema(),await this.createChannel()}createProtobufSchema(){const u=new protobuf.Type("MessageData").add(new protobuf.Field("id",1,"string")).add(new protobuf.Field("targetMessageId",2,"string","optional")).add(new protobuf.Field("type",3,"string")).add(new protobuf.Field("message",4,"string")).add(new protobuf.Field("username",5,"string")).add(new protobuf.Field("address",6,"string")).add(new protobuf.Field("timestamp",7,"uint64")).add(new protobuf.Field("signature",8,"string")).add(new protobuf.Field("index",9,"uint32")).add(new protobuf.Field("chatTopic",10,"string")).add(new protobuf.Field("userTopic",11,"string")).add(new protobuf.Field("additionalProps",12,"string","optional")),h=new protobuf.Type("MessageStateRef").add(new protobuf.Field("reference",1,"string")).add(new protobuf.Field("timestamp",2,"uint64"));this.messagePayloadType=new protobuf.Type("MessagePayload").add(u).add(h).add(new protobuf.Field("message",1,"MessageData")).add(new protobuf.Field("messageStateRefs",2,"MessageStateRef","repeated")),this.logger.info("Protobuf schema created for chat messages")}async createChannel(){if(!this.node)throw new Error("Waku node not initialized");const u=`/solarpunk-msrs-chat/1/${this.chatTopic}/proto`,h=`chat-channel-${this.chatTopic}`,v=this.node.createEncoder({contentTopic:u}),w=this.decoder=this.node.createDecoder({contentTopic:u});this.reliableChannel=await ReliableChannel.create(this.node,h,this.senderId,v,w,{retrieveFrequencyMs:3e3,queryOnConnect:!1}),this.setupChannelEventListeners(this.reliableChannel),this.logger.info(`Created reliable channel for topic: ${this.chatTopic}`)}setupChannelEventListeners(u){this.messageReceivedListener=h=>{this.handleMessageReceived(h.detail)},u.addEventListener("message-received",this.messageReceivedListener)}async stop(){this.reliableChannel&&this.messageReceivedListener&&this.decoder&&(this.reliableChannel.removeEventListener("message-received",this.messageReceivedListener),this.messageReceivedListener=null,await this.reliableChannel.stop(),this.logger.info("Waku reliable channel stopped"))}}class SwarmChat{constructor(u){this.waku=null,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.gsocIndex=null,this.fetchProcessRunning=!1,this.stopFetch=!1,this.isStarted=!1,this.startPromise=null;const h=new beeJs.PrivateKey(remove0x(u.user.privateKey));this.userDetails={privateKey:u.user.privateKey,ownAddress:h.publicKey().address().toString(),nickname:u.user.nickname,ownIndex:-1},this.swarmSettings={bee:new beeJs.Bee(u.infra.beeUrl),beeUrl:u.infra.beeUrl,stamp:u.infra.stamp||"0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",enveloped:u.infra.enveloped,gsocTopic:u.infra.gsocTopic,gsocResourceId:u.infra.gsocResourceId,chatTopic:u.infra.chatTopic,chatAddress:u.infra.chatAddress,wakuNode:u.infra.wakuNode},this.emitter=new EventEmitter$2,this.utils=new SwarmChatUtils(this.userDetails,this.swarmSettings),this.history=new SwarmHistory(this.utils,this.emitter)}async start(){if(this.isStarted){this.logger.debug("SwarmChat is already started, ignoring duplicate start() call");return}if(this.startPromise)return this.logger.debug("SwarmChat start is already in progress, waiting for completion"),this.startPromise;this.startPromise=this.performStart();try{await this.startPromise,this.isStarted=!0}finally{this.startPromise=null}}async performStart(){await this.init(),await this.startMessageFetchProcess()}async startMessageFetchProcess(){const{wakuNode:u}=this.swarmSettings;u?await this.startWakuMessageFetch(u):await this.startPollingMessageFetch()}async stop(){this.isStarted=!1,this.startPromise=null,this.emitter.cleanAll(),this.stopPollingMessageFetch(),this.history.cleanup(),this.waku&&(await this.waku.stop(),this.waku=null)}async startWakuMessageFetch(u){this.logger.info("Waku is enabled");const h=this.swarmSettings.chatTopic;this.waku=new Waku(u,h,v=>{this.emitter.emit(EVENTS.MESSAGE_RECEIVED,v)}),await this.waku.start()}getEmitter(){return this.emitter}orderMessages(u){return this.utils.orderMessages(u)}async sendMessage(u,h,v,w,b){const E=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,$={id:w||v4(),username:this.userDetails.nickname,address:this.userDetails.ownAddress,chatTopic:this.swarmSettings.chatTopic,userTopic:this.utils.generateUserOwnedFeedId(this.swarmSettings.chatTopic,this.userDetails.ownAddress),signature:this.getSignature(u),timestamp:Date.now(),index:E,type:h,targetMessageId:v,message:u,additionalProps:b},M=validateMessageWithAdditionalProperties($);if(!M.isValid){const T=`Invalid message: ${M.errors.join(", ")}`;throw this.logger.error(T),new Error(T)}try{this.emitter.emit(EVENTS.MESSAGE_REQUEST_INITIATED,$),await this.utils.writeOwnFeedDataByIndex(E,JSON.stringify($)),this.userDetails.ownIndex=E,this.emitter.emit(EVENTS.MESSAGE_REQUEST_UPLOADED,$),await this.broadcastUserMessage($)}catch(T){this.emitter.emit(EVENTS.MESSAGE_REQUEST_ERROR,$),this.errorHandler.handleError(T,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(u){this.sendMessage(u.message,u.type,u.targetMessageId,u.id,u.additionalProps)}async retryBroadcastUserMessage(u){await this.broadcastUserMessage(u)}async init(){try{this.emitter.emit(EVENTS.LOADING_INIT,!0);const[u,h]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(u.status==="rejected")throw u.reason;h.status==="fulfilled"&&(this.gsocIndex=h.value),this.emitter.emit(EVENTS.LOADING_INIT,!1)}catch(u){this.errorHandler.handleError(u,"Chat.initSelfState"),this.emitter.emit(EVENTS.CRITICAL_ERROR,u)}}async initOwnIndex(){const{latestIndex:v}=await retryAwaitableAsync(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=v}async fetchLatestMessage(){try{if(!this.gsocIndex)return;const u=beeJs.Topic.fromString(this.swarmSettings.chatTopic),h=makeFeedIdentifier(u,this.gsocIndex),v=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,h.toString()),w=JSON.parse(v);if(!validateGsocMessage(w)){this.logger.warn("Invalid GSOC message during fetching");return}this.emitter.emit(EVENTS.MESSAGE_RECEIVED,w.message),this.gsocIndex=this.gsocIndex.next()}catch(u){if(this.utils.isNotFoundError(u))return;this.errorHandler.handleError(u,"Chat.fetchLatestMessage")}}async broadcastUserMessage(u){try{return retryAwaitableAsync(()=>this.utils.sendMessageToGsoc(JSON.stringify(u)))}catch(h){this.errorHandler.handleError(h,"Chat.broadcastUserMessage")}}getSignature(u){const{ownAddress:h,privateKey:v,nickname:w}=this.userDetails,b=new beeJs.EthAddress(h).toString(),E=new beeJs.PrivateKey(v);if(E.publicKey().address().toString()!==b)throw new Error("The provided address does not match the address derived from the private key");const M=Date.now();return E.sign(JSON.stringify({username:w,address:b,message:u,timestamp:M})).toHex()}async startPollingMessageFetch(){if(this.fetchProcessRunning)return;this.fetchProcessRunning=!0,this.stopFetch=!1;const u=async()=>{if(this.stopFetch){this.fetchProcessRunning=!1;return}await this.fetchLatestMessage(),setTimeout(u,200)};u()}stopPollingMessageFetch(){this.stopFetch=!0}}exports.EVENTS=EVENTS;exports.MessageType=MessageType;exports.SwarmChat=SwarmChat;
|
|
67
|
+
`&&++w,++h===v)throw T("comment");Me=$e,$e=B(h)}while(Me!=="*"||$e!=="/");++h,Be&&(N(Pe,h-2,Re),Re=!0),pe=!0}else return"/"}}while(pe);var je=h;delimRe.lastIndex=0;var we=delimRe.test(B(je++));if(!we)for(;je<v&&!delimRe.test(B(je));)++je;var D=y.substring(h,h=je);return(D==='"'||D==="'")&&(M=D),D}function ce(pe){$.push(pe)}function le(){if(!$.length){var pe=fe();if(pe===null)return null;ce(pe)}return $[0]}function ie(pe,Me){var $e=le(),Pe=$e===pe;if(Pe)return fe(),!0;if(!Me)throw T("token '"+$e+"', '"+pe+"' expected");return!1}function ge(pe){var Me=null,$e;return pe===void 0?($e=E[w-1],delete E[w-1],$e&&(u||$e.type==="*"||$e.lineEmpty)&&(Me=$e.leading?$e.text:null)):(b<pe&&le(),$e=E[pe],delete E[pe],$e&&!$e.lineEmpty&&(u||$e.type==="/")&&(Me=$e.leading?null:$e.text)),Me}return Object.defineProperty({next:fe,peek:le,push:ce,skip:ie,cmnt:ge},"line",{get:function(){return w}})}var parse_1=parse;parse.filename=null;parse.defaults={keepCase:!1};var tokenize=tokenize_1,Root=requireRoot(),Type=requireType(),Field=requireField(),MapField=requireMapfield(),OneOf=requireOneof(),Enum=require_enum(),Service=requireService(),Method=requireMethod(),ReflectionObject=requireObject(),types=requireTypes(),util=requireUtil(),base10Re=/^[1-9][0-9]*$/,base10NegRe=/^-?[1-9][0-9]*$/,base16Re=/^0[x][0-9a-fA-F]+$/,base16NegRe=/^-?0[x][0-9a-fA-F]+$/,base8Re=/^0[0-7]+$/,base8NegRe=/^-?0[0-7]+$/,numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,nameRe=/^[a-zA-Z_][a-zA-Z_0-9]*$/,typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function parse(y,u,h){u instanceof Root||(h=u,u=new Root),h||(h=parse.defaults);var v=h.preferTrailingComment||!1,w=tokenize(y,h.alternateCommentMode||!1),b=w.next,E=w.push,$=w.peek,M=w.skip,T=w.cmnt,C=!0,B,N,H,te="proto2",fe=u,ce=[],le={},ie=h.keepCase?function(ne){return ne}:util.camelCase;function ge(){ce.forEach(ne=>{ne._edition=te,Object.keys(le).forEach(be=>{ne.getOption(be)===void 0&&ne.setOption(be,le[be],!0)})})}function pe(ne,be,Ie){var Le=parse.filename;return Ie||(parse.filename=null),Error("illegal "+(be||"token")+" '"+ne+"' ("+(Le?Le+", ":"")+"line "+w.line+")")}function Me(){var ne=[],be;do{if((be=b())!=='"'&&be!=="'")throw pe(be);ne.push(b()),M(be),be=$()}while(be==='"'||be==="'");return ne.join("")}function $e(ne){var be=b();switch(be){case"'":case'"':return E(be),Me();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return Be(be,!0)}catch{if(typeRefRe.test(be))return be;throw pe(be,"value")}}function Pe(ne,be){var Ie,Le;do if(be&&((Ie=$())==='"'||Ie==="'")){var Fe=Me();if(ne.push(Fe),te>=2023)throw pe(Fe,"id")}else try{ne.push([Le=Re(b()),M("to",!0)?Re(b()):Le])}catch(tt){if(be&&typeRefRe.test(Ie)&&te>=2023)ne.push(Ie);else throw tt}while(M(",",!0));var He={options:void 0};He.setOption=function(tt,Ne){this.options===void 0&&(this.options={}),this.options[tt]=Ne},L(He,function(Ne){if(Ne==="option")he(He,Ne),M(";");else throw pe(Ne)},function(){oe(He)})}function Be(ne,be){var Ie=1;switch(ne.charAt(0)==="-"&&(Ie=-1,ne=ne.substring(1)),ne){case"inf":case"INF":case"Inf":return Ie*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(base10Re.test(ne))return Ie*parseInt(ne,10);if(base16Re.test(ne))return Ie*parseInt(ne,16);if(base8Re.test(ne))return Ie*parseInt(ne,8);if(numberRe.test(ne))return Ie*parseFloat(ne);throw pe(ne,"number",be)}function Re(ne,be){switch(ne){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!be&&ne.charAt(0)==="-")throw pe(ne,"id");if(base10NegRe.test(ne))return parseInt(ne,10);if(base16NegRe.test(ne))return parseInt(ne,16);if(base8NegRe.test(ne))return parseInt(ne,8);throw pe(ne,"id")}function je(){if(B!==void 0)throw pe("package");if(B=b(),!typeRefRe.test(B))throw pe(B,"name");fe=fe.define(B),M(";")}function we(){var ne=$(),be;switch(ne){case"weak":be=H||(H=[]),b();break;case"public":b();default:be=N||(N=[]);break}ne=Me(),M(";"),be.push(ne)}function D(){if(M("="),te=Me(),te<2023)throw pe(te,"syntax");M(";")}function q(){if(M("="),te=Me(),!["2023"].includes(te))throw pe(te,"edition");M(";")}function O(ne,be){switch(be){case"option":return he(ne,be),M(";"),!0;case"message":return X(ne,be),!0;case"enum":return Q(ne,be),!0;case"service":return ye(ne,be),!0;case"extend":return ae(ne,be),!0}return!1}function L(ne,be,Ie){var Le=w.line;if(ne&&(typeof ne.comment!="string"&&(ne.comment=T()),ne.filename=parse.filename),M("{",!0)){for(var Fe;(Fe=b())!=="}";)be(Fe);M(";",!0)}else Ie&&Ie(),M(";"),ne&&(typeof ne.comment!="string"||v)&&(ne.comment=T(Le)||ne.comment)}function X(ne,be){if(!nameRe.test(be=b()))throw pe(be,"type name");var Ie=new Type(be);L(Ie,function(Fe){if(!O(Ie,Fe))switch(Fe){case"map":ee(Ie);break;case"required":if(te!=="proto2")throw pe(Fe);case"repeated":j(Ie,Fe);break;case"optional":if(te==="proto3")j(Ie,"proto3_optional");else{if(te!=="proto2")throw pe(Fe);j(Ie,"optional")}break;case"oneof":F(Ie,Fe);break;case"extensions":Pe(Ie.extensions||(Ie.extensions=[]));break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0);break;default:if(te==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(Ie,"optional");break}}),ne.add(Ie),ne===fe&&ce.push(Ie)}function j(ne,be,Ie){var Le=b();if(Le==="group"){re(ne,be);return}for(;Le.endsWith(".")||$().startsWith(".");)Le+=b();if(!typeRefRe.test(Le))throw pe(Le,"type");var Fe=b();if(!nameRe.test(Fe))throw pe(Fe,"name");Fe=ie(Fe),M("=");var He=new Field(Fe,Re(b()),Le,be,Ie);if(L(He,function(nt){if(nt==="option")he(He,nt),M(";");else throw pe(nt)},function(){oe(He)}),be==="proto3_optional"){var tt=new OneOf("_"+Fe);He.setOption("proto3_optional",!0),tt.add(He),ne.add(tt)}else ne.add(He);ne===fe&&ce.push(He)}function re(ne,be){if(te>=2023)throw pe("group");var Ie=b();if(!nameRe.test(Ie))throw pe(Ie,"name");var Le=util.lcFirst(Ie);Ie===Le&&(Ie=util.ucFirst(Ie)),M("=");var Fe=Re(b()),He=new Type(Ie);He.group=!0;var tt=new Field(Le,Fe,Ie,be);tt.filename=parse.filename,L(He,function(nt){switch(nt){case"option":he(He,nt),M(";");break;case"required":case"repeated":j(He,nt);break;case"optional":te==="proto3"?j(He,"proto3_optional"):j(He,"optional");break;case"message":X(He,nt);break;case"enum":Q(He,nt);break;case"reserved":Pe(He.reserved||(He.reserved=[]),!0);break;default:throw pe(nt)}}),ne.add(He).add(tt)}function ee(ne){M("<");var be=b();if(types.mapKey[be]===void 0)throw pe(be,"type");M(",");var Ie=b();if(!typeRefRe.test(Ie))throw pe(Ie,"type");M(">");var Le=b();if(!nameRe.test(Le))throw pe(Le,"name");M("=");var Fe=new MapField(ie(Le),Re(b()),be,Ie);L(Fe,function(tt){if(tt==="option")he(Fe,tt),M(";");else throw pe(tt)},function(){oe(Fe)}),ne.add(Fe)}function F(ne,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new OneOf(ie(be));L(Ie,function(Fe){Fe==="option"?(he(Ie,Fe),M(";")):(E(Fe),j(Ie,"optional"))}),ne.add(Ie)}function Q(ne,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new Enum(be);L(Ie,function(Fe){switch(Fe){case"option":he(Ie,Fe),M(";");break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0),Ie.reserved===void 0&&(Ie.reserved=[]);break;default:U(Ie,Fe)}}),ne.add(Ie),ne===fe&&ce.push(Ie)}function U(ne,be){if(!nameRe.test(be))throw pe(be,"name");M("=");var Ie=Re(b(),!0),Le={options:void 0};Le.getOption=function(Fe){return this.options[Fe]},Le.setOption=function(Fe,He){ReflectionObject.prototype.setOption.call(Le,Fe,He)},Le.setParsedOption=function(){},L(Le,function(He){if(He==="option")he(Le,He),M(";");else throw pe(He)},function(){oe(Le)}),ne.add(be,Ie,Le.comment,Le.parsedOptions||Le.options)}function he(ne,be){var Ie,Le,Fe=!0;for(be==="option"&&(be=b());be!=="=";){if(be==="("){var He=b();M(")"),be="("+He+")"}if(Fe){if(Fe=!1,be.includes(".")&&!be.includes("(")){var tt=be.split(".");Ie=tt[0]+".",be=tt[1];continue}Ie=be}else Le=Le?Le+=be:be;be=b()}var Ne=Le?Ie.concat(Le):Ie,nt=Oe(ne,Ne);Le=Le&&Le[0]==="."?Le.slice(1):Le,Ie=Ie&&Ie[Ie.length-1]==="."?Ie.slice(0,-1):Ie,Ae(ne,Ie,nt,Le)}function Oe(ne,be){if(M("{",!0)){for(var Ie={};!M("}",!0);){if(!nameRe.test(de=b()))throw pe(de,"name");if(de===null)throw pe(de,"end of input");var Le,Fe=de;if(M(":",!0),$()==="{")Le=Oe(ne,be+"."+de);else if($()==="["){Le=[];var He;if(M("[",!0)){do He=$e(),Le.push(He);while(M(",",!0));M("]"),typeof He<"u"&&Ve(ne,be+"."+de,He)}}else Le=$e(),Ve(ne,be+"."+de,Le);var tt=Ie[Fe];tt&&(Le=[].concat(tt).concat(Le)),Ie[Fe]=Le,M(",",!0),M(";",!0)}return Ie}var Ne=$e();return Ve(ne,be,Ne),Ne}function Ve(ne,be,Ie){if(fe===ne&&/^features\./.test(be)){le[be]=Ie;return}ne.setOption&&ne.setOption(be,Ie)}function Ae(ne,be,Ie,Le){ne.setParsedOption&&ne.setParsedOption(be,Ie,Le)}function oe(ne){if(M("[",!0)){do he(ne,"option");while(M(",",!0));M("]")}return ne}function ye(ne,be){if(!nameRe.test(be=b()))throw pe(be,"service name");var Ie=new Service(be);L(Ie,function(Fe){if(!O(Ie,Fe))if(Fe==="rpc")Ce(Ie,Fe);else throw pe(Fe)}),ne.add(Ie),ne===fe&&ce.push(Ie)}function Ce(ne,be){var Ie=T(),Le=be;if(!nameRe.test(be=b()))throw pe(be,"name");var Fe=be,He,tt,Ne,nt;if(M("("),M("stream",!0)&&(tt=!0),!typeRefRe.test(be=b())||(He=be,M(")"),M("returns"),M("("),M("stream",!0)&&(nt=!0),!typeRefRe.test(be=b())))throw pe(be);Ne=be,M(")");var it=new Method(Fe,Le,He,Ne,tt,nt);it.comment=Ie,L(it,function(ut){if(ut==="option")he(it,ut),M(";");else throw pe(ut)}),ne.add(it)}function ae(ne,be){if(!typeRefRe.test(be=b()))throw pe(be,"reference");var Ie=be;L(null,function(Fe){switch(Fe){case"required":case"repeated":j(ne,Fe,Ie);break;case"optional":te==="proto3"?j(ne,"proto3_optional",Ie):j(ne,"optional",Ie);break;default:if(te==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(ne,"optional",Ie);break}})}for(var de;(de=b())!==null;)switch(de){case"package":if(!C)throw pe(de);je();break;case"import":if(!C)throw pe(de);we();break;case"syntax":if(!C)throw pe(de);D();break;case"edition":if(!C)throw pe(de);q();break;case"option":he(fe,de),M(";",!0);break;default:if(O(fe,de)){C=!1;continue}throw pe(de)}return ge(),parse.filename=null,{package:B,imports:N,weakImports:H,root:u}}var common_1=common,commonRe=/\/|\./;function common(y,u){commonRe.test(y)||(y="google/protobuf/"+y+".proto",u={nested:{google:{nested:{protobuf:{nested:u}}}}}),common[y]=u}common("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var timeType;common("duration",{Duration:timeType={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}});common("timestamp",{Timestamp:timeType});common("empty",{Empty:{fields:{}}});common("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}});common("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}});common("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}});common.get=function y(u){return common[u]||null};var protobuf$1=src.exports=indexLightExports;protobuf$1.build="full";protobuf$1.tokenize=tokenize_1;protobuf$1.parse=parse_1;protobuf$1.common=common_1;protobuf$1.Root._configure(protobuf$1.Type,protobuf$1.parse,protobuf$1.common);var srcExports=src.exports,protobufjs=srcExports;const protobuf=getDefaultExportFromCjs$1(protobufjs);class Waku{constructor(u,h,v){this.node=u,this.chatTopic=h,this.onMessage=v,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.reliableChannel=null,this.decoder=null,this.messagePayloadType=null,this.messageReceivedListener=null,this.senderId=crypto$1.randomBytes(8).toString("hex"),this.handleMessageReceived=async({payload:w})=>{try{if(!w){this.logger.warn("Received Waku message without payload");return}if(!this.messagePayloadType)throw new Error("Protobuf schema not initialized");const b=this.messagePayloadType.decode(w),E=this.messagePayloadType.toObject(b,{longs:String,enums:String,defaults:!0});if(!E.message){this.logger.warn("Decoded object has no message field");return}let $=E.message.additionalProps;if($&&typeof $=="string")try{$=JSON.parse($)}catch{this.logger.warn("Failed to parse additionalProps as JSON:",$)}const M={...E.message,timestamp:Number(E.message.timestamp),additionalProps:$};if(!(M!=null&&M.id)){this.logger.warn("Received invalid message structure via Waku");return}this.onMessage(M)}catch(b){this.errorHandler.handleError(b,"Waku2.handleMessageReceived")}}}async start(){this.createProtobufSchema(),await this.createChannel()}createProtobufSchema(){const u=new protobuf.Type("MessageData").add(new protobuf.Field("id",1,"string")).add(new protobuf.Field("targetMessageId",2,"string","optional")).add(new protobuf.Field("type",3,"string")).add(new protobuf.Field("message",4,"string")).add(new protobuf.Field("username",5,"string")).add(new protobuf.Field("address",6,"string")).add(new protobuf.Field("timestamp",7,"uint64")).add(new protobuf.Field("signature",8,"string")).add(new protobuf.Field("index",9,"uint32")).add(new protobuf.Field("chatTopic",10,"string")).add(new protobuf.Field("userTopic",11,"string")).add(new protobuf.Field("additionalProps",12,"string","optional")),h=new protobuf.Type("MessageStateRef").add(new protobuf.Field("reference",1,"string")).add(new protobuf.Field("timestamp",2,"uint64"));this.messagePayloadType=new protobuf.Type("MessagePayload").add(u).add(h).add(new protobuf.Field("message",1,"MessageData")).add(new protobuf.Field("messageStateRefs",2,"MessageStateRef","repeated")),this.logger.info("Protobuf schema created for chat messages")}async createChannel(){if(!this.node)throw new Error("Waku node not initialized");const u=`/solarpunk-msrs-chat/1/${this.chatTopic}/proto`,h=`chat-channel-${this.chatTopic}`,v=this.node.createEncoder({contentTopic:u}),w=this.decoder=this.node.createDecoder({contentTopic:u});this.reliableChannel=await ReliableChannel.create(this.node,h,this.senderId,v,w,{retrieveFrequencyMs:3e3,queryOnConnect:!1}),this.setupChannelEventListeners(this.reliableChannel),this.logger.info(`Created reliable channel for topic: ${this.chatTopic}`)}setupChannelEventListeners(u){this.messageReceivedListener=h=>{this.handleMessageReceived(h.detail)},u.addEventListener("message-received",this.messageReceivedListener)}async stop(){this.reliableChannel&&this.messageReceivedListener&&this.decoder&&(this.reliableChannel.removeEventListener("message-received",this.messageReceivedListener),this.messageReceivedListener=null,await this.reliableChannel.stop(),this.logger.info("Waku reliable channel stopped"))}}class SwarmChat{constructor(u){this.waku=null,this.isStarted=!1,this.startPromise=null,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.gsocIndex=null,this.fetchProcessRunning=!1,this.stopFetch=!1;const h=new beeJs.PrivateKey(remove0x(u.user.privateKey));this.userDetails={privateKey:u.user.privateKey,ownAddress:h.publicKey().address().toString(),nickname:u.user.nickname,ownIndex:-1},this.swarmSettings={bee:new beeJs.Bee(u.infra.beeUrl),beeUrl:u.infra.beeUrl,stamp:u.infra.stamp||"0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",enveloped:u.infra.enveloped,gsocTopic:u.infra.gsocTopic,gsocResourceId:u.infra.gsocResourceId,chatTopic:u.infra.chatTopic,chatAddress:u.infra.chatAddress,wakuNode:u.infra.wakuNode},this.emitter=new EventEmitter$2,this.utils=new SwarmChatUtils(this.userDetails,this.swarmSettings),this.history=new SwarmHistory(this.utils,this.emitter)}async start(){await this.init(),await this.startMessageFetchProcess()}async startMessageFetchProcess(){const{wakuNode:u}=this.swarmSettings;u?await this.startWakuMessageFetch(u):await this.startPollingMessageFetch()}async stop(){this.emitter.cleanAll(),this.stopPollingMessageFetch(),this.history.cleanup(),this.waku&&(await this.waku.stop(),this.waku=null)}async startWakuMessageFetch(u){this.logger.info("Waku is enabled");const h=this.swarmSettings.chatTopic;this.waku=new Waku(u,h,v=>{this.emitter.emit(EVENTS.MESSAGE_RECEIVED,v)}),await this.waku.start()}getEmitter(){return this.emitter}orderMessages(u){return this.utils.orderMessages(u)}async sendMessage(u,h,v,w,b){const E=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,$={id:w||v4(),username:this.userDetails.nickname,address:this.userDetails.ownAddress,chatTopic:this.swarmSettings.chatTopic,userTopic:this.utils.generateUserOwnedFeedId(this.swarmSettings.chatTopic,this.userDetails.ownAddress),signature:this.getSignature(u),timestamp:Date.now(),index:E,type:h,targetMessageId:v,message:u,additionalProps:b},M=validateMessageWithAdditionalProperties($);if(!M.isValid){const T=`Invalid message: ${M.errors.join(", ")}`;throw this.logger.error(T),new Error(T)}try{this.emitter.emit(EVENTS.MESSAGE_REQUEST_INITIATED,$),await this.utils.writeOwnFeedDataByIndex(E,JSON.stringify($)),this.userDetails.ownIndex=E,this.emitter.emit(EVENTS.MESSAGE_REQUEST_UPLOADED,$),await this.broadcastUserMessage($)}catch(T){this.emitter.emit(EVENTS.MESSAGE_REQUEST_ERROR,$),this.errorHandler.handleError(T,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(u){this.sendMessage(u.message,u.type,u.targetMessageId,u.id,u.additionalProps)}async retryBroadcastUserMessage(u){await this.broadcastUserMessage(u)}async init(){try{this.emitter.emit(EVENTS.LOADING_INIT,!0);const[u,h]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(u.status==="rejected")throw u.reason;h.status==="fulfilled"&&(this.gsocIndex=h.value),this.emitter.emit(EVENTS.LOADING_INIT,!1)}catch(u){this.errorHandler.handleError(u,"Chat.initSelfState"),this.emitter.emit(EVENTS.CRITICAL_ERROR,u)}}async initOwnIndex(){const{latestIndex:v}=await retryAwaitableAsync(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=v}async fetchLatestMessage(){try{if(!this.gsocIndex)return;const u=beeJs.Topic.fromString(this.swarmSettings.chatTopic),h=makeFeedIdentifier(u,this.gsocIndex),v=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,h.toString()),w=JSON.parse(v);if(!validateGsocMessage(w)){this.logger.warn("Invalid GSOC message during fetching");return}this.emitter.emit(EVENTS.MESSAGE_RECEIVED,w.message),this.gsocIndex=this.gsocIndex.next()}catch(u){if(this.utils.isNotFoundError(u))return;this.errorHandler.handleError(u,"Chat.fetchLatestMessage")}}async broadcastUserMessage(u){try{return retryAwaitableAsync(()=>this.utils.sendMessageToGsoc(JSON.stringify(u)))}catch(h){this.errorHandler.handleError(h,"Chat.broadcastUserMessage")}}getSignature(u){const{ownAddress:h,privateKey:v,nickname:w}=this.userDetails,b=new beeJs.EthAddress(h).toString(),E=new beeJs.PrivateKey(v);if(E.publicKey().address().toString()!==b)throw new Error("The provided address does not match the address derived from the private key");const M=Date.now();return E.sign(JSON.stringify({username:w,address:b,message:u,timestamp:M})).toHex()}async startPollingMessageFetch(){if(this.fetchProcessRunning)return;this.fetchProcessRunning=!0,this.stopFetch=!1;const u=async()=>{if(this.stopFetch){this.fetchProcessRunning=!1;return}await this.fetchLatestMessage(),setTimeout(u,200)};u()}stopPollingMessageFetch(){this.stopFetch=!0}}exports.EVENTS=EVENTS;exports.MessageType=MessageType;exports.SwarmChat=SwarmChat;
|
package/dist/lib/core.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ import { AdditionalMessageProperties, ChatSettings, MessageData, MessageType } f
|
|
|
2
2
|
import { EventEmitter } from '../utils/eventEmitter';
|
|
3
3
|
export declare class SwarmChat {
|
|
4
4
|
private waku;
|
|
5
|
+
private isStarted;
|
|
6
|
+
private startPromise;
|
|
5
7
|
private emitter;
|
|
6
8
|
private utils;
|
|
7
9
|
private history;
|
|
@@ -12,11 +14,8 @@ export declare class SwarmChat {
|
|
|
12
14
|
private gsocIndex;
|
|
13
15
|
private fetchProcessRunning;
|
|
14
16
|
private stopFetch;
|
|
15
|
-
private isStarted;
|
|
16
|
-
private startPromise;
|
|
17
17
|
constructor(settings: ChatSettings);
|
|
18
18
|
start(): Promise<void>;
|
|
19
|
-
private performStart;
|
|
20
19
|
private startMessageFetchProcess;
|
|
21
20
|
stop(): Promise<void>;
|
|
22
21
|
private startWakuMessageFetch;
|
package/dist/lib/core.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../../src/lib/core.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,2BAA2B,EAC3B,YAAY,EAGZ,WAAW,EACX,WAAW,EAEZ,MAAM,eAAe,CAAC;AAIvB,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AASrD,qBAAa,SAAS;IACpB,OAAO,CAAC,IAAI,CAAqB;
|
|
1
|
+
{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../../src/lib/core.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,2BAA2B,EAC3B,YAAY,EAGZ,WAAW,EACX,WAAW,EAEZ,MAAM,eAAe,CAAC;AAIvB,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AASrD,qBAAa,SAAS;IACpB,OAAO,CAAC,IAAI,CAAqB;IACjC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,YAAY,CAA8B;IAElD,OAAO,CAAC,OAAO,CAAe;IAC9B,OAAO,CAAC,KAAK,CAAiB;IAC9B,OAAO,CAAC,OAAO,CAAe;IAC9B,OAAO,CAAC,WAAW,CAAmB;IACtC,OAAO,CAAC,aAAa,CAAoB;IAEzC,OAAO,CAAC,MAAM,CAAwB;IACtC,OAAO,CAAC,YAAY,CAA8B;IAElD,OAAO,CAAC,SAAS,CAA0B;IAC3C,OAAO,CAAC,mBAAmB,CAAS;IACpC,OAAO,CAAC,SAAS,CAAS;gBAEd,QAAQ,EAAE,YAAY;IA2BrB,KAAK;YAKJ,wBAAwB;IAUzB,IAAI;YAWH,qBAAqB;IAW5B,UAAU;IAIV,aAAa,CAAC,QAAQ,EAAE,GAAG,EAAE;IAIvB,WAAW,CACtB,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,WAAW,EACjB,eAAe,CAAC,EAAE,MAAM,EACxB,EAAE,CAAC,EAAE,MAAM,EACX,eAAe,CAAC,EAAE,2BAA2B,GAC5C,OAAO,CAAC,IAAI,CAAC;IAwCH,qBAAqB;IAW3B,mBAAmB,IAAI,OAAO;IAIxB,gBAAgB,CAAC,OAAO,EAAE,WAAW;IAIrC,yBAAyB,CAAC,OAAO,EAAE,WAAW;YAI7C,IAAI;YAqBJ,YAAY;YAUZ,kBAAkB;YA4BlB,oBAAoB;IAQlC,OAAO,CAAC,YAAY;YAkBN,wBAAwB;IAmBtC,OAAO,CAAC,uBAAuB;CAGhC"}
|
package/dist/swarm-chat-umd.js
CHANGED
|
@@ -64,4 +64,4 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
64
64
|
`;)Me++;return Me}function fe(){if($.length>0)return $.shift();if(M)return C();var pe,Me,$e,Pe,Be,Re=h===0;do{if(h===v)return null;for(pe=!1;whitespaceRe.test($e=B(h));)if($e===`
|
|
65
65
|
`&&(Re=!0,++w),++h===v)return null;if(B(h)==="/"){if(++h===v)throw T("comment");if(B(h)==="/")if(u){if(Pe=h,Be=!1,H(h-1)){Be=!0;do if(h=te(h),h===v||(h++,!Re))break;while(H(h))}else h=Math.min(v,te(h)+1);Be&&(N(Pe,h,Re),Re=!0),w++,pe=!0}else{for(Be=B(Pe=h+1)==="/";B(++h)!==`
|
|
66
66
|
`;)if(h===v)return null;++h,Be&&(N(Pe,h-1,Re),Re=!0),++w,pe=!0}else if(($e=B(h))==="*"){Pe=h+1,Be=u||B(Pe)==="*";do{if($e===`
|
|
67
|
-
`&&++w,++h===v)throw T("comment");Me=$e,$e=B(h)}while(Me!=="*"||$e!=="/");++h,Be&&(N(Pe,h-2,Re),Re=!0),pe=!0}else return"/"}}while(pe);var je=h;delimRe.lastIndex=0;var we=delimRe.test(B(je++));if(!we)for(;je<v&&!delimRe.test(B(je));)++je;var D=y.substring(h,h=je);return(D==='"'||D==="'")&&(M=D),D}function ce(pe){$.push(pe)}function le(){if(!$.length){var pe=fe();if(pe===null)return null;ce(pe)}return $[0]}function ie(pe,Me){var $e=le(),Pe=$e===pe;if(Pe)return fe(),!0;if(!Me)throw T("token '"+$e+"', '"+pe+"' expected");return!1}function ge(pe){var Me=null,$e;return pe===void 0?($e=E[w-1],delete E[w-1],$e&&(u||$e.type==="*"||$e.lineEmpty)&&(Me=$e.leading?$e.text:null)):(b<pe&&le(),$e=E[pe],delete E[pe],$e&&!$e.lineEmpty&&(u||$e.type==="/")&&(Me=$e.leading?null:$e.text)),Me}return Object.defineProperty({next:fe,peek:le,push:ce,skip:ie,cmnt:ge},"line",{get:function(){return w}})}var parse_1=parse;parse.filename=null,parse.defaults={keepCase:!1};var tokenize=tokenize_1,Root=requireRoot(),Type=requireType(),Field=requireField(),MapField=requireMapfield(),OneOf=requireOneof(),Enum=require_enum(),Service=requireService(),Method=requireMethod(),ReflectionObject=requireObject(),types=requireTypes(),util=requireUtil(),base10Re=/^[1-9][0-9]*$/,base10NegRe=/^-?[1-9][0-9]*$/,base16Re=/^0[x][0-9a-fA-F]+$/,base16NegRe=/^-?0[x][0-9a-fA-F]+$/,base8Re=/^0[0-7]+$/,base8NegRe=/^-?0[0-7]+$/,numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,nameRe=/^[a-zA-Z_][a-zA-Z_0-9]*$/,typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function parse(y,u,h){u instanceof Root||(h=u,u=new Root),h||(h=parse.defaults);var v=h.preferTrailingComment||!1,w=tokenize(y,h.alternateCommentMode||!1),b=w.next,E=w.push,$=w.peek,M=w.skip,T=w.cmnt,C=!0,B,N,H,te="proto2",fe=u,ce=[],le={},ie=h.keepCase?function(ne){return ne}:util.camelCase;function ge(){ce.forEach(ne=>{ne._edition=te,Object.keys(le).forEach(be=>{ne.getOption(be)===void 0&&ne.setOption(be,le[be],!0)})})}function pe(ne,be,Ie){var Le=parse.filename;return Ie||(parse.filename=null),Error("illegal "+(be||"token")+" '"+ne+"' ("+(Le?Le+", ":"")+"line "+w.line+")")}function Me(){var ne=[],be;do{if((be=b())!=='"'&&be!=="'")throw pe(be);ne.push(b()),M(be),be=$()}while(be==='"'||be==="'");return ne.join("")}function $e(ne){var be=b();switch(be){case"'":case'"':return E(be),Me();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return Be(be,!0)}catch{if(typeRefRe.test(be))return be;throw pe(be,"value")}}function Pe(ne,be){var Ie,Le;do if(be&&((Ie=$())==='"'||Ie==="'")){var Fe=Me();if(ne.push(Fe),te>=2023)throw pe(Fe,"id")}else try{ne.push([Le=Re(b()),M("to",!0)?Re(b()):Le])}catch(tt){if(be&&typeRefRe.test(Ie)&&te>=2023)ne.push(Ie);else throw tt}while(M(",",!0));var He={options:void 0};He.setOption=function(tt,Ne){this.options===void 0&&(this.options={}),this.options[tt]=Ne},L(He,function(Ne){if(Ne==="option")he(He,Ne),M(";");else throw pe(Ne)},function(){oe(He)})}function Be(ne,be){var Ie=1;switch(ne.charAt(0)==="-"&&(Ie=-1,ne=ne.substring(1)),ne){case"inf":case"INF":case"Inf":return Ie*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(base10Re.test(ne))return Ie*parseInt(ne,10);if(base16Re.test(ne))return Ie*parseInt(ne,16);if(base8Re.test(ne))return Ie*parseInt(ne,8);if(numberRe.test(ne))return Ie*parseFloat(ne);throw pe(ne,"number",be)}function Re(ne,be){switch(ne){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!be&&ne.charAt(0)==="-")throw pe(ne,"id");if(base10NegRe.test(ne))return parseInt(ne,10);if(base16NegRe.test(ne))return parseInt(ne,16);if(base8NegRe.test(ne))return parseInt(ne,8);throw pe(ne,"id")}function je(){if(B!==void 0)throw pe("package");if(B=b(),!typeRefRe.test(B))throw pe(B,"name");fe=fe.define(B),M(";")}function we(){var ne=$(),be;switch(ne){case"weak":be=H||(H=[]),b();break;case"public":b();default:be=N||(N=[]);break}ne=Me(),M(";"),be.push(ne)}function D(){if(M("="),te=Me(),te<2023)throw pe(te,"syntax");M(";")}function q(){if(M("="),te=Me(),!["2023"].includes(te))throw pe(te,"edition");M(";")}function O(ne,be){switch(be){case"option":return he(ne,be),M(";"),!0;case"message":return X(ne,be),!0;case"enum":return Q(ne,be),!0;case"service":return ye(ne,be),!0;case"extend":return ae(ne,be),!0}return!1}function L(ne,be,Ie){var Le=w.line;if(ne&&(typeof ne.comment!="string"&&(ne.comment=T()),ne.filename=parse.filename),M("{",!0)){for(var Fe;(Fe=b())!=="}";)be(Fe);M(";",!0)}else Ie&&Ie(),M(";"),ne&&(typeof ne.comment!="string"||v)&&(ne.comment=T(Le)||ne.comment)}function X(ne,be){if(!nameRe.test(be=b()))throw pe(be,"type name");var Ie=new Type(be);L(Ie,function(Fe){if(!O(Ie,Fe))switch(Fe){case"map":ee(Ie);break;case"required":if(te!=="proto2")throw pe(Fe);case"repeated":j(Ie,Fe);break;case"optional":if(te==="proto3")j(Ie,"proto3_optional");else{if(te!=="proto2")throw pe(Fe);j(Ie,"optional")}break;case"oneof":F(Ie,Fe);break;case"extensions":Pe(Ie.extensions||(Ie.extensions=[]));break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0);break;default:if(te==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(Ie,"optional");break}}),ne.add(Ie),ne===fe&&ce.push(Ie)}function j(ne,be,Ie){var Le=b();if(Le==="group"){re(ne,be);return}for(;Le.endsWith(".")||$().startsWith(".");)Le+=b();if(!typeRefRe.test(Le))throw pe(Le,"type");var Fe=b();if(!nameRe.test(Fe))throw pe(Fe,"name");Fe=ie(Fe),M("=");var He=new Field(Fe,Re(b()),Le,be,Ie);if(L(He,function(nt){if(nt==="option")he(He,nt),M(";");else throw pe(nt)},function(){oe(He)}),be==="proto3_optional"){var tt=new OneOf("_"+Fe);He.setOption("proto3_optional",!0),tt.add(He),ne.add(tt)}else ne.add(He);ne===fe&&ce.push(He)}function re(ne,be){if(te>=2023)throw pe("group");var Ie=b();if(!nameRe.test(Ie))throw pe(Ie,"name");var Le=util.lcFirst(Ie);Ie===Le&&(Ie=util.ucFirst(Ie)),M("=");var Fe=Re(b()),He=new Type(Ie);He.group=!0;var tt=new Field(Le,Fe,Ie,be);tt.filename=parse.filename,L(He,function(nt){switch(nt){case"option":he(He,nt),M(";");break;case"required":case"repeated":j(He,nt);break;case"optional":te==="proto3"?j(He,"proto3_optional"):j(He,"optional");break;case"message":X(He,nt);break;case"enum":Q(He,nt);break;case"reserved":Pe(He.reserved||(He.reserved=[]),!0);break;default:throw pe(nt)}}),ne.add(He).add(tt)}function ee(ne){M("<");var be=b();if(types.mapKey[be]===void 0)throw pe(be,"type");M(",");var Ie=b();if(!typeRefRe.test(Ie))throw pe(Ie,"type");M(">");var Le=b();if(!nameRe.test(Le))throw pe(Le,"name");M("=");var Fe=new MapField(ie(Le),Re(b()),be,Ie);L(Fe,function(tt){if(tt==="option")he(Fe,tt),M(";");else throw pe(tt)},function(){oe(Fe)}),ne.add(Fe)}function F(ne,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new OneOf(ie(be));L(Ie,function(Fe){Fe==="option"?(he(Ie,Fe),M(";")):(E(Fe),j(Ie,"optional"))}),ne.add(Ie)}function Q(ne,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new Enum(be);L(Ie,function(Fe){switch(Fe){case"option":he(Ie,Fe),M(";");break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0),Ie.reserved===void 0&&(Ie.reserved=[]);break;default:U(Ie,Fe)}}),ne.add(Ie),ne===fe&&ce.push(Ie)}function U(ne,be){if(!nameRe.test(be))throw pe(be,"name");M("=");var Ie=Re(b(),!0),Le={options:void 0};Le.getOption=function(Fe){return this.options[Fe]},Le.setOption=function(Fe,He){ReflectionObject.prototype.setOption.call(Le,Fe,He)},Le.setParsedOption=function(){},L(Le,function(He){if(He==="option")he(Le,He),M(";");else throw pe(He)},function(){oe(Le)}),ne.add(be,Ie,Le.comment,Le.parsedOptions||Le.options)}function he(ne,be){var Ie,Le,Fe=!0;for(be==="option"&&(be=b());be!=="=";){if(be==="("){var He=b();M(")"),be="("+He+")"}if(Fe){if(Fe=!1,be.includes(".")&&!be.includes("(")){var tt=be.split(".");Ie=tt[0]+".",be=tt[1];continue}Ie=be}else Le=Le?Le+=be:be;be=b()}var Ne=Le?Ie.concat(Le):Ie,nt=Oe(ne,Ne);Le=Le&&Le[0]==="."?Le.slice(1):Le,Ie=Ie&&Ie[Ie.length-1]==="."?Ie.slice(0,-1):Ie,Ae(ne,Ie,nt,Le)}function Oe(ne,be){if(M("{",!0)){for(var Ie={};!M("}",!0);){if(!nameRe.test(de=b()))throw pe(de,"name");if(de===null)throw pe(de,"end of input");var Le,Fe=de;if(M(":",!0),$()==="{")Le=Oe(ne,be+"."+de);else if($()==="["){Le=[];var He;if(M("[",!0)){do He=$e(),Le.push(He);while(M(",",!0));M("]"),typeof He<"u"&&Ve(ne,be+"."+de,He)}}else Le=$e(),Ve(ne,be+"."+de,Le);var tt=Ie[Fe];tt&&(Le=[].concat(tt).concat(Le)),Ie[Fe]=Le,M(",",!0),M(";",!0)}return Ie}var Ne=$e();return Ve(ne,be,Ne),Ne}function Ve(ne,be,Ie){if(fe===ne&&/^features\./.test(be)){le[be]=Ie;return}ne.setOption&&ne.setOption(be,Ie)}function Ae(ne,be,Ie,Le){ne.setParsedOption&&ne.setParsedOption(be,Ie,Le)}function oe(ne){if(M("[",!0)){do he(ne,"option");while(M(",",!0));M("]")}return ne}function ye(ne,be){if(!nameRe.test(be=b()))throw pe(be,"service name");var Ie=new Service(be);L(Ie,function(Fe){if(!O(Ie,Fe))if(Fe==="rpc")Ce(Ie,Fe);else throw pe(Fe)}),ne.add(Ie),ne===fe&&ce.push(Ie)}function Ce(ne,be){var Ie=T(),Le=be;if(!nameRe.test(be=b()))throw pe(be,"name");var Fe=be,He,tt,Ne,nt;if(M("("),M("stream",!0)&&(tt=!0),!typeRefRe.test(be=b())||(He=be,M(")"),M("returns"),M("("),M("stream",!0)&&(nt=!0),!typeRefRe.test(be=b())))throw pe(be);Ne=be,M(")");var it=new Method(Fe,Le,He,Ne,tt,nt);it.comment=Ie,L(it,function(ut){if(ut==="option")he(it,ut),M(";");else throw pe(ut)}),ne.add(it)}function ae(ne,be){if(!typeRefRe.test(be=b()))throw pe(be,"reference");var Ie=be;L(null,function(Fe){switch(Fe){case"required":case"repeated":j(ne,Fe,Ie);break;case"optional":te==="proto3"?j(ne,"proto3_optional",Ie):j(ne,"optional",Ie);break;default:if(te==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(ne,"optional",Ie);break}})}for(var de;(de=b())!==null;)switch(de){case"package":if(!C)throw pe(de);je();break;case"import":if(!C)throw pe(de);we();break;case"syntax":if(!C)throw pe(de);D();break;case"edition":if(!C)throw pe(de);q();break;case"option":he(fe,de),M(";",!0);break;default:if(O(fe,de)){C=!1;continue}throw pe(de)}return ge(),parse.filename=null,{package:B,imports:N,weakImports:H,root:u}}var common_1=common,commonRe=/\/|\./;function common(y,u){commonRe.test(y)||(y="google/protobuf/"+y+".proto",u={nested:{google:{nested:{protobuf:{nested:u}}}}}),common[y]=u}common("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var timeType;common("duration",{Duration:timeType={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),common("timestamp",{Timestamp:timeType}),common("empty",{Empty:{fields:{}}}),common("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),common("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),common("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),common.get=function y(u){return common[u]||null};var protobuf$1=src.exports=indexLightExports;protobuf$1.build="full",protobuf$1.tokenize=tokenize_1,protobuf$1.parse=parse_1,protobuf$1.common=common_1,protobuf$1.Root._configure(protobuf$1.Type,protobuf$1.parse,protobuf$1.common);var srcExports=src.exports,protobufjs=srcExports;const protobuf=getDefaultExportFromCjs$1(protobufjs);class Waku{constructor(u,h,v){this.node=u,this.chatTopic=h,this.onMessage=v,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.reliableChannel=null,this.decoder=null,this.messagePayloadType=null,this.messageReceivedListener=null,this.senderId=crypto$1.randomBytes(8).toString("hex"),this.handleMessageReceived=async({payload:w})=>{try{if(!w){this.logger.warn("Received Waku message without payload");return}if(!this.messagePayloadType)throw new Error("Protobuf schema not initialized");const b=this.messagePayloadType.decode(w),E=this.messagePayloadType.toObject(b,{longs:String,enums:String,defaults:!0});if(!E.message){this.logger.warn("Decoded object has no message field");return}let $=E.message.additionalProps;if($&&typeof $=="string")try{$=JSON.parse($)}catch{this.logger.warn("Failed to parse additionalProps as JSON:",$)}const M={...E.message,timestamp:Number(E.message.timestamp),additionalProps:$};if(!(M!=null&&M.id)){this.logger.warn("Received invalid message structure via Waku");return}this.onMessage(M)}catch(b){this.errorHandler.handleError(b,"Waku2.handleMessageReceived")}}}async start(){this.createProtobufSchema(),await this.createChannel()}createProtobufSchema(){const u=new protobuf.Type("MessageData").add(new protobuf.Field("id",1,"string")).add(new protobuf.Field("targetMessageId",2,"string","optional")).add(new protobuf.Field("type",3,"string")).add(new protobuf.Field("message",4,"string")).add(new protobuf.Field("username",5,"string")).add(new protobuf.Field("address",6,"string")).add(new protobuf.Field("timestamp",7,"uint64")).add(new protobuf.Field("signature",8,"string")).add(new protobuf.Field("index",9,"uint32")).add(new protobuf.Field("chatTopic",10,"string")).add(new protobuf.Field("userTopic",11,"string")).add(new protobuf.Field("additionalProps",12,"string","optional")),h=new protobuf.Type("MessageStateRef").add(new protobuf.Field("reference",1,"string")).add(new protobuf.Field("timestamp",2,"uint64"));this.messagePayloadType=new protobuf.Type("MessagePayload").add(u).add(h).add(new protobuf.Field("message",1,"MessageData")).add(new protobuf.Field("messageStateRefs",2,"MessageStateRef","repeated")),this.logger.info("Protobuf schema created for chat messages")}async createChannel(){if(!this.node)throw new Error("Waku node not initialized");const u=`/solarpunk-msrs-chat/1/${this.chatTopic}/proto`,h=`chat-channel-${this.chatTopic}`,v=this.node.createEncoder({contentTopic:u}),w=this.decoder=this.node.createDecoder({contentTopic:u});this.reliableChannel=await ReliableChannel.create(this.node,h,this.senderId,v,w,{retrieveFrequencyMs:3e3,queryOnConnect:!1}),this.setupChannelEventListeners(this.reliableChannel),this.logger.info(`Created reliable channel for topic: ${this.chatTopic}`)}setupChannelEventListeners(u){this.messageReceivedListener=h=>{this.handleMessageReceived(h.detail)},u.addEventListener("message-received",this.messageReceivedListener)}async stop(){this.reliableChannel&&this.messageReceivedListener&&this.decoder&&(this.reliableChannel.removeEventListener("message-received",this.messageReceivedListener),this.messageReceivedListener=null,await this.reliableChannel.stop(),this.logger.info("Waku reliable channel stopped"))}}class SwarmChat{constructor(u){this.waku=null,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.gsocIndex=null,this.fetchProcessRunning=!1,this.stopFetch=!1,this.isStarted=!1,this.startPromise=null;const h=new beeJs.PrivateKey(remove0x(u.user.privateKey));this.userDetails={privateKey:u.user.privateKey,ownAddress:h.publicKey().address().toString(),nickname:u.user.nickname,ownIndex:-1},this.swarmSettings={bee:new beeJs.Bee(u.infra.beeUrl),beeUrl:u.infra.beeUrl,stamp:u.infra.stamp||"0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",enveloped:u.infra.enveloped,gsocTopic:u.infra.gsocTopic,gsocResourceId:u.infra.gsocResourceId,chatTopic:u.infra.chatTopic,chatAddress:u.infra.chatAddress,wakuNode:u.infra.wakuNode},this.emitter=new EventEmitter$2,this.utils=new SwarmChatUtils(this.userDetails,this.swarmSettings),this.history=new SwarmHistory(this.utils,this.emitter)}async start(){if(this.isStarted){this.logger.debug("SwarmChat is already started, ignoring duplicate start() call");return}if(this.startPromise)return this.logger.debug("SwarmChat start is already in progress, waiting for completion"),this.startPromise;this.startPromise=this.performStart();try{await this.startPromise,this.isStarted=!0}finally{this.startPromise=null}}async performStart(){await this.init(),await this.startMessageFetchProcess()}async startMessageFetchProcess(){const{wakuNode:u}=this.swarmSettings;u?await this.startWakuMessageFetch(u):await this.startPollingMessageFetch()}async stop(){this.isStarted=!1,this.startPromise=null,this.emitter.cleanAll(),this.stopPollingMessageFetch(),this.history.cleanup(),this.waku&&(await this.waku.stop(),this.waku=null)}async startWakuMessageFetch(u){this.logger.info("Waku is enabled");const h=this.swarmSettings.chatTopic;this.waku=new Waku(u,h,v=>{this.emitter.emit(EVENTS.MESSAGE_RECEIVED,v)}),await this.waku.start()}getEmitter(){return this.emitter}orderMessages(u){return this.utils.orderMessages(u)}async sendMessage(u,h,v,w,b){const E=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,$={id:w||v4(),username:this.userDetails.nickname,address:this.userDetails.ownAddress,chatTopic:this.swarmSettings.chatTopic,userTopic:this.utils.generateUserOwnedFeedId(this.swarmSettings.chatTopic,this.userDetails.ownAddress),signature:this.getSignature(u),timestamp:Date.now(),index:E,type:h,targetMessageId:v,message:u,additionalProps:b},M=validateMessageWithAdditionalProperties($);if(!M.isValid){const T=`Invalid message: ${M.errors.join(", ")}`;throw this.logger.error(T),new Error(T)}try{this.emitter.emit(EVENTS.MESSAGE_REQUEST_INITIATED,$),await this.utils.writeOwnFeedDataByIndex(E,JSON.stringify($)),this.userDetails.ownIndex=E,this.emitter.emit(EVENTS.MESSAGE_REQUEST_UPLOADED,$),await this.broadcastUserMessage($)}catch(T){this.emitter.emit(EVENTS.MESSAGE_REQUEST_ERROR,$),this.errorHandler.handleError(T,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(u){this.sendMessage(u.message,u.type,u.targetMessageId,u.id,u.additionalProps)}async retryBroadcastUserMessage(u){await this.broadcastUserMessage(u)}async init(){try{this.emitter.emit(EVENTS.LOADING_INIT,!0);const[u,h]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(u.status==="rejected")throw u.reason;h.status==="fulfilled"&&(this.gsocIndex=h.value),this.emitter.emit(EVENTS.LOADING_INIT,!1)}catch(u){this.errorHandler.handleError(u,"Chat.initSelfState"),this.emitter.emit(EVENTS.CRITICAL_ERROR,u)}}async initOwnIndex(){const{latestIndex:v}=await retryAwaitableAsync(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=v}async fetchLatestMessage(){try{if(!this.gsocIndex)return;const u=beeJs.Topic.fromString(this.swarmSettings.chatTopic),h=makeFeedIdentifier(u,this.gsocIndex),v=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,h.toString()),w=JSON.parse(v);if(!validateGsocMessage(w)){this.logger.warn("Invalid GSOC message during fetching");return}this.emitter.emit(EVENTS.MESSAGE_RECEIVED,w.message),this.gsocIndex=this.gsocIndex.next()}catch(u){if(this.utils.isNotFoundError(u))return;this.errorHandler.handleError(u,"Chat.fetchLatestMessage")}}async broadcastUserMessage(u){try{return retryAwaitableAsync(()=>this.utils.sendMessageToGsoc(JSON.stringify(u)))}catch(h){this.errorHandler.handleError(h,"Chat.broadcastUserMessage")}}getSignature(u){const{ownAddress:h,privateKey:v,nickname:w}=this.userDetails,b=new beeJs.EthAddress(h).toString(),E=new beeJs.PrivateKey(v);if(E.publicKey().address().toString()!==b)throw new Error("The provided address does not match the address derived from the private key");const M=Date.now();return E.sign(JSON.stringify({username:w,address:b,message:u,timestamp:M})).toHex()}async startPollingMessageFetch(){if(this.fetchProcessRunning)return;this.fetchProcessRunning=!0,this.stopFetch=!1;const u=async()=>{if(this.stopFetch){this.fetchProcessRunning=!1;return}await this.fetchLatestMessage(),setTimeout(u,200)};u()}stopPollingMessageFetch(){this.stopFetch=!0}}exports.EVENTS=EVENTS,exports.MessageType=MessageType,exports.SwarmChat=SwarmChat,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
|
|
67
|
+
`&&++w,++h===v)throw T("comment");Me=$e,$e=B(h)}while(Me!=="*"||$e!=="/");++h,Be&&(N(Pe,h-2,Re),Re=!0),pe=!0}else return"/"}}while(pe);var je=h;delimRe.lastIndex=0;var we=delimRe.test(B(je++));if(!we)for(;je<v&&!delimRe.test(B(je));)++je;var D=y.substring(h,h=je);return(D==='"'||D==="'")&&(M=D),D}function ce(pe){$.push(pe)}function le(){if(!$.length){var pe=fe();if(pe===null)return null;ce(pe)}return $[0]}function ie(pe,Me){var $e=le(),Pe=$e===pe;if(Pe)return fe(),!0;if(!Me)throw T("token '"+$e+"', '"+pe+"' expected");return!1}function ge(pe){var Me=null,$e;return pe===void 0?($e=E[w-1],delete E[w-1],$e&&(u||$e.type==="*"||$e.lineEmpty)&&(Me=$e.leading?$e.text:null)):(b<pe&&le(),$e=E[pe],delete E[pe],$e&&!$e.lineEmpty&&(u||$e.type==="/")&&(Me=$e.leading?null:$e.text)),Me}return Object.defineProperty({next:fe,peek:le,push:ce,skip:ie,cmnt:ge},"line",{get:function(){return w}})}var parse_1=parse;parse.filename=null,parse.defaults={keepCase:!1};var tokenize=tokenize_1,Root=requireRoot(),Type=requireType(),Field=requireField(),MapField=requireMapfield(),OneOf=requireOneof(),Enum=require_enum(),Service=requireService(),Method=requireMethod(),ReflectionObject=requireObject(),types=requireTypes(),util=requireUtil(),base10Re=/^[1-9][0-9]*$/,base10NegRe=/^-?[1-9][0-9]*$/,base16Re=/^0[x][0-9a-fA-F]+$/,base16NegRe=/^-?0[x][0-9a-fA-F]+$/,base8Re=/^0[0-7]+$/,base8NegRe=/^-?0[0-7]+$/,numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,nameRe=/^[a-zA-Z_][a-zA-Z_0-9]*$/,typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function parse(y,u,h){u instanceof Root||(h=u,u=new Root),h||(h=parse.defaults);var v=h.preferTrailingComment||!1,w=tokenize(y,h.alternateCommentMode||!1),b=w.next,E=w.push,$=w.peek,M=w.skip,T=w.cmnt,C=!0,B,N,H,te="proto2",fe=u,ce=[],le={},ie=h.keepCase?function(ne){return ne}:util.camelCase;function ge(){ce.forEach(ne=>{ne._edition=te,Object.keys(le).forEach(be=>{ne.getOption(be)===void 0&&ne.setOption(be,le[be],!0)})})}function pe(ne,be,Ie){var Le=parse.filename;return Ie||(parse.filename=null),Error("illegal "+(be||"token")+" '"+ne+"' ("+(Le?Le+", ":"")+"line "+w.line+")")}function Me(){var ne=[],be;do{if((be=b())!=='"'&&be!=="'")throw pe(be);ne.push(b()),M(be),be=$()}while(be==='"'||be==="'");return ne.join("")}function $e(ne){var be=b();switch(be){case"'":case'"':return E(be),Me();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return Be(be,!0)}catch{if(typeRefRe.test(be))return be;throw pe(be,"value")}}function Pe(ne,be){var Ie,Le;do if(be&&((Ie=$())==='"'||Ie==="'")){var Fe=Me();if(ne.push(Fe),te>=2023)throw pe(Fe,"id")}else try{ne.push([Le=Re(b()),M("to",!0)?Re(b()):Le])}catch(tt){if(be&&typeRefRe.test(Ie)&&te>=2023)ne.push(Ie);else throw tt}while(M(",",!0));var He={options:void 0};He.setOption=function(tt,Ne){this.options===void 0&&(this.options={}),this.options[tt]=Ne},L(He,function(Ne){if(Ne==="option")he(He,Ne),M(";");else throw pe(Ne)},function(){oe(He)})}function Be(ne,be){var Ie=1;switch(ne.charAt(0)==="-"&&(Ie=-1,ne=ne.substring(1)),ne){case"inf":case"INF":case"Inf":return Ie*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(base10Re.test(ne))return Ie*parseInt(ne,10);if(base16Re.test(ne))return Ie*parseInt(ne,16);if(base8Re.test(ne))return Ie*parseInt(ne,8);if(numberRe.test(ne))return Ie*parseFloat(ne);throw pe(ne,"number",be)}function Re(ne,be){switch(ne){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!be&&ne.charAt(0)==="-")throw pe(ne,"id");if(base10NegRe.test(ne))return parseInt(ne,10);if(base16NegRe.test(ne))return parseInt(ne,16);if(base8NegRe.test(ne))return parseInt(ne,8);throw pe(ne,"id")}function je(){if(B!==void 0)throw pe("package");if(B=b(),!typeRefRe.test(B))throw pe(B,"name");fe=fe.define(B),M(";")}function we(){var ne=$(),be;switch(ne){case"weak":be=H||(H=[]),b();break;case"public":b();default:be=N||(N=[]);break}ne=Me(),M(";"),be.push(ne)}function D(){if(M("="),te=Me(),te<2023)throw pe(te,"syntax");M(";")}function q(){if(M("="),te=Me(),!["2023"].includes(te))throw pe(te,"edition");M(";")}function O(ne,be){switch(be){case"option":return he(ne,be),M(";"),!0;case"message":return X(ne,be),!0;case"enum":return Q(ne,be),!0;case"service":return ye(ne,be),!0;case"extend":return ae(ne,be),!0}return!1}function L(ne,be,Ie){var Le=w.line;if(ne&&(typeof ne.comment!="string"&&(ne.comment=T()),ne.filename=parse.filename),M("{",!0)){for(var Fe;(Fe=b())!=="}";)be(Fe);M(";",!0)}else Ie&&Ie(),M(";"),ne&&(typeof ne.comment!="string"||v)&&(ne.comment=T(Le)||ne.comment)}function X(ne,be){if(!nameRe.test(be=b()))throw pe(be,"type name");var Ie=new Type(be);L(Ie,function(Fe){if(!O(Ie,Fe))switch(Fe){case"map":ee(Ie);break;case"required":if(te!=="proto2")throw pe(Fe);case"repeated":j(Ie,Fe);break;case"optional":if(te==="proto3")j(Ie,"proto3_optional");else{if(te!=="proto2")throw pe(Fe);j(Ie,"optional")}break;case"oneof":F(Ie,Fe);break;case"extensions":Pe(Ie.extensions||(Ie.extensions=[]));break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0);break;default:if(te==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(Ie,"optional");break}}),ne.add(Ie),ne===fe&&ce.push(Ie)}function j(ne,be,Ie){var Le=b();if(Le==="group"){re(ne,be);return}for(;Le.endsWith(".")||$().startsWith(".");)Le+=b();if(!typeRefRe.test(Le))throw pe(Le,"type");var Fe=b();if(!nameRe.test(Fe))throw pe(Fe,"name");Fe=ie(Fe),M("=");var He=new Field(Fe,Re(b()),Le,be,Ie);if(L(He,function(nt){if(nt==="option")he(He,nt),M(";");else throw pe(nt)},function(){oe(He)}),be==="proto3_optional"){var tt=new OneOf("_"+Fe);He.setOption("proto3_optional",!0),tt.add(He),ne.add(tt)}else ne.add(He);ne===fe&&ce.push(He)}function re(ne,be){if(te>=2023)throw pe("group");var Ie=b();if(!nameRe.test(Ie))throw pe(Ie,"name");var Le=util.lcFirst(Ie);Ie===Le&&(Ie=util.ucFirst(Ie)),M("=");var Fe=Re(b()),He=new Type(Ie);He.group=!0;var tt=new Field(Le,Fe,Ie,be);tt.filename=parse.filename,L(He,function(nt){switch(nt){case"option":he(He,nt),M(";");break;case"required":case"repeated":j(He,nt);break;case"optional":te==="proto3"?j(He,"proto3_optional"):j(He,"optional");break;case"message":X(He,nt);break;case"enum":Q(He,nt);break;case"reserved":Pe(He.reserved||(He.reserved=[]),!0);break;default:throw pe(nt)}}),ne.add(He).add(tt)}function ee(ne){M("<");var be=b();if(types.mapKey[be]===void 0)throw pe(be,"type");M(",");var Ie=b();if(!typeRefRe.test(Ie))throw pe(Ie,"type");M(">");var Le=b();if(!nameRe.test(Le))throw pe(Le,"name");M("=");var Fe=new MapField(ie(Le),Re(b()),be,Ie);L(Fe,function(tt){if(tt==="option")he(Fe,tt),M(";");else throw pe(tt)},function(){oe(Fe)}),ne.add(Fe)}function F(ne,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new OneOf(ie(be));L(Ie,function(Fe){Fe==="option"?(he(Ie,Fe),M(";")):(E(Fe),j(Ie,"optional"))}),ne.add(Ie)}function Q(ne,be){if(!nameRe.test(be=b()))throw pe(be,"name");var Ie=new Enum(be);L(Ie,function(Fe){switch(Fe){case"option":he(Ie,Fe),M(";");break;case"reserved":Pe(Ie.reserved||(Ie.reserved=[]),!0),Ie.reserved===void 0&&(Ie.reserved=[]);break;default:U(Ie,Fe)}}),ne.add(Ie),ne===fe&&ce.push(Ie)}function U(ne,be){if(!nameRe.test(be))throw pe(be,"name");M("=");var Ie=Re(b(),!0),Le={options:void 0};Le.getOption=function(Fe){return this.options[Fe]},Le.setOption=function(Fe,He){ReflectionObject.prototype.setOption.call(Le,Fe,He)},Le.setParsedOption=function(){},L(Le,function(He){if(He==="option")he(Le,He),M(";");else throw pe(He)},function(){oe(Le)}),ne.add(be,Ie,Le.comment,Le.parsedOptions||Le.options)}function he(ne,be){var Ie,Le,Fe=!0;for(be==="option"&&(be=b());be!=="=";){if(be==="("){var He=b();M(")"),be="("+He+")"}if(Fe){if(Fe=!1,be.includes(".")&&!be.includes("(")){var tt=be.split(".");Ie=tt[0]+".",be=tt[1];continue}Ie=be}else Le=Le?Le+=be:be;be=b()}var Ne=Le?Ie.concat(Le):Ie,nt=Oe(ne,Ne);Le=Le&&Le[0]==="."?Le.slice(1):Le,Ie=Ie&&Ie[Ie.length-1]==="."?Ie.slice(0,-1):Ie,Ae(ne,Ie,nt,Le)}function Oe(ne,be){if(M("{",!0)){for(var Ie={};!M("}",!0);){if(!nameRe.test(de=b()))throw pe(de,"name");if(de===null)throw pe(de,"end of input");var Le,Fe=de;if(M(":",!0),$()==="{")Le=Oe(ne,be+"."+de);else if($()==="["){Le=[];var He;if(M("[",!0)){do He=$e(),Le.push(He);while(M(",",!0));M("]"),typeof He<"u"&&Ve(ne,be+"."+de,He)}}else Le=$e(),Ve(ne,be+"."+de,Le);var tt=Ie[Fe];tt&&(Le=[].concat(tt).concat(Le)),Ie[Fe]=Le,M(",",!0),M(";",!0)}return Ie}var Ne=$e();return Ve(ne,be,Ne),Ne}function Ve(ne,be,Ie){if(fe===ne&&/^features\./.test(be)){le[be]=Ie;return}ne.setOption&&ne.setOption(be,Ie)}function Ae(ne,be,Ie,Le){ne.setParsedOption&&ne.setParsedOption(be,Ie,Le)}function oe(ne){if(M("[",!0)){do he(ne,"option");while(M(",",!0));M("]")}return ne}function ye(ne,be){if(!nameRe.test(be=b()))throw pe(be,"service name");var Ie=new Service(be);L(Ie,function(Fe){if(!O(Ie,Fe))if(Fe==="rpc")Ce(Ie,Fe);else throw pe(Fe)}),ne.add(Ie),ne===fe&&ce.push(Ie)}function Ce(ne,be){var Ie=T(),Le=be;if(!nameRe.test(be=b()))throw pe(be,"name");var Fe=be,He,tt,Ne,nt;if(M("("),M("stream",!0)&&(tt=!0),!typeRefRe.test(be=b())||(He=be,M(")"),M("returns"),M("("),M("stream",!0)&&(nt=!0),!typeRefRe.test(be=b())))throw pe(be);Ne=be,M(")");var it=new Method(Fe,Le,He,Ne,tt,nt);it.comment=Ie,L(it,function(ut){if(ut==="option")he(it,ut),M(";");else throw pe(ut)}),ne.add(it)}function ae(ne,be){if(!typeRefRe.test(be=b()))throw pe(be,"reference");var Ie=be;L(null,function(Fe){switch(Fe){case"required":case"repeated":j(ne,Fe,Ie);break;case"optional":te==="proto3"?j(ne,"proto3_optional",Ie):j(ne,"optional",Ie);break;default:if(te==="proto2"||!typeRefRe.test(Fe))throw pe(Fe);E(Fe),j(ne,"optional",Ie);break}})}for(var de;(de=b())!==null;)switch(de){case"package":if(!C)throw pe(de);je();break;case"import":if(!C)throw pe(de);we();break;case"syntax":if(!C)throw pe(de);D();break;case"edition":if(!C)throw pe(de);q();break;case"option":he(fe,de),M(";",!0);break;default:if(O(fe,de)){C=!1;continue}throw pe(de)}return ge(),parse.filename=null,{package:B,imports:N,weakImports:H,root:u}}var common_1=common,commonRe=/\/|\./;function common(y,u){commonRe.test(y)||(y="google/protobuf/"+y+".proto",u={nested:{google:{nested:{protobuf:{nested:u}}}}}),common[y]=u}common("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var timeType;common("duration",{Duration:timeType={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),common("timestamp",{Timestamp:timeType}),common("empty",{Empty:{fields:{}}}),common("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),common("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),common("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),common.get=function y(u){return common[u]||null};var protobuf$1=src.exports=indexLightExports;protobuf$1.build="full",protobuf$1.tokenize=tokenize_1,protobuf$1.parse=parse_1,protobuf$1.common=common_1,protobuf$1.Root._configure(protobuf$1.Type,protobuf$1.parse,protobuf$1.common);var srcExports=src.exports,protobufjs=srcExports;const protobuf=getDefaultExportFromCjs$1(protobufjs);class Waku{constructor(u,h,v){this.node=u,this.chatTopic=h,this.onMessage=v,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.reliableChannel=null,this.decoder=null,this.messagePayloadType=null,this.messageReceivedListener=null,this.senderId=crypto$1.randomBytes(8).toString("hex"),this.handleMessageReceived=async({payload:w})=>{try{if(!w){this.logger.warn("Received Waku message without payload");return}if(!this.messagePayloadType)throw new Error("Protobuf schema not initialized");const b=this.messagePayloadType.decode(w),E=this.messagePayloadType.toObject(b,{longs:String,enums:String,defaults:!0});if(!E.message){this.logger.warn("Decoded object has no message field");return}let $=E.message.additionalProps;if($&&typeof $=="string")try{$=JSON.parse($)}catch{this.logger.warn("Failed to parse additionalProps as JSON:",$)}const M={...E.message,timestamp:Number(E.message.timestamp),additionalProps:$};if(!(M!=null&&M.id)){this.logger.warn("Received invalid message structure via Waku");return}this.onMessage(M)}catch(b){this.errorHandler.handleError(b,"Waku2.handleMessageReceived")}}}async start(){this.createProtobufSchema(),await this.createChannel()}createProtobufSchema(){const u=new protobuf.Type("MessageData").add(new protobuf.Field("id",1,"string")).add(new protobuf.Field("targetMessageId",2,"string","optional")).add(new protobuf.Field("type",3,"string")).add(new protobuf.Field("message",4,"string")).add(new protobuf.Field("username",5,"string")).add(new protobuf.Field("address",6,"string")).add(new protobuf.Field("timestamp",7,"uint64")).add(new protobuf.Field("signature",8,"string")).add(new protobuf.Field("index",9,"uint32")).add(new protobuf.Field("chatTopic",10,"string")).add(new protobuf.Field("userTopic",11,"string")).add(new protobuf.Field("additionalProps",12,"string","optional")),h=new protobuf.Type("MessageStateRef").add(new protobuf.Field("reference",1,"string")).add(new protobuf.Field("timestamp",2,"uint64"));this.messagePayloadType=new protobuf.Type("MessagePayload").add(u).add(h).add(new protobuf.Field("message",1,"MessageData")).add(new protobuf.Field("messageStateRefs",2,"MessageStateRef","repeated")),this.logger.info("Protobuf schema created for chat messages")}async createChannel(){if(!this.node)throw new Error("Waku node not initialized");const u=`/solarpunk-msrs-chat/1/${this.chatTopic}/proto`,h=`chat-channel-${this.chatTopic}`,v=this.node.createEncoder({contentTopic:u}),w=this.decoder=this.node.createDecoder({contentTopic:u});this.reliableChannel=await ReliableChannel.create(this.node,h,this.senderId,v,w,{retrieveFrequencyMs:3e3,queryOnConnect:!1}),this.setupChannelEventListeners(this.reliableChannel),this.logger.info(`Created reliable channel for topic: ${this.chatTopic}`)}setupChannelEventListeners(u){this.messageReceivedListener=h=>{this.handleMessageReceived(h.detail)},u.addEventListener("message-received",this.messageReceivedListener)}async stop(){this.reliableChannel&&this.messageReceivedListener&&this.decoder&&(this.reliableChannel.removeEventListener("message-received",this.messageReceivedListener),this.messageReceivedListener=null,await this.reliableChannel.stop(),this.logger.info("Waku reliable channel stopped"))}}class SwarmChat{constructor(u){this.waku=null,this.isStarted=!1,this.startPromise=null,this.logger=Logger$1.getInstance(),this.errorHandler=ErrorHandler.getInstance(),this.gsocIndex=null,this.fetchProcessRunning=!1,this.stopFetch=!1;const h=new beeJs.PrivateKey(remove0x(u.user.privateKey));this.userDetails={privateKey:u.user.privateKey,ownAddress:h.publicKey().address().toString(),nickname:u.user.nickname,ownIndex:-1},this.swarmSettings={bee:new beeJs.Bee(u.infra.beeUrl),beeUrl:u.infra.beeUrl,stamp:u.infra.stamp||"0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",enveloped:u.infra.enveloped,gsocTopic:u.infra.gsocTopic,gsocResourceId:u.infra.gsocResourceId,chatTopic:u.infra.chatTopic,chatAddress:u.infra.chatAddress,wakuNode:u.infra.wakuNode},this.emitter=new EventEmitter$2,this.utils=new SwarmChatUtils(this.userDetails,this.swarmSettings),this.history=new SwarmHistory(this.utils,this.emitter)}async start(){await this.init(),await this.startMessageFetchProcess()}async startMessageFetchProcess(){const{wakuNode:u}=this.swarmSettings;u?await this.startWakuMessageFetch(u):await this.startPollingMessageFetch()}async stop(){this.emitter.cleanAll(),this.stopPollingMessageFetch(),this.history.cleanup(),this.waku&&(await this.waku.stop(),this.waku=null)}async startWakuMessageFetch(u){this.logger.info("Waku is enabled");const h=this.swarmSettings.chatTopic;this.waku=new Waku(u,h,v=>{this.emitter.emit(EVENTS.MESSAGE_RECEIVED,v)}),await this.waku.start()}getEmitter(){return this.emitter}orderMessages(u){return this.utils.orderMessages(u)}async sendMessage(u,h,v,w,b){const E=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,$={id:w||v4(),username:this.userDetails.nickname,address:this.userDetails.ownAddress,chatTopic:this.swarmSettings.chatTopic,userTopic:this.utils.generateUserOwnedFeedId(this.swarmSettings.chatTopic,this.userDetails.ownAddress),signature:this.getSignature(u),timestamp:Date.now(),index:E,type:h,targetMessageId:v,message:u,additionalProps:b},M=validateMessageWithAdditionalProperties($);if(!M.isValid){const T=`Invalid message: ${M.errors.join(", ")}`;throw this.logger.error(T),new Error(T)}try{this.emitter.emit(EVENTS.MESSAGE_REQUEST_INITIATED,$),await this.utils.writeOwnFeedDataByIndex(E,JSON.stringify($)),this.userDetails.ownIndex=E,this.emitter.emit(EVENTS.MESSAGE_REQUEST_UPLOADED,$),await this.broadcastUserMessage($)}catch(T){this.emitter.emit(EVENTS.MESSAGE_REQUEST_ERROR,$),this.errorHandler.handleError(T,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(EVENTS.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(u){this.sendMessage(u.message,u.type,u.targetMessageId,u.id,u.additionalProps)}async retryBroadcastUserMessage(u){await this.broadcastUserMessage(u)}async init(){try{this.emitter.emit(EVENTS.LOADING_INIT,!0);const[u,h]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(u.status==="rejected")throw u.reason;h.status==="fulfilled"&&(this.gsocIndex=h.value),this.emitter.emit(EVENTS.LOADING_INIT,!1)}catch(u){this.errorHandler.handleError(u,"Chat.initSelfState"),this.emitter.emit(EVENTS.CRITICAL_ERROR,u)}}async initOwnIndex(){const{latestIndex:v}=await retryAwaitableAsync(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=v}async fetchLatestMessage(){try{if(!this.gsocIndex)return;const u=beeJs.Topic.fromString(this.swarmSettings.chatTopic),h=makeFeedIdentifier(u,this.gsocIndex),v=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,h.toString()),w=JSON.parse(v);if(!validateGsocMessage(w)){this.logger.warn("Invalid GSOC message during fetching");return}this.emitter.emit(EVENTS.MESSAGE_RECEIVED,w.message),this.gsocIndex=this.gsocIndex.next()}catch(u){if(this.utils.isNotFoundError(u))return;this.errorHandler.handleError(u,"Chat.fetchLatestMessage")}}async broadcastUserMessage(u){try{return retryAwaitableAsync(()=>this.utils.sendMessageToGsoc(JSON.stringify(u)))}catch(h){this.errorHandler.handleError(h,"Chat.broadcastUserMessage")}}getSignature(u){const{ownAddress:h,privateKey:v,nickname:w}=this.userDetails,b=new beeJs.EthAddress(h).toString(),E=new beeJs.PrivateKey(v);if(E.publicKey().address().toString()!==b)throw new Error("The provided address does not match the address derived from the private key");const M=Date.now();return E.sign(JSON.stringify({username:w,address:b,message:u,timestamp:M})).toHex()}async startPollingMessageFetch(){if(this.fetchProcessRunning)return;this.fetchProcessRunning=!0,this.stopFetch=!1;const u=async()=>{if(this.stopFetch){this.fetchProcessRunning=!1;return}await this.fetchLatestMessage(),setTimeout(u,200)};u()}stopPollingMessageFetch(){this.stopFetch=!0}}exports.EVENTS=EVENTS,exports.MessageType=MessageType,exports.SwarmChat=SwarmChat,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@solarpunkltd/swarm-chat-js",
|
|
3
|
-
"version": "6.1.
|
|
3
|
+
"version": "6.1.7",
|
|
4
4
|
"description": "JS library for chatting on Swarm",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.esm.js",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
31
|
"@ethersphere/bee-js": "^9.0.3",
|
|
32
|
-
"@solarpunkltd/waku-sdk": "^0.0.
|
|
32
|
+
"@solarpunkltd/waku-sdk": "^0.0.38",
|
|
33
33
|
"@waku/utils": "^0.0.27",
|
|
34
34
|
"cafe-utility": "^27.12.1",
|
|
35
35
|
"protobufjs": "^7.5.4",
|