cleanup
continuous-integration/drone/push Build is failing Details

This commit is contained in:
Kieran 2023-06-09 00:43:21 +02:00
parent 81ccb95d82
commit ae655dfc69
Signed by: Kieran
GPG Key ID: DE71CEB3925BE941
123 changed files with 93 additions and 4198 deletions

3
.gitignore vendored
View File

@ -2,3 +2,6 @@ node_modules/
.idea
.yarn
yarn.lock
dist/
*.tgz
*.log

View File

@ -2,4 +2,5 @@ tests/
src/
*.tgz
jest.config.js
worker.ts
worker.ts
yarn*

View File

@ -1,90 +0,0 @@
import { ConnectionStats } from "./ConnectionStats";
import { NostrEvent, ReqCommand, TaggedRawEvent, u256 } from "./Nostr";
import { RelayInfo } from "./RelayInfo";
import ExternalStore from "./ExternalStore";
export type AuthHandler = (challenge: string, relay: string) => Promise<NostrEvent | undefined>;
/**
* Relay settings
*/
export interface RelaySettings {
read: boolean;
write: boolean;
}
/**
* Snapshot of connection stats
*/
export interface ConnectionStateSnapshot {
connected: boolean;
disconnects: number;
avgLatency: number;
events: {
received: number;
send: number;
};
settings?: RelaySettings;
info?: RelayInfo;
pendingRequests: Array<string>;
activeRequests: Array<string>;
id: string;
ephemeral: boolean;
address: string;
}
export declare class Connection extends ExternalStore<ConnectionStateSnapshot> {
#private;
Id: string;
Address: string;
Socket: WebSocket | null;
PendingRaw: Array<object>;
PendingRequests: Array<{
cmd: ReqCommand;
cb: () => void;
}>;
ActiveRequests: Set<string>;
Settings: RelaySettings;
Info?: RelayInfo;
ConnectTimeout: number;
Stats: ConnectionStats;
HasStateChange: boolean;
IsClosed: boolean;
ReconnectTimer: ReturnType<typeof setTimeout> | null;
EventsCallback: Map<u256, (msg: boolean[]) => void>;
OnConnected?: () => void;
OnEvent?: (sub: string, e: TaggedRawEvent) => void;
OnEose?: (sub: string) => void;
OnDisconnect?: (id: string) => void;
Auth?: AuthHandler;
AwaitingAuth: Map<string, boolean>;
Authed: boolean;
Ephemeral: boolean;
EphemeralTimeout: ReturnType<typeof setTimeout> | undefined;
Down: boolean;
constructor(addr: string, options: RelaySettings, auth?: AuthHandler, ephemeral?: boolean);
ResetEphemeralTimeout(): void;
Connect(): Promise<void>;
Close(): void;
OnOpen(): void;
OnClose(e: CloseEvent): void;
OnMessage(e: MessageEvent): void;
OnError(e: Event): void;
/**
* Send event on this connection
*/
SendEvent(e: NostrEvent): void;
/**
* Send event on this connection and wait for OK response
*/
SendAsync(e: NostrEvent, timeout?: number): Promise<void>;
/**
* Using relay document to determine if this relay supports a feature
*/
SupportsNip(n: number): boolean;
/**
* Queue or send command to the relay
* @param cmd The REQ to send to the server
*/
QueueReq(cmd: ReqCommand, cbSent: () => void): void;
CloseReq(id: string): void;
takeSnapshot(): ConnectionStateSnapshot;
_OnAuthAsync(challenge: string): Promise<void>;
}
//# sourceMappingURL=Connection.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"Connection.d.ts","sourceRoot":"","sources":["../src/Connection.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AACvE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,OAAO,aAAa,MAAM,iBAAiB,CAAC;AAE5C,MAAM,MAAM,WAAW,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAAC;AAEhG;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,EAAE,OAAO,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC,SAAS,EAAE,OAAO,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE;QACN,QAAQ,EAAE,MAAM,CAAC;QACjB,IAAI,EAAE,MAAM,CAAC;KACd,CAAC;I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C,IAAI,CAAC,EAAE,WAAW,CAAC;IACnB,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,MAAM,UAAS;IACf,SAAS,EAAE,OAAO,CAAC;IACnB,gBAAgB,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,GAAG,SAAS,CAAC;IAC5D,IAAI,UAAQ;gBAEA,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,IAAI,CAAC,EAAE,WAAW,EAAE,SAAS,GAAE,OAAe;IAahG,qBAAqB;IAWf,OAAO;IAsCb,KAAK;IAUL,MAAM;IAWN,OAAO,CAAC,CAAC,EAAE,UAAU;IAwBrB,SAAS,CAAC,CAAC,EAAE,YAAY;IAiDzB,OAAO,CAAC,CAAC,EAAE,KAAK;IAKhB;;OAEG;IACH,SAAS,CAAC,CAAC,EAAE,UAAU;IAUvB;;OAEG;IACG,SAAS,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,SAAO;IAqB7C;;OAEG;IACH,WAAW,CAAC,CAAC,EAAE,MAAM;IAIrB;;;OAGG;IACH,QAAQ,CAAC,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,IAAI;IAe5C,QAAQ,CAAC,EAAE,EAAE,MAAM;IASnB,YAAY,IAAI,uBAAuB;IA2EjC,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAoCrD"}

View File

@ -1,343 +0,0 @@
"use strict";
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _Connection_instances, _Connection_SendQueuedRequests, _Connection_ResetQueues, _Connection_SendJson, _Connection_sendPendingRaw, _Connection_sendOnWire, _Connection_maxSubscriptions_get;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Connection = void 0;
const uuid_1 = require("uuid");
const Const_1 = require("./Const");
const ConnectionStats_1 = require("./ConnectionStats");
const Util_1 = require("./Util");
const ExternalStore_1 = __importDefault(require("./ExternalStore"));
class Connection extends ExternalStore_1.default {
constructor(addr, options, auth, ephemeral = false) {
super();
_Connection_instances.add(this);
this.Socket = null;
this.PendingRaw = [];
this.PendingRequests = [];
this.ActiveRequests = new Set();
this.ConnectTimeout = Const_1.DefaultConnectTimeout;
this.Stats = new ConnectionStats_1.ConnectionStats();
this.HasStateChange = true;
this.Authed = false;
this.Down = true;
this.Id = (0, uuid_1.v4)();
this.Address = addr;
this.Settings = options;
this.IsClosed = false;
this.ReconnectTimer = null;
this.EventsCallback = new Map();
this.AwaitingAuth = new Map();
this.Auth = auth;
this.Ephemeral = ephemeral;
}
ResetEphemeralTimeout() {
if (this.EphemeralTimeout) {
clearTimeout(this.EphemeralTimeout);
}
if (this.Ephemeral) {
this.EphemeralTimeout = setTimeout(() => {
this.Close();
}, 30000);
}
}
async Connect() {
try {
if (this.Info === undefined) {
const u = new URL(this.Address);
const rsp = await fetch(`${u.protocol === "wss:" ? "https:" : "http:"}//${u.host}`, {
headers: {
accept: "application/nostr+json",
},
});
if (rsp.ok) {
const data = await rsp.json();
for (const [k, v] of Object.entries(data)) {
if (v === "unset" || v === "" || v === "~") {
data[k] = undefined;
}
}
this.Info = data;
}
}
}
catch (e) {
console.warn("Could not load relay information", e);
}
if (this.Socket) {
this.Id = (0, uuid_1.v4)();
this.Socket.onopen = null;
this.Socket.onmessage = null;
this.Socket.onerror = null;
this.Socket.onclose = null;
}
this.IsClosed = false;
this.Socket = new WebSocket(this.Address);
this.Socket.onopen = () => this.OnOpen();
this.Socket.onmessage = e => this.OnMessage(e);
this.Socket.onerror = e => this.OnError(e);
this.Socket.onclose = e => this.OnClose(e);
}
Close() {
this.IsClosed = true;
if (this.ReconnectTimer !== null) {
clearTimeout(this.ReconnectTimer);
this.ReconnectTimer = null;
}
this.Socket?.close();
this.notifyChange();
}
OnOpen() {
this.ConnectTimeout = Const_1.DefaultConnectTimeout;
console.log(`[${this.Address}] Open!`);
this.Down = false;
if (this.Ephemeral) {
this.ResetEphemeralTimeout();
}
this.OnConnected?.();
__classPrivateFieldGet(this, _Connection_instances, "m", _Connection_sendPendingRaw).call(this);
}
OnClose(e) {
if (!this.IsClosed) {
this.ConnectTimeout = this.ConnectTimeout * 2;
console.log(`[${this.Address}] Closed (${e.reason}), trying again in ${(this.ConnectTimeout / 1000)
.toFixed(0)
.toLocaleString()} sec`);
this.ReconnectTimer = setTimeout(() => {
this.Connect();
}, this.ConnectTimeout);
this.Stats.Disconnects++;
}
else {
console.log(`[${this.Address}] Closed!`);
this.ReconnectTimer = null;
}
this.OnDisconnect?.(this.Id);
__classPrivateFieldGet(this, _Connection_instances, "m", _Connection_ResetQueues).call(this);
// reset connection Id on disconnect, for query-tracking
this.Id = (0, uuid_1.v4)();
this.notifyChange();
}
OnMessage(e) {
if (e.data.length > 0) {
const msg = JSON.parse(e.data);
const tag = msg[0];
switch (tag) {
case "AUTH": {
this._OnAuthAsync(msg[1])
.then(() => __classPrivateFieldGet(this, _Connection_instances, "m", _Connection_sendPendingRaw).call(this))
.catch(console.error);
this.Stats.EventsReceived++;
this.notifyChange();
break;
}
case "EVENT": {
this.OnEvent?.(msg[1], {
...msg[2],
relays: [this.Address],
});
this.Stats.EventsReceived++;
this.notifyChange();
break;
}
case "EOSE": {
this.OnEose?.(msg[1]);
break;
}
case "OK": {
// feedback to broadcast call
console.debug(`${this.Address} OK: `, msg);
const id = msg[1];
if (this.EventsCallback.has(id)) {
const cb = (0, Util_1.unwrap)(this.EventsCallback.get(id));
this.EventsCallback.delete(id);
cb(msg);
}
break;
}
case "NOTICE": {
console.warn(`[${this.Address}] NOTICE: ${msg[1]}`);
break;
}
default: {
console.warn(`Unknown tag: ${tag}`);
break;
}
}
}
}
OnError(e) {
console.error(e);
this.notifyChange();
}
/**
* Send event on this connection
*/
SendEvent(e) {
if (!this.Settings.write) {
return;
}
const req = ["EVENT", e];
__classPrivateFieldGet(this, _Connection_instances, "m", _Connection_SendJson).call(this, req);
this.Stats.EventsSent++;
this.notifyChange();
}
/**
* Send event on this connection and wait for OK response
*/
async SendAsync(e, timeout = 5000) {
return new Promise(resolve => {
if (!this.Settings.write) {
resolve();
return;
}
const t = setTimeout(() => {
resolve();
}, timeout);
this.EventsCallback.set(e.id, () => {
clearTimeout(t);
resolve();
});
const req = ["EVENT", e];
__classPrivateFieldGet(this, _Connection_instances, "m", _Connection_SendJson).call(this, req);
this.Stats.EventsSent++;
this.notifyChange();
});
}
/**
* Using relay document to determine if this relay supports a feature
*/
SupportsNip(n) {
return this.Info?.supported_nips?.some(a => a === n) ?? false;
}
/**
* Queue or send command to the relay
* @param cmd The REQ to send to the server
*/
QueueReq(cmd, cbSent) {
if (this.ActiveRequests.size >= __classPrivateFieldGet(this, _Connection_instances, "a", _Connection_maxSubscriptions_get)) {
this.PendingRequests.push({
cmd,
cb: cbSent,
});
console.debug("Queuing:", this.Address, cmd);
}
else {
this.ActiveRequests.add(cmd[1]);
__classPrivateFieldGet(this, _Connection_instances, "m", _Connection_SendJson).call(this, cmd);
cbSent();
}
this.notifyChange();
}
CloseReq(id) {
if (this.ActiveRequests.delete(id)) {
__classPrivateFieldGet(this, _Connection_instances, "m", _Connection_SendJson).call(this, ["CLOSE", id]);
this.OnEose?.(id);
__classPrivateFieldGet(this, _Connection_instances, "m", _Connection_SendQueuedRequests).call(this);
}
this.notifyChange();
}
takeSnapshot() {
return {
connected: this.Socket?.readyState === WebSocket.OPEN,
events: {
received: this.Stats.EventsReceived,
send: this.Stats.EventsSent,
},
avgLatency: this.Stats.Latency.length > 0
? this.Stats.Latency.reduce((acc, v) => acc + v, 0) / this.Stats.Latency.length
: 0,
disconnects: this.Stats.Disconnects,
info: this.Info,
id: this.Id,
pendingRequests: [...this.PendingRequests.map(a => a.cmd[1])],
activeRequests: [...this.ActiveRequests],
ephemeral: this.Ephemeral,
address: this.Address,
};
}
async _OnAuthAsync(challenge) {
const authCleanup = () => {
this.AwaitingAuth.delete(challenge);
};
if (!this.Auth) {
throw new Error("Auth hook not registered");
}
this.AwaitingAuth.set(challenge, true);
const authEvent = await this.Auth(challenge, this.Address);
return new Promise(resolve => {
if (!authEvent) {
authCleanup();
return Promise.reject("no event");
}
const t = setTimeout(() => {
authCleanup();
resolve();
}, 10000);
this.EventsCallback.set(authEvent.id, (msg) => {
clearTimeout(t);
authCleanup();
if (msg.length > 3 && msg[2] === true) {
this.Authed = true;
}
resolve();
});
__classPrivateFieldGet(this, _Connection_instances, "m", _Connection_sendOnWire).call(this, ["AUTH", authEvent]);
});
}
}
exports.Connection = Connection;
_Connection_instances = new WeakSet(), _Connection_SendQueuedRequests = function _Connection_SendQueuedRequests() {
const canSend = __classPrivateFieldGet(this, _Connection_instances, "a", _Connection_maxSubscriptions_get) - this.ActiveRequests.size;
if (canSend > 0) {
for (let x = 0; x < canSend; x++) {
const p = this.PendingRequests.shift();
if (p) {
this.ActiveRequests.add(p.cmd[1]);
__classPrivateFieldGet(this, _Connection_instances, "m", _Connection_SendJson).call(this, p.cmd);
p.cb();
console.debug("Sent pending REQ", this.Address, p.cmd);
}
}
}
}, _Connection_ResetQueues = function _Connection_ResetQueues() {
this.ActiveRequests.clear();
this.PendingRequests = [];
this.PendingRaw = [];
this.notifyChange();
}, _Connection_SendJson = function _Connection_SendJson(obj) {
const authPending = !this.Authed && (this.AwaitingAuth.size > 0 || this.Info?.limitation?.auth_required === true);
if (this.Socket?.readyState !== WebSocket.OPEN || authPending) {
this.PendingRaw.push(obj);
if (this.Socket?.readyState === WebSocket.CLOSED && this.Ephemeral && this.IsClosed) {
this.Connect();
}
return false;
}
__classPrivateFieldGet(this, _Connection_instances, "m", _Connection_sendPendingRaw).call(this);
__classPrivateFieldGet(this, _Connection_instances, "m", _Connection_sendOnWire).call(this, obj);
}, _Connection_sendPendingRaw = function _Connection_sendPendingRaw() {
while (this.PendingRaw.length > 0) {
const next = this.PendingRaw.shift();
if (next) {
__classPrivateFieldGet(this, _Connection_instances, "m", _Connection_sendOnWire).call(this, next);
}
}
}, _Connection_sendOnWire = function _Connection_sendOnWire(obj) {
if (this.Socket?.readyState !== WebSocket.OPEN) {
throw new Error(`Socket is not open, state is ${this.Socket?.readyState}`);
}
const json = JSON.stringify(obj);
this.Socket.send(json);
return true;
}, _Connection_maxSubscriptions_get = function _Connection_maxSubscriptions_get() {
return this.Info?.limitation?.max_subscriptions ?? 25;
};
//# sourceMappingURL=Connection.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,30 +0,0 @@
/**
* Stats class for tracking metrics per connection
*/
export declare class ConnectionStats {
/**
* Last n records of how long between REQ->EOSE
*/
Latency: number[];
/**
* Total number of REQ's sent on this connection
*/
Subs: number;
/**
* Count of REQ which took too long and where abandoned
*/
SubsTimeout: number;
/**
* Total number of EVENT messages received
*/
EventsReceived: number;
/**
* Total number of EVENT messages sent
*/
EventsSent: number;
/**
* Total number of times this connection was lost
*/
Disconnects: number;
}
//# sourceMappingURL=ConnectionStats.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"ConnectionStats.d.ts","sourceRoot":"","sources":["../src/ConnectionStats.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,eAAe;IAC1B;;OAEG;IACH,OAAO,EAAE,MAAM,EAAE,CAAM;IAEvB;;OAEG;IACH,IAAI,EAAE,MAAM,CAAK;IAEjB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAK;IAExB;;OAEG;IACH,cAAc,EAAE,MAAM,CAAK;IAE3B;;OAEG;IACH,UAAU,EAAE,MAAM,CAAK;IAEvB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAK;CACzB"}

View File

@ -1,36 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionStats = void 0;
/**
* Stats class for tracking metrics per connection
*/
class ConnectionStats {
constructor() {
/**
* Last n records of how long between REQ->EOSE
*/
this.Latency = [];
/**
* Total number of REQ's sent on this connection
*/
this.Subs = 0;
/**
* Count of REQ which took too long and where abandoned
*/
this.SubsTimeout = 0;
/**
* Total number of EVENT messages received
*/
this.EventsReceived = 0;
/**
* Total number of EVENT messages sent
*/
this.EventsSent = 0;
/**
* Total number of times this connection was lost
*/
this.Disconnects = 0;
}
}
exports.ConnectionStats = ConnectionStats;
//# sourceMappingURL=ConnectionStats.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"ConnectionStats.js","sourceRoot":"","sources":["../src/ConnectionStats.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,MAAa,eAAe;IAA5B;QACE;;WAEG;QACH,YAAO,GAAa,EAAE,CAAC;QAEvB;;WAEG;QACH,SAAI,GAAW,CAAC,CAAC;QAEjB;;WAEG;QACH,gBAAW,GAAW,CAAC,CAAC;QAExB;;WAEG;QACH,mBAAc,GAAW,CAAC,CAAC;QAE3B;;WAEG;QACH,eAAU,GAAW,CAAC,CAAC;QAEvB;;WAEG;QACH,gBAAW,GAAW,CAAC,CAAC;IAC1B,CAAC;CAAA;AA9BD,0CA8BC"}

View File

@ -1,13 +0,0 @@
/**
* Websocket re-connect timeout
*/
export declare const DefaultConnectTimeout = 2000;
/**
* Hashtag regex
*/
export declare const HashtagRegex: RegExp;
/**
* How long profile cache should be considered valid for
*/
export declare const ProfileCacheExpire: number;
//# sourceMappingURL=Const.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"Const.d.ts","sourceRoot":"","sources":["../src/Const.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,qBAAqB,OAAO,CAAC;AAE1C;;GAEG;AAEH,eAAO,MAAM,YAAY,QAA4C,CAAC;AAGtE;;GAEG;AACF,eAAO,MAAM,kBAAkB,QAAsB,CAAC"}

View File

