Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fix (most) slow types by adding explicit return types #378

Merged
merged 1 commit into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions abstract-pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ export type SubscribeManyParams = Omit<SubscriptionParams, 'onclose' | 'id'> & {

export class AbstractSimplePool {
private relays = new Map<string, AbstractRelay>()
public seenOn = new Map<string, Set<AbstractRelay>>()
public seenOn: Map<string, Set<AbstractRelay>> = new Map()
public trackRelays: boolean = false

public verifyEvent: Nostr['verifyEvent']
public trustedRelayURLs = new Set<string>()
public trustedRelayURLs: Set<string> = new Set()

constructor(opts: { verifyEvent: Nostr['verifyEvent'] }) {
this.verifyEvent = opts.verifyEvent
Expand Down
6 changes: 3 additions & 3 deletions abstract-relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class AbstractRelay {

public baseEoseTimeout: number = 4400
public connectionTimeout: number = 4400
public openSubs = new Map<string, Subscription>()
public openSubs: Map<string, Subscription> = new Map()
private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined

private connectionPromise: Promise<void> | undefined
Expand All @@ -44,7 +44,7 @@ export class AbstractRelay {
this.verifyEvent = opts.verifyEvent
}

static async connect(url: string, opts: { verifyEvent: Nostr['verifyEvent'] }) {
static async connect(url: string, opts: { verifyEvent: Nostr['verifyEvent'] }): Promise<AbstractRelay> {
const relay = new AbstractRelay(url, opts)
await relay.connect()
return relay
Expand Down Expand Up @@ -228,7 +228,7 @@ export class AbstractRelay {
})
}

public async auth(signAuthEvent: (evt: EventTemplate) => Promise<VerifiedEvent>) {
public async auth(signAuthEvent: (evt: EventTemplate) => Promise<VerifiedEvent>): Promise<string> {
if (!this.challenge) throw new Error("can't perform auth, no challenge was received")
const evt = await signAuthEvent(makeAuthEvent(this.url, this.challenge))
const ret = new Promise<string>((resolve, reject) => {
Expand Down
8 changes: 4 additions & 4 deletions kinds.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
/** Events are **regular**, which means they're all expected to be stored by relays. */
export function isRegularKind(kind: number) {
export function isRegularKind(kind: number): boolean {
return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind)
}

/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */
export function isReplaceableKind(kind: number) {
export function isReplaceableKind(kind: number): boolean {
return [0, 3].includes(kind) || (10000 <= kind && kind < 20000)
}

/** Events are **ephemeral**, which means they are not expected to be stored by relays. */
export function isEphemeralKind(kind: number) {
export function isEphemeralKind(kind: number): boolean {
return 20000 <= kind && kind < 30000
}

/** Events are **parameterized replaceable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */
export function isParameterizedReplaceableKind(kind: number) {
export function isParameterizedReplaceableKind(kind: number): boolean {
return 30000 <= kind && kind < 40000
}

Expand Down
4 changes: 2 additions & 2 deletions nip11.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ try {
_fetch = fetch
} catch {}

export function useFetchImplementation(fetchImplementation: any) {
export function useFetchImplementation(fetchImplementation: any): void {
_fetch = fetchImplementation
}

export async function fetchRelayInformation(url: string) {
export async function fetchRelayInformation(url: string): Promise<RelayInformation> {
return (await (
await fetch(url.replace('ws://', 'http://').replace('wss://', 'https://'), {
headers: { Accept: 'application/nostr+json' },
Expand Down
2 changes: 1 addition & 1 deletion nip21.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BECH32_REGEX, decode, type DecodeResult } from './nip19.ts'

/** Nostr URI regex, eg `nostr:npub1...` */
export const NOSTR_URI_REGEX = new RegExp(`nostr:(${BECH32_REGEX.source})`)
export const NOSTR_URI_REGEX: RegExp = new RegExp(`nostr:(${BECH32_REGEX.source})`)

/** Test whether the value is a Nostr URI. */
export function test(value: unknown): value is `nostr:${string}` {
Expand Down
2 changes: 1 addition & 1 deletion nip27.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { decode } from './nip19.ts'
import { NOSTR_URI_REGEX, type NostrURI } from './nip21.ts'

/** Regex to find NIP-21 URIs inside event content. */
export const regex = () => new RegExp(`\\b${NOSTR_URI_REGEX.source}\\b`, 'g')
export const regex = (): RegExp => new RegExp(`\\b${NOSTR_URI_REGEX.source}\\b`, 'g')

/** Match result for a Nostr URI in event content. */
export interface NostrURIMatch extends NostrURI {
Expand Down
2 changes: 1 addition & 1 deletion nip30.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
export const EMOJI_SHORTCODE_REGEX = /:(\w+):/

/** Regex to find emoji shortcodes in content. */
export const regex = () => new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`, 'g')
export const regex = (): RegExp => new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`, 'g')

/** Represents a Nostr custom emoji. */
export interface CustomEmoji {
Expand Down
10 changes: 5 additions & 5 deletions nip44.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const u = {
maxPlaintextSize: 0xffff, // 65535 (64kb-1) => padded to 64kb

utf8Encode: utf8ToBytes,
utf8Decode(bytes: Uint8Array) {
utf8Decode(bytes: Uint8Array): string {
return decoder.decode(bytes)
},

Expand All @@ -39,7 +39,7 @@ const u = {
return chunk * (Math.floor((len - 1) / chunk) + 1)
},

writeU16BE(num: number) {
writeU16BE(num: number): Uint8Array {
if (!Number.isSafeInteger(num) || num < u.minPlaintextSize || num > u.maxPlaintextSize)
throw new Error('invalid plaintext size: must be between 1 and 65535 bytes')
const arr = new Uint8Array(2)
Expand Down Expand Up @@ -68,7 +68,7 @@ const u = {
return u.utf8Decode(unpadded)
},

hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array) {
hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array): Uint8Array {
if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes')
const combined = concatBytes(aad, message)
return hmac(sha256, key, combined)
Expand All @@ -80,7 +80,7 @@ const u = {
// ciphertext: 32b+2 to 0xffff+2
// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)
// compressed payload (base64): 132b to 87472b
decodePayload(payload: string) {
decodePayload(payload: string): { nonce: Uint8Array; ciphertext: Uint8Array; mac: Uint8Array } {
if (typeof payload !== 'string') throw new Error('payload must be a valid string')
const plen = payload.length
if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen)
Expand All @@ -103,7 +103,7 @@ const u = {
},
}

function encrypt(plaintext: string, conversationKey: Uint8Array, nonce = randomBytes(32)): string {
function encrypt(plaintext: string, conversationKey: Uint8Array, nonce: Uint8Array = randomBytes(32)): string {
const { chacha_key, chacha_nonce, hmac_key } = u.getMessageKeys(conversationKey, nonce)
const padded = u.pad(plaintext)
const ciphertext = chacha20(chacha_key, chacha_nonce, padded)
Expand Down
16 changes: 13 additions & 3 deletions nip47.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { finalizeEvent } from './pure.ts'
import { type VerifiedEvent, finalizeEvent } from './pure.ts'
import { NWCWalletRequest } from './kinds.ts'
import { encrypt } from './nip04.ts'

export function parseConnectionString(connectionString: string) {
interface NWCConnection {
pubkey: string
relay: string
secret: string
}

export function parseConnectionString(connectionString: string): NWCConnection {
const { pathname, searchParams } = new URL(connectionString)
const pubkey = pathname
const relay = searchParams.get('relay')
Expand All @@ -15,7 +21,11 @@ export function parseConnectionString(connectionString: string) {
return { pubkey, relay, secret }
}

export async function makeNwcRequestEvent(pubkey: string, secretKey: Uint8Array, invoice: string) {
export async function makeNwcRequestEvent(
pubkey: string,
secretKey: Uint8Array,
invoice: string,
): Promise<VerifiedEvent> {
const content = {
method: 'pay_invoice',
params: {
Expand Down
2 changes: 1 addition & 1 deletion pure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export function getEventHash(event: UnsignedEvent): string {
return bytesToHex(eventHash)
}

const i = new JS()
const i: JS = new JS()

export const generateSecretKey = i.generateSecretKey
export const getPublicKey = i.getPublicKey
Expand Down
2 changes: 1 addition & 1 deletion relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class Relay extends AbstractRelay {
super(url, { verifyEvent })
}

static async connect(url: string) {
static async connect(url: string): Promise<Relay> {
const relay = new Relay(url)
await relay.connect()
return relay
Expand Down
8 changes: 4 additions & 4 deletions utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Event } from './core.ts'

export const utf8Decoder = new TextDecoder('utf-8')
export const utf8Encoder = new TextEncoder()
export const utf8Decoder: TextDecoder = new TextDecoder('utf-8')
export const utf8Encoder: TextEncoder = new TextEncoder()

export function normalizeURL(url: string): string {
if (url.indexOf('://') === -1) url = 'wss://' + url
Expand All @@ -14,7 +14,7 @@ export function normalizeURL(url: string): string {
return p.toString()
}

export function insertEventIntoDescendingList(sortedArray: Event[], event: Event) {
export function insertEventIntoDescendingList(sortedArray: Event[], event: Event): Event[] {
const [idx, found] = binarySearch(sortedArray, b => {
if (event.id === b.id) return 0
if (event.created_at === b.created_at) return -1
Expand All @@ -26,7 +26,7 @@ export function insertEventIntoDescendingList(sortedArray: Event[], event: Event
return sortedArray
}

export function insertEventIntoAscendingList(sortedArray: Event[], event: Event) {
export function insertEventIntoAscendingList(sortedArray: Event[], event: Event): Event[] {
const [idx, found] = binarySearch(sortedArray, b => {
if (event.id === b.id) return 0
if (event.created_at === b.created_at) return -1
Expand Down
Loading