Browse Source

Cleaned up all of the parameter calls for ndk

master
silberengel 7 months ago
parent
commit
c86cc266e9
  1. 8
      src/lib/components/CommentBox.svelte
  2. 2
      src/lib/components/CommentViewer.svelte
  3. 2
      src/lib/components/EventDetails.svelte
  4. 1
      src/lib/components/EventInput.svelte
  5. 6
      src/lib/components/EventSearch.svelte
  6. 2
      src/lib/components/Navigation.svelte
  7. 6
      src/lib/components/Notifications.svelte
  8. 2
      src/lib/components/embedded_events/EmbeddedEvent.svelte
  9. 2
      src/lib/components/embedded_events/EmbeddedSnippets.svelte
  10. 6
      src/lib/components/util/ContainingIndexes.svelte
  11. 8
      src/lib/components/util/Profile.svelte
  12. 2
      src/lib/snippets/UserSnippets.svelte
  13. 6
      src/lib/stores/userStore.ts
  14. 10
      src/lib/utils/markup/markupServices.ts
  15. 4
      src/lib/utils/nostrUtils.ts
  16. 6
      src/lib/utils/user_lists.ts
  17. 2
      src/routes/events/+page.svelte
  18. 7
      src/routes/new/compose/+page.svelte
  19. 29
      src/routes/publication/[type]/[identifier]/+layout.svelte
  20. 5
      src/routes/visualize/+page.svelte
  21. 21
      tests/unit/eventInput30040.test.ts
  22. 14
      tests/unit/tagExpansion.test.ts

8
src/lib/components/CommentBox.svelte