@ -1,17 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProfileCacheExpire = exports.HashtagRegex = exports.DefaultConnectTimeout = void 0;
/**
* Websocket re-connect timeout
*/
exports.DefaultConnectTimeout = 2000;
/**
* Hashtag regex
*/
// eslint-disable-next-line no-useless-escape
exports.HashtagRegex = /(#[^\s!@#$%^&*()=+.\/,\[{\]};:'"?><]+)/g;
/**
* How long profile cache should be considered valid for
*/
exports.ProfileCacheExpire = 1000 * 60 * 60 * 6;
//# sourceMappingURL=Const.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"Const.js","sourceRoot":"","sources":["../src/Const.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACU,QAAA,qBAAqB,GAAG,IAAI,CAAC;AAE1C;;GAEG;AACH,6CAA6C;AAChC,QAAA,YAAY,GAAG,yCAAyC,CAAC;AAGtE;;GAEG;AACW,QAAA,kBAAkB,GAAG,IAAK,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC"}

View File

@ -1,20 +0,0 @@
import { EventKind, HexKey, NostrEvent } from ".";
export declare class EventBuilder {
#private;
kind(k: EventKind): this;
content(c: string): this;
createdAt(n: number): this;
pubKey(k: string): this;
tag(t: Array<string>): EventBuilder;
/**
* Extract mentions
*/
processContent(): this;
build(): NostrEvent;
/**
* Build and sign event
* @param pk Private key to sign event with
*/
buildAndSign(pk: HexKey): Promise<NostrEvent>;
}
//# sourceMappingURL=EventBuilder.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"EventBuilder.d.ts","sourceRoot":"","sources":["../src/EventBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,EAAe,UAAU,EAAE,MAAM,GAAG,CAAC;AAM/D,qBAAa,YAAY;;IAOvB,IAAI,CAAC,CAAC,EAAE,SAAS;IAKjB,OAAO,CAAC,CAAC,EAAE,MAAM;IAKjB,SAAS,CAAC,CAAC,EAAE,MAAM;IAKnB,MAAM,CAAC,CAAC,EAAE,MAAM;IAKhB,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,YAAY;IAOnC;;OAEG;IACH,cAAc;IAcd,KAAK;IAcL;;;OAGG;IACG,YAAY,CAAC,EAAE,EAAE,MAAM;CAgC9B"}

View File

@ -1,113 +0,0 @@
"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _EventBuilder_instances, _EventBuilder_kind, _EventBuilder_content, _EventBuilder_createdAt, _EventBuilder_pubkey, _EventBuilder_tags, _EventBuilder_validate, _EventBuilder_replaceMention, _EventBuilder_addHashtag;
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventBuilder = void 0;
const _1 = require(".");
const Const_1 = require("./Const");
const Util_1 = require("./Util");
const EventExt_1 = require("./EventExt");
const NostrLink_1 = require("./NostrLink");
class EventBuilder {
constructor() {
_EventBuilder_instances.add(this);
_EventBuilder_kind.set(this, void 0);
_EventBuilder_content.set(this, void 0);
_EventBuilder_createdAt.set(this, void 0);
_EventBuilder_pubkey.set(this, void 0);
_EventBuilder_tags.set(this, []);
}
kind(k) {
__classPrivateFieldSet(this, _EventBuilder_kind, k, "f");
return this;
}
content(c) {
__classPrivateFieldSet(this, _EventBuilder_content, c, "f");
return this;
}
createdAt(n) {
__classPrivateFieldSet(this, _EventBuilder_createdAt, n, "f");
return this;
}
pubKey(k) {
__classPrivateFieldSet(this, _EventBuilder_pubkey, k, "f");
return this;
}
tag(t) {
const duplicate = __classPrivateFieldGet(this, _EventBuilder_tags, "f").some(a => a.length === t.length && a.every((b, i) => b !== a[i]));
if (duplicate)
return this;
__classPrivateFieldGet(this, _EventBuilder_tags, "f").push(t);
return this;
}
/**
* Extract mentions
*/
processContent() {
if (__classPrivateFieldGet(this, _EventBuilder_content, "f")) {
__classPrivateFieldSet(this, _EventBuilder_content, __classPrivateFieldGet(this, _EventBuilder_content, "f").replace(/@n(pub|profile|event|ote|addr|)1[acdefghjklmnpqrstuvwxyz023456789]+/g, m => __classPrivateFieldGet(this, _EventBuilder_instances, "m", _EventBuilder_replaceMention).call(this, m)), "f");
const hashTags = [...__classPrivateFieldGet(this, _EventBuilder_content, "f").matchAll(Const_1.HashtagRegex)];
hashTags.map(hashTag => {
__classPrivateFieldGet(this, _EventBuilder_instances, "m", _EventBuilder_addHashtag).call(this, hashTag[0]);
});
}
return this;
}
build() {
__classPrivateFieldGet(this, _EventBuilder_instances, "m", _EventBuilder_validate).call(this);
const ev = {
id: "",
pubkey: __classPrivateFieldGet(this, _EventBuilder_pubkey, "f") ?? "",
content: __classPrivateFieldGet(this, _EventBuilder_content, "f") ?? "",
kind: __classPrivateFieldGet(this, _EventBuilder_kind, "f"),
created_at: __classPrivateFieldGet(this, _EventBuilder_createdAt, "f") ?? (0, Util_1.unixNow)(),
tags: __classPrivateFieldGet(this, _EventBuilder_tags, "f"),
};
ev.id = EventExt_1.EventExt.createId(ev);
return ev;
}
/**
* Build and sign event
* @param pk Private key to sign event with
*/
async buildAndSign(pk) {
const ev = this.pubKey((0, Util_1.getPublicKey)(pk)).build();
await EventExt_1.EventExt.sign(ev, pk);
return ev;
}
}
exports.EventBuilder = EventBuilder;
_EventBuilder_kind = new WeakMap(), _EventBuilder_content = new WeakMap(), _EventBuilder_createdAt = new WeakMap(), _EventBuilder_pubkey = new WeakMap(), _EventBuilder_tags = new WeakMap(), _EventBuilder_instances = new WeakSet(), _EventBuilder_validate = function _EventBuilder_validate() {
if (__classPrivateFieldGet(this, _EventBuilder_kind, "f") === undefined) {
throw new Error("Kind must be set");
}
if (__classPrivateFieldGet(this, _EventBuilder_pubkey, "f") === undefined) {
throw new Error("Pubkey must be set");
}
}, _EventBuilder_replaceMention = function _EventBuilder_replaceMention(match) {
const npub = match.slice(1);
const link = (0, NostrLink_1.parseNostrLink)(npub);
if (link) {
if (link.type === _1.NostrPrefix.Profile || link.type === _1.NostrPrefix.PublicKey) {
this.tag(["p", link.id]);
}
return `nostr:${link.encode()}`;
}
else {
return match;
}
}, _EventBuilder_addHashtag = function _EventBuilder_addHashtag(match) {
const tag = match.slice(1);
this.tag(["t", tag.toLowerCase()]);
};
//# sourceMappingURL=EventBuilder.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"EventBuilder.js","sourceRoot":"","sources":["../src/EventBuilder.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,wBAA+D;AAC/D,mCAAuC;AACvC,iCAA+C;AAC/C,yCAAsC;AACtC,2CAA6C;AAE7C,MAAa,YAAY;IAAzB;;QACE,qCAAkB;QAClB,wCAAkB;QAClB,0CAAoB;QACpB,uCAAiB;QACjB,6BAA8B,EAAE,EAAC;IAgGnC,CAAC;IA9FC,IAAI,CAAC,CAAY;QACf,uBAAA,IAAI,sBAAS,CAAC,MAAA,CAAC;QACf,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,CAAC,CAAS;QACf,uBAAA,IAAI,yBAAY,CAAC,MAAA,CAAC;QAClB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,SAAS,CAAC,CAAS;QACjB,uBAAA,IAAI,2BAAc,CAAC,MAAA,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,CAAC,CAAS;QACd,uBAAA,IAAI,wBAAW,CAAC,MAAA,CAAC;QACjB,OAAO,IAAI,CA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GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC3B,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;AACrC,CAAC"}

View File

@ -1,42 +0,0 @@
import { EventKind, HexKey, NostrEvent, Tag } from ".";
export interface Thread {
root?: Tag;
replyTo?: Tag;
mentions: Array<Tag>;
pubKeys: Array<HexKey>;
}
export declare abstract class EventExt {
#private;
/**
* Get the pub key of the creator of this event NIP-26
*/
static getRootPubKey(e: NostrEvent): HexKey;
/**
* Sign this message with a private key
*/
static sign(e: NostrEvent, key: HexKey): void;
/**
* Check the signature of this message
* @returns True if valid signature
*/
static verify(e: NostrEvent): boolean;
static createId(e: NostrEvent): string;
/**
* Create a new event for a specific pubkey
*/
static forPubKey(pk: HexKey, kind: EventKind): NostrEvent;
static extractThread(ev: NostrEvent): Thread | undefined;
/**
* Encrypt the given message content
*/
static encryptData(content: string, pubkey: HexKey, privkey: HexKey): Promise<string>;
/**
* Decrypt the content of the message
*/
static decryptData(cyphertext: string, privkey: HexKey, pubkey: HexKey): Promise<string>;
/**
* Decrypt the content of this message in place
*/
static decryptDm(content: string, privkey: HexKey, pubkey: HexKey): Promise<string>;
}
//# sourceMappingURL=EventExt.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"EventExt.d.ts","sourceRoot":"","sources":["../src/EventExt.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,GAAG,CAAC;AAIvD,MAAM,WAAW,MAAM;IACrB,IAAI,CAAC,EAAE,GAAG,CAAC;IACX,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IACrB,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;CACxB;AAED,8BAAsB,QAAQ;;IAC5B;;OAEG;IACH,MAAM,CAAC,aAAa,CAAC,CAAC,EAAE,UAAU,GAAG,MAAM;IAS3C;;OAEG;IACH,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM;IAUtC;;;OAGG;IACH,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,UAAU;IAM3B,MAAM,CAAC,QAAQ,CAAC,CAAC,EAAE,UAAU;IAW7B;;OAEG;IACH,MAAM,CAAC,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS;IAY5C,MAAM,CAAC,aAAa,CAAC,EAAE,EAAE,UAAU;IAqCnC;;OAEG;WACU,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;IAgBzE;;OAEG;WACU,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAoB5E;;OAEG;WACU,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CASxE"}

View File

@ -1,175 +0,0 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a, _EventExt_getDmSharedKey;
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventExt = void 0;
const secp = __importStar(require("@noble/curves/secp256k1"));
const utils = __importStar(require("@noble/curves/abstract/utils"));
const _1 = require(".");
const base64_1 = __importDefault(require("@protobufjs/base64"));
const Util_1 = require("./Util");
class EventExt {
/**
* Get the pub key of the creator of this event NIP-26
*/
static getRootPubKey(e) {
const delegation = e.tags.find(a => a[0] === "delegation");
if (delegation?.[1]) {
// todo: verify sig
return delegation[1];
}
return e.pubkey;
}
/**
* Sign this message with a private key
*/
static sign(e, key) {
e.id = this.createId(e);
const sig = secp.schnorr.sign(e.id, key);
e.sig = utils.bytesToHex(sig);
if (!(secp.schnorr.verify(e.sig, e.id, e.pubkey))) {
throw new Error("Signing failed");
}
}
/**
* Check the signature of this message
* @returns True if valid signature
*/
static verify(e) {
const id = this.createId(e);
const result = secp.schnorr.verify(e.sig, id, e.pubkey);
return result;
}
static createId(e) {
const payload = [0, e.pubkey, e.created_at, e.kind, e.tags, e.content];
const hash = (0, Util_1.sha256)(JSON.stringify(payload));
if (e.id !== "" && hash !== e.id) {
console.debug(payload);
throw new Error("ID doesnt match!");
}
return hash;
}
/**
* Create a new event for a specific pubkey
*/
static forPubKey(pk, kind) {
return {
pubkey: pk,
kind: kind,
created_at: (0, Util_1.unixNow)(),
content: "",
tags: [],
id: "",
sig: "",
};
}
static extractThread(ev) {
const isThread = ev.tags.some(a => (a[0] === "e" && a[3] !== "mention") || a[0] == "a");
if (!isThread) {
return undefined;
}
const shouldWriteMarkers = ev.kind === _1.EventKind.TextNote;
const ret = {
mentions: [],
pubKeys: [],
};
const eTags = ev.tags.filter(a => a[0] === "e" || a[0] === "a").map((v, i) => new _1.Tag(v, i));
const marked = eTags.some(a => a.Marker !== undefined);
if (!marked) {
ret.root = eTags[0];
ret.root.Marker = shouldWriteMarkers ? "root" : undefined;
if (eTags.length > 1) {
ret.replyTo = eTags[1];
ret.replyTo.Marker = shouldWriteMarkers ? "reply" : undefined;
}
if (eTags.length > 2) {
ret.mentions = eTags.slice(2);
if (shouldWriteMarkers) {
ret.mentions.forEach(a => (a.Marker = "mention"));
}
}
}
else {
const root = eTags.find(a => a.Marker === "root");
const reply = eTags.find(a => a.Marker === "reply");
ret.root = root;
ret.replyTo = reply;
ret.mentions = eTags.filter(a => a.Marker === "mention");
}
ret.pubKeys = Array.from(new Set(ev.tags.filter(a => a[0] === "p").map(a => a[1])));
return ret;
}
/**
* Encrypt the given message content
*/
static async encryptData(content, pubkey, privkey) {
const key = await __classPrivateFieldGet(this, _a, "m", _EventExt_getDmSharedKey).call(this, pubkey, privkey);
const iv = window.crypto.getRandomValues(new Uint8Array(16));
const data = new TextEncoder().encode(content);
const result = await window.crypto.subtle.encrypt({
name: "AES-CBC",
iv: iv,
}, key, data);
const uData = new Uint8Array(result);
return `${base64_1.default.encode(uData, 0, result.byteLength)}?iv=${base64_1.default.encode(iv, 0, 16)}`;
}
/**
* Decrypt the content of the message
*/
static async decryptData(cyphertext, privkey, pubkey) {
const key = await __classPrivateFieldGet(this, _a, "m", _EventExt_getDmSharedKey).call(this, pubkey, privkey);
const cSplit = cyphertext.split("?iv=");
const data = new Uint8Array(base64_1.default.length(cSplit[0]));
base64_1.default.decode(cSplit[0], data, 0);
const iv = new Uint8Array(base64_1.default.length(cSplit[1]));
base64_1.default.decode(cSplit[1], iv, 0);
const result = await window.crypto.subtle.decrypt({
name: "AES-CBC",
iv: iv,
}, key, data);
return new TextDecoder().decode(result);
}
/**
* Decrypt the content of this message in place
*/
static async decryptDm(content, privkey, pubkey) {
return await this.decryptData(content, privkey, pubkey);
}
}
exports.EventExt = EventExt;
_a = EventExt, _EventExt_getDmSharedKey = async function _EventExt_getDmSharedKey(pubkey, privkey) {
const sharedPoint = secp.secp256k1.getSharedSecret(privkey, "02" + pubkey);
const sharedX = sharedPoint.slice(1, 33);
return await window.crypto.subtle.importKey("raw", sharedX, { name: "AES-CBC" }, false, ["encrypt", "decrypt"]);
};
//# sourceMappingURL=EventExt.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,29 +0,0 @@
declare enum EventKind {
Unknown = -1,
SetMetadata = 0,
TextNote = 1,
RecommendServer = 2,
ContactList = 3,
DirectMessage = 4,
Deletion = 5,
Repost = 6,
Reaction = 7,
BadgeAward = 8,
SnortSubscriptions = 1000,
Polls = 6969,
FileHeader = 1063,
Relays = 10002,
Ephemeral = 20000,
Auth = 22242,
PubkeyLists = 30000,
NoteLists = 30001,
TagLists = 30002,
Badge = 30009,
ProfileBadges = 30008,
ZapstrTrack = 31337,
ZapRequest = 9734,
ZapReceipt = 9735,
HttpAuthentication = 27235
}
export default EventKind;
//# sourceMappingURL=EventKind.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"EventKind.d.ts","sourceRoot":"","sources":["../src/EventKind.ts"],"names":[],"mappings":"AAAA,aAAK,SAAS;IACZ,OAAO,KAAK;IACZ,WAAW,IAAI;IACf,QAAQ,IAAI;IACZ,eAAe,IAAI;IACnB,WAAW,IAAI;IACf,aAAa,IAAI;IACjB,QAAQ,IAAI;IACZ,MAAM,IAAI;IACV,QAAQ,IAAI;IACZ,UAAU,IAAI;IACd,kBAAkB,OAAO;IACzB,KAAK,OAAO;IACZ,UAAU,OAAO;IACjB,MAAM,QAAQ;IACd,SAAS,QAAS;IAClB,IAAI,QAAQ;IACZ,WAAW,QAAQ;IACnB,SAAS,QAAQ;IACjB,QAAQ,QAAQ;IAChB,KAAK,QAAQ;IACb,aAAa,QAAQ;IACrB,WAAW,QAAQ;IACnB,UAAU,OAAO;IACjB,UAAU,OAAO;IACjB,kBAAkB,QAAQ;CAC3B;AAED,eAAe,SAAS,CAAC"}

View File

@ -1,32 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var EventKind;
(function (EventKind) {
EventKind[EventKind["Unknown"] = -1] = "Unknown";
EventKind[EventKind["SetMetadata"] = 0] = "SetMetadata";
EventKind[EventKind["TextNote"] = 1] = "TextNote";
EventKind[EventKind["RecommendServer"] = 2] = "RecommendServer";
EventKind[EventKind["ContactList"] = 3] = "ContactList";
EventKind[EventKind["DirectMessage"] = 4] = "DirectMessage";
EventKind[EventKind["Deletion"] = 5] = "Deletion";
EventKind[EventKind["Repost"] = 6] = "Repost";
EventKind[EventKind["Reaction"] = 7] = "Reaction";
EventKind[EventKind["BadgeAward"] = 8] = "BadgeAward";
EventKind[EventKind["SnortSubscriptions"] = 1000] = "SnortSubscriptions";
EventKind[EventKind["Polls"] = 6969] = "Polls";
EventKind[EventKind["FileHeader"] = 1063] = "FileHeader";
EventKind[EventKind["Relays"] = 10002] = "Relays";
EventKind[EventKind["Ephemeral"] = 20000] = "Ephemeral";
EventKind[EventKind["Auth"] = 22242] = "Auth";
EventKind[EventKind["PubkeyLists"] = 30000] = "PubkeyLists";
EventKind[EventKind["NoteLists"] = 30001] = "NoteLists";
EventKind[EventKind["TagLists"] = 30002] = "TagLists";
EventKind[EventKind["Badge"] = 30009] = "Badge";
EventKind[EventKind["ProfileBadges"] = 30008] = "ProfileBadges";
EventKind[EventKind["ZapstrTrack"] = 31337] = "ZapstrTrack";
EventKind[EventKind["ZapRequest"] = 9734] = "ZapRequest";
EventKind[EventKind["ZapReceipt"] = 9735] = "ZapReceipt";
EventKind[EventKind["HttpAuthentication"] = 27235] = "HttpAuthentication";
})(EventKind || (EventKind = {}));
exports.default = EventKind;
//# sourceMappingURL=EventKind.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"EventKind.js","sourceRoot":"","sources":["../src/EventKind.ts"],"names":[],"mappings":";;AAAA,IAAK,SA0BJ;AA1BD,WAAK,SAAS;IACZ,gDAAY,CAAA;IACZ,uDAAe,CAAA;IACf,iDAAY,CAAA;IACZ,+DAAmB,CAAA;IACnB,uDAAe,CAAA;IACf,2DAAiB,CAAA;IACjB,iDAAY,CAAA;IACZ,6CAAU,CAAA;IACV,iDAAY,CAAA;IACZ,qDAAc,CAAA;IACd,wEAAyB,CAAA;IACzB,8CAAY,CAAA;IACZ,wDAAiB,CAAA;IACjB,iDAAc,CAAA;IACd,uDAAkB,CAAA;IAClB,6CAAY,CAAA;IACZ,2DAAmB,CAAA;IACnB,uDAAiB,CAAA;IACjB,qDAAgB,CAAA;IAChB,+CAAa,CAAA;IACb,+DAAqB,CAAA;IACrB,2DAAmB,CAAA;IACnB,wDAAiB,CAAA;IACjB,wDAAiB,CAAA;IACjB,yEAA0B,CAAA;AAC5B,CAAC,EA1BI,SAAS,KAAT,SAAS,QA0Bb;AAED,kBAAe,SAAS,CAAC"}

View File

@ -1,66 +0,0 @@
import { FullRelaySettings, HexKey, Lists, NostrEvent, RelaySettings, SystemInterface, TaggedRawEvent, u256, UserMetadata } from ".";
import { EventBuilder } from "./EventBuilder";
export type EventBuilderHook = (ev: EventBuilder) => EventBuilder;
declare global {
interface Window {
nostr?: {
getPublicKey: () => Promise<HexKey>;
signEvent: <T extends NostrEvent>(event: T) => Promise<T>;
getRelays?: () => Promise<Record<string, {
read: boolean;
write: boolean;
}>>;
nip04?: {
encrypt?: (pubkey: HexKey, plaintext: string) => Promise<string>;
decrypt?: (pubkey: HexKey, ciphertext: string) => Promise<string>;
};
};
}
}
export declare class EventPublisher {
#private;
constructor(system: SystemInterface, pubKey: string, privKey?: string);
nip4Encrypt(content: string, key: HexKey): Promise<string>;
nip4Decrypt(content: string, otherKey: HexKey): Promise<string>;
nip42Auth(challenge: string, relay: string): Promise<NostrEvent>;
broadcast(ev: NostrEvent): void;
/**
* Write event to all given relays.
*/
broadcastAll(ev: NostrEvent, relays: string[]): void;
muted(keys: HexKey[], priv: HexKey[]): Promise<NostrEvent>;
noteList(notes: u256[], list: Lists): Promise<NostrEvent>;
tags(tags: string[]): Promise<NostrEvent>;
metadata(obj: UserMetadata): Promise<NostrEvent>;
/**
* Create a basic text note
*/
note(msg: string, fnExtra?: EventBuilderHook): Promise<NostrEvent>;
/**
* Create a zap request event for a given target event/profile
* @param amount Millisats amout!
* @param author Author pubkey to tag in the zap
* @param note Note Id to tag in the zap
* @param msg Custom message to be included in the zap
*/
zap(amount: number, author: HexKey, relays: Array<string>, note?: HexKey, msg?: string, fnExtra?: EventBuilderHook): Promise<NostrEvent>;
/**
* Reply to a note
*/
reply(replyTo: TaggedRawEvent, msg: string, fnExtra?: EventBuilderHook): Promise<NostrEvent>;
react(evRef: NostrEvent, content?: string): Promise<NostrEvent>;
relayList(relays: Array<FullRelaySettings> | Record<string, RelaySettings>): Promise<NostrEvent>;
contactList(follows: Array<HexKey>, relays: Record<string, RelaySettings>): Promise<NostrEvent>;
/**
* Delete an event (NIP-09)
*/
delete(id: u256): Promise<NostrEvent>;
/**
* Repost a note (NIP-18)
*/
repost(note: NostrEvent): Promise<NostrEvent>;
decryptDm(note: NostrEvent): Promise<string>;
sendDm(content: string, to: HexKey): Promise<NostrEvent>;
generic(fnHook: EventBuilderHook): Promise<NostrEvent>;
}
//# sourceMappingURL=EventPublisher.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"EventPublisher.d.ts","sourceRoot":"","sources":["../src/EventPublisher.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,iBAAiB,EACjB,MAAM,EACN,KAAK,EACL,UAAU,EACV,aAAa,EACb,eAAe,EACf,cAAc,EACd,IAAI,EACJ,YAAY,EACb,MAAM,GAAG,CAAC;AAGX,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAM9C,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,YAAY,KAAK,YAAY,CAAC;AAElE,OAAO,C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,QAAQ,CAAC,GAAG,EAAE,YAAY;IAMhC;;OAEG;IACG,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB;IAQlD;;;;;;OAMG;IACG,GAAG,CACP,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,EACrB,IAAI,CAAC,EAAE,MAAM,EACb,GAAG,CAAC,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,gBAAgB;IAe5B;;OAEG;IACG,KAAK,CAAC,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB;IA8BtE,KAAK,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,SAAM;IAQtC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC;IAqB1E,WAAW,CAAC,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC;IAS/E;;OAEG;IACG,MAAM,CAAC,EAAE,EAAE,IAAI;IAKrB;;OAEG;IACG,MAAM,CAAC,IAAI,EAAE,UAAU;IAOvB,SAAS,CAAC,IAAI,EAAE,UAAU;IAQ1B,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;IAOlC,OAAO,CAAC,MAAM,EAAE,gBAAgB;CAMvC"}

View File

@ -1,295 +0,0 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _EventPublisher_instances, _EventPublisher_system, _EventPublisher_pubKey, _EventPublisher_privateKey, _EventPublisher_hasNip07_get, _EventPublisher_eb, _EventPublisher_sign;
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventPublisher = void 0;
const secp = __importStar(require("@noble/curves/secp256k1"));
const utils = __importStar(require("@noble/curves/abstract/utils"));
const _1 = require(".");
const Util_1 = require("./Util");
const EventBuilder_1 = require("./EventBuilder");
const EventExt_1 = require("./EventExt");
const WorkQueue_1 = require("./WorkQueue");
const Nip7Queue = [];
(0, WorkQueue_1.processWorkQueue)(Nip7Queue);
class EventPublisher {
constructor(system, pubKey, privKey) {
_EventPublisher_instances.add(this);
_EventPublisher_system.set(this, void 0);
_EventPublisher_pubKey.set(this, void 0);
_EventPublisher_privateKey.set(this, void 0);
__classPrivateFieldSet(this, _EventPublisher_system, system, "f");
if (privKey) {
__classPrivateFieldSet(this, _EventPublisher_privateKey, privKey, "f");
__classPrivateFieldSet(this, _EventPublisher_pubKey, utils.bytesToHex(secp.schnorr.getPublicKey(privKey)), "f");
}
else {
__classPrivateFieldSet(this, _EventPublisher_pubKey, pubKey, "f");
}
}
async nip4Encrypt(content, key) {
if (__classPrivateFieldGet(this, _EventPublisher_instances, "a", _EventPublisher_hasNip07_get) && !__classPrivateFieldGet(this, _EventPublisher_privateKey, "f")) {
const nip7PubKey = await (0, WorkQueue_1.barrierQueue)(Nip7Queue, () => (0, Util_1.unwrap)(window.nostr).getPublicKey());
if (nip7PubKey !== __classPrivateFieldGet(this, _EventPublisher_pubKey, "f")) {
throw new Error("Can't encrypt content, NIP-07 pubkey does not match");
}
return await (0, WorkQueue_1.barrierQueue)(Nip7Queue, () => (0, Util_1.unwrap)(window.nostr?.nip04?.encrypt).call(window.nostr?.nip04, key, content));
}
else if (__classPrivateFieldGet(this, _EventPublisher_privateKey, "f")) {
return await EventExt_1.EventExt.encryptData(content, key, __classPrivateFieldGet(this, _EventPublisher_privateKey, "f"));
}
else {
throw new Error("Can't encrypt content, no private keys available");
}
}
async nip4Decrypt(content, otherKey) {
if (__classPrivateFieldGet(this, _EventPublisher_instances, "a", _EventPublisher_hasNip07_get) && !__classPrivateFieldGet(this, _EventPublisher_privateKey, "f") && window.nostr?.nip04?.decrypt) {
return await (0, WorkQueue_1.barrierQueue)(Nip7Queue, () => (0, Util_1.unwrap)(window.nostr?.nip04?.decrypt).call(window.nostr?.nip04, otherKey, content));
}
else if (__classPrivateFieldGet(this, _EventPublisher_privateKey, "f")) {
return await EventExt_1.EventExt.decryptDm(content, __classPrivateFieldGet(this, _EventPublisher_privateKey, "f"), otherKey);
}
else {
throw new Error("Can't decrypt content, no private keys available");
}
}
async nip42Auth(challenge, relay) {
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.Auth);
eb.tag(["relay", relay]);
eb.tag(["challenge", challenge]);
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
broadcast(ev) {
console.debug(ev);
__classPrivateFieldGet(this, _EventPublisher_system, "f").BroadcastEvent(ev);
}
/**
* Write event to all given relays.
*/
broadcastAll(ev, relays) {
for (const k of relays) {
__classPrivateFieldGet(this, _EventPublisher_system, "f").WriteOnceToRelay(k, ev);
}
}
async muted(keys, priv) {
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.PubkeyLists);
eb.tag(["d", _1.Lists.Muted]);
keys.forEach(p => {
eb.tag(["p", p]);
});
if (priv.length > 0) {
const ps = priv.map(p => ["p", p]);
const plaintext = JSON.stringify(ps);
eb.content(await this.nip4Encrypt(plaintext, __classPrivateFieldGet(this, _EventPublisher_pubKey, "f")));
}
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
async noteList(notes, list) {
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.NoteLists);
eb.tag(["d", list]);
notes.forEach(n => {
eb.tag(["e", n]);
});
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
async tags(tags) {
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.TagLists);
eb.tag(["d", _1.Lists.Followed]);
tags.forEach(t => {
eb.tag(["t", t]);
});
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
async metadata(obj) {
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.SetMetadata);
eb.content(JSON.stringify(obj));
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
/**
* Create a basic text note
*/
async note(msg, fnExtra) {
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.TextNote);
eb.content(msg);
eb.processContent();
fnExtra?.(eb);
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
/**
* Create a zap request event for a given target event/profile
* @param amount Millisats amout!
* @param author Author pubkey to tag in the zap
* @param note Note Id to tag in the zap
* @param msg Custom message to be included in the zap
*/
async zap(amount, author, relays, note, msg, fnExtra) {
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.ZapRequest);
eb.content(msg ?? "");
if (note) {
eb.tag(["e", note]);
}
eb.tag(["p", author]);
eb.tag(["relays", ...relays.map(a => a.trim())]);
eb.tag(["amount", amount.toString()]);
eb.processContent();
fnExtra?.(eb);
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
/**
* Reply to a note
*/
async reply(replyTo, msg, fnExtra) {
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.TextNote);
eb.content(msg);
const thread = EventExt_1.EventExt.extractThread(replyTo);
if (thread) {
if (thread.root || thread.replyTo) {
eb.tag(["e", thread.root?.Event ?? thread.replyTo?.Event ?? "", "", "root"]);
}
eb.tag(["e", replyTo.id, replyTo.relays?.[0] ?? "", "reply"]);
eb.tag(["p", replyTo.pubkey]);
for (const pk of thread.pubKeys) {
if (pk === __classPrivateFieldGet(this, _EventPublisher_pubKey, "f")) {
continue;
}
eb.tag(["p", pk]);
}
}
else {
eb.tag(["e", replyTo.id, "", "reply"]);
// dont tag self in replies
if (replyTo.pubkey !== __classPrivateFieldGet(this, _EventPublisher_pubKey, "f")) {
eb.tag(["p", replyTo.pubkey]);
}
}
eb.processContent();
fnExtra?.(eb);
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
async react(evRef, content = "+") {
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.Reaction);
eb.content(content);
eb.tag(["e", evRef.id]);
eb.tag(["p", evRef.pubkey]);
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
async relayList(relays) {
if (!Array.isArray(relays)) {
relays = Object.entries(relays).map(([k, v]) => ({
url: k,
settings: v,
}));
}
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.Relays);
for (const rx of relays) {
const rTag = ["r", rx.url];
if (rx.settings.read && !rx.settings.write) {
rTag.push("read");
}
if (rx.settings.write && !rx.settings.read) {
rTag.push("write");
}
eb.tag(rTag);
}
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
async contactList(follows, relays) {
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.ContactList);
eb.content(JSON.stringify(relays));
const temp = new Set(follows.filter(a => a.length === 64).map(a => a.toLowerCase()));
temp.forEach(a => eb.tag(["p", a]));
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
/**
* Delete an event (NIP-09)
*/
async delete(id) {
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.Deletion);
eb.tag(["e", id]);
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
/**
* Repost a note (NIP-18)
*/
async repost(note) {
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.Repost);
eb.tag(["e", note.id, ""]);
eb.tag(["p", note.pubkey]);
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
async decryptDm(note) {
if (note.pubkey !== __classPrivateFieldGet(this, _EventPublisher_pubKey, "f") && !note.tags.some(a => a[1] === __classPrivateFieldGet(this, _EventPublisher_pubKey, "f"))) {
throw new Error("Can't decrypt, DM does not belong to this user");
}
const otherPubKey = note.pubkey === __classPrivateFieldGet(this, _EventPublisher_pubKey, "f") ? (0, Util_1.unwrap)(note.tags.find(a => a[0] === "p")?.[1]) : note.pubkey;
return await this.nip4Decrypt(note.content, otherPubKey);
}
async sendDm(content, to) {
const eb = __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_eb).call(this, _1.EventKind.DirectMessage);
eb.content(await this.nip4Encrypt(content, to));
eb.tag(["p", to]);
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
async generic(fnHook) {
const eb = new EventBuilder_1.EventBuilder();
eb.pubKey(__classPrivateFieldGet(this, _EventPublisher_pubKey, "f"));
fnHook(eb);
return await __classPrivateFieldGet(this, _EventPublisher_instances, "m", _EventPublisher_sign).call(this, eb);
}
}
exports.EventPublisher = EventPublisher;
_EventPublisher_system = new WeakMap(), _EventPublisher_pubKey = new WeakMap(), _EventPublisher_privateKey = new WeakMap(), _EventPublisher_instances = new WeakSet(), _EventPublisher_hasNip07_get = function _EventPublisher_hasNip07_get() {
return "nostr" in window;
}, _EventPublisher_eb = function _EventPublisher_eb(k) {
const eb = new EventBuilder_1.EventBuilder();
return eb.pubKey(__classPrivateFieldGet(this, _EventPublisher_pubKey, "f")).kind(k);
}, _EventPublisher_sign = async function _EventPublisher_sign(eb) {
if (__classPrivateFieldGet(this, _EventPublisher_instances, "a", _EventPublisher_hasNip07_get) && !__classPrivateFieldGet(this, _EventPublisher_privateKey, "f")) {
const nip7PubKey = await (0, WorkQueue_1.barrierQueue)(Nip7Queue, () => (0, Util_1.unwrap)(window.nostr).getPublicKey());
if (nip7PubKey !== __classPrivateFieldGet(this, _EventPublisher_pubKey, "f")) {
throw new Error("Can't sign event, NIP-07 pubkey does not match");
}
const ev = eb.build();
return await (0, WorkQueue_1.barrierQueue)(Nip7Queue, () => (0, Util_1.unwrap)(window.nostr).signEvent(ev));
}
else if (__classPrivateFieldGet(this, _EventPublisher_privateKey, "f")) {
return await eb.buildAndSign(__classPrivateFieldGet(this, _EventPublisher_privateKey, "f"));
}
else {
throw new Error("Can't sign event, no private keys available");
}
};
//# sourceMappingURL=EventPublisher.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,13 +0,0 @@
type HookFn<TSnapshot> = (e?: TSnapshot) => void;
/**
* Simple React hookable store with manual change notifications
*/
export default abstract class ExternalStore<TSnapshot> {
#private;
hook(fn: HookFn<TSnapshot>): () => void;
snapshot(): Readonly<TSnapshot>;
protected notifyChange(sn?: TSnapshot): void;
abstract takeSnapshot(): TSnapshot;
}
export {};
//# sourceMappingURL=ExternalStore.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"ExternalStore.d.ts","sourceRoot":"","sources":["../src/ExternalStore.ts"],"names":[],"mappings":"AAAA,KAAK,MAAM,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EAAE,SAAS,KAAK,IAAI,CAAC;AAMjD;;GAEG;AACH,MAAM,CAAC,OAAO,CAAC,QAAQ,OAAO,aAAa,CAAC,SAAS;;IAKnD,IAAI,CAAC,EAAE,EAAE,MAAM,CAAC,SAAS,CAAC;IAY1B,QAAQ;IAQR,SAAS,CAAC,YAAY,CAAC,EAAE,CAAC,EAAE,SAAS;IAKrC,QAAQ,CAAC,YAAY,IAAI,SAAS;CACnC"}

View File

@ -1,49 +0,0 @@
"use strict";
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var _ExternalStore_hooks, _ExternalStore_snapshot, _ExternalStore_changed;
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Simple React hookable store with manual change notifications
*/
class ExternalStore {
constructor() {
_ExternalStore_hooks.set(this, []);
_ExternalStore_snapshot.set(this, {});
_ExternalStore_changed.set(this, true);
}
hook(fn) {
__classPrivateFieldGet(this, _ExternalStore_hooks, "f").push({
fn,
});
return () => {
const idx = __classPrivateFieldGet(this, _ExternalStore_hooks, "f").findIndex(a => a.fn === fn);
if (idx >= 0) {
__classPrivateFieldGet(this, _ExternalStore_hooks, "f").splice(idx, 1);
}
};
}
snapshot() {
if (__classPrivateFieldGet(this, _ExternalStore_changed, "f")) {
__classPrivateFieldSet(this, _ExternalStore_snapshot, this.takeSnapshot(), "f");
__classPrivateFieldSet(this, _ExternalStore_changed, false, "f");
}
return __classPrivateFieldGet(this, _ExternalStore_snapshot, "f");
}
notifyChange(sn) {
__classPrivateFieldSet(this, _ExternalStore_changed, true, "f");
__classPrivateFieldGet(this, _ExternalStore_hooks, "f").forEach(h => h.fn(sn));
}
}
exports.default = ExternalStore;
_ExternalStore_hooks = new WeakMap(), _ExternalStore_snapshot = new WeakMap(), _ExternalStore_changed = new WeakMap();
//# sourceMappingURL=ExternalStore.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"ExternalStore.js","sourceRoot":"","sources":["../src/ExternalStore.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAMA;;GAEG;AACH,MAA8B,aAAa;IAA3C;QACE,+BAAuC,EAAE,EAAC;QAC1C,kCAAiC,EAAyB,EAAC;QAC3D,iCAAW,IAAI,EAAC;IA4BlB,CAAC;IA1BC,IAAI,CAAC,EAAqB;QACxB,uBAAA,IAAI,4BAAO,CAAC,IAAI,CAAC;YACf,EAAE;SACH,CAAC,CAAC;QACH,OAAO,GAAG,EAAE;YACV,MAAM,GAAG,GAAG,uBAAA,IAAI,4BAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;YACpD,IAAI,GAAG,IAAI,CAAC,EAAE;gBACZ,uBAAA,IAAI,4BAAO,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;aAC5B;QACH,CAAC,CAAC;IACJ,CAAC;IAED,QAAQ;QACN,IAAI,uBAAA,IAAI,8BAAS,EAAE;YACjB,uBAAA,IAAI,2BAAa,IAAI,CAAC,YAAY,EAAE,MAAA,CAAC;YACrC,uBAAA,IAAI,0BAAY,KAAK,MAAA,CAAC;SACvB;QACD,OAAO,uBAAA,IAAI,+BAAU,CAAC;IACxB,CAAC;IAES,YAAY,CAAC,EAAc;QACnC,uBAAA,IAAI,0BAAY,IAAI,MAAA,CAAC;QACrB,uBAAA,IAAI,4BAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACrC,CAAC;CAGF;AA/BD,gCA+BC"}

View File

@ -1,20 +0,0 @@
import { FullRelaySettings, ReqFilter } from ".";
export interface RelayTaggedFilter {
relay: string;
filter: ReqFilter;
}
export interface RelayTaggedFilters {
relay: string;
filters: Array<ReqFilter>;
}
export interface RelayCache {
get(pubkey?: string): Array<FullRelaySettings> | undefined;
}
export declare function splitAllByWriteRelays(cache: RelayCache, filters: Array<ReqFilter>): RelayTaggedFilters[];
/**
* Split filters by authors
* @param filter
* @returns
*/
export declare function splitByWriteRelays(cache: RelayCache, filter: ReqFilter): Array<RelayTaggedFilter>;
//# sourceMappingURL=GossipModel.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"GossipModel.d.ts","sourceRoot":"","sources":["../src/GossipModel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,GAAG,CAAC;AAMjD,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,SAAS,CAAC;CACnB;AAED,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;CAC3B;AAED,MAAM,WAAW,UAAU;IACzB,GAAG,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC,iBAAiB,CAAC,GAAG,SAAS,CAAC;CAC5D;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,wBAqBjF;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,GAAG,KAAK,CAAC,iBAAiB,CAAC,CAoEjG"}

View File

@ -1,102 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.splitByWriteRelays = exports.splitAllByWriteRelays = void 0;
const Util_1 = require("./Util");
const debug_1 = __importDefault(require("debug"));
const PickNRelays = 2;
function splitAllByWriteRelays(cache, filters) {
const allSplit = filters
.map(a => splitByWriteRelays(cache, a))
.reduce((acc, v) => {
for (const vn of v) {
const existing = acc.get(vn.relay);
if (existing) {
existing.push(vn.filter);
}
else {
acc.set(vn.relay, [vn.filter]);
}
}
return acc;
}, new Map());
return [...allSplit.entries()].map(([k, v]) => {
return {
relay: k,
filters: v,
};
});
}
exports.splitAllByWriteRelays = splitAllByWriteRelays;
/**
* Split filters by authors
* @param filter
* @returns
*/
function splitByWriteRelays(cache, filter) {
if ((filter.authors?.length ?? 0) === 0)
return [
{
relay: "",
filter,
},
];
const allRelays = (0, Util_1.unwrap)(filter.authors).map(a => {
return {
key: a,
relays: cache.get(a)?.filter(a => a.settings.write),
};
});
const missing = allRelays.filter(a => a.relays === undefined);
const hasRelays = allRelays.filter(a => a.relays !== undefined);
const relayUserMap = hasRelays.reduce((acc, v) => {
for (const r of (0, Util_1.unwrap)(v.relays)) {
if (!acc.has(r.url)) {
acc.set(r.url, new Set([v.key]));
}
else {
(0, Util_1.unwrap)(acc.get(r.url)).add(v.key);
}
}
return acc;
}, new Map());
// selection algo will just pick relays with the most users
const topRelays = [...relayUserMap.entries()].sort(([, v], [, v1]) => v1.size - v.size);
// <relay, key[]> - count keys per relay
// <key, relay[]> - pick n top relays
// <relay, key[]> - map keys per relay (for subscription filter)
const userPickedRelays = (0, Util_1.unwrap)(filter.authors).map(k => {
// pick top 3 relays for this key
const relaysForKey = topRelays
.filter(([, v]) => v.has(k))
.slice(0, PickNRelays)
.map(([k]) => k);
return { k, relaysForKey };
});
const pickedRelays = new Set(userPickedRelays.map(a => a.relaysForKey).flat());
const picked = [...pickedRelays].map(a => {
const keysOnPickedRelay = new Set(userPickedRelays.filter(b => b.relaysForKey.includes(a)).map(b => b.k));
return {
relay: a,
filter: {
...filter,
authors: [...keysOnPickedRelay],
},
};
});
if (missing.length > 0) {
picked.push({
relay: "",
filter: {
...filter,
authors: missing.map(a => a.key),
},
});
}
(0, debug_1.default)("GOSSIP")("Picked %o", picked);
return picked;
}
exports.splitByWriteRelays = splitByWriteRelays;
//# sourceMappingURL=GossipModel.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"GossipModel.js","sourceRoot":"","sources":["../src/GossipModel.ts"],"names":[],"mappings":";;;;;;AACA,iCAAgC;AAChC,kDAA0B;AAE1B,MAAM,WAAW,GAAG,CAAC,CAAC;AAgBtB,SAAgB,qBAAqB,CAAC,KAAiB,EAAE,OAAyB;IAChF,MAAM,QAAQ,GAAG,OAAO;SACrB,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,kBAAkB,CAAC,KAAK,EAAE,CAAC,CAAC,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AC,CAAC;IACrC,OAAO,MAAM,CAAC;AAChB,CAAC;AApED,gDAoEC"}

View File

@ -1,24 +0,0 @@
import { HexKey } from "./Nostr";
export declare enum NostrPrefix {
PublicKey = "npub",
PrivateKey = "nsec",
Note = "note",
Profile = "nprofile",
Event = "nevent",
Relay = "nrelay",
Address = "naddr"
}
export declare enum TLVEntryType {
Special = 0,
Relay = 1,
Author = 2,
Kind = 3
}
export interface TLVEntry {
type: TLVEntryType;
length: number;
value: string | HexKey | number;
}
export declare function encodeTLV(prefix: NostrPrefix, id: string, relays?: string[], kind?: number, author?: string): string;
export declare function decodeTLV(str: string): TLVEntry[];
//# sourceMappingURL=Links.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"Links.d.ts","sourceRoot":"","sources":["../src/Links.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEjC,oBAAY,WAAW;IACrB,SAAS,SAAS;IAClB,UAAU,SAAS;IACnB,IAAI,SAAS;IAGb,OAAO,aAAa;IACpB,KAAK,WAAW;IAChB,KAAK,WAAW;IAChB,OAAO,UAAU;CAClB;AAED,oBAAY,YAAY;IACtB,OAAO,IAAI;IACX,KAAK,IAAI;IACT,MAAM,IAAI;IACV,IAAI,IAAI;CACT;AAED,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,YAAY,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;CACjC;AAED,wBAAgB,SAAS,CAAC,MAAM,EAAE,WAAW,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,UAiB3G;AAED,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,cAkBpC"}

View File

@ -1,102 +0,0 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodeTLV = exports.encodeTLV = exports.TLVEntryType = exports.NostrPrefix = void 0;
const utils = __importStar(require("@noble/curves/abstract/utils"));
const bech32_1 = require("bech32");
var NostrPrefix;
(function (NostrPrefix) {
NostrPrefix["PublicKey"] = "npub";
NostrPrefix["PrivateKey"] = "nsec";
NostrPrefix["Note"] = "note";
// TLV prefixes
NostrPrefix["Profile"] = "nprofile";
NostrPrefix["Event"] = "nevent";
NostrPrefix["Relay"] = "nrelay";
NostrPrefix["Address"] = "naddr";
})(NostrPrefix = exports.NostrPrefix || (exports.NostrPrefix = {}));
var TLVEntryType;
(function (TLVEntryType) {
TLVEntryType[TLVEntryType["Special"] = 0] = "Special";
TLVEntryType[TLVEntryType["Relay"] = 1] = "Relay";
TLVEntryType[TLVEntryType["Author"] = 2] = "Author";
TLVEntryType[TLVEntryType["Kind"] = 3] = "Kind";
})(TLVEntryType = exports.TLVEntryType || (exports.TLVEntryType = {}));
function encodeTLV(prefix, id, relays, kind, author) {
const enc = new TextEncoder();
const buf = prefix === NostrPrefix.Address ? enc.encode(id) : utils.hexToBytes(id);
const tl0 = [0, buf.length, ...buf];
const tl1 = relays
?.map(a => {
const data = enc.encode(a);
return [1, data.length, ...data];
})
.flat() ?? [];
const tl2 = author ? [2, 32, ...utils.hexToBytes(author)] : [];
const tl3 = kind ? [3, 4, ...new Uint8Array(new Uint32Array([kind]).buffer).reverse()] : [];
return bech32_1.bech32.encode(prefix, bech32_1.bech32.toWords([...tl0, ...tl1, ...tl2, ...tl3]), 1000);
}
exports.encodeTLV = encodeTLV;
function decodeTLV(str) {
const decoded = bech32_1.bech32.decode(str, 1000);
const data = bech32_1.bech32.fromWords(decoded.words);
const entries = [];
let x = 0;
while (x < data.length) {
const t = data[x];
const l = data[x + 1];
const v = data.slice(x + 2, x + 2 + l);
entries.push({
type: t,
length: l,
value: decodeTLVEntry(t, decoded.prefix, new Uint8Array(v)),
});
x += 2 + l;
}
return entries;
}
exports.decodeTLV = decodeTLV;
function decodeTLVEntry(type, prefix, data) {
switch (type) {
case TLVEntryType.Special: {
if (prefix === NostrPrefix.Address) {
return new TextDecoder("ASCII").decode(data);
}
else {
return utils.bytesToHex(data);
}
}
case TLVEntryType.Author: {
return utils.bytesToHex(data);
}
case TLVEntryType.Kind: {
return new Uint32Array(new Uint8Array(data.reverse()).buffer)[0];
}
case TLVEntryType.Relay: {
return new TextDecoder("ASCII").decode(data);
}
}
}
//# sourceMappingURL=Links.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"Links.js","sourceRoot":"","sources":["../src/Links.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oEAAsD;AACtD,mCAAgC;AAGhC,IAAY,WAUX;AAVD,WAAY,WAAW;IACrB,iCAAkB,CAAA;IAClB,kCAAmB,CAAA;IACnB,4BAAa,CAAA;IAEb,eAAe;IACf,mCAAoB,CAAA;IACpB,+BAAgB,CAAA;IAChB,+BAAgB,CAAA;IAChB,gCAAiB,CAAA;AACnB,CAAC,EAVW,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAUtB;AAED,IAAY,YAKX;AALD,WAAY,YAAY;IACtB,qDAAW,C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;gBACL,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;aAC/B;SACF;QACD,KAAK,YAAY,CAAC,MAAM,CAAC,CAAC;YACxB,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;SAC/B;QACD,KAAK,YAAY,CAAC,IAAI,CAAC,CAAC;YACtB,OAAO,IAAI,WAAW,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;SAClE;QACD,KAAK,YAAY,CAAC,KAAK,CAAC,CAAC;YACvB,OAAO,IAAI,WAAW,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;SAC9C;KACF;AACH,CAAC"}

View File

@ -1,4 +0,0 @@
export declare enum Nips {
Search = 50
}
//# sourceMappingURL=Nips.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"Nips.d.ts","sourceRoot":"","sources":["../src/Nips.ts"],"names":[],"mappings":"AAAA,oBAAY,IAAI;IACd,MAAM,KAAK;CACZ"}

View File

@ -1,8 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Nips = void 0;
var Nips;
(function (Nips) {
Nips[Nips["Search"] = 50] = "Search";
})(Nips = exports.Nips || (exports.Nips = {}));
//# sourceMappingURL=Nips.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"Nips.js","sourceRoot":"","sources":["../src/Nips.ts"],"names":[],"mappings":";;;AAAA,IAAY,IAEX;AAFD,WAAY,IAAI;IACd,oCAAW,CAAA;AACb,CAAC,EAFW,IAAI,GAAJ,YAAI,KAAJ,YAAI,QAEf"}

View File

@ -1,75 +0,0 @@
import { RelaySettings } from "./Connection";
export interface NostrEvent {
id: u256;
pubkey: HexKey;
created_at: number;
kind: number;
tags: Array<Array<string>>;
content: string;
sig: string;
}
export interface TaggedRawEvent extends NostrEvent {
/**
* A list of relays this event was seen on
*/
relays: string[];
}
/**
* Basic raw key as hex
*/
export type HexKey = string;
/**
* Optional HexKey
*/
export type MaybeHexKey = HexKey | undefined;
/**
* A 256bit hex id
*/
export type u256 = string;
export type ReqCommand = [cmd: "REQ", id: string, ...filters: Array<ReqFilter>];
/**
* Raw REQ filter object
*/
export interface ReqFilter {
ids?: u256[];
authors?: u256[];
kinds?: number[];
"#e"?: u256[];
"#p"?: u256[];
"#t"?: string[];
"#d"?: string[];
"#r"?: string[];
search?: string;
since?: number;
until?: number;
limit?: number;
}
/**
* Medatadata event content
*/
export type UserMetadata = {
name?: string;
display_name?: string;
about?: string;
picture?: string;
website?: string;
banner?: string;
nip05?: string;
lud06?: string;
lud16?: string;
};
/**
* NIP-51 list types
*/
export declare enum Lists {
Muted = "mute",
Pinned = "pin",
Bookmarked = "bookmark",
Followed = "follow",
Badges = "profile_badges"
}
export interface FullRelaySettings {
url: string;
settings: RelaySettings;
}
//# sourceMappingURL=Nostr.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"Nostr.d.ts","sourceRoot":"","sources":["../src/Nostr.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,IAAI,CAAC;IACT,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,cAAe,SAAQ,UAAU;IAChD;;OAEG;IACH,MAAM,EAAE,MAAM,EAAE,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC;AAE5B;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,SAAS,CAAC;AAE7C;;GAEG;AACH,MAAM,M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,MAAM,CAAC;IACZ,QAAQ,EAAE,aAAa,CAAC;CACzB"}

View File

@ -1,15 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Lists = void 0;
/**
* NIP-51 list types
*/
var Lists;
(function (Lists) {
Lists["Muted"] = "mute";
Lists["Pinned"] = "pin";
Lists["Bookmarked"] = "bookmark";
Lists["Followed"] = "follow";
Lists["Badges"] = "profile_badges";
})(Lists = exports.Lists || (exports.Lists = {}));
//# sourceMappingURL=Nostr.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"Nostr.js","sourceRoot":"","sources":["../src/Nostr.ts"],"names":[],"mappings":";;;AAqEA;;GAEG;AACH,IAAY,KAMX;AAND,WAAY,KAAK;IACf,uBAAc,CAAA;IACd,uBAAc,CAAA;IACd,gCAAuB,CAAA;IACvB,4BAAmB,CAAA;IACnB,kCAAyB,CAAA;AAC3B,CAAC,EANW,KAAK,GAAL,aAAK,KAAL,aAAK,QAMhB"}

View File

@ -1,13 +0,0 @@
import { NostrPrefix } from ".";
export interface NostrLink {
type: NostrPrefix;
id: string;
kind?: number;
author?: string;
relays?: Array<string>;
encode(): string;
}
export declare function validateNostrLink(link: string): boolean;
export declare function tryParseNostrLink(link: string, prefixHint?: NostrPrefix): NostrLink | undefined;
export declare function parseNostrLink(link: string, prefixHint?: NostrPrefix): NostrLink;
//# sourceMappingURL=NostrLink.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"NostrLink.d.ts","sourceRoot":"","sources":["../src/NostrLink.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAA2B,MAAM,GAAG,CAAC;AAEzD,MAAM,WAAW,SAAS;IACtB,IAAI,EAAE,WAAW,CAAC;IAClB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACvB,MAAM,IAAI,MAAM,CAAC;CAClB;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAcvD;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,WAAW,GAAG,SAAS,GAAG,SAAS,CAM/F;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,WAAW,GAAG,SAAS,CAwEhF"}

View File

@ -1,110 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseNostrLink = exports.tryParseNostrLink = exports.validateNostrLink = void 0;
const Util_1 = require("./Util");
const _1 = require(".");
function validateNostrLink(link) {
try {
const parsedLink = parseNostrLink(link);
if (!parsedLink) {
return false;
}
if (parsedLink.type === _1.NostrPrefix.PublicKey || parsedLink.type === _1.NostrPrefix.Note) {
return parsedLink.id.length === 64;
}
return true;
}
catch {
return false;
}
}
exports.validateNostrLink = validateNostrLink;
function tryParseNostrLink(link, prefixHint) {
try {
return parseNostrLink(link, prefixHint);
}
catch {
return undefined;
}
}
exports.tryParseNostrLink = tryParseNostrLink;
function parseNostrLink(link, prefixHint) {
const entity = link.startsWith("web+nostr:") || link.startsWith("nostr:") ? link.split(":")[1] : link;
const isPrefix = (prefix) => {
return entity.startsWith(prefix);
};
if (isPrefix(_1.NostrPrefix.PublicKey)) {
const id = (0, Util_1.bech32ToHex)(entity);
if (id.length !== 64)
throw new Error("Invalid nostr link, must contain 32 byte id");
return {
type: _1.NostrPrefix.PublicKey,
id: id,
encode: () => (0, Util_1.hexToBech32)(_1.NostrPrefix.PublicKey, id),
};
}
else if (isPrefix(_1.NostrPrefix.Note)) {
const id = (0, Util_1.bech32ToHex)(entity);
if (id.length !== 64)
throw new Error("Invalid nostr link, must contain 32 byte id");
return {
type: _1.NostrPrefix.Note,
id: id,
encode: () => (0, Util_1.hexToBech32)(_1.NostrPrefix.Note, id),
};
}
else if (isPrefix(_1.NostrPrefix.Profile) || isPrefix(_1.NostrPrefix.Event) || isPrefix(_1.NostrPrefix.Address)) {
const decoded = (0, _1.decodeTLV)(entity);
const id = decoded.find(a => a.type === _1.TLVEntryType.Special)?.value;
const relays = decoded.filter(a => a.type === _1.TLVEntryType.Relay).map(a => a.value);
const author = decoded.find(a => a.type === _1.TLVEntryType.Author)?.value;
const kind = decoded.find(a => a.type === _1.TLVEntryType.Kind)?.value;
const encode = () => {
return entity; // return original
};
if (isPrefix(_1.NostrPrefix.Profile)) {
if (id.length !== 64)
throw new Error("Invalid nostr link, must contain 32 byte id");
return {
type: _1.NostrPrefix.Profile,
id,
relays,
kind,
author,
encode,
};
}
else if (isPrefix(_1.NostrPrefix.Event)) {
if (id.length !== 64)
throw new Error("Invalid nostr link, must contain 32 byte id");
return {
type: _1.NostrPrefix.Event,
id,
relays,
kind,
author,
encode,
};
}
else if (isPrefix(_1.NostrPrefix.Address)) {
return {
type: _1.NostrPrefix.Address,
id,
relays,
kind,
author,
encode,
};
}
}
else if (prefixHint) {
return {
type: prefixHint,
id: link,
encode: () => (0, Util_1.hexToBech32)(prefixHint, link),
};
}
throw new Error("Invalid nostr link");
}
exports.parseNostrLink = parseNostrLink;
//# sourceMappingURL=NostrLink.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"NostrLink.js","sourceRoot":"","sources":["../src/NostrLink.ts"],"names":[],"mappings":";;;AAAA,iCAAkD;AAClD,wBAAyD;AAWvD,SAAgB,iBAAiB,CAAC,IAAY;IAC5C,IAAI;QACF,MAAM,UAAU,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC;QACxC,IAAI,CAAC,UAAU,EAAE;YACf,OAAO,KAAK,CAAC;SACd;QACD,IAAI,UAAU,CAAC,IAAI,KAAK,cAAW,CAAC,SAAS,IAAI,UAAU,CAAC,IAAI,KAAK,cAAW,CAAC,IAAI,EAAE;YACrF,OAAO,UAAU,CAAC,EAAE,CAAC,MAAM,KAAK,EAAE,CAAC;SACpC;QAED,OAAO,IAAI,CA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OAAO;gBACL,IAAI,EAAE,cAAW,CAAC,OAAO;gBACzB,EAAE;gBACF,MAAM;gBACN,IAAI;gBACJ,MAAM;gBACN,MAAM;aACP,CAAC;SACH;aAAM,IAAI,QAAQ,CAAC,cAAW,CAAC,KAAK,CAAC,EAAE;YACtC,IAAI,EAAE,CAAC,MAAM,KAAK,EAAE;gBAAE,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;YACrF,OAAO;gBACL,IAAI,EAAE,cAAW,CAAC,KAAK;gBACvB,EAAE;gBACF,MAAM;gBACN,IAAI;gBACJ,MAAM;gBACN,MAAM;aACP,CAAC;SACH;aAAM,IAAI,QAAQ,CAAC,cAAW,CAAC,OAAO,CAAC,EAAE;YACxC,OAAO;gBACL,IAAI,EAAE,cAAW,CAAC,OAAO;gBACzB,EAAE;gBACF,MAAM;gBACN,IAAI;gBACJ,MAAM;gBACN,MAAM;aACP,CAAC;SACH;KACF;SAAM,IAAI,UAAU,EAAE;QACrB,OAAO;YACL,IAAI,EAAE,UAAU;YAChB,EAAE,EAAE,IAAI;YACR,MAAM,EAAE,GAAG,EAAE,CAAC,IAAA,kBAAW,EAAC,UAAU,EAAE,IAAI,CAAC;SAC5C,CAAC;KACH;IACD,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;AACxC,CAAC;AAxED,wCAwEC"}

View File

@ -1,75 +0,0 @@
import ExternalStore from "./ExternalStore";
import { NostrEvent, TaggedRawEvent } from "./Nostr";
import { AuthHandler, Connection, RelaySettings, ConnectionStateSnapshot } from "./Connection";
import { Query } from "./Query";
import { RelayCache } from "./GossipModel";
import { NoteStore } from "./NoteCollection";
import { BuiltRawReqFilter, RequestBuilder } from "./RequestBuilder";
import { SystemInterface, SystemSnapshot } from ".";
/**
* Manages nostr content retrieval system
*/
export declare class NostrSystem extends ExternalStore<SystemSnapshot> implements SystemInterface {
#private;
/**
* All active queries
*/
Queries: Map<string, Query>;
/**
* Handler function for NIP-42
*/
HandleAuth?: AuthHandler;
constructor(relayCache: RelayCache);
get Sockets(): ConnectionStateSnapshot[];
/**
* Connect to a NOSTR relay if not already connected
*/
ConnectToRelay(address: string, options: RelaySettings): Promise<void>;
OnRelayDisconnect(id: string): void;
OnEndOfStoredEvents(c: Readonly<Connection>, sub: string): void;
OnEvent(sub: string, ev: TaggedRawEvent): void;
/**
*
* @param address Relay address URL
*/
ConnectEphemeralRelay(address: string): Promise<Connection | undefined>;
/**
* Disconnect from a relay
*/
DisconnectRelay(address: string): void;
GetQuery(id: string): Query | undefined;
Query<T extends NoteStore>(type: {
new (): T;
}, req: RequestBuilder): Query;
SendQuery(q: Query, qSend: BuiltRawReqFilter): Promise<{
readonly id: string;
readonly start: number;
sent?: number | undefined;
eose?: number | undefined;
close?: number | undefined;
"__#9@#wasForceClosed": boolean;
readonly "__#9@#fnClose": (id: string) => void;
readonly "__#9@#fnProgress": () => void;
readonly relay: string;
readonly filters: import("./Nostr").ReqFilter[];
readonly connId: string;
sentToRelay(): void;
gotEose(): void;
forceEose(): void;
sendClose(): void;
readonly queued: number;
readonly runtime: number;
readonly responseTime: number;
readonly finished: boolean;
}[]>;
/**
* Send events to writable relays
*/
BroadcastEvent(ev: NostrEvent): void;
/**
* Write an event to a relay then disconnect
*/
WriteOnceToRelay(address: string, ev: NostrEvent): Promise<void>;
takeSnapshot(): SystemSnapshot;
}
//# sourceMappingURL=NostrSystem.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"NostrSystem.d.ts","sourceRoot":"","sources":["../src/NostrSystem.ts"],"names":[],"mappings":"AAEA,OAAO,aAAa,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,aAAa,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAC/F,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,MA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AAE,MAAM,EAAE,EAAE,EAAE,UAAU;IAetD,YAAY,IAAI,cAAc;CA2B/B"}

View File

@ -1,237 +0,0 @@
"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _NostrSystem_instances, _NostrSystem_sockets, _NostrSystem_log, _NostrSystem_relayCache, _NostrSystem_cleanup;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NostrSystem = void 0;
const debug_1 = __importDefault(require("debug"));
const ExternalStore_1 = __importDefault(require("./ExternalStore"));
const Connection_1 = require("./Connection");
const Query_1 = require("./Query");
const Util_1 = require("./Util");
/**
* Manages nostr content retrieval system
*/
class NostrSystem extends ExternalStore_1.default {
constructor(relayCache) {
super();
_NostrSystem_instances.add(this);
/**
* All currently connected websockets
*/
_NostrSystem_sockets.set(this, new Map());
/**
* All active queries
*/
this.Queries = new Map();
_NostrSystem_log.set(this, (0, debug_1.default)("System"));
_NostrSystem_relayCache.set(this, void 0);
__classPrivateFieldSet(this, _NostrSystem_relayCache, relayCache, "f");
__classPrivateFieldGet(this, _NostrSystem_instances, "m", _NostrSystem_cleanup).call(this);
}
get Sockets() {
return [...__classPrivateFieldGet(this, _NostrSystem_sockets, "f").values()].map(a => a.snapshot());
}
/**
* Connect to a NOSTR relay if not already connected
*/
async ConnectToRelay(address, options) {
try {
const addr = (0, Util_1.unwrap)((0, Util_1.sanitizeRelayUrl)(address));
if (!__classPrivateFieldGet(this, _NostrSystem_sockets, "f").has(addr)) {
const c = new Connection_1.Connection(addr, options, this.HandleAuth?.bind(this));
__classPrivateFieldGet(this, _NostrSystem_sockets, "f").set(addr, c);
c.OnEvent = (s, e) => this.OnEvent(s, e);
c.OnEose = s => this.OnEndOfStoredEvents(c, s);
c.OnDisconnect = id => this.OnRelayDisconnect(id);
await c.Connect();
}
else {
// update settings if already connected
(0, Util_1.unwrap)(__classPrivateFieldGet(this, _NostrSystem_sockets, "f").get(addr)).Settings = options;
}
}
catch (e) {
console.error(e);
}
}
OnRelayDisconnect(id) {
for (const [, q] of this.Queries) {
q.connectionLost(id);
}
}
OnEndOfStoredEvents(c, sub) {
for (const [, v] of this.Queries) {
v.eose(sub, c);
}
}
OnEvent(sub, ev) {
for (const [, v] of this.Queries) {
v.onEvent(sub, ev);
}
}
/**
*
* @param address Relay address URL
*/
async ConnectEphemeralRelay(address) {
try {
const addr = (0, Util_1.unwrap)((0, Util_1.sanitizeRelayUrl)(address));
if (!__classPrivateFieldGet(this, _NostrSystem_sockets, "f").has(addr)) {
const c = new Connection_1.Connection(addr, { read: true, write: false }, this.HandleAuth?.bind(this), true);
__classPrivateFieldGet(this, _NostrSystem_sockets, "f").set(addr, c);
c.OnEvent = (s, e) => this.OnEvent(s, e);
c.OnEose = s => this.OnEndOfStoredEvents(c, s);
c.OnDisconnect = id => this.OnRelayDisconnect(id);
await c.Connect();
return c;
}
}
catch (e) {
console.error(e);
}
}
/**
* Disconnect from a relay
*/
DisconnectRelay(address) {
const c = __classPrivateFieldGet(this, _NostrSystem_sockets, "f").get(address);
if (c) {
__classPrivateFieldGet(this, _NostrSystem_sockets, "f").delete(address);
c.Close();
}
}
GetQuery(id) {
return this.Queries.get(id);
}
Query(type, req) {
const existing = this.Queries.get(req.id);
if (existing) {
const filters = !req.options?.skipDiff
? req.buildDiff(__classPrivateFieldGet(this, _NostrSystem_relayCache, "f"), existing.filters)
: req.build(__classPrivateFieldGet(this, _NostrSystem_relayCache, "f"));
if (filters.length === 0 && !!req.options?.skipDiff) {
return existing;
}
else {
for (const subQ of filters) {
this.SendQuery(existing, subQ).then(qta => qta.forEach(v => __classPrivateFieldGet(this, _NostrSystem_log, "f").call(this, "New QT from diff %s %s %O from: %O", req.id, v.id, v.filters, existing.filters)));
}
this.notifyChange();
return existing;
}
}
else {
const store = new type();
const filters = req.build(__classPrivateFieldGet(this, _NostrSystem_relayCache, "f"));
const q = new Query_1.Query(req.id, store, req.options?.leaveOpen);
this.Queries.set(req.id, q);
for (const subQ of filters) {
this.SendQuery(q, subQ).then(qta => qta.forEach(v => __classPrivateFieldGet(this, _NostrSystem_log, "f").call(this, "New QT from diff %s %s %O", req.id, v.id, v.filters)));
}
this.notifyChange();
return q;
}
}
async SendQuery(q, qSend) {
if (qSend.relay) {
__classPrivateFieldGet(this, _NostrSystem_log, "f").call(this, "Sending query to %s %O", qSend.relay, qSend);
const s = __classPrivateFieldGet(this, _NostrSystem_sockets, "f").get(qSend.relay);
if (s) {
const qt = q.sendToRelay(s, qSend);
if (qt) {
return [qt];
}
}
else {
const nc = await this.ConnectEphemeralRelay(qSend.relay);
if (nc) {
const qt = q.sendToRelay(nc, qSend);
if (qt) {
return [qt];
}
}
else {
console.warn("Failed to connect to new relay for:", qSend.relay, q);
}
}
}
else {
const ret = [];
for (const [, s] of __classPrivateFieldGet(this, _NostrSystem_sockets, "f")) {
if (!s.Ephemeral) {
const qt = q.sendToRelay(s, qSend);
if (qt) {
ret.push(qt);
}
}
}
return ret;
}
return [];
}
/**
* Send events to writable relays
*/
BroadcastEvent(ev) {
for (const [, s] of __classPrivateFieldGet(this, _NostrSystem_sockets, "f")) {
s.SendEvent(ev);
}
}
/**
* Write an event to a relay then disconnect
*/
async WriteOnceToRelay(address, ev) {
return new Promise((resolve, reject) => {
const c = new Connection_1.Connection(address, { write: true, read: false }, this.HandleAuth, true);
const t = setTimeout(reject, 5000);
c.OnConnected = async () => {
clearTimeout(t);
await c.SendAsync(ev);
c.Close();
resolve();
};
c.Connect();
});
}
takeSnapshot() {
return {
queries: [...this.Queries.values()].map(a => {
return {
id: a.id,
filters: a.filters,
subFilters: [],
};
}),
};
}
}
exports.NostrSystem = NostrSystem;
_NostrSystem_sockets = new WeakMap(), _NostrSystem_log = new WeakMap(), _NostrSystem_relayCache = new WeakMap(), _NostrSystem_instances = new WeakSet(), _NostrSystem_cleanup = function _NostrSystem_cleanup() {
let changed = false;
for (const [k, v] of this.Queries) {
if (v.canRemove()) {
v.sendClose();
this.Queries.delete(k);
__classPrivateFieldGet(this, _NostrSystem_log, "f").call(this, "Deleted query %s", k);
changed = true;
}
}
if (changed) {
this.notifyChange();
}
setTimeout(() => __classPrivateFieldGet(this, _NostrSystem_instances, "m", _NostrSystem_cleanup).call(this), 1000);
};
//# sourceMappingURL=NostrSystem.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,91 +0,0 @@
import { TaggedRawEvent } from ".";
export interface StoreSnapshot<TSnapshot> {
data: TSnapshot | undefined;
clear: () => void;
loading: () => boolean;
add: (ev: Readonly<TaggedRawEvent> | Readonly<Array<TaggedRawEvent>>) => void;
}
export declare const EmptySnapshot: StoreSnapshot<FlatNoteStore>;
export type NoteStoreSnapshotData = Readonly<Array<TaggedRawEvent>> | Readonly<TaggedRawEvent>;
export type NoteStoreHook = () => void;
export type NoteStoreHookRelease = () => void;
export type OnEventCallback = (e: Readonly<Array<TaggedRawEvent>>) => void;
export type OnEventCallbackRelease = () => void;
export type OnEoseCallback = (c: string) => void;
export type OnEoseCallbackRelease = () => void;
/**
* Generic note store interface
*/
export declare abstract class NoteStore {
abstract add(ev: Readonly<TaggedRawEvent> | Readonly<Array<TaggedRawEvent>>): void;
abstract clear(): void;
abstract hook(cb: NoteStoreHook): NoteStoreHookRelease;
abstract getSnapshotData(): NoteStoreSnapshotData | undefined;
abstract onEvent(cb: OnEventCallback): OnEventCallbackRelease;
abstract get snapshot(): StoreSnapshot<NoteStoreSnapshotData>;
abstract get loading(): boolean;
abstract set loading(v: boolean);
}
export declare abstract class HookedNoteStore<TSnapshot extends NoteStoreSnapshotData> implements NoteStore {
#private;
get snapshot(): StoreSnapshot<TSnapshot>;
get loading(): boolean;
set loading(v: boolean);
abstract add(ev: Readonly<TaggedRawEvent> | Readonly<Array<TaggedRawEvent>>): void;
abstract clear(): void;
hook(cb: NoteStoreHook): NoteStoreHookRelease;
getSnapshotData(): TSnapshot | undefined;
onEvent(cb: OnEventCallback): OnEventCallbackRelease;
protected abstract takeSnapshot(): TSnapshot | undefined;
protected onChange(changes: Readonly<Array<TaggedRawEvent>>): void;
}
/**
* A simple flat container of events with no duplicates
*/
export declare class FlatNoteStore extends HookedNoteStore<Readonly<Array<TaggedRawEvent>>> {
#private;
add(ev: TaggedRawEvent | Array<TaggedRawEvent>): void;
clear(): void;
takeSnapshot(): TaggedRawEvent[];
}
/**
* A note store that holds a single replaceable event for a given user defined key generator function
*/
export declare class KeyedReplaceableNoteStore extends HookedNoteStore<Readonly<Array<TaggedRawEvent>>> {
#private;
constructor(fn: (ev: TaggedRawEvent) => string);
add(ev: TaggedRawEvent | Array<TaggedRawEvent>): void;
clear(): void;
takeSnapshot(): TaggedRawEvent[];
}
/**
* A note store that holds a single replaceable event
*/
export declare class ReplaceableNoteStore extends HookedNoteStore<Readonly<TaggedRawEvent>> {
#private;
add(ev: TaggedRawEvent | Array<TaggedRawEvent>): void;
clear(): void;
takeSnapshot(): Readonly<{
relays: string[];
id: string;
pubkey: string;
created_at: number;
kind: number;
tags: string[][];
content: string;
sig: string;
}> | undefined;
}
/**
* A note store that holds a single replaceable event per pubkey
*/
export declare class PubkeyReplaceableNoteStore extends KeyedReplaceableNoteStore {
constructor();
}
/**
* A note store that holds a single replaceable event per "pubkey-dtag"
*/
export declare class ParameterizedReplaceableNoteStore extends KeyedReplaceableNoteStore {
constructor();
}
//# sourceMappingURL=NoteCollection.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"NoteCollection.d.ts","sourceRoot":"","sources":["../src/NoteCollection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAQ,MAAM,GAAG,CAAC;AAGzC,MAAM,WAAW,aAAa,CAAC,SAAS;IACtC,IAAI,EAAE,SAAS,GAAG,SAAS,CAAC;IAC5B,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB,OAAO,EAAE,MAAM,OAAO,CAAC;IACvB,GAAG,EAAE,CAAC,EAAE,EAAE,QAAQ,CAAC,cAAc,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC,KAAK,IAAI,CAAC;CAC/E;AAED,eAAO,MAAM,aAAa,8BASO,CAAC;AAElC,MAAM,MAAM,qBAAqB,GAAG,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC,GAAG,QAAQ,CAAC,cAAc,CAAC,CAAC;AAC/F,MAAM,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC;AACvC,MAAM,MAAM,oBAAoB,GAAG,MAAM,IAAI,CAAC;AAC9C,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,EAAE,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC,KAAK,IAAI,CAAC;AAC3E,MAAM,MAAM,sBAAsB,GAAG,MAAM,IAAI,CAAC;AAChD,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;AACjD,MAAM,MAAM,qBAAqB,GAAG,MAAM,IAAI,CAAC;AAE/C;;GAEG;AACH,8BAAsB,SAAS;IAC7B,QAAQ,CAAC,GAAG,CAAC,EAAE,EAAE,QAAQ,CAAC,cAAc,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC,GAAG,IAAI;IAClF,QAAQ,CAAC,KAAK,IAAI,I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AC,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC,CAAC;;gBAIjF,EAAE,EAAE,CAAC,EAAE,EAAE,cAAc,KAAK,MAAM;IAK9C,GAAG,CAAC,EAAE,EAAE,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IAgB9C,KAAK;IAKL,YAAY;CAGb;AAED;;GAEG;AACH,qBAAa,oBAAqB,SAAQ,eAAe,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;;IAGjF,GAAG,CAAC,EAAE,EAAE,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IAe9C,KAAK;IAKL,YAAY;;;;;;;;;;CAKb;AAED;;GAEG;AACH,qBAAa,0BAA2B,SAAQ,yBAAyB;;CAIxE;AAED;;GAEG;AACH,qBAAa,iCAAkC,SAAQ,yBAAyB;;CAO/E"}

View File

@ -1,240 +0,0 @@
"use strict";
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var _HookedNoteStore_instances, _HookedNoteStore_hooks, _HookedNoteStore_eventHooks, _HookedNoteStore_loading, _HookedNoteStore_storeSnapshot, _HookedNoteStore_needsSnapshot, _HookedNoteStore_nextNotifyTimer, _HookedNoteStore_updateSnapshot, _FlatNoteStore_events, _FlatNoteStore_ids, _KeyedReplaceableNoteStore_keyFn, _KeyedReplaceableNoteStore_events, _ReplaceableNoteStore_event;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ParameterizedReplaceableNoteStore = exports.PubkeyReplaceableNoteStore = exports.ReplaceableNoteStore = exports.KeyedReplaceableNoteStore = exports.FlatNoteStore = exports.HookedNoteStore = exports.NoteStore = exports.EmptySnapshot = void 0;
const Util_1 = require("./Util");
exports.EmptySnapshot = {
data: undefined,
clear: () => {
// empty
},
loading: () => true,
add: () => {
// empty
},
};
/**
* Generic note store interface
*/
class NoteStore {
}
exports.NoteStore = NoteStore;
class HookedNoteStore {
constructor() {
_HookedNoteStore_instances.add(this);
_HookedNoteStore_hooks.set(this, []);
_HookedNoteStore_eventHooks.set(this, []);
_HookedNoteStore_loading.set(this, true);
_HookedNoteStore_storeSnapshot.set(this, {
clear: () => this.clear(),
loading: () => this.loading,
add: ev => this.add(ev),
data: undefined,
});
_HookedNoteStore_needsSnapshot.set(this, true);
_HookedNoteStore_nextNotifyTimer.set(this, void 0);
}
get snapshot() {
__classPrivateFieldGet(this, _HookedNoteStore_instances, "m", _HookedNoteStore_updateSnapshot).call(this);
return __classPrivateFieldGet(this, _HookedNoteStore_storeSnapshot, "f");
}
get loading() {
return __classPrivateFieldGet(this, _HookedNoteStore_loading, "f");
}
set loading(v) {
__classPrivateFieldSet(this, _HookedNoteStore_loading, v, "f");
this.onChange([]);
}
hook(cb) {
__classPrivateFieldGet(this, _HookedNoteStore_hooks, "f").push(cb);
return () => {
const idx = __classPrivateFieldGet(this, _HookedNoteStore_hooks, "f").findIndex(a => a === cb);
__classPrivateFieldGet(this, _HookedNoteStore_hooks, "f").splice(idx, 1);
};
}
getSnapshotData() {
__classPrivateFieldGet(this, _HookedNoteStore_instances, "m", _HookedNoteStore_updateSnapshot).call(this);
return __classPrivateFieldGet(this, _HookedNoteStore_storeSnapshot, "f").data;
}
onEvent(cb) {
const existing = __classPrivateFieldGet(this, _HookedNoteStore_eventHooks, "f").find(a => a === cb);
if (!existing) {
__classPrivateFieldGet(this, _HookedNoteStore_eventHooks, "f").push(cb);
return () => {
const idx = __classPrivateFieldGet(this, _HookedNoteStore_eventHooks, "f").findIndex(a => a === cb);
__classPrivateFieldGet(this, _HookedNoteStore_eventHooks, "f").splice(idx, 1);
};
}
return () => {
//noop
};
}
onChange(changes) {
__classPrivateFieldSet(this, _HookedNoteStore_needsSnapshot, true, "f");
if (!__classPrivateFieldGet(this, _HookedNoteStore_nextNotifyTimer, "f")) {
__classPrivateFieldSet(this, _HookedNoteStore_nextNotifyTimer, setTimeout(() => {
__classPrivateFieldSet(this, _HookedNoteStore_nextNotifyTimer, undefined, "f");
for (const hk of __classPrivateFieldGet(this, _HookedNoteStore_hooks, "f")) {
hk();
}
}, 500), "f");
}
if (changes.length > 0) {
for (const hkE of __classPrivateFieldGet(this, _HookedNoteStore_eventHooks, "f")) {
hkE(changes);
}
}
}
}
exports.HookedNoteStore = HookedNoteStore;
_HookedNoteStore_hooks = new WeakMap(), _HookedNoteStore_eventHooks = new WeakMap(), _HookedNoteStore_loading = new WeakMap(), _HookedNoteStore_storeSnapshot = new WeakMap(), _HookedNoteStore_needsSnapshot = new WeakMap(), _HookedNoteStore_nextNotifyTimer = new WeakMap(), _HookedNoteStore_instances = new WeakSet(), _HookedNoteStore_updateSnapshot = function _HookedNoteStore_updateSnapshot() {
if (__classPrivateFieldGet(this, _HookedNoteStore_needsSnapshot, "f")) {
__classPrivateFieldSet(this, _HookedNoteStore_storeSnapshot, {
...__classPrivateFieldGet(this, _HookedNoteStore_storeSnapshot, "f"),
data: this.takeSnapshot(),
}, "f");
__classPrivateFieldSet(this, _HookedNoteStore_needsSnapshot, false, "f");
}
};
/**
* A simple flat container of events with no duplicates
*/
class FlatNoteStore extends HookedNoteStore {
constructor() {
super(...arguments);
_FlatNoteStore_events.set(this, []);
_FlatNoteStore_ids.set(this, new Set());
}
add(ev) {
ev = Array.isArray(ev) ? ev : [ev];
const changes = [];
ev.forEach(a => {
if (!__classPrivateFieldGet(this, _FlatNoteStore_ids, "f").has(a.id)) {
__classPrivateFieldGet(this, _FlatNoteStore_events, "f").push(a);
__classPrivateFieldGet(this, _FlatNoteStore_ids, "f").add(a.id);
changes.push(a);
}
else {
const existing = __classPrivateFieldGet(this, _FlatNoteStore_events, "f").find(b => b.id === a.id);
if (existing) {
existing.relays = (0, Util_1.appendDedupe)(existing.relays, a.relays);
}
}
});
if (changes.length > 0) {
this.onChange(changes);
}
}
clear() {
__classPrivateFieldSet(this, _FlatNoteStore_events, [], "f");
__classPrivateFieldGet(this, _FlatNoteStore_ids, "f").clear();
this.onChange([]);
}
takeSnapshot() {
return [...__classPrivateFieldGet(this, _FlatNoteStore_events, "f")];
}
}
exports.FlatNoteStore = FlatNoteStore;
_FlatNoteStore_events = new WeakMap(), _FlatNoteStore_ids = new WeakMap();
/**
* A note store that holds a single replaceable event for a given user defined key generator function
*/
class KeyedReplaceableNoteStore extends HookedNoteStore {
constructor(fn) {
super();
_KeyedReplaceableNoteStore_keyFn.set(this, void 0);
_KeyedReplaceableNoteStore_events.set(this, new Map());
__classPrivateFieldSet(this, _KeyedReplaceableNoteStore_keyFn, fn, "f");
}
add(ev) {
ev = Array.isArray(ev) ? ev : [ev];
const changes = [];
ev.forEach(a => {
const keyOnEvent = __classPrivateFieldGet(this, _KeyedReplaceableNoteStore_keyFn, "f").call(this, a);
const existingCreated = __classPrivateFieldGet(this, _KeyedReplaceableNoteStore_events, "f").get(keyOnEvent)?.created_at ?? 0;
if (a.created_at > existingCreated) {
__classPrivateFieldGet(this, _KeyedReplaceableNoteStore_events, "f").set(keyOnEvent, a);
changes.push(a);
}
});
if (changes.length > 0) {
this.onChange(changes);
}
}
clear() {
__classPrivateFieldGet(this, _KeyedReplaceableNoteStore_events, "f").clear();
this.onChange([]);
}
takeSnapshot() {
return [...__classPrivateFieldGet(this, _KeyedReplaceableNoteStore_events, "f").values()];
}
}
exports.KeyedReplaceableNoteStore = KeyedReplaceableNoteStore;
_KeyedReplaceableNoteStore_keyFn = new WeakMap(), _KeyedReplaceableNoteStore_events = new WeakMap();
/**
* A note store that holds a single replaceable event
*/
class ReplaceableNoteStore extends HookedNoteStore {
constructor() {
super(...arguments);
_ReplaceableNoteStore_event.set(this, void 0);
}
add(ev) {
ev = Array.isArray(ev) ? ev : [ev];
const changes = [];
ev.forEach(a => {
const existingCreated = __classPrivateFieldGet(this, _ReplaceableNoteStore_event, "f")?.created_at ?? 0;
if (a.created_at > existingCreated) {
__classPrivateFieldSet(this, _ReplaceableNoteStore_event, a, "f");
changes.push(a);
}
});
if (changes.length > 0) {
this.onChange(changes);
}
}
clear() {
__classPrivateFieldSet(this, _ReplaceableNoteStore_event, undefined, "f");
this.onChange([]);
}
takeSnapshot() {
if (__classPrivateFieldGet(this, _ReplaceableNoteStore_event, "f")) {
return Object.freeze({ ...__classPrivateFieldGet(this, _ReplaceableNoteStore_event, "f") });
}
}
}
exports.ReplaceableNoteStore = ReplaceableNoteStore;
_ReplaceableNoteStore_event = new WeakMap();
/**
* A note store that holds a single replaceable event per pubkey
*/
class PubkeyReplaceableNoteStore extends KeyedReplaceableNoteStore {
constructor() {
super(e => e.pubkey);
}
}
exports.PubkeyReplaceableNoteStore = PubkeyReplaceableNoteStore;
/**
* A note store that holds a single replaceable event per "pubkey-dtag"
*/
class ParameterizedReplaceableNoteStore extends KeyedReplaceableNoteStore {
constructor() {
super(ev => {
const dTag = (0, Util_1.findTag)(ev, "d");
return `${ev.pubkey}-${dTag}`;
});
}
}
exports.ParameterizedReplaceableNoteStore = ParameterizedReplaceableNoteStore;
//# sourceMappingURL=NoteCollection.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,20 +0,0 @@
import { HexKey, SystemInterface, TaggedRawEvent } from ".";
import { CacheStore, MetadataCache } from "./cache";
export declare class ProfileLoaderService {
#private;
/**
* List of pubkeys to fetch metadata for
*/
WantsMetadata: Set<HexKey>;
constructor(system: SystemInterface, cache: CacheStore<MetadataCache>);
/**
* Request profile metadata for a set of pubkeys
*/
TrackMetadata(pk: HexKey | Array<HexKey>): void;
/**
* Stop tracking metadata for a set of pubkeys
*/
UntrackMetadata(pk: HexKey | Array<HexKey>): void;
onProfileEvent(e: Readonly<TaggedRawEvent>): Promise<void>;
}
//# sourceMappingURL=ProfileCache.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"ProfileCache.d.ts","sourceRoot":"","sources":["../src/ProfileCache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,MAAM,EAAE,eAAe,EAAE,cAAc,EAA8C,MAAM,GAAG,CAAC;AAEnH,OAAO,EAAE,UAAU,EAAqB,aAAa,EAAE,MAAM,SAAS,CAAC;AAIvE,qBAAa,oBAAoB;;IAI/B;;OAEG;IACH,aAAa,EAAE,GAAG,CAAC,MAAM,CAAC,CAAa;gBAI3B,MAAM,EAAE,eAAe,EAAE,KAAK,EAAE,UAAU,CAAC,aAAa,CAAC;IAMrE;;OAEG;IACH,aAAa,CAAC,EAAE,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;IAUxC;;OAEG;IACH,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;IAQpC,cAAc,CAAC,CAAC,EAAE,QAAQ,CAAC,cAAc,CAAC;CA4EjD"}

View File

@ -1,129 +0,0 @@
"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _ProfileLoaderService_instances, _ProfileLoaderService_system, _ProfileLoaderService_cache, _ProfileLoaderService_log, _ProfileLoaderService_FetchMetadata;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProfileLoaderService = void 0;
const _1 = require(".");
const Const_1 = require("./Const");
const cache_1 = require("./cache");
const Util_1 = require("./Util");
const debug_1 = __importDefault(require("debug"));
class ProfileLoaderService {
constructor(system, cache) {
_ProfileLoaderService_instances.add(this);
_ProfileLoaderService_system.set(this, void 0);
_ProfileLoaderService_cache.set(this, void 0);
/**
* List of pubkeys to fetch metadata for
*/
this.WantsMetadata = new Set();
_ProfileLoaderService_log.set(this, (0, debug_1.default)("ProfileCache"));
__classPrivateFieldSet(this, _ProfileLoaderService_system, system, "f");
__classPrivateFieldSet(this, _ProfileLoaderService_cache, cache, "f");
__classPrivateFieldGet(this, _ProfileLoaderService_instances, "m", _ProfileLoaderService_FetchMetadata).call(this);
}
/**
* Request profile metadata for a set of pubkeys
*/
TrackMetadata(pk) {
const bufferNow = [];
for (const p of Array.isArray(pk) ? pk : [pk]) {
if (p.length > 0 && this.WantsMetadata.add(p)) {
bufferNow.push(p);
}
}
__classPrivateFieldGet(this, _ProfileLoaderService_cache, "f").buffer(bufferNow);
}
/**
* Stop tracking metadata for a set of pubkeys
*/
UntrackMetadata(pk) {
for (const p of Array.isArray(pk) ? pk : [pk]) {
if (p.length > 0) {
this.WantsMetadata.delete(p);
}
}
}
async onProfileEvent(e) {
const profile = (0, cache_1.mapEventToProfile)(e);
if (profile) {
await __classPrivateFieldGet(this, _ProfileLoaderService_cache, "f").update(profile);
}
}
}
exports.ProfileLoaderService = ProfileLoaderService;
_ProfileLoaderService_system = new WeakMap(), _ProfileLoaderService_cache = new WeakMap(), _ProfileLoaderService_log = new WeakMap(), _ProfileLoaderService_instances = new WeakSet(), _ProfileLoaderService_FetchMetadata = async function _ProfileLoaderService_FetchMetadata() {
const missingFromCache = await __classPrivateFieldGet(this, _ProfileLoaderService_cache, "f").buffer([...this.WantsMetadata]);
const expire = (0, Util_1.unixNowMs)() - Const_1.ProfileCacheExpire;
const expired = [...this.WantsMetadata]
.filter(a => !missingFromCache.includes(a))
.filter(a => (__classPrivateFieldGet(this, _ProfileLoaderService_cache, "f").getFromCache(a)?.loaded ?? 0) < expire);
const missing = new Set([...missingFromCache, ...expired]);
if (missing.size > 0) {
__classPrivateFieldGet(this, _ProfileLoaderService_log, "f").call(this, "Wants profiles: %d missing, %d expired", missingFromCache.length, expired.length);
const sub = new _1.RequestBuilder("profiles");
sub
.withOptions({
skipDiff: true,
})
.withFilter()
.kinds([_1.EventKind.SetMetadata])
.authors([...missing]);
const newProfiles = new Set();
const q = __classPrivateFieldGet(this, _ProfileLoaderService_system, "f").Query(_1.PubkeyReplaceableNoteStore, sub);
const feed = q?.feed ?? new _1.PubkeyReplaceableNoteStore();
// never release this callback, it will stop firing anyway after eose
const releaseOnEvent = feed.onEvent(async (e) => {
for (const pe of e) {
newProfiles.add(pe.id);
await this.onProfileEvent(pe);
}
});
const results = await new Promise(resolve => {
let timeout = undefined;
const release = feed.hook(() => {
if (!feed.loading) {
clearTimeout(timeout);
resolve(feed.getSnapshotData() ?? []);
__classPrivateFieldGet(this, _ProfileLoaderService_log, "f").call(this, "Profiles finished: %s", sub.id);
release();
}
});
timeout = setTimeout(() => {
release();
resolve(feed.getSnapshotData() ?? []);
__classPrivateFieldGet(this, _ProfileLoaderService_log, "f").call(this, "Profiles timeout: %s", sub.id);
}, 5000);
});
releaseOnEvent();
const couldNotFetch = [...missing].filter(a => !results.some(b => b.pubkey === a));
if (couldNotFetch.length > 0) {
__classPrivateFieldGet(this, _ProfileLoaderService_log, "f").call(this, "No profiles: %o", couldNotFetch);
const empty = couldNotFetch.map(a => __classPrivateFieldGet(this, _ProfileLoaderService_cache, "f").update({
pubkey: a,
loaded: (0, Util_1.unixNowMs)() - Const_1.ProfileCacheExpire + 5000,
created: 69,
}));
await Promise.all(empty);
}
// When we fetch an expired profile and its the same as what we already have
// onEvent is not fired and the loaded timestamp never gets updated
const expiredSame = results.filter(a => !newProfiles.has(a.id) && expired.includes(a.pubkey));
await Promise.all(expiredSame.map(v => this.onProfileEvent(v)));
}
setTimeout(() => __classPrivateFieldGet(this, _ProfileLoaderService_instances, "m", _ProfileLoaderService_FetchMetadata).call(this), 500);
};
//# sourceMappingURL=ProfileCache.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"ProfileCache.js","sourceRoot":"","sources":["../src/ProfileCache.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,wBAAmH;AACnH,mCAA6C;AAC7C,mCAAuE;AACvE,iCAAmC;AACnC,kDAA0B;AAE1B,MAAa,oBAAoB;IAW/B,YAAY,MAAuB,EAAE,KAAgC;;QAVrE,+CAAyB;QACzB,8CAAkC;QAElC;;WAEG;QACH,kBAAa,GAAgB,IAAI,GAAG,EAAE,CAAC;QAE9B,oCAAO,IAAA,eAAK,EAAC,cAAc,CAAC,EAAC;QAGpC,uBAAA,IAAI,gCAAW,MAAM,MAAA,CAAC;QACtB,uBAAA,IAAI,+BAAU,KAAK,MAAA,CAAC;QACpB,uBAAA,IAAI,4EAAe,MAAnB,IAAI,CAAiB,CAAC;IACxB,CAAC;IAED;;OAEG;IACH,aAAa,CAAC,EAA0B;QACtC,MAAM,SAAS,GAAG,EAAE,CAAC;QACrB,KAAK,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE;YAC7C,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE;gBAC7C,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAA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,IAAI,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;QAC9F,MAAM,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;KACjE;IAED,UAAU,CAAC,GAAG,EAAE,CAAC,uBAAA,IAAI,4EAAe,MAAnB,IAAI,CAAiB,EAAE,GAAG,CAAC,CAAC;AAC/C,CAAC"}

View File

@ -1,86 +0,0 @@
import { Connection, ReqFilter, TaggedRawEvent } from ".";
import { NoteStore } from "./NoteCollection";
import { BuiltRawReqFilter } from "./RequestBuilder";
/**
* Tracing for relay query status
*/
declare class QueryTrace {
#private;
readonly relay: string;
readonly filters: Array<ReqFilter>;
readonly connId: string;
readonly id: string;
readonly start: number;
sent?: number;
eose?: number;
close?: number;
constructor(relay: string, filters: Array<ReqFilter>, connId: string, fnClose: (id: string) => void, fnProgress: () => void);
sentToRelay(): void;
gotEose(): void;
forceEose(): void;
sendClose(): void;
/**
* Time spent in queue
*/
get queued(): number;
/**
* Total query runtime
*/
get runtime(): number;
/**
* Total time spent waiting for relay to respond
*/
get responseTime(): number;
/**
* If tracing is finished, we got EOSE or timeout
*/
get finished(): boolean;
}
export interface QueryBase {
/**
* Uniquie ID of this query
*/
id: string;
/**
* The query payload (REQ filters)
*/
filters: Array<ReqFilter>;
/**
* List of relays to send this query to
*/
relays?: Array<string>;
}
/**
* Active or queued query on the system
*/
export declare class Query implements QueryBase {
#private;
/**
* Uniquie ID of this query
*/
id: string;
constructor(id: string, feed: NoteStore, leaveOpen?: boolean);
canRemove(): boolean;
/**
* Recompute the complete set of compressed filters from all query traces
*/
get filters(): ReqFilter[];
get feed(): NoteStore;
onEvent(sub: string, e: TaggedRawEvent): void;
/**
* This function should be called when this Query object and FeedStore is no longer needed
*/
cancel(): void;
uncancel(): void;
cleanup(): void;
sendToRelay(c: Connection, subq: BuiltRawReqFilter): QueryTrace | undefined;
connectionLost(id: string): void;
sendClose(): void;
eose(sub: string, conn: Readonly<Connection>): void;
/**
* Get the progress to EOSE, can be used to determine when we should load more content
*/
get progress(): number;
}
export {};
//# sourceMappingURL=Query.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"Query.d.ts","sourceRoot":"","sources":["../src/Query.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAQ,cAAc,EAAE,MAAM,GAAG,CAAC;AAEhE,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAGrD;;GAEG;AACH,cAAM,UAAU;;IAWZ,QAAQ,CAAC,KAAK,EAAE,MAAM;IACtB,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC;IAClC,QAAQ,CAAC,MAAM,EAAE,MAAM;IAZzB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;gBAMJ,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,EACzB,MAAM,EAAE,MAAM,EACvB,OAAO,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,EAC7B,UAAU,EAAE,MAAM,IAAI;IAQxB,WAAW;IAKX,OAAO;IAKP,SAAS;IAOT,SAAS;IAMT;;OAEG;IACH,IAAI,MAAM,WAET;IAED;;OAEG;IACH,IAAI,OAAO,WAEV;IAED;;OAEG;IACH,IAAI,YAAY,WAEf;IAED;;OAEG;IACH,IAAI,QAAQ,YAEX;CACF;AAED,MAAM,WAAW,SAAS;IACxB;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;OAEG;IACH,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IAE1B;;OAEG;IACH,MAAM,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;CACxB;AAED;;GAEG;AACH,qBAAa,KAAM,YAAW,SAAS;;IACrC;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;gBA8BC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,CAAC,EAAE,OAAO;IAO5D,SAAS;IAIT;;OAEG;IACH,IAAI,OAAO,gBAEV;IAED,IAAI,IAAI,cAEP;IAED,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,CAAC,EAAE,cAAc;IAStC;;OAEG;IACH,MAAM;IAIN,QAAQ;IAIR,OAAO;IAIP,WAAW,CAAC,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,iBAAiB;IAOlD,cAAc,CAAC,EAAE,EAAE,MAAM;IAIzB,SAAS;IAOT,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,UAAU,CAAC;IAQ5C;;OAEG;IACH,IAAI,QAAQ,WAMX;CA6DF"}

View File

@ -1,228 +0,0 @@
"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _QueryTrace_wasForceClosed, _QueryTrace_fnClose, _QueryTrace_fnProgress, _Query_instances, _Query_tracing, _Query_leaveOpen, _Query_cancelAt, _Query_checkTrace, _Query_feed, _Query_log, _Query_allFilters, _Query_onProgress, _Query_stopCheckTraces, _Query_checkTraces, _Query_canSendQuery, _Query_sendQueryInternal, _Query_reComputeFilters;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Query = void 0;
const uuid_1 = require("uuid");
const debug_1 = __importDefault(require("debug"));
const _1 = require(".");
const Util_1 = require("./Util");
const RequestMerger_1 = require("./RequestMerger");
const RequestExpander_1 = require("./RequestExpander");
/**
* Tracing for relay query status
*/
class QueryTrace {
constructor(relay, filters, connId, fnClose, fnProgress) {
this.relay = relay;
this.filters = filters;
this.connId = connId;
_QueryTrace_wasForceClosed.set(this, false);
_QueryTrace_fnClose.set(this, void 0);
_QueryTrace_fnProgress.set(this, void 0);
this.id = (0, uuid_1.v4)();
this.start = (0, Util_1.unixNowMs)();
__classPrivateFieldSet(this, _QueryTrace_fnClose, fnClose, "f");
__classPrivateFieldSet(this, _QueryTrace_fnProgress, fnProgress, "f");
}
sentToRelay() {
this.sent = (0, Util_1.unixNowMs)();
__classPrivateFieldGet(this, _QueryTrace_fnProgress, "f").call(this);
}
gotEose() {
this.eose = (0, Util_1.unixNowMs)();
__classPrivateFieldGet(this, _QueryTrace_fnProgress, "f").call(this);
}
forceEose() {
this.eose = (0, Util_1.unixNowMs)();
__classPrivateFieldSet(this, _QueryTrace_wasForceClosed, true, "f");
__classPrivateFieldGet(this, _QueryTrace_fnProgress, "f").call(this);
this.sendClose();
}
sendClose() {
this.close = (0, Util_1.unixNowMs)();
__classPrivateFieldGet(this, _QueryTrace_fnClose, "f").call(this, this.id);
__classPrivateFieldGet(this, _QueryTrace_fnProgress, "f").call(this);
}
/**
* Time spent in queue
*/
get queued() {
return (this.sent === undefined ? (0, Util_1.unixNowMs)() : __classPrivateFieldGet(this, _QueryTrace_wasForceClosed, "f") ? (0, Util_1.unwrap)(this.eose) : this.sent) - this.start;
}
/**
* Total query runtime
*/
get runtime() {
return (this.eose === undefined ? (0, Util_1.unixNowMs)() : this.eose) - this.start;
}
/**
* Total time spent waiting for relay to respond
*/
get responseTime() {
return this.finished ? (0, Util_1.unwrap)(this.eose) - (0, Util_1.unwrap)(this.sent) : 0;
}
/**
* If tracing is finished, we got EOSE or timeout
*/
get finished() {
return this.eose !== undefined;
}
}
_QueryTrace_wasForceClosed = new WeakMap(), _QueryTrace_fnClose = new WeakMap(), _QueryTrace_fnProgress = new WeakMap();
/**
* Active or queued query on the system
*/
class Query {
constructor(id, feed, leaveOpen) {
_Query_instances.add(this);
/**
* Which relays this query has already been executed on
*/
_Query_tracing.set(this, []);
/**
* Leave the query open until its removed
*/
_Query_leaveOpen.set(this, false);
/**
* Time when this query can be removed
*/
_Query_cancelAt.set(this, void 0);
/**
* Timer used to track tracing status
*/
_Query_checkTrace.set(this, void 0);
/**
* Feed object which collects events
*/
_Query_feed.set(this, void 0);
_Query_log.set(this, (0, debug_1.default)("Query"));
_Query_allFilters.set(this, []);
this.id = id;
__classPrivateFieldSet(this, _Query_feed, feed, "f");
__classPrivateFieldSet(this, _Query_leaveOpen, leaveOpen ?? false, "f");
__classPrivateFieldGet(this, _Query_instances, "m", _Query_checkTraces).call(this);
}
canRemove() {
return __classPrivateFieldGet(this, _Query_cancelAt, "f") !== undefined && __classPrivateFieldGet(this, _Query_cancelAt, "f") < (0, Util_1.unixNowMs)();
}
/**
* Recompute the complete set of compressed filters from all query traces
*/
get filters() {
return __classPrivateFieldGet(this, _Query_allFilters, "f");
}
get feed() {
return __classPrivateFieldGet(this, _Query_feed, "f");
}
onEvent(sub, e) {
for (const t of __classPrivateFieldGet(this, _Query_tracing, "f")) {
if (t.id === sub) {
this.feed.add(e);
break;
}
}
}
/**
* This function should be called when this Query object and FeedStore is no longer needed
*/
cancel() {
__classPrivateFieldSet(this, _Query_cancelAt, (0, Util_1.unixNowMs)() + 5000, "f");
}
uncancel() {
__classPrivateFieldSet(this, _Query_cancelAt, undefined, "f");
}
cleanup() {
__classPrivateFieldGet(this, _Query_instances, "m", _Query_stopCheckTraces).call(this);
}
sendToRelay(c, subq) {
if (!__classPrivateFieldGet(this, _Query_instances, "m", _Query_canSendQuery).call(this, c, subq)) {
return;
}
return __classPrivateFieldGet(this, _Query_instances, "m", _Query_sendQueryInternal).call(this, c, subq);
}
connectionLost(id) {
__classPrivateFieldGet(this, _Query_tracing, "f").filter(a => a.connId == id).forEach(a => a.forceEose());
}
sendClose() {
for (const qt of __classPrivateFieldGet(this, _Query_tracing, "f")) {
qt.sendClose();
}
this.cleanup();
}
eose(sub, conn) {
const qt = __classPrivateFieldGet(this, _Query_tracing, "f").find(a => a.id === sub && a.connId === conn.Id);
qt?.gotEose();
if (!__classPrivateFieldGet(this, _Query_leaveOpen, "f")) {
qt?.sendClose();
}
}
/**
* Get the progress to EOSE, can be used to determine when we should load more content
*/
get progress() {
const thisProgress = __classPrivateFieldGet(this, _Query_tracing, "f").reduce((acc, v) => (acc += v.finished ? 1 : 0), 0) / __classPrivateFieldGet(this, _Query_tracing, "f").length;
if (isNaN(thisProgress)) {
return 0;
}
return thisProgress;
}
}
exports.Query = Query;
_Query_tracing = new WeakMap(), _Query_leaveOpen = new WeakMap(), _Query_cancelAt = new WeakMap(), _Query_checkTrace = new WeakMap(), _Query_feed = new WeakMap(), _Query_log = new WeakMap(), _Query_allFilters = new WeakMap(), _Query_instances = new WeakSet(), _Query_onProgress = function _Query_onProgress() {
const isFinished = this.progress === 1;
if (this.feed.loading !== isFinished) {
__classPrivateFieldGet(this, _Query_log, "f").call(this, "%s loading=%s, progress=%d", this.id, this.feed.loading, this.progress);
this.feed.loading = isFinished;
}
}, _Query_stopCheckTraces = function _Query_stopCheckTraces() {
if (__classPrivateFieldGet(this, _Query_checkTrace, "f")) {
clearInterval(__classPrivateFieldGet(this, _Query_checkTrace, "f"));
}
}, _Query_checkTraces = function _Query_checkTraces() {
__classPrivateFieldGet(this, _Query_instances, "m", _Query_stopCheckTraces).call(this);
__classPrivateFieldSet(this, _Query_checkTrace, setInterval(() => {
for (const v of __classPrivateFieldGet(this, _Query_tracing, "f")) {
if (v.runtime > 5000 && !v.finished) {
v.forceEose();
}
}
}, 500), "f");
}, _Query_canSendQuery = function _Query_canSendQuery(c, q) {
if (q.relay && q.relay !== c.Address) {
return false;
}
if (!q.relay && c.Ephemeral) {
__classPrivateFieldGet(this, _Query_log, "f").call(this, "Cant send non-specific REQ to ephemeral connection %O %O %O", q, q.relay, c);
return false;
}
if (q.filters.some(a => a.search) && !c.SupportsNip(_1.Nips.Search)) {
__classPrivateFieldGet(this, _Query_log, "f").call(this, "Cant send REQ to non-search relay", c.Address);
return false;
}
return true;
}, _Query_sendQueryInternal = function _Query_sendQueryInternal(c, q) {
const qt = new QueryTrace(c.Address, q.filters, c.Id, x => c.CloseReq(x), () => __classPrivateFieldGet(this, _Query_instances, "m", _Query_onProgress).call(this));
__classPrivateFieldGet(this, _Query_tracing, "f").push(qt);
__classPrivateFieldGet(this, _Query_instances, "m", _Query_reComputeFilters).call(this);
c.QueueReq(["REQ", qt.id, ...q.filters], () => qt.sentToRelay());
return qt;
}, _Query_reComputeFilters = function _Query_reComputeFilters() {
console.time("reComputeFilters");
__classPrivateFieldSet(this, _Query_allFilters, (0, RequestMerger_1.flatMerge)(__classPrivateFieldGet(this, _Query_tracing, "f").flatMap(a => a.filters).flatMap(RequestExpander_1.expandFilter)), "f");
console.timeEnd("reComputeFilters");
};
//# sourceMappingURL=Query.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,17 +0,0 @@
export interface RelayInfo {
name?: string;
description?: string;
pubkey?: string;
contact?: string;
supported_nips?: number[];
software?: string;
version?: string;
limitation?: {
payment_required: boolean;
max_subscriptions: number;
max_filters: number;
max_event_tags: number;
auth_required: boolean;
};
}
//# sourceMappingURL=RelayInfo.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"RelayInfo.d.ts","sourceRoot":"","sources":["../src/RelayInfo.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,SAAS;IACxB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE;QACX,gBAAgB,EAAE,OAAO,CAAC;QAC1B,iBAAiB,EAAE,MAAM,CAAC;QAC1B,WAAW,EAAE,MAAM,CAAC;QACpB,cAAc,EAAE,MAAM,CAAC;QACvB,aAAa,EAAE,OAAO,CAAC;KACxB,CAAC;CACH"}

View File

@ -1,3 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=RelayInfo.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"RelayInfo.js","sourceRoot":"","sources":["../src/RelayInfo.ts"],"names":[],"mappings":""}

