mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Merge branch 'nsite-versions' into 'main'
Add support for nsite snapshot versions See merge request soapbox-pub/shakespeare!115
This commit is contained in:
commit
f0ce172890
11 files changed
+1329
-257
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud } from 'lucide-react';
|
||||
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud, History } from 'lucide-react';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -23,7 +23,8 @@ import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
||||
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
||||
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
|
||||
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
|
||||
import { NsiteSettingsDialog } from '@/components/deploy/NsiteSettingsDialog';
|
||||
import { NsiteVersionsDialog } from '@/components/deploy/NsiteVersionsDialog';
|
||||
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
|
||||
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
|
||||
import { RailwayDeployForm } from '@/components/deploy/RailwayDeployForm';
|
||||
@@ -39,6 +40,7 @@ import { RailwayAdapter } from '@/lib/deploy/RailwayAdapter';
|
||||
import { readNsiteVfsConfig, writeNsiteVfsConfig } from '@/lib/nsiteConfig';
|
||||
import type { NsiteVfsConfig } from '@/lib/nsiteConfig';
|
||||
import { projectNameToDTag } from '@/lib/utils/nsite';
|
||||
import type { NsiteProvider } from '@/contexts/DeploySettingsContext';
|
||||
|
||||
/**
|
||||
* Normalize a URL string to ensure it has a protocol
|
||||
@@ -104,10 +106,25 @@ interface ShakespeareFormData {
|
||||
subdomain: string;
|
||||
}
|
||||
|
||||
interface NsiteFormData {
|
||||
siteTitle: string;
|
||||
siteDescription: string;
|
||||
dTag: string;
|
||||
/**
|
||||
* Build a complete NsiteVfsConfig from provider defaults — used when the
|
||||
* project has no .nsite/config.json yet. The dTag is derived from the
|
||||
* project name so the very first deploy already has a stable identifier.
|
||||
*/
|
||||
async function buildSeedNsiteConfig(
|
||||
nsiteProvider: NsiteProvider,
|
||||
projectName: string,
|
||||
): Promise<NsiteVfsConfig> {
|
||||
const dTag = await projectNameToDTag(projectName);
|
||||
return {
|
||||
relays: nsiteProvider.relayUrls,
|
||||
servers: nsiteProvider.blossomServers,
|
||||
id: dTag,
|
||||
title: projectName,
|
||||
fallback: '/index.html',
|
||||
gatewayHostnames: [nsiteProvider.gateway],
|
||||
publishSnapshotOnDeploy: false,
|
||||
};
|
||||
}
|
||||
|
||||
interface NetlifyFormData {
|
||||
@@ -154,12 +171,14 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
|
||||
|
||||
// .nsite/config.json state — loaded once on mount, used to skip config form on re-deploy
|
||||
// .nsite/config.json state — loaded once on mount. Source of truth for all
|
||||
// per-project site settings (relays, servers, title, etc.). Editable via the
|
||||
// NsiteSettingsDialog. When the project has no config yet, we auto-seed one
|
||||
// from the selected nsite provider so deploy works out of the box.
|
||||
const [nsiteVfsConfig, setNsiteVfsConfig] = useState<NsiteVfsConfig | null>(null);
|
||||
const [nsiteVfsConfigLoading, setNsiteVfsConfigLoading] = useState(true);
|
||||
// When a .nsite/config.json already exists, hide the full form and show a summary instead.
|
||||
// The user can click "Edit" to expand it.
|
||||
const [nsiteShowFullForm, setNsiteShowFullForm] = useState(false);
|
||||
const [nsiteSettingsOpen, setNsiteSettingsOpen] = useState(false);
|
||||
const [nsiteVersionsOpen, setNsiteVersionsOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!projectId) {
|
||||
@@ -167,22 +186,9 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
return;
|
||||
}
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
setNsiteVfsConfigLoading(true);
|
||||
readNsiteVfsConfig(fs, projectPath)
|
||||
.then((cfg) => {
|
||||
setNsiteVfsConfig(cfg);
|
||||
// If a config already exists, seed the form from it and stay in summary mode.
|
||||
// If not, show the full form so the user can configure for the first time.
|
||||
if (cfg) {
|
||||
setNsiteForm({
|
||||
siteTitle: cfg.title ?? '',
|
||||
siteDescription: cfg.description ?? '',
|
||||
dTag: (cfg.id != null && cfg.id !== '') ? cfg.id : '',
|
||||
});
|
||||
setNsiteShowFullForm(false);
|
||||
} else {
|
||||
setNsiteShowFullForm(true);
|
||||
}
|
||||
})
|
||||
.then((cfg) => setNsiteVfsConfig(cfg))
|
||||
.finally(() => setNsiteVfsConfigLoading(false));
|
||||
}, [fs, projectsPath, projectId]);
|
||||
|
||||
@@ -190,11 +196,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
|
||||
subdomain: projectId,
|
||||
});
|
||||
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
|
||||
siteTitle: '',
|
||||
siteDescription: '',
|
||||
dTag: '',
|
||||
});
|
||||
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
|
||||
siteId: '',
|
||||
siteName: '',
|
||||
@@ -233,6 +234,46 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
|
||||
const selectedProvider = settings.providers.find(p => p.id === selectedProviderId);
|
||||
|
||||
// Auto-seed .nsite/config.json from the provider when:
|
||||
// - an nsite provider is selected,
|
||||
// - the load effect has finished,
|
||||
// - and the project has no config yet.
|
||||
// This means a fresh project immediately surfaces a summary card with sane
|
||||
// defaults and the user can edit anytime via the settings dialog.
|
||||
useEffect(() => {
|
||||
if (!projectId) return;
|
||||
if (nsiteVfsConfigLoading) return;
|
||||
if (nsiteVfsConfig) return;
|
||||
if (selectedProvider?.type !== 'nsite') return;
|
||||
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
let cancelled = false;
|
||||
|
||||
buildSeedNsiteConfig(selectedProvider, projectName || projectId)
|
||||
.then(async (cfg) => {
|
||||
if (cancelled) return;
|
||||
try {
|
||||
await writeNsiteVfsConfig(fs, projectPath, cfg);
|
||||
if (cancelled) return;
|
||||
setNsiteVfsConfig(cfg);
|
||||
} catch (err) {
|
||||
console.warn('Failed to auto-seed .nsite/config.json:', err);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [
|
||||
projectId,
|
||||
projectsPath,
|
||||
nsiteVfsConfig,
|
||||
nsiteVfsConfigLoading,
|
||||
selectedProvider,
|
||||
fs,
|
||||
projectName,
|
||||
]);
|
||||
|
||||
const handleDeploy = async () => {
|
||||
if (!selectedProvider) return;
|
||||
|
||||
@@ -265,21 +306,28 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
throw new Error('You must be logged in to deploy to nsite.');
|
||||
}
|
||||
|
||||
if (!nsiteVfsConfig) {
|
||||
throw new Error('nsite settings are not configured for this project yet.');
|
||||
}
|
||||
|
||||
const sourceUrl = await resolveNsiteSourceUrl(
|
||||
await git.getRemoteURL(projectPath, 'origin')
|
||||
);
|
||||
|
||||
// Source of truth is .nsite/config.json — provider only contributes the
|
||||
// gateway (host-level, not a manifest field).
|
||||
adapter = new NsiteAdapter({
|
||||
fs,
|
||||
nostr,
|
||||
signer: user.signer,
|
||||
gateway: nsiteProvider.gateway,
|
||||
relayUrls: nsiteProvider.relayUrls,
|
||||
blossomServers: nsiteProvider.blossomServers,
|
||||
siteTitle: nsiteForm.siteTitle || undefined,
|
||||
siteDescription: nsiteForm.siteDescription || undefined,
|
||||
relayUrls: nsiteVfsConfig.relays,
|
||||
blossomServers: nsiteVfsConfig.servers,
|
||||
siteTitle: nsiteVfsConfig.title || undefined,
|
||||
siteDescription: nsiteVfsConfig.description || undefined,
|
||||
sourceUrl,
|
||||
siteIdentifier: nsiteForm.dTag || undefined,
|
||||
siteIdentifier: (nsiteVfsConfig.id != null && nsiteVfsConfig.id !== '') ? nsiteVfsConfig.id : undefined,
|
||||
publishSnapshotOnDeploy: nsiteVfsConfig.publishSnapshotOnDeploy ?? false,
|
||||
});
|
||||
} else if (selectedProvider.type === 'netlify') {
|
||||
const netlifyProvider = selectedProvider;
|
||||
@@ -388,28 +436,23 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
type: 'nsite',
|
||||
url: result.url,
|
||||
data: {
|
||||
siteTitle: nsiteForm.siteTitle || undefined,
|
||||
siteDescription: nsiteForm.siteDescription || undefined,
|
||||
dTag: nsiteForm.dTag || undefined,
|
||||
siteTitle: nsiteVfsConfig?.title || undefined,
|
||||
siteDescription: nsiteVfsConfig?.description || undefined,
|
||||
dTag: nsiteVfsConfig?.id || undefined,
|
||||
},
|
||||
});
|
||||
|
||||
// Write .nsite/config.json for nsyte CLI interoperability.
|
||||
// This file is safe to commit — it never contains the nsec.
|
||||
const nsiteProvider = selectedProvider;
|
||||
const newNsiteVfsConfig: NsiteVfsConfig = {
|
||||
relays: nsiteProvider.relayUrls,
|
||||
servers: nsiteProvider.blossomServers,
|
||||
id: nsiteForm.dTag || undefined,
|
||||
title: nsiteForm.siteTitle || undefined,
|
||||
description: nsiteForm.siteDescription || undefined,
|
||||
fallback: '/index.html',
|
||||
gatewayHostnames: [nsiteProvider.gateway],
|
||||
};
|
||||
await writeNsiteVfsConfig(fs, projectPath, newNsiteVfsConfig);
|
||||
// Update in-memory state so summary view reflects new values immediately
|
||||
setNsiteVfsConfig(newNsiteVfsConfig);
|
||||
setNsiteShowFullForm(false);
|
||||
// Refresh .nsite/config.json's gatewayHostnames so the file reflects
|
||||
// the most recent provider the project actually deployed through.
|
||||
// All other fields are already authoritative on disk.
|
||||
if (nsiteVfsConfig) {
|
||||
const refreshed: NsiteVfsConfig = {
|
||||
...nsiteVfsConfig,
|
||||
gatewayHostnames: [selectedProvider.gateway],
|
||||
};
|
||||
await writeNsiteVfsConfig(fs, projectPath, refreshed);
|
||||
setNsiteVfsConfig(refreshed);
|
||||
}
|
||||
} else if (selectedProvider.type === 'netlify') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'netlify',
|
||||
@@ -517,14 +560,12 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
setError(null);
|
||||
// Reset forms
|
||||
setShakespeareForm({ subdomain: projectId });
|
||||
setNsiteForm({ siteTitle: '', siteDescription: '', dTag: '' });
|
||||
setNetlifyForm({ siteId: '', siteName: '' });
|
||||
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
||||
setCloudflareForm({ projectName: projectName || projectId });
|
||||
setDenoDeployForm({ projectName: projectName || projectId });
|
||||
setRailwayForm({ workspaceId: '', projectId: '', environmentId: '', serviceId: '', projectName: projectName || projectId });
|
||||
// Return to summary mode so next open shows the compact view (if config exists)
|
||||
setNsiteShowFullForm(false);
|
||||
setNsiteSettingsOpen(false);
|
||||
onClose();
|
||||
};
|
||||
|
||||
@@ -536,18 +577,12 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
setIsShakespeareFormValid(isValid);
|
||||
}, []);
|
||||
|
||||
const handleNsiteSiteTitleChange = useCallback((siteTitle: string) => {
|
||||
setNsiteForm(prev => ({ ...prev, siteTitle }));
|
||||
// Derive the dTag from the title so the user never has to think about it.
|
||||
// Falls back to projectName when the title is blank.
|
||||
projectNameToDTag(siteTitle || projectName).then(dTag => {
|
||||
setNsiteForm(prev => ({ ...prev, dTag }));
|
||||
});
|
||||
}, [projectName]);
|
||||
|
||||
const handleNsiteSiteDescriptionChange = useCallback((siteDescription: string) => {
|
||||
setNsiteForm(prev => ({ ...prev, siteDescription }));
|
||||
}, []);
|
||||
const handleNsiteSettingsSave = useCallback(async (cfg: NsiteVfsConfig) => {
|
||||
if (!projectId) return;
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
await writeNsiteVfsConfig(fs, projectPath, cfg);
|
||||
setNsiteVfsConfig(cfg);
|
||||
}, [projectId, projectsPath, fs]);
|
||||
|
||||
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
|
||||
setNetlifyForm({ siteId, siteName });
|
||||
@@ -595,72 +630,30 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'nsite') {
|
||||
// While the .nsite/config.json load is still in flight, render nothing to avoid flicker
|
||||
if (nsiteVfsConfigLoading) return null;
|
||||
// While the .nsite/config.json load + auto-seed is still in flight,
|
||||
// render nothing to avoid flicker.
|
||||
if (nsiteVfsConfigLoading || !nsiteVfsConfig) return null;
|
||||
|
||||
// Summary view: shown when .nsite/config.json already exists and user hasn't clicked Edit
|
||||
if (nsiteVfsConfig && !nsiteShowFullForm) {
|
||||
const relayCount = nsiteVfsConfig.relays?.length ?? 0;
|
||||
const serverCount = nsiteVfsConfig.servers?.length ?? 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-md border bg-muted/30 p-3 space-y-2 text-sm">
|
||||
{nsiteVfsConfig.title && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Title</span>
|
||||
<span className="font-medium">{nsiteVfsConfig.title}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Relays</span>
|
||||
<span className="font-medium">{relayCount} configured</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Blossom servers</span>
|
||||
<span className="font-medium">{serverCount} configured</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground underline hover:text-foreground transition-colors"
|
||||
onClick={() => setNsiteShowFullForm(true)}
|
||||
>
|
||||
Edit site settings
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Full config form: shown on first deploy or when user clicks "Edit site settings"
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const legacy = savedConfig?.type === 'nsite' ? savedConfig.data : undefined;
|
||||
|
||||
// .nsite/config.json wins; .git/shakespeare/deploy.json is the legacy fallback
|
||||
const savedSiteTitle = nsiteVfsConfig?.title ?? legacy?.siteTitle;
|
||||
const savedSiteDescription = nsiteVfsConfig?.description ?? legacy?.siteDescription;
|
||||
const relayCount = nsiteVfsConfig.relays?.length ?? 0;
|
||||
const serverCount = nsiteVfsConfig.servers?.length ?? 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<NsiteDeployForm
|
||||
key={selectedProviderId}
|
||||
projectName={projectName || projectId}
|
||||
savedNsec={legacy?.nsec}
|
||||
savedSiteTitle={savedSiteTitle}
|
||||
savedSiteDescription={savedSiteDescription}
|
||||
onSiteTitleChange={handleNsiteSiteTitleChange}
|
||||
onSiteDescriptionChange={handleNsiteSiteDescriptionChange}
|
||||
/>
|
||||
{nsiteVfsConfig && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground underline hover:text-foreground transition-colors"
|
||||
onClick={() => setNsiteShowFullForm(false)}
|
||||
>
|
||||
Back to summary
|
||||
</button>
|
||||
<div className="rounded-md border bg-muted/30 p-3 space-y-2 text-sm">
|
||||
{nsiteVfsConfig.title && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Title</span>
|
||||
<span className="font-medium">{nsiteVfsConfig.title}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Relays</span>
|
||||
<span className="font-medium">{relayCount} configured</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Blossom servers</span>
|
||||
<span className="font-medium">{serverCount} configured</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -767,6 +760,27 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{nsiteVfsConfig && (
|
||||
<NsiteSettingsDialog
|
||||
open={nsiteSettingsOpen}
|
||||
onOpenChange={setNsiteSettingsOpen}
|
||||
projectName={projectName || projectId}
|
||||
initialConfig={nsiteVfsConfig}
|
||||
onSave={handleNsiteSettingsSave}
|
||||
/>
|
||||
)}
|
||||
|
||||
{nsiteVfsConfig && user && selectedProvider?.type === 'nsite' && (
|
||||
<NsiteVersionsDialog
|
||||
open={nsiteVersionsOpen}
|
||||
onOpenChange={setNsiteVersionsOpen}
|
||||
pubkey={user.pubkey}
|
||||
siteIdentifier={(nsiteVfsConfig.id != null && nsiteVfsConfig.id !== '') ? nsiteVfsConfig.id : undefined}
|
||||
gateway={selectedProvider.gateway}
|
||||
relayUrls={nsiteVfsConfig.relays}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<h3 className="font-semibold mb-1">Deploy your project</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
@@ -946,33 +960,62 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
)}
|
||||
|
||||
{selectedProvider && (
|
||||
<Button
|
||||
onClick={handleDeploy}
|
||||
disabled={
|
||||
isDeploying ||
|
||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
|
||||
(selectedProvider.type === 'nsite' && !user) ||
|
||||
(selectedProvider.type === 'nsite' && !nsiteForm.dTag) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
|
||||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
|
||||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
|
||||
(selectedProvider.type === 'railway' && !railwayForm.workspaceId)
|
||||
}
|
||||
className="w-full"
|
||||
>
|
||||
{isDeploying ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
|
||||
Deploying...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Rocket className="h-4 w-4 mr-2" />
|
||||
Deploy
|
||||
</>
|
||||
<div className="flex gap-2">
|
||||
{selectedProvider.type === 'nsite' && nsiteVfsConfig && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => setNsiteSettingsOpen(true)}
|
||||
title="Site settings"
|
||||
aria-label="Site settings"
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={handleDeploy}
|
||||
disabled={
|
||||
isDeploying ||
|
||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
|
||||
(selectedProvider.type === 'nsite' && !user) ||
|
||||
(selectedProvider.type === 'nsite' && !nsiteVfsConfig) ||
|
||||
(selectedProvider.type === 'nsite' && (!nsiteVfsConfig?.relays?.length || !nsiteVfsConfig?.servers?.length)) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
|
||||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
|
||||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
|
||||
(selectedProvider.type === 'railway' && !railwayForm.workspaceId)
|
||||
}
|
||||
className="flex-1"
|
||||
>
|
||||
{isDeploying ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
|
||||
Deploying...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Rocket className="h-4 w-4 mr-2" />
|
||||
Deploy
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{selectedProvider.type === 'nsite' && nsiteVfsConfig?.publishSnapshotOnDeploy && user && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => setNsiteVersionsOpen(true)}
|
||||
title="Version history"
|
||||
aria-label="Version history"
|
||||
>
|
||||
<History className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1,105 +1,161 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
import { AlertCircle } from "lucide-react";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
|
||||
interface NsiteDeployFormProps {
|
||||
/** Human-readable project name — used to default the title */
|
||||
projectName: string;
|
||||
/** Persisted values from a previous deployment */
|
||||
savedSiteTitle?: string;
|
||||
savedSiteDescription?: string;
|
||||
/** Present only when the project was previously deployed with a dedicated keypair (v1) */
|
||||
savedNsec?: string;
|
||||
onSiteTitleChange: (title: string) => void;
|
||||
onSiteDescriptionChange: (description: string) => void;
|
||||
/** Human-readable project name — used to default the title */
|
||||
projectName: string;
|
||||
/** Persisted values from a previous deployment */
|
||||
savedSiteTitle?: string;
|
||||
savedSiteDescription?: string;
|
||||
savedPublishSnapshotOnDeploy?: boolean;
|
||||
/** Present only when the project was previously deployed with a dedicated keypair (v1) */
|
||||
savedNsec?: string;
|
||||
onSiteTitleChange: (title: string) => void;
|
||||
onSiteDescriptionChange: (description: string) => void;
|
||||
onPublishSnapshotOnDeployChange: (enabled: boolean) => void;
|
||||
}
|
||||
|
||||
export function NsiteDeployForm({
|
||||
projectName,
|
||||
savedSiteTitle,
|
||||
savedSiteDescription,
|
||||
savedNsec,
|
||||
onSiteTitleChange,
|
||||
onSiteDescriptionChange,
|
||||
projectName,
|
||||
savedSiteTitle,
|
||||
savedSiteDescription,
|
||||
savedPublishSnapshotOnDeploy,
|
||||
savedNsec,
|
||||
onSiteTitleChange,
|
||||
onSiteDescriptionChange,
|
||||
onPublishSnapshotOnDeployChange,
|
||||
}: NsiteDeployFormProps) {
|
||||
const [siteTitle, setSiteTitle] = useState(savedSiteTitle ?? projectName);
|
||||
const [siteDescription, setSiteDescription] = useState(savedSiteDescription ?? '');
|
||||
const [siteTitle, setSiteTitle] = useState(savedSiteTitle ?? projectName);
|
||||
const [siteDescription, setSiteDescription] = useState(
|
||||
savedSiteDescription ?? "",
|
||||
);
|
||||
const [publishSnapshotOnDeploy, setPublishSnapshotOnDeploy] = useState(
|
||||
savedPublishSnapshotOnDeploy ?? false,
|
||||
);
|
||||
|
||||
// On mount: sync all saved values to parent and set defaults.
|
||||
// The component is keyed by selectedProviderId in DeploySteps, so this always
|
||||
// runs with fresh props — no initialized guard needed.
|
||||
const initializedRef = useRef(false);
|
||||
const stableSyncToParent = useCallback(() => {
|
||||
if (initializedRef.current) return;
|
||||
initializedRef.current = true;
|
||||
// On mount: sync all saved values to parent and set defaults.
|
||||
// The component is keyed by selectedProviderId in DeploySteps, so this always
|
||||
// runs with fresh props — no initialized guard needed.
|
||||
const initializedRef = useRef(false);
|
||||
const stableSyncToParent = useCallback(() => {
|
||||
if (initializedRef.current) return;
|
||||
initializedRef.current = true;
|
||||
|
||||
if (savedSiteDescription) onSiteDescriptionChange(savedSiteDescription);
|
||||
if (savedSiteDescription) onSiteDescriptionChange(savedSiteDescription);
|
||||
|
||||
const initialTitle = savedSiteTitle ?? projectName;
|
||||
if (initialTitle !== siteTitle) setSiteTitle(initialTitle);
|
||||
onSiteTitleChange(initialTitle);
|
||||
}, [savedSiteDescription, savedSiteTitle, siteTitle, projectName, onSiteDescriptionChange, onSiteTitleChange]);
|
||||
const initialTitle = savedSiteTitle ?? projectName;
|
||||
if (initialTitle !== siteTitle) setSiteTitle(initialTitle);
|
||||
onSiteTitleChange(initialTitle);
|
||||
|
||||
useEffect(() => {
|
||||
stableSyncToParent();
|
||||
}, [stableSyncToParent]);
|
||||
onPublishSnapshotOnDeployChange(savedPublishSnapshotOnDeploy ?? false);
|
||||
}, [
|
||||
savedSiteDescription,
|
||||
savedSiteTitle,
|
||||
savedPublishSnapshotOnDeploy,
|
||||
siteTitle,
|
||||
projectName,
|
||||
onSiteDescriptionChange,
|
||||
onSiteTitleChange,
|
||||
onPublishSnapshotOnDeployChange,
|
||||
]);
|
||||
|
||||
const handleSiteTitleChange = (value: string) => {
|
||||
setSiteTitle(value);
|
||||
onSiteTitleChange(value);
|
||||
};
|
||||
useEffect(() => {
|
||||
stableSyncToParent();
|
||||
}, [stableSyncToParent]);
|
||||
|
||||
const handleSiteDescriptionChange = (value: string) => {
|
||||
setSiteDescription(value);
|
||||
onSiteDescriptionChange(value);
|
||||
};
|
||||
const handleSiteTitleChange = (value: string) => {
|
||||
setSiteTitle(value);
|
||||
onSiteTitleChange(value);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
const handleSiteDescriptionChange = (value: string) => {
|
||||
setSiteDescription(value);
|
||||
onSiteDescriptionChange(value);
|
||||
};
|
||||
|
||||
{/* Migration notice */}
|
||||
{savedNsec && (
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
<strong>Site identity is changing.</strong> This project was previously deployed with a
|
||||
dedicated private key. Going forward, it will deploy under your Nostr identity. The old
|
||||
site will remain at its original address until overwritten.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
const handlePublishSnapshotOnDeployChange = (value: boolean) => {
|
||||
setPublishSnapshotOnDeploy(value);
|
||||
onPublishSnapshotOnDeployChange(value);
|
||||
};
|
||||
|
||||
{/* Site title */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nsite-title">Site Title</Label>
|
||||
<Input
|
||||
id="nsite-title"
|
||||
value={siteTitle}
|
||||
onChange={(e) => handleSiteTitleChange(e.target.value)}
|
||||
placeholder="My Nostr Site"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Shown by nsite gateways and directories. Included as a title tag in the manifest.
|
||||
</p>
|
||||
</div>
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Migration notice */}
|
||||
{savedNsec && (
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
<strong>Site identity is changing.</strong> This project was
|
||||
previously deployed with a dedicated private key. Going forward, it
|
||||
will deploy under your Nostr identity. The old site will remain at
|
||||
its original address until overwritten.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Site description */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nsite-description">Description <span className="text-muted-foreground font-normal">(optional)</span></Label>
|
||||
<Textarea
|
||||
id="nsite-description"
|
||||
value={siteDescription}
|
||||
onChange={(e) => handleSiteDescriptionChange(e.target.value)}
|
||||
placeholder="A short description of this site…"
|
||||
rows={3}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Included as a description tag in the manifest.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
{/* Site title */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nsite-title">Site Title</Label>
|
||||
<Input
|
||||
id="nsite-title"
|
||||
value={siteTitle}
|
||||
onChange={(e) => handleSiteTitleChange(e.target.value)}
|
||||
placeholder="My Nostr Site"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Shown by nsite gateways and directories. Included as a title tag in
|
||||
the manifest.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Site description */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nsite-description">
|
||||
Description{" "}
|
||||
<span className="text-muted-foreground font-normal">(optional)</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id="nsite-description"
|
||||
value={siteDescription}
|
||||
onChange={(e) => handleSiteDescriptionChange(e.target.value)}
|
||||
placeholder="A short description of this site…"
|
||||
rows={3}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Included as a description tag in the manifest.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Version history toggle */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-start space-x-2">
|
||||
<Checkbox
|
||||
id="nsite-publish-snapshot-on-deploy"
|
||||
checked={publishSnapshotOnDeploy}
|
||||
onCheckedChange={(checked) =>
|
||||
handlePublishSnapshotOnDeployChange(checked === true)
|
||||
}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div className="space-y-1 leading-none">
|
||||
<Label
|
||||
htmlFor="nsite-publish-snapshot-on-deploy"
|
||||
className="text-sm font-medium cursor-pointer"
|
||||
>
|
||||
Publish version history
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Publishes a version each time the app is deployed. This allows
|
||||
users to use older versions of the app.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible';
|
||||
import { UrlListEditor } from '@/components/UrlListEditor';
|
||||
import { projectNameToDTag } from '@/lib/utils/nsite';
|
||||
import type { NsiteVfsConfig } from '@/lib/nsiteConfig';
|
||||
|
||||
interface NsiteSettingsDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** Used to default the title when blank */
|
||||
projectName: string;
|
||||
/** Current persisted config — controls initial field values */
|
||||
initialConfig: NsiteVfsConfig;
|
||||
/** Called with the new config when the user clicks Save. May throw. */
|
||||
onSave: (cfg: NsiteVfsConfig) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-project nsite settings editor.
|
||||
*
|
||||
* Edits the full `.nsite/config.json` for a project: title, description,
|
||||
* relays, blossom servers, and the "publish version history" flag. The `d`
|
||||
* tag identifier is auto-derived from the title on save and never surfaced
|
||||
* in the UI.
|
||||
*
|
||||
* The `gatewayHostnames` and `fallback` fields are preserved untouched so
|
||||
* provider/CLI-managed metadata isn't clobbered.
|
||||
*/
|
||||
export function NsiteSettingsDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
projectName,
|
||||
initialConfig,
|
||||
onSave,
|
||||
}: NsiteSettingsDialogProps) {
|
||||
const [title, setTitle] = useState(initialConfig.title ?? '');
|
||||
const [description, setDescription] = useState(initialConfig.description ?? '');
|
||||
const [relays, setRelays] = useState<string[]>(initialConfig.relays ?? []);
|
||||
const [servers, setServers] = useState<string[]>(initialConfig.servers ?? []);
|
||||
const [publishSnapshotOnDeploy, setPublishSnapshotOnDeploy] = useState(
|
||||
initialConfig.publishSnapshotOnDeploy ?? false,
|
||||
);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||
|
||||
// Reset local state whenever the dialog re-opens with a different config
|
||||
// (e.g. after a save from another tab, or when switching projects).
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setTitle(initialConfig.title ?? '');
|
||||
setDescription(initialConfig.description ?? '');
|
||||
setRelays(initialConfig.relays ?? []);
|
||||
setServers(initialConfig.servers ?? []);
|
||||
setPublishSnapshotOnDeploy(initialConfig.publishSnapshotOnDeploy ?? false);
|
||||
setError(null);
|
||||
setAdvancedOpen(false);
|
||||
}, [open, initialConfig]);
|
||||
|
||||
const hasRelays = relays.length > 0;
|
||||
const hasServers = servers.length > 0;
|
||||
const canSave = hasRelays && hasServers && !saving;
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!canSave) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const effectiveTitle = title.trim() || projectName;
|
||||
const dTag = await projectNameToDTag(effectiveTitle);
|
||||
|
||||
const cfg: NsiteVfsConfig = {
|
||||
...initialConfig,
|
||||
relays,
|
||||
servers,
|
||||
id: dTag,
|
||||
title: title.trim() || undefined,
|
||||
description: description.trim() || undefined,
|
||||
fallback: initialConfig.fallback ?? '/index.html',
|
||||
publishSnapshotOnDeploy,
|
||||
};
|
||||
|
||||
await onSave(cfg);
|
||||
onOpenChange(false);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to save settings');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg max-h-[85vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>nsite settings</DialogTitle>
|
||||
<DialogDescription>
|
||||
Per-project configuration for this nsite deployment. Saved to <code>.nsite/config.json</code>.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-2">
|
||||
{/* Title */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nsite-settings-title">Site Title</Label>
|
||||
<Input
|
||||
id="nsite-settings-title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder={projectName}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Shown by nsite gateways and directories. Defaults to the project name when blank.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nsite-settings-description">
|
||||
Description <span className="text-muted-foreground font-normal">(optional)</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id="nsite-settings-description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="A short description of this site…"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Version history */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-start space-x-2">
|
||||
<Checkbox
|
||||
id="nsite-settings-publish-snapshot"
|
||||
checked={publishSnapshotOnDeploy}
|
||||
onCheckedChange={(checked) =>
|
||||
setPublishSnapshotOnDeploy(checked === true)
|
||||
}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div className="space-y-1 leading-none">
|
||||
<Label
|
||||
htmlFor="nsite-settings-publish-snapshot"
|
||||
className="text-sm font-medium cursor-pointer"
|
||||
>
|
||||
Publish version history
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Publishes a version each time the app is deployed. This allows users to use older versions of the app.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Advanced: relays + blossom servers */}
|
||||
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center gap-2 w-full text-sm text-muted-foreground hover:text-foreground transition-colors py-2 border-t"
|
||||
>
|
||||
<ChevronDown
|
||||
className={`h-4 w-4 transition-transform ${advancedOpen ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
<span>Advanced</span>
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="space-y-4 pt-2">
|
||||
<UrlListEditor
|
||||
label="Relays"
|
||||
items={relays}
|
||||
onChange={setRelays}
|
||||
protocol="wss"
|
||||
placeholder="relay.ditto.pub"
|
||||
required
|
||||
/>
|
||||
<UrlListEditor
|
||||
label="Blossom Servers"
|
||||
items={servers}
|
||||
onChange={setServers}
|
||||
protocol="https"
|
||||
placeholder="blossom.ditto.pub"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={!canSave}>
|
||||
{saving ? 'Saving…' : 'Save'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { ExternalLink, History, Loader2, Trash2 } from 'lucide-react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { buildNsiteParentRef } from '@/lib/utils/nsiteAggregateHash';
|
||||
import { buildNsiteSnapshotUrl } from '@/lib/utils/nsite';
|
||||
|
||||
const NSITE_SNAPSHOT_KIND = 5128;
|
||||
const QUERY_LIMIT = 500;
|
||||
const QUERY_TIMEOUT_MS = 8_000;
|
||||
|
||||
interface NsiteVersionsDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** Author of the snapshots — typically the logged-in user's pubkey */
|
||||
pubkey: string;
|
||||
/** Named-site dTag (empty for root sites) */
|
||||
siteIdentifier?: string;
|
||||
/** Gateway hostname used to build snapshot URLs (e.g. "nsite.lol") */
|
||||
gateway: string;
|
||||
/** Relays to query and to publish deletion events through */
|
||||
relayUrls: string[];
|
||||
}
|
||||
|
||||
interface VersionRow {
|
||||
id: string;
|
||||
createdAt: number;
|
||||
fileCount: number;
|
||||
/** Lower-case aggregate hash hex if present on the event */
|
||||
aggregateHash?: string;
|
||||
}
|
||||
|
||||
function countPathTags(event: NostrEvent): number {
|
||||
let n = 0;
|
||||
for (const tag of event.tags) {
|
||||
if (tag[0] === 'path') n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function extractAggregateHash(event: NostrEvent): string | undefined {
|
||||
for (const tag of event.tags) {
|
||||
if (tag[0] === 'x' && tag[2] === 'aggregate') return tag[1];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const dateFormatter = new Intl.DateTimeFormat(undefined, {
|
||||
dateStyle: 'medium',
|
||||
timeStyle: 'short',
|
||||
});
|
||||
|
||||
export function NsiteVersionsDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
pubkey,
|
||||
siteIdentifier,
|
||||
gateway,
|
||||
relayUrls,
|
||||
}: NsiteVersionsDialogProps) {
|
||||
const { nostr } = useNostr();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
|
||||
const [versions, setVersions] = useState<VersionRow[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Pending delete: which event id is awaiting confirmation
|
||||
const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
|
||||
// Currently in-flight deletions (event ids)
|
||||
const [deletingIds, setDeletingIds] = useState<Set<string>>(new Set());
|
||||
|
||||
const parentRef = buildNsiteParentRef(pubkey, siteIdentifier);
|
||||
|
||||
const loadVersions = useCallback(async () => {
|
||||
if (!pubkey) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const relayClient = nostr.group(relayUrls);
|
||||
const signal = AbortSignal.timeout(QUERY_TIMEOUT_MS);
|
||||
|
||||
// Fetch snapshots and the user's NIP-09 delete events in parallel.
|
||||
// The delete query is scoped to kind 5128 (the snapshot kind) so it
|
||||
// returns only deletions relevant to nsite versions.
|
||||
const [snapshotEvents, deleteEvents] = await Promise.all([
|
||||
relayClient.query(
|
||||
[{
|
||||
kinds: [NSITE_SNAPSHOT_KIND],
|
||||
authors: [pubkey],
|
||||
'#a': [parentRef],
|
||||
limit: QUERY_LIMIT,
|
||||
}],
|
||||
{ signal },
|
||||
),
|
||||
relayClient.query(
|
||||
[{
|
||||
kinds: [5],
|
||||
authors: [pubkey],
|
||||
'#k': [String(NSITE_SNAPSHOT_KIND)],
|
||||
limit: QUERY_LIMIT,
|
||||
}],
|
||||
{ signal },
|
||||
).catch(() => []),
|
||||
]);
|
||||
|
||||
// Collect every event id targeted by a delete event authored by this
|
||||
// user (NIP-09 requires author match, which the filter already enforces).
|
||||
const deletedIds = new Set<string>();
|
||||
for (const ev of deleteEvents) {
|
||||
for (const tag of ev.tags) {
|
||||
if (tag[0] === 'e' && tag[1]) deletedIds.add(tag[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// Dedup by event id (relays may return duplicates), filter out tombstones,
|
||||
// and sort newest-first.
|
||||
const byId = new Map<string, NostrEvent>();
|
||||
for (const ev of snapshotEvents) {
|
||||
if (deletedIds.has(ev.id)) continue;
|
||||
byId.set(ev.id, ev);
|
||||
}
|
||||
|
||||
const rows: VersionRow[] = Array.from(byId.values())
|
||||
.sort((a, b) => b.created_at - a.created_at)
|
||||
.map(ev => ({
|
||||
id: ev.id,
|
||||
createdAt: ev.created_at,
|
||||
fileCount: countPathTags(ev),
|
||||
aggregateHash: extractAggregateHash(ev),
|
||||
}));
|
||||
|
||||
setVersions(rows);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load versions');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [nostr, relayUrls, pubkey, parentRef]);
|
||||
|
||||
// Refetch each time the dialog opens so the list is fresh after a new deploy.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
loadVersions();
|
||||
}, [open, loadVersions]);
|
||||
|
||||
const handleDelete = async (eventId: string) => {
|
||||
setConfirmDeleteId(null);
|
||||
setDeletingIds(prev => new Set(prev).add(eventId));
|
||||
try {
|
||||
// NIP-09 deletion: kind 5 event with `e` tag for the event id and `k` tag
|
||||
// for its kind so clients can scope the deletion intent.
|
||||
await publishEvent({
|
||||
kind: 5,
|
||||
content: '',
|
||||
tags: [
|
||||
['e', eventId],
|
||||
['k', String(NSITE_SNAPSHOT_KIND)],
|
||||
],
|
||||
});
|
||||
// Optimistically drop from the list — relay propagation is best-effort.
|
||||
setVersions(prev => prev.filter(v => v.id !== eventId));
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete version');
|
||||
} finally {
|
||||
setDeletingIds(prev => {
|
||||
const next = new Set(prev);
|
||||
next.delete(eventId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const pendingDelete = confirmDeleteId
|
||||
? versions.find(v => v.id === confirmDeleteId)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg max-h-[85vh] overflow-hidden flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<History className="h-4 w-4" />
|
||||
Version history
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Snapshots published for this nsite. Each version is a permanent,
|
||||
shareable copy of the site at the time it was deployed.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto -mx-6 px-6">
|
||||
{loading && versions.length === 0 ? (
|
||||
<div className="flex items-center justify-center py-12 text-muted-foreground">
|
||||
<Loader2 className="h-5 w-5 animate-spin mr-2" />
|
||||
<span className="text-sm">Loading versions…</span>
|
||||
</div>
|
||||
) : error ? (
|
||||
<p className="text-sm text-destructive py-4">{error}</p>
|
||||
) : versions.length === 0 ? (
|
||||
<div className="py-12 text-center text-sm text-muted-foreground">
|
||||
<p className="mb-2">No published versions yet.</p>
|
||||
<p className="text-xs">
|
||||
Enable "Publish version history" in site settings to start
|
||||
tracking deploys.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="divide-y">
|
||||
{versions.map((v) => {
|
||||
const url = buildNsiteSnapshotUrl({ eventIdHex: v.id, gateway });
|
||||
const deleting = deletingIds.has(v.id);
|
||||
return (
|
||||
<li key={v.id} className="py-3 flex items-center gap-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium">
|
||||
{dateFormatter.format(new Date(v.createdAt * 1000))}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{v.fileCount} {v.fileCount === 1 ? 'file' : 'files'}
|
||||
{v.aggregateHash && (
|
||||
<>
|
||||
<span className="mx-1.5">·</span>
|
||||
<code className="font-mono">{v.aggregateHash.slice(0, 8)}</code>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
asChild
|
||||
title="Open this version in the gateway"
|
||||
>
|
||||
<a href={url} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
</a>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setConfirmDeleteId(v.id)}
|
||||
disabled={deleting}
|
||||
title="Delete this version (publishes a NIP-09 delete event)"
|
||||
>
|
||||
{deleting ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
|
||||
{/* Delete confirmation */}
|
||||
<AlertDialog
|
||||
open={confirmDeleteId !== null}
|
||||
onOpenChange={(o) => { if (!o) setConfirmDeleteId(null); }}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete this version?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{pendingDelete && (
|
||||
<>
|
||||
Publishes a Nostr delete event for the snapshot from{' '}
|
||||
<strong>{dateFormatter.format(new Date(pendingDelete.createdAt * 1000))}</strong>.
|
||||
Relays that honor NIP-09 will drop the event; gateways may continue
|
||||
serving cached copies until they refresh.
|
||||
</>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => confirmDeleteId && handleDelete(confirmDeleteId)}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -4,12 +4,16 @@ import { nip19 } from 'nostr-tools';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import type { DeployAdapter, DeployOptions, DeployResult, NsiteDeployConfig } from './types';
|
||||
import { buildNsiteUrl } from '../utils/nsite';
|
||||
import {
|
||||
buildNsiteParentRef,
|
||||
buildNsiteSnapshotTags,
|
||||
computeNsiteAggregateHash,
|
||||
NSITE_NAMED_SITE_KIND,
|
||||
NSITE_ROOT_SITE_KIND,
|
||||
} from '../utils/nsiteAggregateHash';
|
||||
|
||||
/** nsite v2 root-site kind (replaceable by pubkey+kind) */
|
||||
const NSITE_ROOT_SITE_KIND = 15128;
|
||||
|
||||
/** nsite v2 named-site kind (addressable by pubkey+kind+d) */
|
||||
const NSITE_NAMED_SITE_KIND = 35128;
|
||||
/** nsite v2 manifest snapshot kind (regular event capturing a point-in-time manifest) */
|
||||
const NSITE_SNAPSHOT_KIND = 5128;
|
||||
|
||||
/** BUD-02 Blossom authorization event kind */
|
||||
const BLOSSOM_AUTH_KIND = 24242;
|
||||
@@ -268,6 +272,7 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
private siteDescription?: string;
|
||||
private sourceUrl?: string;
|
||||
private siteIdentifier?: string;
|
||||
private publishSnapshotOnDeploy: boolean;
|
||||
|
||||
constructor(config: NsiteDeployConfig) {
|
||||
this.fs = config.fs;
|
||||
@@ -280,6 +285,7 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
this.siteDescription = config.siteDescription;
|
||||
this.sourceUrl = config.sourceUrl;
|
||||
this.siteIdentifier = config.siteIdentifier;
|
||||
this.publishSnapshotOnDeploy = config.publishSnapshotOnDeploy ?? false;
|
||||
}
|
||||
|
||||
async deploy(options: DeployOptions): Promise<DeployResult> {
|
||||
@@ -364,11 +370,18 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
// SPA fallback: map /404.html to the same blob as /index.html so that
|
||||
// React Router (and other SPAs) work correctly — the nsite host server
|
||||
// serves /404.html when a path is not found, acting as a client-side router fallback.
|
||||
// The SPA fallback IS a published `path` tag, so it is included in the
|
||||
// aggregate hash below.
|
||||
const indexFile = files.find(f => f.path === '/index.html');
|
||||
if (indexFile && !files.some(f => f.path === '/404.html')) {
|
||||
pathTags.push(['path', '/404.html', indexFile.sha256]);
|
||||
}
|
||||
|
||||
// NIP-5A aggregate hash — deterministic digest of the manifest's path tags.
|
||||
// Always attached so the published manifest is indexable and discoverable,
|
||||
// and so the snapshot event (when emitted) can carry exactly the same value.
|
||||
const aggregateHash = await computeNsiteAggregateHash(pathTags);
|
||||
|
||||
const serverTags: string[][] = serverBases.map(url => ['server', url]);
|
||||
const relayTags: string[][] = this.relayUrls.map(url => ['relay', url]);
|
||||
|
||||
@@ -379,7 +392,7 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
tags.push(['d', this.siteIdentifier]);
|
||||
}
|
||||
|
||||
tags.push(...pathTags, ...serverTags, ...relayTags);
|
||||
tags.push(...pathTags, ['x', aggregateHash, 'aggregate'], ...serverTags, ...relayTags);
|
||||
|
||||
if (this.siteTitle) {
|
||||
tags.push(['title', this.siteTitle]);
|
||||
@@ -393,10 +406,12 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
tags.push(['source', this.sourceUrl]);
|
||||
}
|
||||
|
||||
const createdAt = Math.floor(Date.now() / 1000);
|
||||
|
||||
const manifestEvent = await this.signer.signEvent({
|
||||
kind: manifestKind,
|
||||
content: '',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
created_at: createdAt,
|
||||
tags,
|
||||
});
|
||||
|
||||
@@ -405,6 +420,58 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
// no separate kind 10002 or kind 10063 events are published.
|
||||
await relayClient.event(manifestEvent, { signal: AbortSignal.timeout(10_000) });
|
||||
|
||||
// ── Step 6: Optionally publish a manifest snapshot (NIP-5A kind 5128) ────
|
||||
// When enabled, this captures the current manifest as an immutable, id-addressable
|
||||
// event so historical versions remain reachable. Off by default — the user
|
||||
// opts in per-project via .nsite/config.json (`publishSnapshotOnDeploy: true`).
|
||||
//
|
||||
// Deduplication: skip the snapshot publish if a kind-5128 event with the
|
||||
// same aggregate hash for the same site already exists on the relays. A new
|
||||
// snapshot of a byte-for-byte equivalent version would just be relay noise.
|
||||
//
|
||||
// Inferred from signer.signEvent so the full NostrEvent shape is preserved
|
||||
// when this is later passed to relayClient.event().
|
||||
let snapshotEvent: Awaited<ReturnType<typeof this.signer.signEvent>> | undefined;
|
||||
let snapshotSkippedReason: 'unchanged' | undefined;
|
||||
if (this.publishSnapshotOnDeploy) {
|
||||
const parentRef = buildNsiteParentRef(pubkey, this.siteIdentifier);
|
||||
|
||||
const existingSnapshots = await relayClient.query(
|
||||
[{
|
||||
kinds: [NSITE_SNAPSHOT_KIND],
|
||||
authors: [pubkey],
|
||||
'#a': [parentRef],
|
||||
'#x': [aggregateHash],
|
||||
limit: 1,
|
||||
}],
|
||||
{ signal: AbortSignal.timeout(5_000) },
|
||||
).catch(() => []);
|
||||
|
||||
if (existingSnapshots.length > 0) {
|
||||
snapshotSkippedReason = 'unchanged';
|
||||
} else {
|
||||
const snapshotTags = buildNsiteSnapshotTags({
|
||||
pubkey,
|
||||
siteIdentifier: this.siteIdentifier,
|
||||
pathTags,
|
||||
aggregateHash,
|
||||
serverTags,
|
||||
title: this.siteTitle,
|
||||
description: this.siteDescription,
|
||||
sourceUrl: this.sourceUrl,
|
||||
});
|
||||
|
||||
snapshotEvent = await this.signer.signEvent({
|
||||
kind: NSITE_SNAPSHOT_KIND,
|
||||
content: '',
|
||||
created_at: createdAt,
|
||||
tags: snapshotTags,
|
||||
});
|
||||
|
||||
await relayClient.event(snapshotEvent, { signal: AbortSignal.timeout(10_000) });
|
||||
}
|
||||
}
|
||||
|
||||
// Build the canonical deployed URL (always the long-form base36 or npub URL)
|
||||
const siteUrl = buildNsiteUrl({
|
||||
pubkeyHex: pubkey,
|
||||
@@ -433,6 +500,10 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
manifestKind,
|
||||
vanityUrl,
|
||||
canonicalUrl: siteUrl,
|
||||
aggregateHash,
|
||||
snapshotId: snapshotEvent?.id,
|
||||
snapshotCreatedAt: snapshotEvent?.created_at,
|
||||
snapshotSkipped: snapshotSkippedReason,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -66,6 +66,11 @@ export interface NsiteDeployConfig {
|
||||
* When absent → publishes kind 15128 (root site), URL = {npub}.{gateway}
|
||||
*/
|
||||
siteIdentifier?: string;
|
||||
/**
|
||||
* When true, also publish a NIP-5A kind 5128 manifest snapshot event alongside
|
||||
* the main manifest so historical versions remain addressable by event id.
|
||||
*/
|
||||
publishSnapshotOnDeploy?: boolean;
|
||||
}
|
||||
|
||||
export interface CloudflareDeployConfig {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { MockFS } from '@/test/MockFS';
|
||||
import { readNsiteVfsConfig, writeNsiteVfsConfig } from './nsiteConfig';
|
||||
|
||||
const PROJECT = '/projects/demo';
|
||||
|
||||
describe('nsiteConfig.publishSnapshotOnDeploy', () => {
|
||||
let fs: MockFS;
|
||||
|
||||
beforeEach(() => {
|
||||
fs = new MockFS();
|
||||
});
|
||||
|
||||
it('round-trips publishSnapshotOnDeploy=true', async () => {
|
||||
await writeNsiteVfsConfig(fs, PROJECT, {
|
||||
relays: ['wss://relay.example.com'],
|
||||
servers: ['https://blossom.example.com'],
|
||||
publishSnapshotOnDeploy: true,
|
||||
});
|
||||
const read = await readNsiteVfsConfig(fs, PROJECT);
|
||||
expect(read?.publishSnapshotOnDeploy).toBe(true);
|
||||
});
|
||||
|
||||
it('round-trips publishSnapshotOnDeploy=false', async () => {
|
||||
await writeNsiteVfsConfig(fs, PROJECT, {
|
||||
relays: ['wss://relay.example.com'],
|
||||
servers: ['https://blossom.example.com'],
|
||||
publishSnapshotOnDeploy: false,
|
||||
});
|
||||
const read = await readNsiteVfsConfig(fs, PROJECT);
|
||||
expect(read?.publishSnapshotOnDeploy).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts a config without publishSnapshotOnDeploy (backward compatibility)', async () => {
|
||||
await fs.writeFile(
|
||||
`${PROJECT}/.nsite/config.json`,
|
||||
JSON.stringify({
|
||||
relays: ['wss://relay.example.com'],
|
||||
servers: ['https://blossom.example.com'],
|
||||
}),
|
||||
);
|
||||
const read = await readNsiteVfsConfig(fs, PROJECT);
|
||||
expect(read).not.toBeNull();
|
||||
expect(read?.publishSnapshotOnDeploy).toBeUndefined();
|
||||
});
|
||||
|
||||
it('rejects non-boolean publishSnapshotOnDeploy values', async () => {
|
||||
await fs.writeFile(
|
||||
`${PROJECT}/.nsite/config.json`,
|
||||
JSON.stringify({
|
||||
relays: ['wss://relay.example.com'],
|
||||
servers: ['https://blossom.example.com'],
|
||||
publishSnapshotOnDeploy: 'yes',
|
||||
}),
|
||||
);
|
||||
// Invalid types are coerced to null per readNsiteVfsConfig's error handling.
|
||||
const read = await readNsiteVfsConfig(fs, PROJECT);
|
||||
expect(read).toBeNull();
|
||||
});
|
||||
|
||||
it('preserves unknown keys when merging on write', async () => {
|
||||
await fs.writeFile(
|
||||
`${PROJECT}/.nsite/config.json`,
|
||||
JSON.stringify({
|
||||
relays: ['wss://relay.example.com'],
|
||||
servers: ['https://blossom.example.com'],
|
||||
customField: 'kept-from-nsyte-cli',
|
||||
}),
|
||||
);
|
||||
await writeNsiteVfsConfig(fs, PROJECT, {
|
||||
relays: ['wss://relay.example.com'],
|
||||
servers: ['https://blossom.example.com'],
|
||||
publishSnapshotOnDeploy: true,
|
||||
});
|
||||
const raw = await fs.readFile(`${PROJECT}/.nsite/config.json`, 'utf8');
|
||||
const parsed = JSON.parse(raw as string);
|
||||
expect(parsed.customField).toBe('kept-from-nsyte-cli');
|
||||
expect(parsed.publishSnapshotOnDeploy).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -40,6 +40,12 @@ export interface NsiteVfsConfig {
|
||||
fallback?: string;
|
||||
/** Gateway hostnames that serve this nsite */
|
||||
gatewayHostnames?: string[];
|
||||
/**
|
||||
* When true, every deploy also publishes a kind 5128 manifest snapshot event
|
||||
* so older versions of the site remain reachable by event id.
|
||||
* Absent/false → snapshots are not published.
|
||||
*/
|
||||
publishSnapshotOnDeploy?: boolean;
|
||||
}
|
||||
|
||||
const nsiteVfsConfigSchema = z
|
||||
@@ -51,6 +57,7 @@ const nsiteVfsConfigSchema = z
|
||||
description: z.string().optional(),
|
||||
fallback: z.string().optional(),
|
||||
gatewayHostnames: z.array(z.string()).optional(),
|
||||
publishSnapshotOnDeploy: z.boolean().optional(),
|
||||
})
|
||||
.passthrough(); // preserve unknown keys in existing files
|
||||
|
||||
|
||||
+22
-5
@@ -63,16 +63,19 @@ export function isValidDTag(value: string): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a 32-byte pubkey (as hex string) into a 50-character lowercase base36 string.
|
||||
* Used to build named-site subdomain URLs: `{base36pubkey}{dTag}.{gateway}`
|
||||
* Encode a 32-byte hex value into a 50-character lowercase base36 string.
|
||||
*
|
||||
* Used to build canonical nsite subdomain URLs:
|
||||
* - Named site: `{base36pubkey}{dTag}.{gateway}`
|
||||
* - Snapshot: `v{base36snapshotId}.{gateway}`
|
||||
*
|
||||
* Ported from nsite.run/apps/spa/src/lib/base36.js
|
||||
*/
|
||||
export function pubkeyToBase36(pubkeyHex: string): string {
|
||||
export function hex32ToBase36(hex: string): string {
|
||||
// hex → Uint8Array
|
||||
const bytes = new Uint8Array(32);
|
||||
for (let i = 0; i < 32; i++) {
|
||||
bytes[i] = parseInt(pubkeyHex.slice(i * 2, i * 2 + 2), 16);
|
||||
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
|
||||
const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
|
||||
@@ -92,6 +95,9 @@ export function pubkeyToBase36(pubkeyHex: string): string {
|
||||
return digits.reverse().join('').padStart(50, '0');
|
||||
}
|
||||
|
||||
/** @deprecated use {@link hex32ToBase36} — kept as an alias for callers that still use this name. */
|
||||
export const pubkeyToBase36 = hex32ToBase36;
|
||||
|
||||
/**
|
||||
* Build the deployed URL for an nsite.
|
||||
*
|
||||
@@ -106,8 +112,19 @@ export function buildNsiteUrl(opts: {
|
||||
}): string {
|
||||
const { pubkeyHex, npub, gateway, siteIdentifier } = opts;
|
||||
if (siteIdentifier) {
|
||||
const base36 = pubkeyToBase36(pubkeyHex);
|
||||
const base36 = hex32ToBase36(pubkeyHex);
|
||||
return `https://${base36}${siteIdentifier}.${gateway}`;
|
||||
}
|
||||
return `https://${npub}.${gateway}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the canonical URL for an nsite manifest snapshot (NIP-5A kind 5128).
|
||||
* `https://v{base36snapshotId}.{gateway}`
|
||||
*/
|
||||
export function buildNsiteSnapshotUrl(opts: {
|
||||
eventIdHex: string;
|
||||
gateway: string;
|
||||
}): string {
|
||||
return `https://v${hex32ToBase36(opts.eventIdHex)}.${opts.gateway}`;
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
buildNsiteSnapshotTags,
|
||||
computeNsiteAggregateHash,
|
||||
NSITE_NAMED_SITE_KIND,
|
||||
NSITE_ROOT_SITE_KIND,
|
||||
} from './nsiteAggregateHash';
|
||||
|
||||
describe('computeNsiteAggregateHash', () => {
|
||||
// Two-file example from the NIP-5A spec:
|
||||
// 186ea5fd14e88fd1ac49351759e7ab906fa94892002b60bf7f5a428f28ca1c99 /index.html
|
||||
// fedcba0987654321fedcba0987654321fedcba0987654321fedcba0987654321 /favicon.ico
|
||||
//
|
||||
// Sorted lines (lex ascending) then sha256 → c2ff582b...9638
|
||||
// Verified out-of-band with:
|
||||
// printf '<line1>\n<line2>\n' | sha256sum
|
||||
const EXPECTED_TWO_FILE_DIGEST =
|
||||
'c2ff582b672a4c689c5e1753528f03dd31b95ec1fdcc3d82d25e7d91e8769638';
|
||||
|
||||
const indexTag = [
|
||||
'path',
|
||||
'/index.html',
|
||||
'186ea5fd14e88fd1ac49351759e7ab906fa94892002b60bf7f5a428f28ca1c99',
|
||||
];
|
||||
const faviconTag = [
|
||||
'path',
|
||||
'/favicon.ico',
|
||||
'fedcba0987654321fedcba0987654321fedcba0987654321fedcba0987654321',
|
||||
];
|
||||
|
||||
it('matches the known digest for the NIP-5A spec example', async () => {
|
||||
const digest = await computeNsiteAggregateHash([indexTag, faviconTag]);
|
||||
expect(digest).toBe(EXPECTED_TWO_FILE_DIGEST);
|
||||
});
|
||||
|
||||
it('is independent of path-tag order', async () => {
|
||||
const forwards = await computeNsiteAggregateHash([indexTag, faviconTag]);
|
||||
const reverse = await computeNsiteAggregateHash([faviconTag, indexTag]);
|
||||
expect(forwards).toBe(reverse);
|
||||
});
|
||||
|
||||
it('ignores non-path tags', async () => {
|
||||
const withNoise = await computeNsiteAggregateHash([
|
||||
['d', 'blog'],
|
||||
indexTag,
|
||||
['title', 'My Site'],
|
||||
faviconTag,
|
||||
['server', 'https://example.com'],
|
||||
]);
|
||||
expect(withNoise).toBe(EXPECTED_TWO_FILE_DIGEST);
|
||||
});
|
||||
|
||||
it('returns lowercase hex of length 64', async () => {
|
||||
const digest = await computeNsiteAggregateHash([indexTag]);
|
||||
expect(digest).toMatch(/^[0-9a-f]{64}$/);
|
||||
});
|
||||
|
||||
it('produces a different digest when a path or hash changes', async () => {
|
||||
const baseline = await computeNsiteAggregateHash([indexTag, faviconTag]);
|
||||
const renamed = await computeNsiteAggregateHash([
|
||||
indexTag,
|
||||
['path', '/icon.ico', faviconTag[2]],
|
||||
]);
|
||||
expect(renamed).not.toBe(baseline);
|
||||
});
|
||||
|
||||
it('returns the sha256 of empty input when no path tags are present', async () => {
|
||||
// sha256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
|
||||
const digest = await computeNsiteAggregateHash([['title', 'noop']]);
|
||||
expect(digest).toBe(
|
||||
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildNsiteSnapshotTags', () => {
|
||||
const pubkey = '266815e0c9210dfa324c6cba3573b14bee49da4209a9456f9484e5106cd408a5';
|
||||
const aggregateHash =
|
||||
'c2ff582b672a4c689c5e1753528f03dd31b95ec1fdcc3d82d25e7d91e8769638';
|
||||
const pathTags = [
|
||||
['path', '/index.html', '186ea5fd14e88fd1ac49351759e7ab906fa94892002b60bf7f5a428f28ca1c99'],
|
||||
['path', '/favicon.ico', 'fedcba0987654321fedcba0987654321fedcba0987654321fedcba0987654321'],
|
||||
];
|
||||
|
||||
it('builds a named-site `a` tag of the form 35128:<pubkey>:<dTag>', () => {
|
||||
const tags = buildNsiteSnapshotTags({
|
||||
pubkey,
|
||||
siteIdentifier: 'blog',
|
||||
pathTags,
|
||||
aggregateHash,
|
||||
});
|
||||
const aTags = tags.filter(t => t[0] === 'a');
|
||||
expect(aTags).toHaveLength(1);
|
||||
expect(aTags[0]).toEqual(['a', `${NSITE_NAMED_SITE_KIND}:${pubkey}:blog`]);
|
||||
});
|
||||
|
||||
it('builds a root-site `a` tag of the form 15128:<pubkey>: with empty d-identifier', () => {
|
||||
const tags = buildNsiteSnapshotTags({
|
||||
pubkey,
|
||||
pathTags,
|
||||
aggregateHash,
|
||||
});
|
||||
const aTags = tags.filter(t => t[0] === 'a');
|
||||
expect(aTags).toHaveLength(1);
|
||||
expect(aTags[0]).toEqual(['a', `${NSITE_ROOT_SITE_KIND}:${pubkey}:`]);
|
||||
});
|
||||
|
||||
it('includes exactly one aggregate `x` tag matching the input hash', () => {
|
||||
const tags = buildNsiteSnapshotTags({
|
||||
pubkey,
|
||||
siteIdentifier: 'blog',
|
||||
pathTags,
|
||||
aggregateHash,
|
||||
});
|
||||
const xTags = tags.filter(t => t[0] === 'x');
|
||||
expect(xTags).toHaveLength(1);
|
||||
expect(xTags[0]).toEqual(['x', aggregateHash, 'aggregate']);
|
||||
});
|
||||
|
||||
it('copies every path tag from the source manifest', () => {
|
||||
const tags = buildNsiteSnapshotTags({
|
||||
pubkey,
|
||||
siteIdentifier: 'blog',
|
||||
pathTags,
|
||||
aggregateHash,
|
||||
});
|
||||
const copiedPathTags = tags.filter(t => t[0] === 'path');
|
||||
expect(copiedPathTags).toEqual(pathTags);
|
||||
});
|
||||
|
||||
it('does not mutate the input path tags', () => {
|
||||
const original = pathTags.map(t => [...t]);
|
||||
buildNsiteSnapshotTags({
|
||||
pubkey,
|
||||
siteIdentifier: 'blog',
|
||||
pathTags,
|
||||
aggregateHash,
|
||||
}).push(['mutated']);
|
||||
expect(pathTags).toEqual(original);
|
||||
});
|
||||
|
||||
it('includes optional title, description, source, and server tags when provided', () => {
|
||||
const tags = buildNsiteSnapshotTags({
|
||||
pubkey,
|
||||
siteIdentifier: 'blog',
|
||||
pathTags,
|
||||
aggregateHash,
|
||||
serverTags: [['server', 'https://blossom.example.com']],
|
||||
title: 'My Blog',
|
||||
description: 'Hosted on Nostr',
|
||||
sourceUrl: 'https://github.com/example/blog',
|
||||
});
|
||||
expect(tags).toContainEqual(['title', 'My Blog']);
|
||||
expect(tags).toContainEqual(['description', 'Hosted on Nostr']);
|
||||
expect(tags).toContainEqual(['source', 'https://github.com/example/blog']);
|
||||
expect(tags).toContainEqual(['server', 'https://blossom.example.com']);
|
||||
});
|
||||
|
||||
it('omits an `A` tag (spec: non-copied snapshots SHOULD omit it)', () => {
|
||||
const tags = buildNsiteSnapshotTags({
|
||||
pubkey,
|
||||
siteIdentifier: 'blog',
|
||||
pathTags,
|
||||
aggregateHash,
|
||||
});
|
||||
expect(tags.some(t => t[0] === 'A')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
/** NIP-5A nsite manifest kinds. */
|
||||
export const NSITE_ROOT_SITE_KIND = 15128;
|
||||
export const NSITE_NAMED_SITE_KIND = 35128;
|
||||
|
||||
/**
|
||||
* NIP-5A aggregate hash for nsite manifests.
|
||||
*
|
||||
* The aggregate hash is a deterministic digest of a manifest's `path` tags. It
|
||||
* identifies a specific site version and is shared by equivalent manifests
|
||||
* published by different pubkeys.
|
||||
*
|
||||
* Algorithm (from NIP-5A):
|
||||
* 1. For every `path` tag, produce a line `<sha256hash> <absolute-path>\n`.
|
||||
* 2. Sort the lines in ascending lexicographic order.
|
||||
* 3. Concatenate the sorted lines as UTF-8 bytes.
|
||||
* 4. SHA-256 the bytes and return the digest as lowercase hex.
|
||||
*
|
||||
* The algorithm uses only `path` tags and is independent of tag order.
|
||||
*/
|
||||
export async function computeNsiteAggregateHash(
|
||||
pathTags: ReadonlyArray<readonly string[]>,
|
||||
): Promise<string> {
|
||||
const lines: string[] = [];
|
||||
for (const tag of pathTags) {
|
||||
if (tag[0] !== 'path') continue;
|
||||
const path = tag[1];
|
||||
const hash = tag[2];
|
||||
if (typeof path !== 'string' || typeof hash !== 'string') continue;
|
||||
lines.push(`${hash} ${path}\n`);
|
||||
}
|
||||
lines.sort();
|
||||
|
||||
const bytes = new TextEncoder().encode(lines.join(''));
|
||||
const digest = await crypto.subtle.digest('SHA-256', bytes);
|
||||
return Array.from(new Uint8Array(digest))
|
||||
.map(b => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the addressable `a` reference to an nsite manifest for use in snapshot
|
||||
* (and snapshot-dedup query) tags.
|
||||
*
|
||||
* - Named site (kind 35128): `35128:<pubkey>:<dTag>`
|
||||
* - Root site (kind 15128): `15128:<pubkey>:` (empty d-identifier)
|
||||
*/
|
||||
export function buildNsiteParentRef(pubkey: string, siteIdentifier?: string): string {
|
||||
return siteIdentifier
|
||||
? `${NSITE_NAMED_SITE_KIND}:${pubkey}:${siteIdentifier}`
|
||||
: `${NSITE_ROOT_SITE_KIND}:${pubkey}:`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the tag array for a NIP-5A kind-5128 manifest snapshot of a non-copied site.
|
||||
*
|
||||
* Per the spec, a snapshot MUST:
|
||||
* - include exactly one `a` tag referencing the source manifest
|
||||
* (named: `35128:<pubkey>:<dTag>`, root: `15128:<pubkey>:`)
|
||||
* - copy the source manifest's `path` tags
|
||||
* - include exactly one `x` aggregate tag matching the source's aggregate hash
|
||||
*
|
||||
* It MAY also copy `server`, `title`, `description`, and `source` tags.
|
||||
*/
|
||||
export function buildNsiteSnapshotTags(opts: {
|
||||
pubkey: string;
|
||||
siteIdentifier?: string;
|
||||
pathTags: ReadonlyArray<readonly string[]>;
|
||||
aggregateHash: string;
|
||||
serverTags?: ReadonlyArray<readonly string[]>;
|
||||
title?: string;
|
||||
description?: string;
|
||||
sourceUrl?: string;
|
||||
}): string[][] {
|
||||
const tags: string[][] = [
|
||||
['a', buildNsiteParentRef(opts.pubkey, opts.siteIdentifier)],
|
||||
...opts.pathTags.map(t => [...t]),
|
||||
['x', opts.aggregateHash, 'aggregate'],
|
||||
...(opts.serverTags ?? []).map(t => [...t]),
|
||||
];
|
||||
|
||||
if (opts.title) tags.push(['title', opts.title]);
|
||||
if (opts.description) tags.push(['description', opts.description]);
|
||||
if (opts.sourceUrl) tags.push(['source', opts.sourceUrl]);
|
||||
|
||||
return tags;
|
||||
}
|
||||
Reference in new issue
Block a user