@ -23,13 +23,15 @@
} from "$lib/utils/nostrEventService"; } from "$lib/utils/nostrEventService";
import { tick } from "svelte"; import { tick } from "svelte";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { activeInboxRelays, activeOutboxRelays } from "$lib/ndk"; import { activeInboxRelays, activeOutboxRelays, getNdkContext } from "$lib/ndk";
const props = $props<{ const props = $props<{
event: NDKEvent; event: NDKEvent;
userRelayPreference: boolean; userRelayPreference: boolean;
}>(); }>();
const ndk = getNdkContext();
let content = $state(""); let content = $state("");
let preview = $state(""); let preview = $state("");
let isSubmitting = $state(false); let isSubmitting = $state(false);
@ -216,7 +218,7 @@
relays = $activeOutboxRelays.slice(0, 3); // Use first 3 outbox relays relays = $activeOutboxRelays.slice(0, 3); // Use first 3 outbox relays
} }
const successfulRelays = await publishEvent(signedEvent, relays); const successfulRelays = await publishEvent(signedEvent, relays, ndk);
success = { success = {
relay: successfulRelays[0] || "Unknown relay", relay: successfulRelays[0] || "Unknown relay",
@ -282,7 +284,7 @@
try { try {
console.log("Search promise created, waiting for result..."); console.log("Search promise created, waiting for result...");
const result = await searchProfiles(mentionSearch.trim()); const result = await searchProfiles(mentionSearch.trim(), ndk);
console.log("Search completed, found profiles:", result.profiles.length); console.log("Search completed, found profiles:", result.profiles.length);
console.log("Profile details:", result.profiles); console.log("Profile details:", result.profiles);
console.log("Community status:", result.Status); console.log("Community status:", result.Status);

2
src/lib/components/CommentViewer.svelte

@ -40,7 +40,7 @@
if (!npub) return; if (!npub) return;
// Force fetch to ensure we get the latest profile data // Force fetch to ensure we get the latest profile data
const profile = await getUserMetadata(npub, true); const profile = await getUserMetadata(npub, ndk, true);
const newProfiles = new Map(profiles); const newProfiles = new Map(profiles);
newProfiles.set(pubkey, profile); newProfiles.set(pubkey, profile);
profiles = newProfiles; profiles = newProfiles;

2
src/lib/components/EventDetails.svelte

@ -196,7 +196,7 @@
return; return;
} }
getUserMetadata(toNpub(event.pubkey) as string).then((profile) => { getUserMetadata(toNpub(event.pubkey) as string, undefined).then((profile) => {
authorDisplayName = authorDisplayName =
profile.displayName || profile.displayName ||
(profile as any).display_name || (profile as any).display_name ||

1
src/lib/components/EventInput.svelte

@ -265,6 +265,7 @@
content, content,
tags, tags,
baseEvent, baseEvent,
ndk,
); );
console.log("Index event:", indexEvent); console.log("Index event:", indexEvent);
console.log("Section events:", sectionEvents); console.log("Section events:", sectionEvents);

6
src/lib/components/EventSearch.svelte

@ -8,6 +8,7 @@
searchBySubscription, searchBySubscription,
searchNip05, searchNip05,
} from "$lib/utils/search_utility"; } from "$lib/utils/search_utility";
import type { SearchCallbacks } from "$lib/utils/search_types";
import { neventEncode, naddrEncode, nprofileEncode } from "$lib/utils"; import { neventEncode, naddrEncode, nprofileEncode } from "$lib/utils";
import { activeInboxRelays, activeOutboxRelays, getNdkContext } from "$lib/ndk"; import { activeInboxRelays, activeOutboxRelays, getNdkContext } from "$lib/ndk";
import { getMatchingTags, toNpub } from "$lib/utils/nostrUtils"; import { getMatchingTags, toNpub } from "$lib/utils/nostrUtils";
@ -81,7 +82,7 @@
// AI-NOTE: 2025-01-24 - Core search handlers extracted for better organization // AI-NOTE: 2025-01-24 - Core search handlers extracted for better organization
async function handleNip05Search(query: string) { async function handleNip05Search(query: string) {
try { try {
const foundEvent = await searchNip05(query); const foundEvent = await searchNip05(query, ndk);
if (foundEvent) { if (foundEvent) {
handleFoundEvent(foundEvent); handleFoundEvent(foundEvent);
updateSearchState(false, true, 1, "nip05"); updateSearchState(false, true, 1, "nip05");
@ -96,7 +97,7 @@
async function handleEventSearch(query: string) { async function handleEventSearch(query: string) {
try { try {
const foundEvent = await searchEvent(query); const foundEvent = await searchEvent(query, ndk);
if (!foundEvent) { if (!foundEvent) {
console.warn("[Events] Event not found for query:", query); console.warn("[Events] Event not found for query:", query);
localError = "Event not found"; localError = "Event not found";
@ -505,6 +506,7 @@
const searchPromise = searchBySubscription( const searchPromise = searchBySubscription(
searchType, searchType,
searchTerm, searchTerm,
ndk,
{ {
onSecondOrderUpdate: (updatedResult) => { onSecondOrderUpdate: (updatedResult) => {
console.log("EventSearch: Second order update:", updatedResult); console.log("EventSearch: Second order update:", updatedResult);

2
src/lib/components/Navigation.svelte

@ -22,7 +22,7 @@
</NavBrand> </NavBrand>
</div> </div>
<div class="flex md:order-2"> <div class="flex md:order-2">
<Profile isNav={true} pubkey={userState.npub || undefined} /> <Profile isNav={true} />
<NavHamburger class="btn-leather" /> <NavHamburger class="btn-leather" />
</div> </div>
<NavUl class="ul-leather"> <NavUl class="ul-leather">

6
src/lib/components/Notifications.svelte

@ -263,7 +263,7 @@
try { try {
console.log("Recipient search promise created, waiting for result..."); console.log("Recipient search promise created, waiting for result...");
const result = await searchProfiles(recipientSearch.trim()); const result = await searchProfiles(recipientSearch.trim(), ndk);
console.log("Recipient search completed, found profiles:", result.profiles.length); console.log("Recipient search completed, found profiles:", result.profiles.length);
console.log("Profile details:", result.profiles); console.log("Profile details:", result.profiles);
console.log("Community status:", result.Status); console.log("Community status:", result.Status);
@ -388,7 +388,7 @@
// Get relay sets for all recipients and combine them // Get relay sets for all recipients and combine them
const relaySetPromises = recipientPubkeys.map(recipientPubkey => const relaySetPromises = recipientPubkeys.map(recipientPubkey =>
getKind24RelaySet(senderPubkey, recipientPubkey) getKind24RelaySet(senderPubkey, recipientPubkey, ndk)
); );
const relaySets = await Promise.all(relaySetPromises); const relaySets = await Promise.all(relaySetPromises);
@ -623,7 +623,7 @@
// Get relay sets for all recipients and combine them // Get relay sets for all recipients and combine them
const relaySetPromises = recipientPubkeys.map(recipientPubkey => const relaySetPromises = recipientPubkeys.map(recipientPubkey =>
getKind24RelaySet(senderPubkey, recipientPubkey) getKind24RelaySet(senderPubkey, recipientPubkey, ndk)
); );
const relaySets = await Promise.all(relaySetPromises); const relaySets = await Promise.all(relaySetPromises);

2
src/lib/components/embedded_events/EmbeddedEvent.svelte

@ -107,7 +107,7 @@
if (event?.pubkey) { if (event?.pubkey) {
const npub = toNpub(event.pubkey); const npub = toNpub(event.pubkey);
if (npub) { if (npub) {
const userProfile = await getUserMetadata(npub); const userProfile = await getUserMetadata(npub, ndk);
authorDisplayName = authorDisplayName =
userProfile.displayName || userProfile.displayName ||
(userProfile as any).display_name || (userProfile as any).display_name ||

2
src/lib/components/embedded_events/EmbeddedSnippets.svelte

@ -104,7 +104,7 @@
if (!npub) return; if (!npub) return;
// Try cache first // Try cache first
let profile = await getUserMetadata(npub, false); let profile = await getUserMetadata(npub, ndk, false);
if (profile && (profile.name || profile.displayName || profile.picture)) { if (profile && (profile.name || profile.displayName || profile.picture)) {
authorProfiles.set(pubkey, profile); authorProfiles.set(pubkey, profile);
return; return;

6
src/lib/components/util/ContainingIndexes.svelte

@ -5,12 +5,14 @@
import { findContainingIndexEvents } from "$lib/utils/event_search"; import { findContainingIndexEvents } from "$lib/utils/event_search";
import { getMatchingTags } from "$lib/utils/nostrUtils"; import { getMatchingTags } from "$lib/utils/nostrUtils";
import { naddrEncode } from "$lib/utils"; import { naddrEncode } from "$lib/utils";
import { activeInboxRelays, activeOutboxRelays } from "$lib/ndk"; import { activeInboxRelays, activeOutboxRelays, getNdkContext } from "$lib/ndk";
let { event } = $props<{ let { event } = $props<{
event: NDKEvent; event: NDKEvent;
}>(); }>();
const ndk = getNdkContext();
let containingIndexes = $state<NDKEvent[]>([]); let containingIndexes = $state<NDKEvent[]>([]);
let loading = $state(false); let loading = $state(false);
let error = $state<string | null>(null); let error = $state<string | null>(null);
@ -25,7 +27,7 @@
error = null; error = null;
try { try {
containingIndexes = await findContainingIndexEvents(event); containingIndexes = await findContainingIndexEvents(event, ndk);
console.log( console.log(
"[ContainingIndexes] Found containing indexes:", "[ContainingIndexes] Found containing indexes:",
containingIndexes.length, containingIndexes.length,

8
src/lib/components/util/Profile.svelte

@ -235,7 +235,7 @@
// Fallback to getUserMetadata // Fallback to getUserMetadata
console.log("Falling back to getUserMetadata"); console.log("Falling back to getUserMetadata");
const freshProfile = await getUserMetadata(userState.npub, true); // Force fresh fetch const freshProfile = await getUserMetadata(userState.npub, ndk, true); // Force fresh fetch
console.log("Fresh profile data from getUserMetadata:", freshProfile); console.log("Fresh profile data from getUserMetadata:", freshProfile);
// Update the userStore with fresh profile data // Update the userStore with fresh profile data
@ -325,7 +325,7 @@
qrCodeDataUrl = qrCodeDataUrl =
(await generateQrCode(amberSigner.nostrConnectUri)) ?? undefined; (await generateQrCode(amberSigner.nostrConnectUri)) ?? undefined;
const user = await amberSigner.blockUntilReady(); const user = await amberSigner.blockUntilReady();
await loginWithAmber(amberSigner, user); await loginWithAmber(amberSigner, user, ndk);
showQrCode = false; showQrCode = false;
} else { } else {
throw new Error("Failed to generate Nostr Connect URI"); throw new Error("Failed to generate Nostr Connect URI");
@ -343,7 +343,7 @@
const inputNpub = prompt("Enter your npub (public key):"); const inputNpub = prompt("Enter your npub (public key):");
if (inputNpub) { if (inputNpub) {
try { try {
await loginWithNpub(inputNpub); await loginWithNpub(inputNpub, ndk);
} catch (err: unknown) { } catch (err: unknown) {
showResultMessage( showResultMessage(
`❌ npub login failed: ${err instanceof Error ? err.message : String(err)}`, `❌ npub login failed: ${err instanceof Error ? err.message : String(err)}`,
@ -355,7 +355,7 @@
async function handleSignOutClick() { async function handleSignOutClick() {
localStorage.removeItem("amber/nsec"); localStorage.removeItem("amber/nsec");
localStorage.removeItem("alexandria/amber/fallback"); localStorage.removeItem("alexandria/amber/fallback");
logoutUser(); logoutUser(ndk);
} }
function handleViewProfile() { function handleViewProfile() {

2
src/lib/snippets/UserSnippets.svelte

@ -45,7 +45,7 @@
</span> </span>
{/await} {/await}
{:else} {:else}
{#await createProfileLinkWithVerification(npub as string, displayText)} {#await createProfileLinkWithVerification(npub as string, displayText, undefined)}
<span class="inline-flex items-center gap-0.5"> <span class="inline-flex items-center gap-0.5">
<button <button
class="npub-badge bg-transparent border-none p-0 underline cursor-pointer" class="npub-badge bg-transparent border-none p-0 underline cursor-pointer"

6
src/lib/stores/userStore.ts

@ -178,7 +178,7 @@ export async function loginWithExtension(ndk: NDK) {
let profile: NostrProfile | null = null; let profile: NostrProfile | null = null;
try { try {
console.log("Login with extension - attempting to fetch profile..."); console.log("Login with extension - attempting to fetch profile...");
profile = await getUserMetadata(npub, true); // Force fresh fetch profile = await getUserMetadata(npub, ndk, true); // Force fresh fetch
console.log("Login with extension - fetched profile:", profile); console.log("Login with extension - fetched profile:", profile);
} catch (error) { } catch (error) {
console.warn("Failed to fetch user metadata during login:", error); console.warn("Failed to fetch user metadata during login:", error);
@ -253,7 +253,7 @@ export async function loginWithAmber(amberSigner: NDKSigner, user: NDKUser, ndk:
let profile: NostrProfile | null = null; let profile: NostrProfile | null = null;
try { try {
profile = await getUserMetadata(npub, true); // Force fresh fetch profile = await getUserMetadata(npub, ndk, true); // Force fresh fetch
console.log("Login with Amber - fetched profile:", profile); console.log("Login with Amber - fetched profile:", profile);
} catch (error) { } catch (error) {
console.warn("Failed to fetch user metadata during Amber login:", error); console.warn("Failed to fetch user metadata during Amber login:", error);
@ -368,7 +368,7 @@ export async function loginWithNpub(pubkeyOrNpub: string, ndk: NDK) {
await new Promise((resolve) => setTimeout(resolve, 500)); await new Promise((resolve) => setTimeout(resolve, 500));
try { try {
profile = await getUserMetadata(npub, true); // Force fresh fetch profile = await getUserMetadata(npub, ndk, true); // Force fresh fetch
console.log("Login with npub - fetched profile:", profile); console.log("Login with npub - fetched profile:", profile);
} catch (error) { } catch (error) {
console.warn("Failed to fetch user metadata during npub login:", error); console.warn("Failed to fetch user metadata during npub login:", error);

10
src/lib/utils/markup/markupServices.ts

@ -1,3 +1,4 @@
import NDK from "@nostr-dev-kit/ndk";
import { import {
createProfileLink, createProfileLink,
getUserMetadata, getUserMetadata,
@ -85,6 +86,7 @@ export function processMediaUrl(url: string, alt?: string): string {
*/ */
export async function processNostrIdentifiersInText( export async function processNostrIdentifiersInText(
text: string, text: string,
ndk?: NDK,
): Promise<string> { ): Promise<string> {
let processedText = text; let processedText = text;
@ -113,7 +115,13 @@ export async function processNostrIdentifiersInText(
} }
// Get user metadata and create link // Get user metadata and create link
const metadata = await getUserMetadata(identifier); let metadata;
if (ndk) {
metadata = await getUserMetadata(identifier, ndk);
} else {
// Fallback when NDK is not available - just use the identifier
metadata = { name: identifier.slice(0, 8) + "..." + identifier.slice(-4) };
}
const displayText = metadata.displayName || metadata.name; const displayText = metadata.displayName || metadata.name;
const link = createProfileLink(identifier, displayText); const link = createProfileLink(identifier, displayText);

4
src/lib/utils/nostrUtils.ts

@ -67,7 +67,7 @@ function escapeRegExp(string: string): string {
*/ */
export async function getUserMetadata( export async function getUserMetadata(
identifier: string, identifier: string,
ndk: NDK, ndk?: NDK,
force = false, force = false,
): Promise<NostrProfile> { ): Promise<NostrProfile> {
// Remove nostr: prefix if present // Remove nostr: prefix if present
@ -175,7 +175,7 @@ export function createProfileLink(
export async function createProfileLinkWithVerification( export async function createProfileLinkWithVerification(
identifier: string, identifier: string,
displayText: string | undefined, displayText: string | undefined,
ndk: NDK, ndk?: NDK,
): Promise<string> { ): Promise<string> {
if (!ndk) { if (!ndk) {
return createProfileLink(identifier, displayText); return createProfileLink(identifier, displayText);

6
src/lib/utils/user_lists.ts

@ -1,4 +1,4 @@
import { ndkInstance, activeInboxRelays } from "../ndk.ts"; import { getNdkContext, activeInboxRelays } from "../ndk.ts";
import { get } from "svelte/store"; import { get } from "svelte/store";
import type { NDKEvent } from "@nostr-dev-kit/ndk"; import type { NDKEvent } from "@nostr-dev-kit/ndk";
import { userStore } from "../stores/userStore.ts"; import { userStore } from "../stores/userStore.ts";
@ -52,7 +52,7 @@ export async function fetchUserLists(
pubkey: string, pubkey: string,
listKinds: number[] = [...PEOPLE_LIST_KINDS] listKinds: number[] = [...PEOPLE_LIST_KINDS]
): Promise<UserListEvent[]> { ): Promise<UserListEvent[]> {
const ndk = get(ndkInstance); const ndk = getNdkContext();
if (!ndk) { if (!ndk) {
console.warn("fetchUserLists: No NDK instance available"); console.warn("fetchUserLists: No NDK instance available");
return []; return [];
@ -211,7 +211,7 @@ export async function updateProfileCacheForPubkeys(pubkeys: string[]): Promise<v
try { try {
console.log(`Updating profile cache for ${pubkeys.length} pubkeys`); console.log(`Updating profile cache for ${pubkeys.length} pubkeys`);
const ndk = get(ndkInstance); const ndk = getNdkContext();
if (!ndk) { if (!ndk) {
console.warn("updateProfileCacheForPubkeys: No NDK instance available"); console.warn("updateProfileCacheForPubkeys: No NDK instance available");
return; return;

2
src/routes/events/+page.svelte

@ -76,7 +76,7 @@
const npub = toNpub(pubkey); const npub = toNpub(pubkey);
if (npub) { if (npub) {
// Force fetch to ensure profile is cached // Force fetch to ensure profile is cached
await getUserMetadata(npub, true); await getUserMetadata(npub, undefined, true);
console.log(`[Events Page] Cached profile for pubkey: ${pubkey}`); console.log(`[Events Page] Cached profile for pubkey: ${pubkey}`);
} }
} catch (error) { } catch (error) {

7
src/routes/new/compose/+page.svelte

@ -6,6 +6,9 @@
import { nip19 } from "nostr-tools"; import { nip19 } from "nostr-tools";
import { publishMultipleZettels } from "$lib/services/publisher"; import { publishMultipleZettels } from "$lib/services/publisher";
import { parseAsciiDocWithMetadata } from "$lib/utils/asciidoc_metadata"; import { parseAsciiDocWithMetadata } from "$lib/utils/asciidoc_metadata";
import { getNdkContext } from "$lib/ndk";
const ndk = getNdkContext();
let content = $state(""); let content = $state("");
let showPreview = $state(false); let showPreview = $state(false);
@ -38,7 +41,7 @@
// Only used for catastrophic errors // Only used for catastrophic errors
publishResults = { successCount: 0, total: 0, errors: [error], successfulEvents: [], failedEvents: [] }; publishResults = { successCount: 0, total: 0, errors: [error], successfulEvents: [], failedEvents: [] };
}, },
}); }, ndk);
const successCount = results.filter(r => r.success).length; const successCount = results.filter(r => r.success).length;
const errors = results.filter(r => !r.success && r.error).map(r => r.error!); const errors = results.filter(r => !r.success && r.error).map(r => r.error!);
@ -91,7 +94,7 @@
onError: (error) => { onError: (error) => {
console.error('Retry failed:', error); console.error('Retry failed:', error);
}, },
}); }, ndk);
if (result[0]?.success && result[0]?.eventId) { if (result[0]?.success && result[0]?.eventId) {
// Update the successful events list // Update the successful events list

29
src/routes/publication/[type]/[identifier]/+layout.svelte

@ -6,27 +6,38 @@
// AI-NOTE: Use metadata from server-side load for SEO and social sharing // AI-NOTE: Use metadata from server-side load for SEO and social sharing
const { metadata } = data; const { metadata } = data;
// Type assertion for optional metadata properties
const meta = metadata as typeof metadata & {
title?: string;
summary?: string;
image?: string;
};
</script> </script>
<!-- TODO: Provide fallback metadata values to use if the publication is on an auth-to-read relay. --> <!-- TODO: Provide fallback metadata values to use if the publication is on an auth-to-read relay. -->
<svelte:head> <svelte:head>
<!-- Basic meta tags --> <!-- Basic meta tags -->
<title>{metadata.title}</title> <title>{meta.title || "Alexandria - Nostr Publications"}</title>
<meta name="description" content={metadata.summary} /> <meta name="description" content={meta.summary || "Read and discover long-form content on Nostr"} />
<!-- OpenGraph meta tags --> <!-- OpenGraph meta tags -->
<meta property="og:title" content={metadata.title} /> <meta property="og:title" content={meta.title || "Alexandria - Nostr Publications"} />
<meta property="og:description" content={metadata.summary} /> <meta property="og:description" content={meta.summary || "Read and discover long-form content on Nostr"} />
<meta property="og:url" content={metadata.currentUrl} /> <meta property="og:url" content={meta.currentUrl} />
<meta property="og:type" content="article" /> <meta property="og:type" content="article" />
<meta property="og:site_name" content="Alexandria" /> <meta property="og:site_name" content="Alexandria" />
<meta property="og:image" content={metadata.image} /> {#if meta.image}
<meta property="og:image" content={meta.image} />
{/if}
<!-- Twitter Card meta tags --> <!-- Twitter Card meta tags -->
<meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={metadata.title} /> <meta name="twitter:title" content={meta.title || "Alexandria - Nostr Publications"} />
<meta name="twitter:description" content={metadata.summary} /> <meta name="twitter:description" content={meta.summary || "Read and discover long-form content on Nostr"} />
<meta name="twitter:image" content={metadata.image} /> {#if meta.image}
<meta name="twitter:image" content={meta.image} />
{/if}
</svelte:head> </svelte:head>
{@render children()} {@render children()}

5
src/routes/visualize/+page.svelte

@ -578,7 +578,8 @@
profileEvents = await batchFetchProfiles( profileEvents = await batchFetchProfiles(
Array.from(allPubkeys), Array.from(allPubkeys),
(fetched, total) => { ndk,
(fetched: number, total: number) => {
profileLoadingProgress = { current: fetched, total }; profileLoadingProgress = { current: fetched, total };
} }
); );
@ -681,6 +682,7 @@
tags, tags,
existingEventIds, existingEventIds,
baseEvents, baseEvents,
ndk,
debug debug
); );
newPublications = result.publications; newPublications = result.publications;
@ -698,6 +700,7 @@
await fetchProfilesForNewEvents( await fetchProfilesForNewEvents(
newPublications, newPublications,
newContentEvents, newContentEvents,
ndk,
(progress: { current: number; total: number } | null) => { profileLoadingProgress = progress; }, (progress: { current: number; total: number } | null) => { profileLoadingProgress = progress; },
debug debug
); );

21
tests/unit/eventInput30040.test.ts

@ -18,13 +18,12 @@ vi.mock("@nostr-dev-kit/ndk", () => ({
})), })),
})); }));
// TODO: Replace with getNdkContext mock. // Mock NDK context
vi.mock("../../src/lib/ndk", () => ({ const mockNdk = {
ndkInstance: {
subscribe: vi.fn(), subscribe: vi.fn(),
}, fetchEvents: vi.fn(),
getNdk: vi.fn(() => ({})), pool: { relays: new Map() },
})); };
vi.mock("svelte/store", () => ({ vi.mock("svelte/store", () => ({
get: vi.fn(() => ({})), get: vi.fn(() => ({})),
@ -67,6 +66,7 @@ This is the content of the second section.`;
content, content,
tags, tags,
baseEvent, baseEvent,
mockNdk as any,
); );
// Test index event // Test index event
@ -163,6 +163,7 @@ This is the content of the second section.`;
content, content,
tags, tags,
baseEvent, baseEvent,
mockNdk as any,
); );
// Test index event // Test index event
@ -240,6 +241,7 @@ This is the preamble content.
content, content,
tags, tags,
baseEvent, baseEvent,
mockNdk as any,
); );
// Test index event // Test index event
@ -295,6 +297,7 @@ This is the preamble content.
content, content,
tags, tags,
baseEvent, baseEvent,
mockNdk as any,
); );
// Test index event // Test index event
@ -343,6 +346,7 @@ index card`;
content, content,
tags, tags,
baseEvent, baseEvent,
mockNdk as any,
); );
// Test index event // Test index event
@ -368,6 +372,7 @@ index card`;
content, content,
tags, tags,
baseEvent, baseEvent,
mockNdk as any,
); );
// Test index event // Test index event
@ -435,6 +440,7 @@ This is the section content.`;
content, content,
tags, tags,
baseEvent, baseEvent,
mockNdk as any,
); );
// Test index event metadata // Test index event metadata
@ -574,6 +580,7 @@ This is just preamble content.`;
content, content,
tags, tags,
baseEvent, baseEvent,
mockNdk as any,
); );
expect(indexEvent.kind).toBe(30040); expect(indexEvent.kind).toBe(30040);
@ -602,6 +609,7 @@ Content here.`;
content, content,
tags, tags,
baseEvent, baseEvent,
mockNdk as any,
); );
expect(indexEvent.kind).toBe(30040); expect(indexEvent.kind).toBe(30040);
@ -631,6 +639,7 @@ Content here.`;
content, content,
tags, tags,
baseEvent, baseEvent,
mockNdk as any,
); );
expect(indexEvent.kind).toBe(30040); expect(indexEvent.kind).toBe(30040);

14
tests/unit/tagExpansion.test.ts

@ -44,7 +44,12 @@ class MockNDKEvent {
// Mock NDK instance // Mock NDK instance
const mockNDK = { const mockNDK = {
fetchEvents: vi.fn(), fetchEvents: vi.fn(),
}; pool: {},
debug: false,
mutedIds: new Set(),
queuesZapConfig: {},
// Add other required properties as needed for the mock
} as any;
// Mock the ndkInstance store // Mock the ndkInstance store
// TODO: Replace with getNdkContext mock. // TODO: Replace with getNdkContext mock.
@ -167,6 +172,7 @@ describe("Tag Expansion Tests", () => {
["bitcoin"], ["bitcoin"],
existingEventIds, existingEventIds,
baseEvents, baseEvents,
mockNDK as any,
debug, debug,
); );
@ -205,6 +211,7 @@ describe("Tag Expansion Tests", () => {
["bitcoin"], ["bitcoin"],
existingEventIds, existingEventIds,
baseEvents, baseEvents,
mockNDK as any,
debug, debug,
); );
@ -227,6 +234,7 @@ describe("Tag Expansion Tests", () => {
[], [],
existingEventIds, existingEventIds,
baseEvents, baseEvents,
mockNDK as any,
debug, debug,
); );
@ -336,6 +344,7 @@ describe("Tag Expansion Tests", () => {
await fetchProfilesForNewEvents( await fetchProfilesForNewEvents(
mockPublications as NDKEvent[], mockPublications as NDKEvent[],
mockContentEvents as NDKEvent[], mockContentEvents as NDKEvent[],
mockNDK as any,
onProgressUpdate, onProgressUpdate,
debug, debug,
); );
@ -357,6 +366,7 @@ describe("Tag Expansion Tests", () => {
await fetchProfilesForNewEvents( await fetchProfilesForNewEvents(
[], [],
[], [],
mockNDK as any,
onProgressUpdate, onProgressUpdate,
debug, debug,
); );
@ -390,6 +400,7 @@ describe("Tag Expansion Tests", () => {
["bitcoin"], ["bitcoin"],
existingEventIds, existingEventIds,
baseEvents, baseEvents,
mockNDK as any,
debug, debug,
); );
@ -413,6 +424,7 @@ describe("Tag Expansion Tests", () => {
await fetchProfilesForNewEvents( await fetchProfilesForNewEvents(
relayResult.publications, relayResult.publications,
relayResult.contentEvents, relayResult.contentEvents,
mockNDK as any,
onProgressUpdate, onProgressUpdate,
debug, debug,
); );

Loading…
Cancel
Save