View File

@ -1,93 +0,0 @@
import { ReqFilter, u256, HexKey, EventKind } from ".";
import { RelayCache } from "./GossipModel";
/**
* Which strategy is used when building REQ filters
*/
export declare enum RequestStrategy {
/**
* Use the users default relays to fetch events,
* this is the fallback option when there is no better way to query a given filter set
*/
DefaultRelays = 1,
/**
* Using a cached copy of the authors relay lists NIP-65, split a given set of request filters by pubkey
*/
AuthorsRelays = 2,
/**
* Relay hints are usually provided when using replies
*/
RelayHintedEventIds = 3
}
/**
* A built REQ filter ready for sending to System
*/
export interface BuiltRawReqFilter {
filters: Array<ReqFilter>;
relay: string;
strategy: RequestStrategy;
}
export interface RequestBuilderOptions {
leaveOpen?: boolean;
relays?: Array<string>;
/**
* Do not apply diff logic and always use full filters for query
*/
skipDiff?: boolean;
}
/**
* Nostr REQ builder
*/
export declare class RequestBuilder {
#private;
id: string;
constructor(id: string);
get numFilters(): number;
get options(): RequestBuilderOptions | undefined;
withFilter(): RequestFilterBuilder;
withOptions(opt: RequestBuilderOptions): this;
buildRaw(): Array<ReqFilter>;
build(relays: RelayCache): Array<BuiltRawReqFilter>;
/**
* Detects a change in request from a previous set of filters
* @param q All previous filters merged
* @returns
*/
buildDiff(relays: RelayCache, filters: Array<ReqFilter>): Array<BuiltRawReqFilter>;
}
/**
* Builder class for a single request filter
*/
export declare class RequestFilterBuilder {
#private;
get filter(): {
ids?: string[] | undefined; /**
* Relay hints are usually provided when using replies
*/
authors?: string[] | undefined;
kinds?: number[] | undefined;
"#e"?: string[] | undefined;
"#p"?: string[] | undefined;
"#t"?: string[] | undefined;
"#d"?: string[] | undefined;
"#r"?: string[] | undefined;
search?: string | undefined;
since?: number | undefined;
until?: number | undefined;
limit?: number | undefined;
};
get relayHints(): Map<string, string[]>;
ids(ids: Array<u256>): this;
id(id: u256, relay?: string): this;
authors(authors?: Array<HexKey>): this;
kinds(kinds?: Array<EventKind>): this;
since(since?: number): this;
until(until?: number): this;
limit(limit?: number): this;
tag(key: "e" | "p" | "d" | "t" | "r", value?: Array<string>): this;
search(keyword?: string): this;
/**
* Build/expand this filter into a set of relay specific queries
*/
build(relays: RelayCache, id: string): Array<BuiltRawReqFilter>;
}
//# sourceMappingURL=RequestBuilder.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"RequestBuilder.d.ts","sourceRoot":"","sources":["../src/RequestBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,CAAC;AAGvD,OAAO,EAAE,UAAU,EAA6C,MAAM,eAAe,CAAC;AAGtF;;GAEG;AACH,oBAAY,eAAe;IACzB;;;OAGG;IACH,aAAa,IAAI;IAEjB;;OAEG;IACH,aAAa,IAAI;IAEjB;;OAEG;IACH,mBAAmB,IAAI;CAC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AAC,EAAE,MAAM;IAMpB,GAAG,CAAC,GAAG,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,EAAE,KAAK,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC;IAM3D,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM;IAMvB;;OAEG;IACH,KAAK,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE,EAAE,MAAM,GAAG,KAAK,CAAC,iBAAiB,CAAC;CAuChE"}

