Skip to content

Commit

Permalink
Fix fetch to work in the edge and node environments, cleanup type issues
Browse files Browse the repository at this point in the history
- Fix "TypeError: Invalid redirect value, must be one of "follow" or "manual" ("error" won't be implemented since it does not make sense at the edge; use "manual" and check the response status code)." that is thrown when trying to use fetch in the edge environment  (e.g., workers)
- Cleanup types and variable definitions.
  • Loading branch information
fishcakeday authored and fiatjaf committed Oct 28, 2024
1 parent c1d03cf commit 94f841f
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions nip05.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,24 @@ export type Nip05 = `${string}@${string}`
export const NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/
export const isNip05 = (value?: string | null): value is Nip05 => NIP05_REGEX.test(value || '')

var _fetch: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let _fetch: any

try {
_fetch = fetch
} catch {}
} catch (_) {null}

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

export async function searchDomain(domain: string, query = ''): Promise<{ [name: string]: string }> {
try {
const url = `https://${domain}/.well-known/nostr.json?name=${query}`
const res = await _fetch(url, { redirect: 'error' })
const res = await _fetch(url, { redirect: 'manual' })
if (res.status !== 200) {
throw Error("Wrong response code")
}
const json = await res.json()
return json.names
} catch (_) {
Expand All @@ -37,20 +41,24 @@ export async function queryProfile(fullname: string): Promise<ProfilePointer | n
const match = fullname.match(NIP05_REGEX)
if (!match) return null

const [_, name = '_', domain] = match
const [, name = '_', domain] = match

try {
const url = `https://${domain}/.well-known/nostr.json?name=${name}`
const res = await (await _fetch(url, { redirect: 'error' })).json()
const res = await _fetch(url, { redirect: 'manual' })
if (res.status !== 200) {
throw Error("Wrong response code")
}
const json = await res.json()

let pubkey = res.names[name]
return pubkey ? { pubkey, relays: res.relays?.[pubkey] } : null
const pubkey = json.names[name]
return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null
} catch (_e) {
return null
}
}

export async function isValid(pubkey: string, nip05: Nip05): Promise<boolean> {
let res = await queryProfile(nip05)
const res = await queryProfile(nip05)
return res ? res.pubkey === pubkey : false
}

0 comments on commit 94f841f

Please sign in to comment.