@nostrgg/client
Advanced tools
Comparing version 0.1.0 to 0.1.1
@@ -385,6 +385,6 @@ 'use strict'; | ||
if (val < 16) return String.fromCharCode(97 + val - 10); | ||
return ''; | ||
return ""; | ||
} | ||
function hexEncode(buffer) { | ||
var str = ''; | ||
var str = ""; | ||
for (var i = 0; i < buffer.length; i++) { | ||
@@ -486,3 +486,3 @@ var c = buffer[i]; | ||
if (!ws || ws.readyState !== 1) { | ||
log('error', "\u274C nostrgg: Couldn't send event! Websocket connection to " + relayUrl + " is not open."); | ||
log("error", "\u274C nostrgg: Couldn't send event! Websocket connection to " + relayUrl + " is not open."); | ||
return; | ||
@@ -493,4 +493,4 @@ } | ||
var eventWithSubId = [eventType, subId, args]; | ||
var eventToSend = eventType === 'EVENT' ? event : eventWithSubId; | ||
log('info', '⬆️ nostrgg: Sending event:', eventToSend); | ||
var eventToSend = eventType === "EVENT" ? event : eventWithSubId; | ||
log("info", "⬆️ nostrgg: Sending event:", eventToSend); | ||
var msg = JSON.stringify(eventToSend); | ||
@@ -507,11 +507,11 @@ ws.send(msg); | ||
ws.onopen = function () { | ||
log('info', "\u2705 nostrgg: Connected to " + relayUrl); | ||
log("info", "\u2705 nostrgg: Connected to " + relayUrl); | ||
onConnect == null ? void 0 : onConnect(relayUrl, sendEvent); | ||
}; | ||
ws.onerror = function (ev) { | ||
log('error', "\u274C nostrgg: Error connecting to " + relayUrl + "!"); | ||
log("error", "\u274C nostrgg: Error connecting to " + relayUrl + "!"); | ||
onError == null ? void 0 : onError(relayUrl, ev); | ||
}; | ||
ws.onclose = function () { | ||
log('warn', "\uD83D\uDC4B nostrgg: Connection closed for " + relayUrl); | ||
log("warn", "\uD83D\uDC4B nostrgg: Connection closed for " + relayUrl); | ||
onClose == null ? void 0 : onClose(relayUrl); | ||
@@ -521,3 +521,3 @@ }; | ||
var data = JSON.parse(msg.data); | ||
log('info', '⬇️ nostrgg: Received event:', data); | ||
log("info", "⬇️ nostrgg: Received event:", data); | ||
if (data[0] === exports.ReceiveMsgType.EVENT) { | ||
@@ -535,4 +535,5 @@ var event = data[2]; | ||
exports.dateToUnix = dateToUnix; | ||
exports.generateSignedEvent = generateSignedEvent; | ||
exports.initNostr = initNostr; | ||
//# sourceMappingURL=client.cjs.development.js.map |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e,r,n=require("@noble/secp256k1");function o(){o=function(){return t};var t={},e=Object.prototype,r=e.hasOwnProperty,n=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function s(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{s({},"")}catch(t){s=function(t,e,r){return t[e]=r}}function f(t,e,r,o){var i=Object.create((e&&e.prototype instanceof p?e:p).prototype),a=new T(o||[]);return n(i,"_invoke",{value:b(t,r,a)}),i}function l(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=f;var h={};function p(){}function v(){}function d(){}var y={};s(y,a,(function(){return this}));var g=Object.getPrototypeOf,m=g&&g(g(N([])));m&&m!==e&&r.call(m,a)&&(y=m);var w=d.prototype=p.prototype=Object.create(y);function E(t){["next","throw","return"].forEach((function(e){s(t,e,(function(t){return this._invoke(e,t)}))}))}function x(t,e){function o(n,i,a,c){var u=l(t[n],t,i);if("throw"!==u.type){var s=u.arg,f=s.value;return f&&"object"==typeof f&&r.call(f,"__await")?e.resolve(f.__await).then((function(t){o("next",t,a,c)}),(function(t){o("throw",t,a,c)})):e.resolve(f).then((function(t){s.value=t,a(s)}),(function(t){return o("throw",t,a,c)}))}c(u.arg)}var i;n(this,"_invoke",{value:function(t,r){function n(){return new e((function(e,n){o(t,r,e,n)}))}return i=i?i.then(n,n):n()}})}function b(t,e,r){var n="suspendedStart";return function(o,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw i;return{value:void 0,done:!0}}for(r.method=o,r.arg=i;;){var a=r.delegate;if(a){var c=L(a,r);if(c){if(c===h)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var u=l(t,e,r);if("normal"===u.type){if(n=r.done?"completed":"suspendedYield",u.arg===h)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(n="completed",r.method="throw",r.arg=u.arg)}}}function L(t,e){var r=e.method,n=t.iterator[r];if(void 0===n)return e.delegate=null,"throw"===r&&t.iterator.return&&(e.method="return",e.arg=void 0,L(t,e),"throw"===e.method)||"return"!==r&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+r+"' method")),h;var o=l(n,t.iterator,e.arg);if("throw"===o.type)return e.method="throw",e.arg=o.arg,e.delegate=null,h;var i=o.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,h):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function S(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function T(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function N(t){if(t){var e=t[a];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,o=function e(){for(;++n<t.length;)if(r.call(t,n))return e.value=t[n],e.done=!1,e;return e.value=void 0,e.done=!0,e};return o.next=o}}return{next:_}}function _(){return{value:void 0,done:!0}}return v.prototype=d,n(w,"constructor",{value:d,configurable:!0}),n(d,"constructor",{value:v,configurable:!0}),v.displayName=s(d,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===v||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,d):(t.__proto__=d,s(t,u,"GeneratorFunction")),t.prototype=Object.create(w),t},t.awrap=function(t){return{__await:t}},E(x.prototype),s(x.prototype,c,(function(){return this})),t.AsyncIterator=x,t.async=function(e,r,n,o,i){void 0===i&&(i=Promise);var a=new x(f(e,r,n,o),i);return t.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},E(w),s(w,u,"Generator"),s(w,a,(function(){return this})),s(w,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},t.values=N,T.prototype={constructor:T,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(S),!t)for(var e in this)"t"===e.charAt(0)&&r.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function n(r,n){return a.type="throw",a.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var c=r.call(i,"catchLoc"),u=r.call(i,"finallyLoc");if(c&&u){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,h):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),h},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),S(r),h}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;S(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:N(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),h}},t}function i(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function a(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var a=t.apply(e,r);function c(t){i(a,n,o,c,u,"next",t)}function u(t){i(a,n,o,c,u,"throw",t)}c(void 0)}))}}function c(){return c=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},c.apply(this,arguments)}exports.Kind=void 0,(t=exports.Kind||(exports.Kind={}))[t.Metadata=0]="Metadata",t[t.TextNote=1]="TextNote",t[t.RecommendServer=2]="RecommendServer",t[t.ContactList=3]="ContactList",t[t.DirectMessage=4]="DirectMessage",t[t.Deletion=5]="Deletion",exports.SendMsgType=void 0,(e=exports.SendMsgType||(exports.SendMsgType={})).EVENT="EVENT",e.REQ="REQ",e.CLOSE="CLOSE",exports.ReceiveMsgType=void 0,(r=exports.ReceiveMsgType||(exports.ReceiveMsgType={})).EVENT="EVENT",r.NOTICE="NOTICE",r.EOSE="EOSE",r.CLOSE="CLOSE";var u=n.utils.sha256;function s(t){return t<10?String.fromCharCode(48+t):t<16?String.fromCharCode(97+t-10):""}function f(t){for(var e="",r=0;r<t.length;r++){var n=t[r];n&&(e+=s(n>>4),e+=s(15&n))}return e}function l(t){return h.apply(this,arguments)}function h(){return(h=a(o().mark((function t(e){var r,n;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r=JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]),n=(new TextEncoder).encode(r),t.next=6,u(n);case 6:return t.abrupt("return",f(t.sent));case 8:case"end":return t.stop()}}),t)})))).apply(this,arguments)}var p=function(){var t=a(o().mark((function t(e,r){var i,a,u,s,h;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=f(n.getPublicKey(r,!0)),a=i.substring(2),u=c({},e,{pubkey:a,created_at:(o=new Date,p=void 0,p=o||new Date,Math.floor(p.getTime()/1e3))}),t.next=5,l(u);case 5:return s=t.sent,t.next=8,n.schnorr.sign(s,r);case 8:return h=t.sent,u.id=s,u.sig=f(h),t.abrupt("return",u);case 12:case"end":return t.stop()}var o,p}),t)})));return function(e,r){return t.apply(this,arguments)}}(),v={},d=Math.random().toString().slice(2);exports.generateSignedEvent=p,exports.initNostr=function(t){var e=t.onConnect,r=t.onEvent,n=t.onError,o=t.onClose,i=t.debug,a=function(t){var e;if(i){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];(e=console)[t].apply(e,n)}},c=function(t,e){(e?[e]:Object.keys(v)).forEach((function(e){var r=v[e];if(r&&1===r.readyState){var n=t[0],o="EVENT"===n?t:[n,d,t[1]];a("info","⬆️ nostrgg: Sending event:",o);var i=JSON.stringify(o);r.send(i)}else a("error","❌ nostrgg: Couldn't send event! Websocket connection to "+e+" is not open.")}))};return t.relayUrls.forEach((function(t){if(!v[t]){v[t]=new WebSocket(t);var i=v[t];if(!i)return;i.onopen=function(){a("info","✅ nostrgg: Connected to "+t),null==e||e(t,c)},i.onerror=function(e){a("error","❌ nostrgg: Error connecting to "+t+"!"),null==n||n(t,e)},i.onclose=function(){a("warn","👋 nostrgg: Connection closed for "+t),null==o||o(t)},i.onmessage=function(e){var n=JSON.parse(e.data);a("info","⬇️ nostrgg: Received event:",n),n[0]===exports.ReceiveMsgType.EVENT&&(null==r||r(t,n[2]))}}})),{sendEvent:c}}; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e,r,n=require("@noble/secp256k1");function o(){o=function(){return t};var t={},e=Object.prototype,r=e.hasOwnProperty,n=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function s(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{s({},"")}catch(t){s=function(t,e,r){return t[e]=r}}function f(t,e,r,o){var i=Object.create((e&&e.prototype instanceof p?e:p).prototype),a=new T(o||[]);return n(i,"_invoke",{value:b(t,r,a)}),i}function l(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=f;var h={};function p(){}function v(){}function d(){}var y={};s(y,a,(function(){return this}));var g=Object.getPrototypeOf,m=g&&g(g(N([])));m&&m!==e&&r.call(m,a)&&(y=m);var w=d.prototype=p.prototype=Object.create(y);function E(t){["next","throw","return"].forEach((function(e){s(t,e,(function(t){return this._invoke(e,t)}))}))}function x(t,e){function o(n,i,a,c){var u=l(t[n],t,i);if("throw"!==u.type){var s=u.arg,f=s.value;return f&&"object"==typeof f&&r.call(f,"__await")?e.resolve(f.__await).then((function(t){o("next",t,a,c)}),(function(t){o("throw",t,a,c)})):e.resolve(f).then((function(t){s.value=t,a(s)}),(function(t){return o("throw",t,a,c)}))}c(u.arg)}var i;n(this,"_invoke",{value:function(t,r){function n(){return new e((function(e,n){o(t,r,e,n)}))}return i=i?i.then(n,n):n()}})}function b(t,e,r){var n="suspendedStart";return function(o,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw i;return{value:void 0,done:!0}}for(r.method=o,r.arg=i;;){var a=r.delegate;if(a){var c=L(a,r);if(c){if(c===h)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var u=l(t,e,r);if("normal"===u.type){if(n=r.done?"completed":"suspendedYield",u.arg===h)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(n="completed",r.method="throw",r.arg=u.arg)}}}function L(t,e){var r=e.method,n=t.iterator[r];if(void 0===n)return e.delegate=null,"throw"===r&&t.iterator.return&&(e.method="return",e.arg=void 0,L(t,e),"throw"===e.method)||"return"!==r&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+r+"' method")),h;var o=l(n,t.iterator,e.arg);if("throw"===o.type)return e.method="throw",e.arg=o.arg,e.delegate=null,h;var i=o.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,h):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function S(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function T(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function N(t){if(t){var e=t[a];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,o=function e(){for(;++n<t.length;)if(r.call(t,n))return e.value=t[n],e.done=!1,e;return e.value=void 0,e.done=!0,e};return o.next=o}}return{next:_}}function _(){return{value:void 0,done:!0}}return v.prototype=d,n(w,"constructor",{value:d,configurable:!0}),n(d,"constructor",{value:v,configurable:!0}),v.displayName=s(d,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===v||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,d):(t.__proto__=d,s(t,u,"GeneratorFunction")),t.prototype=Object.create(w),t},t.awrap=function(t){return{__await:t}},E(x.prototype),s(x.prototype,c,(function(){return this})),t.AsyncIterator=x,t.async=function(e,r,n,o,i){void 0===i&&(i=Promise);var a=new x(f(e,r,n,o),i);return t.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},E(w),s(w,u,"Generator"),s(w,a,(function(){return this})),s(w,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},t.values=N,T.prototype={constructor:T,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(S),!t)for(var e in this)"t"===e.charAt(0)&&r.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function n(r,n){return a.type="throw",a.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var c=r.call(i,"catchLoc"),u=r.call(i,"finallyLoc");if(c&&u){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,h):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),h},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),S(r),h}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;S(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:N(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),h}},t}function i(t,e,r,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void r(t)}c.done?e(u):Promise.resolve(u).then(n,o)}function a(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var a=t.apply(e,r);function c(t){i(a,n,o,c,u,"next",t)}function u(t){i(a,n,o,c,u,"throw",t)}c(void 0)}))}}function c(){return c=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},c.apply(this,arguments)}exports.Kind=void 0,(t=exports.Kind||(exports.Kind={}))[t.Metadata=0]="Metadata",t[t.TextNote=1]="TextNote",t[t.RecommendServer=2]="RecommendServer",t[t.ContactList=3]="ContactList",t[t.DirectMessage=4]="DirectMessage",t[t.Deletion=5]="Deletion",exports.SendMsgType=void 0,(e=exports.SendMsgType||(exports.SendMsgType={})).EVENT="EVENT",e.REQ="REQ",e.CLOSE="CLOSE",exports.ReceiveMsgType=void 0,(r=exports.ReceiveMsgType||(exports.ReceiveMsgType={})).EVENT="EVENT",r.NOTICE="NOTICE",r.EOSE="EOSE",r.CLOSE="CLOSE";var u=function(t){var e=t||new Date;return Math.floor(e.getTime()/1e3)},s=n.utils.sha256;function f(t){return t<10?String.fromCharCode(48+t):t<16?String.fromCharCode(97+t-10):""}function l(t){for(var e="",r=0;r<t.length;r++){var n=t[r];n&&(e+=f(n>>4),e+=f(15&n))}return e}function h(t){return p.apply(this,arguments)}function p(){return(p=a(o().mark((function t(e){var r,n;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r=JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]),n=(new TextEncoder).encode(r),t.next=6,s(n);case 6:return t.abrupt("return",l(t.sent));case 8:case"end":return t.stop()}}),t)})))).apply(this,arguments)}var v=function(){var t=a(o().mark((function t(e,r){var i,a,s,f,p;return o().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=l(n.getPublicKey(r,!0)),a=i.substring(2),s=c({},e,{pubkey:a,created_at:u(new Date)}),t.next=5,h(s);case 5:return f=t.sent,t.next=8,n.schnorr.sign(f,r);case 8:return p=t.sent,s.id=f,s.sig=l(p),t.abrupt("return",s);case 12:case"end":return t.stop()}}),t)})));return function(e,r){return t.apply(this,arguments)}}(),d={},y=Math.random().toString().slice(2);exports.dateToUnix=u,exports.generateSignedEvent=v,exports.initNostr=function(t){var e=t.onConnect,r=t.onEvent,n=t.onError,o=t.onClose,i=t.debug,a=function(t){var e;if(i){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];(e=console)[t].apply(e,n)}},c=function(t,e){(e?[e]:Object.keys(d)).forEach((function(e){var r=d[e];if(r&&1===r.readyState){var n=t[0],o="EVENT"===n?t:[n,y,t[1]];a("info","⬆️ nostrgg: Sending event:",o);var i=JSON.stringify(o);r.send(i)}else a("error","❌ nostrgg: Couldn't send event! Websocket connection to "+e+" is not open.")}))};return t.relayUrls.forEach((function(t){if(!d[t]){d[t]=new WebSocket(t);var i=d[t];if(!i)return;i.onopen=function(){a("info","✅ nostrgg: Connected to "+t),null==e||e(t,c)},i.onerror=function(e){a("error","❌ nostrgg: Error connecting to "+t+"!"),null==n||n(t,e)},i.onclose=function(){a("warn","👋 nostrgg: Connection closed for "+t),null==o||o(t)},i.onmessage=function(e){var n=JSON.parse(e.data);a("info","⬇️ nostrgg: Received event:",n),n[0]===exports.ReceiveMsgType.EVENT&&(null==r||r(t,n[2]))}}})),{sendEvent:c}}; | ||
//# sourceMappingURL=client.cjs.production.min.js.map |
@@ -381,6 +381,6 @@ import { schnorr, getPublicKey, utils } from '@noble/secp256k1'; | ||
if (val < 16) return String.fromCharCode(97 + val - 10); | ||
return ''; | ||
return ""; | ||
} | ||
function hexEncode(buffer) { | ||
var str = ''; | ||
var str = ""; | ||
for (var i = 0; i < buffer.length; i++) { | ||
@@ -482,3 +482,3 @@ var c = buffer[i]; | ||
if (!ws || ws.readyState !== 1) { | ||
log('error', "\u274C nostrgg: Couldn't send event! Websocket connection to " + relayUrl + " is not open."); | ||
log("error", "\u274C nostrgg: Couldn't send event! Websocket connection to " + relayUrl + " is not open."); | ||
return; | ||
@@ -489,4 +489,4 @@ } | ||
var eventWithSubId = [eventType, subId, args]; | ||
var eventToSend = eventType === 'EVENT' ? event : eventWithSubId; | ||
log('info', '⬆️ nostrgg: Sending event:', eventToSend); | ||
var eventToSend = eventType === "EVENT" ? event : eventWithSubId; | ||
log("info", "⬆️ nostrgg: Sending event:", eventToSend); | ||
var msg = JSON.stringify(eventToSend); | ||
@@ -503,11 +503,11 @@ ws.send(msg); | ||
ws.onopen = function () { | ||
log('info', "\u2705 nostrgg: Connected to " + relayUrl); | ||
log("info", "\u2705 nostrgg: Connected to " + relayUrl); | ||
onConnect == null ? void 0 : onConnect(relayUrl, sendEvent); | ||
}; | ||
ws.onerror = function (ev) { | ||
log('error', "\u274C nostrgg: Error connecting to " + relayUrl + "!"); | ||
log("error", "\u274C nostrgg: Error connecting to " + relayUrl + "!"); | ||
onError == null ? void 0 : onError(relayUrl, ev); | ||
}; | ||
ws.onclose = function () { | ||
log('warn', "\uD83D\uDC4B nostrgg: Connection closed for " + relayUrl); | ||
log("warn", "\uD83D\uDC4B nostrgg: Connection closed for " + relayUrl); | ||
onClose == null ? void 0 : onClose(relayUrl); | ||
@@ -517,3 +517,3 @@ }; | ||
var data = JSON.parse(msg.data); | ||
log('info', '⬇️ nostrgg: Received event:', data); | ||
log("info", "⬇️ nostrgg: Received event:", data); | ||
if (data[0] === ReceiveMsgType.EVENT) { | ||
@@ -531,3 +531,3 @@ var event = data[2]; | ||
export { Kind, ReceiveMsgType, SendMsgType, generateSignedEvent, initNostr }; | ||
export { Kind, ReceiveMsgType, SendMsgType, dateToUnix, generateSignedEvent, initNostr }; | ||
//# sourceMappingURL=client.esm.js.map |
@@ -1,4 +0,4 @@ | ||
import { NostrEvent } from './types'; | ||
type PartialNostrEvent = Omit<NostrEvent, 'id' | 'pubkey' | 'sig' | 'created_at'>; | ||
import { NostrEvent } from "./types"; | ||
type PartialNostrEvent = Omit<NostrEvent, "id" | "pubkey" | "sig" | "created_at">; | ||
export declare const generateSignedEvent: (partialEvent: PartialNostrEvent, privKey: string) => Promise<NostrEvent>; | ||
export {}; |
@@ -1,4 +0,5 @@ | ||
import { NostrEvent, SendEvent } from './types'; | ||
export * from './types'; | ||
export * from './crypto'; | ||
import { NostrEvent, SendEvent } from "./types"; | ||
export * from "./types"; | ||
export * from "./crypto"; | ||
export * from "./utils"; | ||
export type SendEventFunc = (event: SendEvent, url?: string) => void; | ||
@@ -5,0 +6,0 @@ export type OnConnectFunc = (relayUrl: string, sendEvent: SendEventFunc) => void; |
{ | ||
"name": "@nostrgg/client", | ||
"version": "0.1.0", | ||
"version": "0.1.1", | ||
"license": "MIT", | ||
@@ -21,2 +21,6 @@ "author": "t4t5 (https://t4t5.xyz)", | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/nostrgg/nostrgg-client" | ||
}, | ||
"husky": { | ||
@@ -27,8 +31,2 @@ "hooks": { | ||
}, | ||
"prettier": { | ||
"printWidth": 80, | ||
"semi": true, | ||
"singleQuote": true, | ||
"trailingComma": "es5" | ||
}, | ||
"jest": { | ||
@@ -54,4 +52,10 @@ "testEnvironment": "node" | ||
"@tsconfig/recommended": "^1.0.1", | ||
"@typescript-eslint/eslint-plugin": "^5.47.0", | ||
"@typescript-eslint/parser": "^5.47.0", | ||
"dts-cli": "^1.6.0", | ||
"eslint": "^8.30.0", | ||
"eslint-config-prettier": "^8.5.0", | ||
"eslint-plugin-prettier": "^4.2.1", | ||
"husky": "^8.0.2", | ||
"prettier": "^2.8.1", | ||
"size-limit": "^8.1.0", | ||
@@ -58,0 +62,0 @@ "tslib": "^2.4.1", |
@@ -14,2 +14,8 @@ # @nostrgg/client | ||
```typescript | ||
import { | ||
initNostr, | ||
SendMsgType, | ||
Kind, | ||
} from "@nostrgg/client" | ||
initNostr({ | ||
@@ -20,4 +26,12 @@ relayUrls: [ | ||
], | ||
onConnect: (relayUrl: string) => { | ||
onConnect: (relayUrl, sendEvent) => { | ||
console.log("Nostr connected to:", relayUrl) | ||
// Send a REQ event to start listening to events from that relayer: | ||
sendEvent([SendMsgType.REQ, { | ||
filter: { | ||
kinds: [Kind.TextNote], | ||
since: 0, // All events since the dawn of time | ||
}, | ||
}], relayUrl) | ||
}, | ||
@@ -27,4 +41,5 @@ onEvent: (relayUrl, event) => { | ||
}, | ||
debug: true, // Enable logs | ||
}); | ||
``` | ||
@@ -1,33 +0,33 @@ | ||
import { dateToUnix } from './utils'; | ||
import { utils, schnorr, getPublicKey } from '@noble/secp256k1'; | ||
const { sha256 } = utils; | ||
import { dateToUnix } from "./utils" | ||
import { utils, schnorr, getPublicKey } from "@noble/secp256k1" | ||
const { sha256 } = utils | ||
import { NostrEvent } from './types'; | ||
import { NostrEvent } from "./types" | ||
function hexChar(val: number) { | ||
if (val < 10) return String.fromCharCode(48 + val); | ||
if (val < 16) return String.fromCharCode(97 + val - 10); | ||
return ''; | ||
if (val < 10) return String.fromCharCode(48 + val) | ||
if (val < 16) return String.fromCharCode(97 + val - 10) | ||
return "" | ||
} | ||
function hexEncode(buffer: Uint8Array) { | ||
let str = ''; | ||
let str = "" | ||
for (let i = 0; i < buffer.length; i++) { | ||
const c = buffer[i]; | ||
const c = buffer[i] | ||
if (c) { | ||
str += hexChar(c >> 4); | ||
str += hexChar(c & 0xf); | ||
str += hexChar(c >> 4) | ||
str += hexChar(c & 0xf) | ||
} | ||
} | ||
return str; | ||
return str | ||
} | ||
async function generateEventId(event: NostrEvent) { | ||
const { content, created_at, kind, tags, pubkey } = event; | ||
const serialized = [0, pubkey, created_at, kind, tags, content]; | ||
const commit = JSON.stringify(serialized); | ||
const buffer = new TextEncoder().encode(commit); | ||
const shaBuffer = await sha256(buffer); | ||
return hexEncode(shaBuffer); | ||
const { content, created_at, kind, tags, pubkey } = event | ||
const serialized = [0, pubkey, created_at, kind, tags, content] | ||
const commit = JSON.stringify(serialized) | ||
const buffer = new TextEncoder().encode(commit) | ||
const shaBuffer = await sha256(buffer) | ||
return hexEncode(shaBuffer) | ||
} | ||
@@ -37,12 +37,12 @@ | ||
NostrEvent, | ||
'id' | 'pubkey' | 'sig' | 'created_at' | ||
>; | ||
"id" | "pubkey" | "sig" | "created_at" | ||
> | ||
export const generateSignedEvent = async ( | ||
partialEvent: PartialNostrEvent, | ||
privKey: string | ||
privKey: string, | ||
) => { | ||
const _pubkey = hexEncode(getPublicKey(privKey, true)); | ||
const _pubkey = hexEncode(getPublicKey(privKey, true)) | ||
// Remove "02" at beginning of pubkey: | ||
const pubkey = _pubkey.substring(2); | ||
const pubkey = _pubkey.substring(2) | ||
@@ -53,12 +53,12 @@ const event: NostrEvent = { | ||
created_at: dateToUnix(new Date()), | ||
}; | ||
} | ||
const eventId = await generateEventId(event); | ||
const signedId = await schnorr.sign(eventId, privKey); | ||
const eventId = await generateEventId(event) | ||
const signedId = await schnorr.sign(eventId, privKey) | ||
event.id = eventId; | ||
event.sig = hexEncode(signedId); | ||
event.id = eventId | ||
event.sig = hexEncode(signedId) | ||
// Return signed event: | ||
return event; | ||
}; | ||
return event | ||
} |
120
src/index.ts
@@ -1,33 +0,31 @@ | ||
import { NostrEvent, ReceiveEvent, ReceiveMsgType, SendEvent } from './types'; | ||
import { NostrEvent, ReceiveEvent, ReceiveMsgType, SendEvent } from "./types" | ||
export * from './types'; | ||
export * from './crypto'; | ||
export * from "./types" | ||
export * from "./crypto" | ||
export * from "./utils" | ||
export type SendEventFunc = (event: SendEvent, url?: string) => void; | ||
export type SendEventFunc = (event: SendEvent, url?: string) => void | ||
export type OnConnectFunc = ( | ||
relayUrl: string, | ||
sendEvent: SendEventFunc | ||
) => void; | ||
export type OnConnectFunc = (relayUrl: string, sendEvent: SendEventFunc) => void | ||
export type OnEventFunc = (relayUrl: string, event: NostrEvent) => void; | ||
export type OnEventFunc = (relayUrl: string, event: NostrEvent) => void | ||
interface RelayOptions { | ||
relayUrls: string[]; | ||
onConnect?: OnConnectFunc; | ||
onError?: (relayUrl: string, err: Event) => void; | ||
onClose?: (relayUrl: string) => void; | ||
onEvent?: OnEventFunc; | ||
debug?: boolean; | ||
relayUrls: string[] | ||
onConnect?: OnConnectFunc | ||
onError?: (relayUrl: string, err: Event) => void | ||
onClose?: (relayUrl: string) => void | ||
onEvent?: OnEventFunc | ||
debug?: boolean | ||
} | ||
const connections: Record<string, WebSocket> = {}; | ||
const connections: Record<string, WebSocket> = {} | ||
export type NostrClient = { | ||
sendEvent: SendEventFunc; | ||
}; | ||
sendEvent: SendEventFunc | ||
} | ||
const subId = Math.random() | ||
.toString() | ||
.slice(2); | ||
.slice(2) | ||
@@ -42,74 +40,74 @@ export const initNostr = ({ | ||
}: RelayOptions): NostrClient => { | ||
const log = (type: 'info' | 'error' | 'warn', ...args: unknown[]) => { | ||
if (!debug) return; | ||
console[type](...args); | ||
}; | ||
const log = (type: "info" | "error" | "warn", ...args: unknown[]) => { | ||
if (!debug) return | ||
console[type](...args) | ||
} | ||
const sendEvent = (event: SendEvent, relayUrl?: string) => { | ||
const urls = relayUrl ? [relayUrl] : Object.keys(connections); | ||
const urls = relayUrl ? [relayUrl] : Object.keys(connections) | ||
urls.forEach(relayUrl => { | ||
const ws = connections[relayUrl]; | ||
urls.forEach((relayUrl) => { | ||
const ws = connections[relayUrl] | ||
if (!ws || ws.readyState !== 1) { | ||
log( | ||
'error', | ||
`❌ nostrgg: Couldn't send event! Websocket connection to ${relayUrl} is not open.` | ||
); | ||
return; | ||
"error", | ||
`❌ nostrgg: Couldn't send event! Websocket connection to ${relayUrl} is not open.`, | ||
) | ||
return | ||
} | ||
const [eventType, args] = event; | ||
const [eventType, args] = event | ||
const eventWithSubId = [eventType, subId, args]; | ||
const eventToSend = eventType === 'EVENT' ? event : eventWithSubId; | ||
const eventWithSubId = [eventType, subId, args] | ||
const eventToSend = eventType === "EVENT" ? event : eventWithSubId | ||
log('info', '⬆️ nostrgg: Sending event:', eventToSend); | ||
log("info", "⬆️ nostrgg: Sending event:", eventToSend) | ||
const msg = JSON.stringify(eventToSend); | ||
const msg = JSON.stringify(eventToSend) | ||
ws.send(msg); | ||
}); | ||
}; | ||
ws.send(msg) | ||
}) | ||
} | ||
relayUrls.forEach(relayUrl => { | ||
const connection = connections[relayUrl]; | ||
relayUrls.forEach((relayUrl) => { | ||
const connection = connections[relayUrl] | ||
if (!connection) { | ||
connections[relayUrl] = new WebSocket(relayUrl); | ||
const ws = connections[relayUrl]; | ||
connections[relayUrl] = new WebSocket(relayUrl) | ||
const ws = connections[relayUrl] | ||
if (!ws) return; | ||
if (!ws) return | ||
ws.onopen = () => { | ||
log('info', `✅ nostrgg: Connected to ${relayUrl}`); | ||
onConnect?.(relayUrl, sendEvent); | ||
}; | ||
log("info", `✅ nostrgg: Connected to ${relayUrl}`) | ||
onConnect?.(relayUrl, sendEvent) | ||
} | ||
ws.onerror = ev => { | ||
log('error', `❌ nostrgg: Error connecting to ${relayUrl}!`); | ||
onError?.(relayUrl, ev); | ||
}; | ||
ws.onerror = (ev) => { | ||
log("error", `❌ nostrgg: Error connecting to ${relayUrl}!`) | ||
onError?.(relayUrl, ev) | ||
} | ||
ws.onclose = () => { | ||
log('warn', `👋 nostrgg: Connection closed for ${relayUrl}`); | ||
onClose?.(relayUrl); | ||
}; | ||
log("warn", `👋 nostrgg: Connection closed for ${relayUrl}`) | ||
onClose?.(relayUrl) | ||
} | ||
ws.onmessage = (msg: MessageEvent) => { | ||
const data = JSON.parse(msg.data) as ReceiveEvent; | ||
const data = JSON.parse(msg.data) as ReceiveEvent | ||
log('info', '⬇️ nostrgg: Received event:', data); | ||
log("info", "⬇️ nostrgg: Received event:", data) | ||
if (data[0] === ReceiveMsgType.EVENT) { | ||
const event = data[2]; | ||
onEvent?.(relayUrl, event); | ||
const event = data[2] | ||
onEvent?.(relayUrl, event) | ||
} | ||
}; | ||
} | ||
} | ||
}); | ||
}) | ||
return { | ||
sendEvent, | ||
}; | ||
}; | ||
} | ||
} |
@@ -11,30 +11,30 @@ export enum Kind { | ||
export type Filter = { | ||
ids?: string[]; | ||
kinds?: Kind[]; | ||
authors?: string[]; | ||
since?: number; | ||
until?: number; | ||
}; | ||
ids?: string[] | ||
kinds?: Kind[] | ||
authors?: string[] | ||
since?: number | ||
until?: number | ||
} | ||
export type NostrEvent = { | ||
id?: string; | ||
sig?: string; | ||
kind: number; | ||
tags: string[][]; | ||
pubkey: string; | ||
content: string; | ||
created_at: number; | ||
}; | ||
id?: string | ||
sig?: string | ||
kind: number | ||
tags: string[][] | ||
pubkey: string | ||
content: string | ||
created_at: number | ||
} | ||
export enum SendMsgType { | ||
EVENT = 'EVENT', | ||
REQ = 'REQ', | ||
CLOSE = 'CLOSE', | ||
EVENT = "EVENT", | ||
REQ = "REQ", | ||
CLOSE = "CLOSE", | ||
} | ||
export enum ReceiveMsgType { | ||
EVENT = 'EVENT', | ||
NOTICE = 'NOTICE', | ||
EOSE = 'EOSE', | ||
CLOSE = 'CLOSE', | ||
EVENT = "EVENT", | ||
NOTICE = "NOTICE", | ||
EOSE = "EOSE", | ||
CLOSE = "CLOSE", | ||
} | ||
@@ -44,6 +44,6 @@ | ||
| [SendMsgType.REQ, Filter] | ||
| [SendMsgType.EVENT, NostrEvent]; | ||
| [SendMsgType.EVENT, NostrEvent] | ||
export type ReceiveEvent = | ||
| [ReceiveMsgType.EOSE, string] | ||
| [ReceiveMsgType.EVENT, string, NostrEvent]; | ||
| [ReceiveMsgType.EVENT, string, NostrEvent] |
export const dateToUnix = (_date?: Date) => { | ||
const date = _date || new Date(); | ||
const date = _date || new Date() | ||
return Math.floor(date.getTime() / 1000); | ||
}; | ||
return Math.floor(date.getTime() / 1000) | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No repository
Supply chain riskPackage does not have a linked source code repository. Without this field, a package will have no reference to the location of the source code use to generate the package.
Found 1 instance in 1 package
101857
43
1
13