View File

@ -1,225 +0,0 @@
"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _RequestBuilder_instances, _RequestBuilder_builders, _RequestBuilder_options, _RequestBuilder_groupByRelay, _RequestFilterBuilder_filter, _RequestFilterBuilder_relayHints;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequestFilterBuilder = exports.RequestBuilder = exports.RequestStrategy = void 0;
const Util_1 = require("./Util");
const RequestSplitter_1 = require("./RequestSplitter");
const GossipModel_1 = require("./GossipModel");
const RequestMerger_1 = require("./RequestMerger");
/**
* Which strategy is used when building REQ filters
*/
var RequestStrategy;
(function (RequestStrategy) {
/**
* Use the users default relays to fetch events,
* this is the fallback option when there is no better way to query a given filter set
*/
RequestStrategy[RequestStrategy["DefaultRelays"] = 1] = "DefaultRelays";
/**
* Using a cached copy of the authors relay lists NIP-65, split a given set of request filters by pubkey
*/
RequestStrategy[RequestStrategy["AuthorsRelays"] = 2] = "AuthorsRelays";
/**
* Relay hints are usually provided when using replies
*/
RequestStrategy[RequestStrategy["RelayHintedEventIds"] = 3] = "RelayHintedEventIds";
})(RequestStrategy = exports.RequestStrategy || (exports.RequestStrategy = {}));
/**
* Nostr REQ builder
*/
class RequestBuilder {
constructor(id) {
_RequestBuilder_instances.add(this);
_RequestBuilder_builders.set(this, void 0);
_RequestBuilder_options.set(this, void 0);
this.id = id;
__classPrivateFieldSet(this, _RequestBuilder_builders, [], "f");
}
get numFilters() {
return __classPrivateFieldGet(this, _RequestBuilder_builders, "f").length;
}
get options() {
return __classPrivateFieldGet(this, _RequestBuilder_options, "f");
}
withFilter() {
const ret = new RequestFilterBuilder();
__classPrivateFieldGet(this, _RequestBuilder_builders, "f").push(ret);
return ret;
}
withOptions(opt) {
__classPrivateFieldSet(this, _RequestBuilder_options, {
...__classPrivateFieldGet(this, _RequestBuilder_options, "f"),
...opt,
}, "f");
return this;
}
buildRaw() {
return __classPrivateFieldGet(this, _RequestBuilder_builders, "f").map(f => f.filter);
}
build(relays) {
const expanded = __classPrivateFieldGet(this, _RequestBuilder_builders, "f").flatMap(a => a.build(relays, this.id));
return __classPrivateFieldGet(this, _RequestBuilder_instances, "m", _RequestBuilder_groupByRelay).call(this, expanded);
}
/**
* Detects a change in request from a previous set of filters
* @param q All previous filters merged
* @returns
*/
buildDiff(relays, filters) {
const next = this.buildRaw();
const diff = (0, RequestSplitter_1.diffFilters)(filters, next);
if (diff.changed) {
return (0, GossipModel_1.splitAllByWriteRelays)(relays, diff.added).map(a => {
return {
strategy: RequestStrategy.AuthorsRelays,
filters: a.filters,
relay: a.relay,
};
});
}
return [];
}
}
exports.RequestBuilder = RequestBuilder;
_RequestBuilder_builders = new WeakMap(), _RequestBuilder_options = new WeakMap(), _RequestBuilder_instances = new WeakSet(), _RequestBuilder_groupByRelay = function _RequestBuilder_groupByRelay(expanded) {
const relayMerged = expanded.reduce((acc, v) => {
const existing = acc.get(v.relay);
if (existing) {
existing.push(v);
}
else {
acc.set(v.relay, [v]);
}
return acc;
}, new Map());
const filtersSquashed = [...relayMerged.values()].map(a => {
return {
filters: (0, RequestMerger_1.mergeSimilar)(a.flatMap(b => b.filters)),
relay: a[0].relay,
strategy: a[0].strategy,
};
});
return filtersSquashed;
};
/**
* Builder class for a single request filter
*/
class RequestFilterBuilder {
constructor() {
_RequestFilterBuilder_filter.set(this, {});
_RequestFilterBuilder_relayHints.set(this, new Map());
}
get filter() {
return { ...__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f") };
}
get relayHints() {
return new Map(__classPrivateFieldGet(this, _RequestFilterBuilder_relayHints, "f"));
}
ids(ids) {
__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f").ids = (0, Util_1.appendDedupe)(__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f").ids, ids);
return this;
}
id(id, relay) {
if (relay) {
__classPrivateFieldGet(this, _RequestFilterBuilder_relayHints, "f").set(id, (0, Util_1.appendDedupe)(__classPrivateFieldGet(this, _RequestFilterBuilder_relayHints, "f").get(id), [relay]));
}
return this.ids([id]);
}
authors(authors) {
if (!authors)
return this;
__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f").authors = (0, Util_1.appendDedupe)(__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f").authors, authors);
return this;
}
kinds(kinds) {
if (!kinds)
return this;
__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f").kinds = (0, Util_1.appendDedupe)(__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f").kinds, kinds);
return this;
}
since(since) {
if (!since)
return this;
__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f").since = since;
return this;
}
until(until) {
if (!until)
return this;
__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f").until = until;
return this;
}
limit(limit) {
if (!limit)
return this;
__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f").limit = limit;
return this;
}
tag(key, value) {
if (!value)
return this;
__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f")[`#${key}`] = value;
return this;
}
search(keyword) {
if (!keyword)
return this;
__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f").search = keyword;
return this;
}
/**
* Build/expand this filter into a set of relay specific queries
*/
build(relays, id) {
// when querying for specific event ids with relay hints
// take the first approach which is to split the filter by relay
if (__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f").ids && __classPrivateFieldGet(this, _RequestFilterBuilder_relayHints, "f").size > 0) {
const relays = (0, Util_1.dedupe)([...__classPrivateFieldGet(this, _RequestFilterBuilder_relayHints, "f").values()].flat());
return relays.map(r => {
return {
filters: [
{
...__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f"),
ids: [...__classPrivateFieldGet(this, _RequestFilterBuilder_relayHints, "f").entries()].filter(([, v]) => v.includes(r)).map(([k]) => k),
},
],
relay: r,
strategy: RequestStrategy.RelayHintedEventIds,
};
});
}
// If any authors are set use the gossip model to fetch data for each author
if (__classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f").authors) {
const split = (0, GossipModel_1.splitByWriteRelays)(relays, __classPrivateFieldGet(this, _RequestFilterBuilder_filter, "f"));
return split.map(a => {
return {
filters: [a.filter],
relay: a.relay,
strategy: RequestStrategy.AuthorsRelays,
};
});
}
return [
{
filters: [this.filter],
relay: "",
strategy: RequestStrategy.DefaultRelays,
},
];
}
}
exports.RequestFilterBuilder = RequestFilterBuilder;
_RequestFilterBuilder_filter = new WeakMap(), _RequestFilterBuilder_relayHints = new WeakMap();
//# sourceMappingURL=RequestBuilder.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,20 +0,0 @@
import { u256, ReqFilter } from "./Nostr";
export interface FlatReqFilter {
ids?: u256;
authors?: u256;
kinds?: number;
"#e"?: u256;
"#p"?: u256;
"#t"?: string;
"#d"?: string;
"#r"?: string;
search?: string;
since?: number;
until?: number;
limit?: number;
}
/**
* Expand a filter into its most fine grained form
*/
export declare function expandFilter(f: ReqFilter): Array<FlatReqFilter>;
//# sourceMappingURL=RequestExpander.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"RequestExpander.d.ts","sourceRoot":"","sources":["../src/RequestExpander.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAE1C,MAAM,WAAW,aAAa;IAC5B,GAAG,CAAC,EAAE,IAAI,CAAC;IACX,OAAO,CAAC,EAAE,IAAI,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,SAAS,GAAG,KAAK,CAAC,aAAa,CAAC,CA2B/D"}

View File

@ -1,31 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.expandFilter = void 0;
/**
* Expand a filter into its most fine grained form
*/
function expandFilter(f) {
const ret = [];
const src = Object.entries(f);
const keys = src.filter(([, v]) => Array.isArray(v)).map(a => a[0]);
const props = src.filter(([, v]) => !Array.isArray(v));
function generateCombinations(index, currentCombination) {
if (index === keys.length) {
ret.push(currentCombination);
return;
}
const key = keys[index];
const values = f[key];
for (let i = 0; i < values.length; i++) {
const value = values[i];
const updatedCombination = { ...currentCombination, [key]: value };
generateCombinations(index + 1, updatedCombination);
}
}
generateCombinations(0, {
...Object.fromEntries(props),
});
return ret;
}
exports.expandFilter = expandFilter;
//# sourceMappingURL=RequestExpander.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"RequestExpander.js","sourceRoot":"","sources":["../src/RequestExpander.ts"],"names":[],"mappings":";;;AAiBA;;GAEG;AACH,SAAgB,YAAY,CAAC,CAAY;IACvC,MAAM,GAAG,GAAyB,EAAE,CAAC;IACrC,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAC9B,MAAM,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACpE,MAAM,KAAK,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAEvD,SAAS,oBAAoB,CAAC,KAAa,EAAE,kBAAiC;QAC5E,IAAI,KAAK,KAAK,IAAI,CAAC,MAAM,EAAE;YACzB,GAAG,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC;YAC7B,OAAO;SACR;QAED,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;QACxB,MAAM,MAAM,GAAI,CAA4C,CAAC,GAAG,CAAC,CAAC;QAElE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACtC,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;YACxB,MAAM,kBAAkB,GAAG,EAAE,GAAG,kBAAkB,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC;YACnE,oBAAoB,CAAC,KAAK,GAAG,CAAC,EAAE,kBAAkB,CAAC,CAAC;SACrD;IACH,CAAC;IAED,oBAAoB,CAAC,CAAC,EAAE;QACtB,GAAG,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC;KAC7B,CAAC,CAAC;IAEH,OAAO,GAAG,CAAC;AACb,CAAC;AA3BD,oCA2BC"}

View File

@ -1,3 +0,0 @@
import { NostrEvent, ReqFilter } from "./Nostr";
export declare function eventMatchesFilter(ev: NostrEvent, filter: ReqFilter): boolean;
//# sourceMappingURL=RequestMatcher.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"RequestMatcher.d.ts","sourceRoot":"","sources":["../src/RequestMatcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEhD,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,WAiBnE"}

View File

@ -1,23 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.eventMatchesFilter = void 0;
function eventMatchesFilter(ev, filter) {
if (!(filter.ids?.includes(ev.id) ?? false)) {
return false;
}
if (!(filter.authors?.includes(ev.pubkey) ?? false)) {
return false;
}
if (!(filter.kinds?.includes(ev.kind) ?? false)) {
return false;
}
if (filter.since && ev.created_at < filter.since) {
return false;
}
if (filter.until && ev.created_at > filter.until) {
return false;
}
return true;
}
exports.eventMatchesFilter = eventMatchesFilter;
//# sourceMappingURL=RequestMatcher.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"RequestMatcher.js","sourceRoot":"","sources":["../src/RequestMatcher.ts"],"names":[],"mappings":";;;AAEA,SAAgB,kBAAkB,CAAC,EAAc,EAAE,MAAiB;IAClE,IAAI,CAAC,CAAC,MAAM,CAAC,GAAG,EAAE,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,KAAK,CAAC,EAAE;QAC3C,OAAO,KAAK,CAAC;KACd;IACD,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,EAAE;QACnD,OAAO,KAAK,CAAC;KACd;IACD,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,EAAE;QAC/C,OAAO,KAAK,CAAC;KACd;IACD,IAAI,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC,UAAU,GAAG,MAAM,CAAC,KAAK,EAAE;QAChD,OAAO,KAAK,CAAC;KACd;IACD,IAAI,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC,UAAU,GAAG,MAAM,CAAC,KAAK,EAAE;QAChD,OAAO,KAAK,CAAC;KACd;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAjBD,gDAiBC"}

View File

@ -1,24 +0,0 @@
import { ReqFilter } from ".";
import { FlatReqFilter } from "./RequestExpander";
export declare function canMergeFilters(a: FlatReqFilter | ReqFilter, b: FlatReqFilter | ReqFilter): boolean;
export declare function mergeSimilar(filters: Array<ReqFilter>): Array<ReqFilter>;
/**
* Simply flatten all filters into one
* @param filters
* @returns
*/
export declare function simpleMerge(filters: Array<ReqFilter>): ReqFilter;
/**
* Check if a filter includes another filter, as in the bigger filter will include the same results as the samller filter
* @param bigger
* @param smaller
* @returns
*/
export declare function filterIncludes(bigger: ReqFilter, smaller: ReqFilter): boolean;
/**
* Merge expanded flat filters into combined concise filters
* @param all
* @returns
*/
export declare function flatMerge(all: Array<FlatReqFilter>): Array<ReqFilter>;
//# sourceMappingURL=RequestMerger.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"RequestMerger.d.ts","sourceRoot":"","sources":["../src/RequestMerger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,GAAG,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAQlD,wBAAgB,eAAe,CAAC,CAAC,EAAE,aAAa,GAAG,SAAS,EAAE,CAAC,EAAE,aAAa,GAAG,SAAS,GAAG,OAAO,CAWnG;AAED,wBAAgB,YAAY,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,SAAS,CAAC,CAmBxE;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,aAkBpD;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,WAoBnE;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,KAAK,CAAC,aAAa,CAAC,GAAG,KAAK,CAAC,SAAS,CAAC,CAsDrE"}

View File

@ -1,150 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.flatMerge = exports.filterIncludes = exports.simpleMerge = exports.mergeSimilar = exports.canMergeFilters = void 0;
const Util_1 = require("./Util");
/**
* Keys which can change the entire meaning of the filter outside the array types
*/
const DiscriminatorKeys = ["since", "until", "limit", "search"];
function canMergeFilters(a, b) {
const aObj = a;
const bObj = b;
for (const key of DiscriminatorKeys) {
if (key in aObj || key in bObj) {
if (aObj[key] !== bObj[key]) {
return false;
}
}
}
return (0, Util_1.distance)(aObj, bObj) <= 1;
}
exports.canMergeFilters = canMergeFilters;
function mergeSimilar(filters) {
console.time("mergeSimilar");
const ret = [];
const fCopy = [...filters];
while (fCopy.length > 0) {
const current = fCopy.shift();
const mergeSet = [current];
for (let i = 0; i < fCopy.length; i++) {
const f = fCopy[i];
if (mergeSet.every(v => canMergeFilters(v, f))) {
mergeSet.push(fCopy.splice(i, 1)[0]);
i--;
}
}
ret.push(simpleMerge(mergeSet));
}
console.timeEnd("mergeSimilar");
return ret;
}
exports.mergeSimilar = mergeSimilar;
/**
* Simply flatten all filters into one
* @param filters
* @returns
*/
function simpleMerge(filters) {
const result = {};
filters.forEach(filter => {
Object.entries(filter).forEach(([key, value]) => {
if (Array.isArray(value)) {
if (result[key] === undefined) {
result[key] = [...value];
}
else {
result[key] = [...new Set([...result[key], ...value])];
}
}
else {
result[key] = value;
}
});
});
return result;
}
exports.simpleMerge = simpleMerge;
/**
* Check if a filter includes another filter, as in the bigger filter will include the same results as the samller filter
* @param bigger
* @param smaller
* @returns
*/
function filterIncludes(bigger, smaller) {
const outside = bigger;
for (const [k, v] of Object.entries(smaller)) {
if (outside[k] === undefined) {
return false;
}
if (Array.isArray(v) && v.some(a => !outside[k].includes(a))) {
return false;
}
if (typeof v === "number") {
if (k === "since" && outside[k] > v) {
return false;
}
if (k === "until" && outside[k] < v) {
return false;
}
// limit cannot be checked and is ignored
}
}
return true;
}
exports.filterIncludes = filterIncludes;
/**
* Merge expanded flat filters into combined concise filters
* @param all
* @returns
*/
function flatMerge(all) {
console.time("flatMerge");
let ret = [];
// to compute filters which can be merged we need to calucate the distance change between each filter
// then we can merge filters which are exactly 1 change diff from each other
function mergeFiltersInSet(filters) {
const result = {};
filters.forEach(f => {
const filter = f;
Object.entries(filter).forEach(([key, value]) => {
if (!DiscriminatorKeys.includes(key)) {
if (result[key] === undefined) {
result[key] = [value];
}
else {
result[key] = [...new Set([...result[key], value])];
}
}
else {
result[key] = value;
}
});
});
return result;
}
// reducer, kinda verbose
while (all.length > 0) {
const currentFilter = all.shift();
const mergeSet = [currentFilter];
for (let i = 0; i < all.length; i++) {
const f = all[i];
if (mergeSet.every(a => canMergeFilters(a, f))) {
mergeSet.push(all.splice(i, 1)[0]);
i--;
}
}
ret.push(mergeFiltersInSet(mergeSet));
}
while (true) {
const n = mergeSimilar([...ret]);
if (n.length === ret.length) {
break;
}
ret = n;
}
console.timeEnd("flatMerge");
console.debug(ret);
return ret;
}
exports.flatMerge = flatMerge;
//# sourceMappingURL=RequestMerger.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"RequestMerger.js","sourceRoot":"","sources":["../src/RequestMerger.ts"],"names":[],"mappings":";;;AAEA,iCAAkC;AAElC;;GAEG;AACH,MAAM,iBA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+0,0 @@
import { ReqFilter } from ".";
export declare function diffFilters(prev: Array<ReqFilter>, next: Array<ReqFilter>): {
added: ReqFilter[];
removed: ReqFilter[];
changed: boolean;
};
//# sourceMappingURL=RequestSplitter.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"RequestSplitter.d.ts","sourceRoot":"","sources":["../src/RequestSplitter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,GAAG,CAAC;AAK9B,wBAAgB,WAAW,CAAC,IAAI,EAAE,KAAK,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,SAAS,CAAC;;;;EAYzE"}

View File

@ -1,19 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.diffFilters = void 0;
const Util_1 = require("./Util");
const RequestExpander_1 = require("./RequestExpander");
const RequestMerger_1 = require("./RequestMerger");
function diffFilters(prev, next) {
const prevExpanded = prev.flatMap(RequestExpander_1.expandFilter);
const nextExpanded = next.flatMap(RequestExpander_1.expandFilter);
const added = (0, RequestMerger_1.flatMerge)(nextExpanded.filter(a => !prevExpanded.some(b => (0, Util_1.deepEqual)(a, b))));
const removed = (0, RequestMerger_1.flatMerge)(prevExpanded.filter(a => !nextExpanded.some(b => (0, Util_1.deepEqual)(a, b))));
return {
added,
removed,
changed: added.length > 0 || removed.length > 0,
};
}
exports.diffFilters = diffFilters;
//# sourceMappingURL=RequestSplitter.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"RequestSplitter.js","sourceRoot":"","sources":["../src/RequestSplitter.ts"],"names":[],"mappings":";;;AACA,iCAAmC;AACnC,uDAAiD;AACjD,mDAA4C;AAE5C,SAAgB,WAAW,CAAC,IAAsB,EAAE,IAAsB;IACxE,MAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,8BAAY,CAAC,CAAC;IAChD,MAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,8BAAY,CAAC,CAAC;IAEhD,MAAM,KAAK,GAAG,IAAA,yBAAS,EAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAA,gBAAS,EAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5F,MAAM,OAAO,GAAG,IAAA,yBAAS,EAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAA,gBAAS,EAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAE9F,OAAO;QACL,KAAK;QACL,OAAO;QACP,OAAO,EAAE,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC;KAChD,CAAC;AACJ,CAAC;AAZD,kCAYC"}

View File

@ -1,22 +0,0 @@
import { SystemSnapshot, SystemInterface } from ".";
import { AuthHandler, ConnectionStateSnapshot, RelaySettings } from "./Connection";
import ExternalStore from "./ExternalStore";
import { NostrEvent } from "./Nostr";
import { NoteStore } from "./NoteCollection";
import { Query } from "./Query";
import { RequestBuilder } from "./RequestBuilder";
export declare class SystemWorker extends ExternalStore<SystemSnapshot> implements SystemInterface {
#private;
constructor();
HandleAuth?: AuthHandler;
get Sockets(): ConnectionStateSnapshot[];
Query<T extends NoteStore>(type: new () => T, req: RequestBuilder | null): Query | undefined;
CancelQuery(sub: string): void;
GetQuery(sub: string): Query | undefined;
ConnectToRelay(address: string, options: RelaySettings): Promise<void>;
DisconnectRelay(address: string): void;
BroadcastEvent(ev: NostrEvent): void;
WriteOnceToRelay(relay: string, ev: NostrEvent): Promise<void>;
takeSnapshot(): SystemSnapshot;
}
//# sourceMappingURL=SystemWorker.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"SystemWorker.d.ts","sourceRoot":"","sources":["../src/SystemWorker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,GAAG,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,uBAAuB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACnF,OAAO,aAAa,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,qBAAa,YAAa,SAAQ,aAAa,CAAC,cAAc,CAAE,YAAW,eAAe;;;IAcxF,UAAU,CAAC,EAAE,WAAW,CAAC;IAEzB,IAAI,OAAO,IAAI,uBAAuB,EAAE,CAEvC;IAED,KAAK,CAAC,CAAC,SAAS,SAAS,EAAE,IAAI,EAAE,UAAU,CAAC,EAAE,GAAG,EAAE,cAAc,GAAG,IAAI,GAAG,KAAK,GAAG,SAAS;IAI5F,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAI9B,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,KAAK,GAAG,SAAS;IAIxC,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;IAItE,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAItC,cAAc,CAAC,EAAE,EAAE,UAAU,GAAG,IAAI;IAIpC,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAI9D,YAAY,IAAI,cAAc;CAO/B"}

View File

@ -1,66 +0,0 @@
"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _SystemWorker_instances, _SystemWorker_port, _SystemWorker_onMessage;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SystemWorker = void 0;
const ExternalStore_1 = __importDefault(require("./ExternalStore"));
class SystemWorker extends ExternalStore_1.default {
constructor() {
super();
_SystemWorker_instances.add(this);
_SystemWorker_port.set(this, void 0);
if ("SharedWorker" in window) {
const worker = new SharedWorker("/system.js");
__classPrivateFieldSet(this, _SystemWorker_port, worker.port, "f");
__classPrivateFieldGet(this, _SystemWorker_port, "f").onmessage = m => __classPrivateFieldGet(this, _SystemWorker_instances, "m", _SystemWorker_onMessage).call(this, m);
}
else {
throw new Error("SharedWorker is not supported");
}
}
get Sockets() {
throw new Error("Method not implemented.");
}
Query(type, req) {
throw new Error("Method not implemented.");
}
CancelQuery(sub) {
throw new Error("Method not implemented.");
}
GetQuery(sub) {
throw new Error("Method not implemented.");
}
ConnectToRelay(address, options) {
throw new Error("Method not implemented.");
}
DisconnectRelay(address) {
throw new Error("Method not implemented.");
}
BroadcastEvent(ev) {
throw new Error("Method not implemented.");
}
WriteOnceToRelay(relay, ev) {
throw new Error("Method not implemented.");
}
takeSnapshot() {
throw new Error("Method not implemented.");
}
}
exports.SystemWorker = SystemWorker;
_SystemWorker_port = new WeakMap(), _SystemWorker_instances = new WeakSet(), _SystemWorker_onMessage = function _SystemWorker_onMessage(e) {
console.debug(e);
};
//# sourceMappingURL=SystemWorker.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"SystemWorker.js","sourceRoot":"","sources":["../src/SystemWorker.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAEA,oEAA4C;AAM5C,MAAa,YAAa,SAAQ,uBAA6B;IAG7D;QACE,KAAK,EAAE,CAAC;;QAHV,qCAAmB;QAIjB,IAAI,cAAc,IAAI,MAAM,EAAE;YAC5B,MAAM,MAAM,GAAG,IAAI,YAAY,CAAC,YAAY,CAAC,CAAC;YAC9C,uBAAA,IAAI,sBAAS,MAAM,CAAC,IAAI,MAAA,CAAC;YACzB,uBAAA,IAAI,0BAAM,CAAC,SAAS,GAAG,CAAC,CAAC,EAAE,CAAC,uBAAA,IAAI,wDAAW,MAAf,IAAI,EAAY,CAAC,CAAC,CAAC;SAChD;aAAM;YACL,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;SAClD;IACH,CAAC;IAID,IAAI,OAAO;QACT,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IAED,KAAK,CAAsB,IAAiB,EAAE,GAA0B;QACtE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IAED,WAAW,CAAC,GAAW;QACrB,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IAED,QAAQ,CAAC,GAAW;QAClB,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IAED,cAAc,CAAC,OAAe,EAAE,OAAsB;QACpD,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IAED,eAAe,CAAC,OAAe;QAC7B,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IAED,cAAc,CAAC,EAAc;QAC3B,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IAED,gBAAgB,CAAC,KAAa,EAAE,EAAc;QAC5C,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IAED,YAAY;QACV,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;CAKF;AAvDD,oCAuDC;wIAHY,CAAoB;IAC7B,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnB,CAAC"}

View File

@ -1,18 +0,0 @@
import { HexKey, u256 } from "./Nostr";
export default class Tag {
Original: string[];
Key: string;
Event?: u256;
PubKey?: HexKey;
Relay?: string;
Marker?: string;
Hashtag?: string;
DTag?: string;
ATag?: string;
Index: number;
Invalid: boolean;
LNURL?: string;
constructor(tag: string[], index: number);
ToObject(): string[] | null;
}
//# sourceMappingURL=Tag.d.ts.map

View File

@ -1 +0,0 @@
{"version":3,"file":"Tag.d.ts","sourceRoot":"","sources":["../src/Tag.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAGvC,MAAM,CAAC,OAAO,OAAO,GAAG;IACtB,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,IAAI,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;gBAEH,GAAG,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,MAAM;IAgDxC,QAAQ,IAAI,MAAM,EAAE,GAAG,IAAI;CAsB5B"}

Some files were not shown because too many files have changed in this diff Show More