Add full-content discovery search and backlink ranking to waterfall-wiki
wiki CI and deployment / verify-and-deploy (push) Failing after 25m11s

This commit is contained in:
2026-10-26 20:20:55 +08:00
parent c3765e7a07
commit 7f37aa4c93
24 changed files with 150 additions and 35 deletions
+3 -2
View File
@@ -10,7 +10,7 @@
"build": "next build && esbuild src/worker.ts --bundle --platform=node --format=cjs --external:pg-native --external:playwright-core --outfile=dist/worker.cjs && esbuild scripts/bootstrap.ts --bundle --platform=node --format=cjs --external:pg-native --external:playwright-core --outfile=dist/bootstrap.cjs && esbuild scripts/publish-learning-series.ts --bundle --platform=node --format=cjs --external:pg-native --external:playwright-core --outfile=dist/publish-learning-series.cjs && node scripts/prepare-standalone.mjs",
"start": "next start",
"typecheck": "next typegen && tsc --noEmit",
"test": "tsx --test tests/api-documentation.test.ts tests/health.test.ts tests/model.test.ts tests/learning-series.test.ts tests/skill-docs.test.ts tests/wiki.test.ts tests/explore.test.ts tests/preview.test.ts tests/note-markdown.test.tsx tests/api-publication.test.ts",
"test": "tsx --test tests/api-documentation.test.ts tests/health.test.ts tests/model.test.ts tests/learning-series.test.ts tests/skill-docs.test.ts tests/wiki.test.ts tests/explore.test.ts tests/preview.test.ts tests/note-markdown.test.tsx tests/api-publication.test.ts tests/discovery.test.ts",
"test:smoke": "node scripts/smoke.mjs",
"storage:prepare": "tsx scripts/bootstrap.ts",
"content:publish-learning": "tsx scripts/publish-learning-series.ts",
@@ -29,7 +29,8 @@
"react-markdown": "10.1.0",
"remark-gfm": "4.0.1",
"sharp": "0.35.5",
"zod": "4.6.7"
"zod": "4.6.7",
"mdast-util-from-markdown": "2.1.0"
},
"devDependencies": {
"@tailwindcss/postcss": "4.3.3",
+3
View File
@@ -17,6 +17,9 @@ importers:
lucide-react:
specifier: 1.61.0
version: 1.61.0(@types/react@19.3.0)(react@19.3.1)
mdast-util-from-markdown:
specifier: 2.1.0
version: 2.1.0
next:
specifier: 16.4.2
version: 16.4.2(@types/node@24.19.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
+2 -2
View File
@@ -31,7 +31,7 @@ export function ExploreDetail({entry:initial,background}:{entry:ExploreEntry;bac
setCopied(mode);setCopyError('');
}catch{setCopied('');setCopyError('复制失败,请重试。')}
}
return <Shell><Head><title>{entry.title} · PROMPT</title><link rel="canonical" href={exploreUrl(entry.id)}/><link rel="alternate" type="text/plain" href={exploreUrl(entry.id)+'?agent_mode=True'}/></Head>
return <Shell><Head><title>{entry.title} · waterfall-wiki</title><link rel="canonical" href={exploreUrl(entry.id)}/><link rel="alternate" type="text/plain" href={exploreUrl(entry.id)+'?agent_mode=True'}/></Head>
<div aria-hidden="true" inert><ExploreFeed key={entry.revision} initial={background.map(e=>e.id===entry.id?entry:e)}/></div>
<div className="note-overlay" onClick={()=>{if(!editing)close()}}><div className="note-dialog" ref={detailRef} role="dialog" aria-modal="true" aria-labelledby="note-title" onClick={e=>e.stopPropagation()}>
<button className="note-close" ref={closeRef} aria-label={editing?'取消编辑':'关闭详情'} onClick={close}><X/></button>
@@ -39,7 +39,7 @@ export function ExploreDetail({entry:initial,background}:{entry:ExploreEntry;bac
{media?.kind==='image'?<img key={media.url} src={previewUrl(media.url,1280)} alt={media.title} decoding="async"/>:media?.kind==='video'?<video controls playsInline preload="metadata" src={media.url} poster={media.poster?previewUrl(media.poster,960):undefined}/>:media?.kind==='audio'?<div className="note-audio"><span>♫</span><audio controls preload="metadata" src={media.url}/></div>:<div className="note-title-cover" style={{background:entry.color}}><small>{entry.namespace}</small><strong>{entry.title}</strong><span>灵感笔记</span></div>}
{entry.media.length>1&&<><button className="note-prev" aria-label="上一张" disabled={index===0} onClick={()=>setIndex(n=>n-1)}><ChevronLeft/></button><button className="note-next" aria-label="下一张" disabled={index===entry.media.length-1} onClick={()=>setIndex(n=>n+1)}><ChevronRight/></button><div className="note-dots">{entry.media.map((_,i)=><button key={i} className={i===index?'selected':''} aria-label={'查看第 '+(i+1)+' 张'} aria-pressed={i===index} onClick={()=>setIndex(i)}/>)}</div><span className="note-count">{index+1} / {entry.media.length}</span></>}
</section><section className="note-info"><div className="note-content">
{editing?<NoteEditor key={entry.id} entry={entry} onCancel={()=>setEditing(false)} onSaved={updated=>{setEntry(updated);setEditing(false);setCopied('')}}/>:<><h1 id="note-title">{entry.title}</h1><p className="note-description">{entry.description}</p><div className="note-tags">{entry.categories.map(c=><Link key={c} href={'/categories?category='+encodeURIComponent(c)}>#{c} </Link>)}</div><NoteMarkdown text={entry.markdown.replace(/^# [^\n]*(?:\n|$)\n?/,'')}/><div className="note-id">内容 ID · {entry.id}</div></>}
{editing?<NoteEditor key={entry.id} entry={entry} onCancel={()=>setEditing(false)} onSaved={updated=>{setEntry(updated);setEditing(false);setCopied('')}}/>:<><h1 id="note-title">{entry.title}</h1><p className="note-description">{entry.description}</p><div className="note-tags">{entry.categories.map(c=><Link key={c} href={'/categories?category='+encodeURIComponent(c)}>#{c} </Link>)}</div><NoteMarkdown text={entry.markdown.replace(/^# [^\n]*(?:\n|$)\n?/,'')}/><section id="backlinks" className="note-backlinks"><h2>被 {entry.backlinkCount??0} 篇笔记引用</h2>{entry.backlinks?.length?<ul>{entry.backlinks.map(ref=><li key={ref.id}><Link href={exploreUrl(ref.id)}>{ref.title}</Link></li>)}</ul>:<p>还没有笔记引用本文。</p>}</section><div className="note-id">内容 ID · {entry.id}</div></>}
</div>{!editing&&<footer><button onClick={()=>void copy('web')}><LinkIcon size={18}/>{copied==='web'?'网页链接已复制':'复制网页链接'}</button><button onClick={()=>void copy('agent')}><FileText size={18}/>{copied==='agent'?'纯文本链接已复制':'复制纯文本链接'}</button><button onClick={()=>setEditing(true)}><Pencil size={17}/>编辑</button>{copyError&&<span role="status">{copyError}</span>}</footer>}</section>
</div></div></Shell>;
}
+6 -5
View File
@@ -1,16 +1,17 @@
import Link from 'next/link';
import {useState} from 'react';
import {Images} from 'lucide-react';
import {Images,Link2} from 'lucide-react';
import type {ExploreEntry} from '@/lib/explore';
import {exploreUrl,previewUrl} from '@/content/page-links';
export function ExploreFeed({initial,cursor:initialCursor=null,q='',category=''}:{initial:ExploreEntry[];cursor?:string|null;q?:string;category?:string}){
export function ExploreFeed({initial,cursor:initialCursor=null,q='',category='',total}:{initial:ExploreEntry[];cursor?:string|null;q?:string;category?:string;total?:number}){
const [entries,setEntries]=useState(initial);const [cursor,setCursor]=useState(initialCursor);const [busy,setBusy]=useState(false);const [error,setError]=useState('');
async function more(){setBusy(true);try{const res=await fetch('/api/explore-feed?'+new URLSearchParams({q,category,cursor:cursor||''}));if(!res.ok)throw Error();const data=await res.json();setEntries(old=>[...old,...data.entries.filter((e:ExploreEntry)=>!old.some(o=>o.id===e.id))]);setCursor(data.nextCursor);setError('');}catch{setError('加载失败,点击重试')}finally{setBusy(false)}}
return <><div className="discovery-grid">{entries.map((entry,i)=><article key={entry.id} className="discovery-card">
return <>{q&&<div className="search-results-heading" role="status">搜索「{q}」{total!==undefined?` · ${total} 篇`:""}<span>按匹配程度、被引用数排序</span></div>}<div className="discovery-grid">{entries.map((entry,i)=><article key={entry.id} className="discovery-card">
<Link href={exploreUrl(entry.id)} className="discovery-note-link"><div className="discovery-cover" style={{background:entry.color,aspectRatio:i%3===1?'1 / 1':'3 / 4'}}>
{entry.media[0]?<img src={previewUrl(entry.media[0].poster||entry.media[0].url,480)} alt={entry.media[0].title} loading={i<4?'eager':'lazy'} decoding="async"/>:<><small>{entry.namespace.toUpperCase()}</small><strong>{entry.title}</strong><span>记录 · 连接 · 灵感</span></>}
{entry.imageCount>1&&<span className="discovery-image-count" aria-label={`${entry.imageCount} 张图片`}><Images size={13}/>{entry.imageCount}</span>}
</div><h2>{entry.title}</h2><p className="discovery-description">{entry.description}</p></Link>
</div><h2>{entry.title}</h2><p className="discovery-description">{entry.description}</p>{q&&entry.searchExcerpt&&<p className="search-excerpt">{entry.searchExcerpt}</p>}</Link>
<Link className="backlink-count" href={exploreUrl(entry.id)+"#backlinks"} aria-label={`被 ${entry.backlinkCount??0} 篇笔记引用`}><Link2 size={14}/>被引用 {entry.backlinkCount??0}</Link>
{entry.categories.length>0&&<div className="discovery-tags" aria-label="笔记标签">{entry.categories.map(tag=><Link key={tag} href={'/categories?category='+encodeURIComponent(tag)}>#{tag}</Link>)}</div>}
</article>)}</div>{!entries.length&&<p className="discovery-empty">这个分类还没有内容。</p>}{cursor&&<div className="load-more"><button disabled={busy} onClick={more}>{busy?'加载中…':error||'再看一些'}</button></div>}</>;
</article>)}</div>{!entries.length&&<p className="discovery-empty">{q?'没有匹配的内容,试试更短的关键词。':'这个分类还没有内容。'}</p>}{cursor&&<div className="load-more"><button disabled={busy} onClick={more}>{busy?'加载中…':error||'再看一些'}</button></div>}</>;
}
+2 -2
View File
@@ -31,12 +31,12 @@ export function Feed({initial,section='',tagPath=''}:{initial:FeedData;section?:
useEffect(()=>{generation.current++;setPosts(initial.posts);setCursor(initial.nextCursor);setError('');setBusy(false);},[initial,router.query.q]);
const current=sections.find(s=>s.path===section);const target=initial.tags.find(t=>t.path===tagPath);const children=initial.tags;
async function load(){const gen=generation.current;setBusy(true);setError('');try{const q=new URLSearchParams({section,path:tagPath,cursor:cursor||'',q:String(router.query.q||'')});const res=await fetch('/api/feed?'+q);const d=await res.json();if(!res.ok)throw new Error(d.error);if(gen===generation.current){setPosts(old=>[...old,...d.posts.filter((p:Post)=>!old.some(a=>a.id===p.id))]);setCursor(d.nextCursor);}}catch{if(gen===generation.current)setError('加载没有完成,点击重试。');}finally{if(gen===generation.current)setBusy(false);}}
return <Shell><Head><title>{target?.name||current?.name||'灵感首页'} · PROMPT</title><meta name="description" content="自己的图文、视频与声音创作空间"/><link rel="alternate" type="text/markdown" href="/index.md" title="Agent 文档入口"/></Head>
return <Shell><Head><title>{target?.name||current?.name||'灵感首页'} · waterfall-wiki</title><meta name="description" content="自己的图文、视频与声音创作空间"/><link rel="alternate" type="text/markdown" href="/index.md" title="Agent 文档入口"/></Head>
{current&&<header className="page-header feed-heading"><div><h1>{target?.name||current.name}</h1><p>{current.hint}</p></div></header>}
{tagPath&&<div className="breadcrumbs"><Link href={`/${section}`}>全部{current?.name}</Link>{tagPath.split('/').map((_,i)=>{const path=tagPath.split('/').slice(0,i+1).join('/');return <span key={path}> / <Link href={`/${section}/${path}`}>{initial.tags.find(t=>t.path===path)?.name}</Link></span>;})}</div>}
<div className="feed-toolbar"><div className="feed-tabs">{!section?<><Link className="selected" href="/">全部</Link>{sections.map(s=><Link key={s.path} href={`/${s.path}`}>{s.name}</Link>)}</>:<><Link className={!tagPath?'selected':''} href={`/${section}`}>全部</Link>{children.map(t=><Link key={t.id} href={`/${section}/${t.path}`}>{t.name}</Link>)}</>}</div><span className="sort-label"><ArrowDown size={13}/>最近收录</span></div>
{initial.unavailable?<div className="empty-state"><Layers/><h2>素材库暂时没有连接上</h2><p>请稍后刷新,已保存的内容不会因此丢失。</p></div>:(posts.length||(!section&&skillCatalog.some(s=>(s.title+s.description+s.category).toLowerCase().includes(String(router.query.q||'').toLowerCase()))))?<Masonry posts={posts} includeSkills={!section} q={String(router.query.q||'')}/>:<div className="empty-state"><div className="empty-art"><span/><ImageIcon size={42} strokeWidth={1.2}/><i><AudioLines size={18}/></i><b><Film size={19}/></b></div><span className="eyebrow">A LITTLE SPACE FOR SOMETHING GOOD</span><h2>{router.query.q?'还没有找到这份灵感':'这里还没有内容'}</h2><p>{router.query.q?'换一个词试试看。':'导入图片、视频或声音,开始整理你的素材。'}</p><Link className="primary-button" href={`/library/import${current&&['image','video','audio'].includes(current.kind)?'?kind='+current.kind:''}`}><Upload size={16}/>导入素材<ArrowUpRight size={16}/></Link><small>图文和动态作品通过代码加入,自由决定每一个像素。</small></div>}
{cursor&&<div className="load-more"><button disabled={busy} onClick={load}>{busy?'正在翻找…':error||'再看一些'}<ArrowDown size={14}/></button></div>}
<footer className="page-footer">PROMPT <span>·</span> PROBABLY RENDERING ONE MORE PIXEL TONIGHT</footer>
<footer className="page-footer">waterfall-wiki <span>·</span> PROBABLY RENDERING ONE MORE PIXEL TONIGHT</footer>
</Shell>;
}
+1 -1
View File
@@ -4,7 +4,7 @@ import {Shell} from './Shell';
import {SkillCard} from './SkillCard';
import {skillCatalog} from '@/content/skills/catalog';
import {guidanceDocuments,humanDocumentUrl} from '@/content/skills/guidance';
export function GuidanceIndex(){return <Shell><Head><title>指导文档 · PROMPT</title><link rel="canonical" href="/skills"/><link rel="alternate" type="text/markdown" href="/skills/index.md" title="指导文档"/></Head>
export function GuidanceIndex(){return <Shell><Head><title>指导文档 · waterfall-wiki</title><link rel="canonical" href="/skills"/><link rel="alternate" type="text/markdown" href="/skills/index.md" title="指导文档"/></Head>
<header className="page-header"><div><h1>指导文档</h1><p>每篇都有独立地址,网页与 Markdown 一一对应。沿着引用,找到需要的方法。</p></div></header>
<article className="docs-body"><h2>全部文档</h2><p>这些分组只帮助浏览。任何一篇都可以独立进入,也可以引用其他文档。</p><div className="guidance-directory">{guidanceDocuments.map(doc=><div key={doc.path}><Link href={humanDocumentUrl(doc.path)}>{doc.title}</Link><small>{doc.collection}</small><a href={`${humanDocumentUrl(doc.path)}/index.md`}>Markdown ↗</a></div>)}</div></article>
<h2>按创作主题浏览</h2>
+2 -2
View File
@@ -7,9 +7,9 @@ export function Shell({children}:{children:ReactNode}){
const router=useRouter();const [open,setOpen]=useState(false);const [query,setQuery]=useState(String(router.query.q||''));
useEffect(()=>setQuery(String(router.query.q||'')),[router.query.q]);
return <div className="app-shell"><button className="mobile-menu icon-button" aria-label={open?"关闭导航":"展开导航"} aria-expanded={open} onClick={()=>setOpen(!open)}>{open?<X size={22}/>:<Menu size={22}/>}</button>
<aside className={`sidebar ${open?'is-open':''}`}><Link href="/" className="brand" aria-label="PROMPT 首页" onClick={()=>setOpen(false)}><img className="brand-mark" src="/brand-mark.svg" width={40} height={40} alt=""/><strong>PROMPT</strong></Link>
<aside className={`sidebar ${open?'is-open':''}`}><Link href="/" className="brand" aria-label="waterfall-wiki 首页" onClick={()=>setOpen(false)}><img className="brand-mark" src="/brand-mark.svg" width={40} height={40} alt=""/><strong>waterfall-wiki</strong></Link>
<nav>{groups.map((g,i)=><div className="nav-group" key={i}>{g.label&&<p>{g.label}</p>}{g.items.map(item=>{const active=item.href==='/'?router.asPath.split('?')[0]==='/':router.asPath.split('?')[0].startsWith(item.href);return <Link key={item.href} href={item.href} title={item.label} className={`nav-item ${active?'active':''}`} onClick={()=>setOpen(false)}><item.icon size={24} strokeWidth={active?2.2:1.8}/><span>{item.label}</span></Link>;})}</div>)}</nav>
</aside><main className="main-content"><div className="global-topbar"><form className="global-search" role="search" onSubmit={e=>{e.preventDefault();const path=router.asPath.split('?')[0];const destination=path==='/categories'?path:'/';void router.push({pathname:destination,query:query?{q:query}:{}});}}><Search size={24}/><input aria-label="搜索素材包" placeholder="搜索知识、灵感和素材" value={query} onChange={e=>setQuery(e.target.value)}/>{query&&<button type="button" aria-label="清空搜索" onClick={()=>setQuery('')}><X size={20}/></button>}</form></div>{children}</main>{open&&<button className="nav-scrim" aria-label="关闭导航" onClick={()=>setOpen(false)}/>}
</aside><main className="main-content"><div className="global-topbar"><form className="global-search" role="search" onSubmit={e=>{e.preventDefault();const path=router.asPath.split('?')[0];const destination=path==='/categories'?path:'/';void router.push({pathname:destination,query:{...(destination==='/categories'&&router.query.category?{category:router.query.category}:{}),...(query.trim()?{q:query.trim()}:{})}});}}><Search size={24}/><input aria-label="搜索笔记全文" placeholder="搜索知识、灵感和素材" value={query} onChange={e=>setQuery(e.target.value)}/>{query&&<button type="button" aria-label="清空搜索" onClick={()=>{setQuery('');void router.push({pathname:router.pathname==='/categories'?'/categories':'/',query:router.query.category?{category:router.query.category}:{}})}}><X size={20}/></button>}<button type="submit" className="search-submit">搜索</button></form></div>{children}</main>{open&&<button className="nav-scrim" aria-label="关闭导航" onClick={()=>setOpen(false)}/>}
</div>;
}
+1 -1
View File
@@ -26,7 +26,7 @@ export function SkillDocs({documentPath,documentId='index',skillId='street-peopl
setCopied(true);
}catch{setCopied(false)}
}
return <Shell><Head><title>{doc.title} · 指导文档 · PROMPT</title><link rel="canonical" href={humanDocumentUrl(path)}/><link rel="alternate" type="text/markdown" href={markdownDocumentUrl(path)} title={doc.title}/></Head>
return <Shell><Head><title>{doc.title} · 指导文档 · waterfall-wiki</title><link rel="canonical" href={humanDocumentUrl(path)}/><link rel="alternate" type="text/markdown" href={markdownDocumentUrl(path)} title={doc.title}/></Head>
<div className="docs-top"><Link href="/skills">← 全部指导文档</Link><button onClick={()=>setOpen(v=>!v)} aria-expanded={open}><PanelRight size={16}/>文档与来源 · {doc.resources.length}</button></div>
<div className={`docs-layout ${open?'with-sources':''}`}><article className="docs-body">
<div className="docs-eyebrow">{doc.collection} / 指导文档</div><h1>{doc.title}</h1>
+1 -1
View File
@@ -58,6 +58,6 @@ export function guidanceMarkdown(path:string,base=origin){
}
export function guidanceIndexMarkdown(root=false,base=origin){
const url=(href:string)=>new URL(href,base).href;
return `# ${root?'PROMPT':'指导文档'}\n\n[网页版本](${url(root?'/':'/skills')}) · [指导文档目录](${url('/skills/index.md')})\n\n每篇指导文档都有独立网址,网页地址加 /index.md 即为对应的 Markdown。文档可以相互引用,不要求从某个技能入口逐级进入。\n\n## 全部指导文档\n\n`+
return `# ${root?'waterfall-wiki':'指导文档'}\n\n[网页版本](${url(root?'/':'/skills')}) · [指导文档目录](${url('/skills/index.md')})\n\n每篇指导文档都有独立网址,网页地址加 /index.md 即为对应的 Markdown。文档可以相互引用,不要求从某个技能入口逐级进入。\n\n## 全部指导文档\n\n`+
guidanceDocuments.map(d=>`- [${d.title}](${url(markdownDocumentUrl(d.path))}) — ${d.collection}`).join('\n')+'\n';
}
+1 -1
View File
@@ -2,7 +2,7 @@ export const namespaces=['Main','File','Category','Template','Draft','Help'] as
export type Namespace=typeof namespaces[number];
export type WikiPage={namespace:Namespace;slug:string;title:string;summary:string;body:string;categories:string[];color:string};
export const wikiPages:WikiPage[]=[
{namespace:'Main',slug:'welcome',title:'让灵感有处可寻',summary:'像翻阅笔记一样,发现和连接知识。',body:'这里是 PROMPT Wiki。每个条目都有一个稳定的页面地址,以及对应的 Markdown 正文。\n\n名字空间决定页面的用途,分类把不同用途的内容连接起来。素材可以被多篇条目引用,草稿也可以在成熟后成为正式条目。',categories:['创作方法'],color:'#f5ddd2'},
{namespace:'Main',slug:'welcome',title:'让灵感有处可寻',summary:'像翻阅笔记一样,发现和连接知识。',body:'这里是 waterfall-wiki Wiki。每个条目都有一个稳定的页面地址,以及对应的 Markdown 正文。\n\n名字空间决定页面的用途,分类把不同用途的内容连接起来。素材可以被多篇条目引用,草稿也可以在成熟后成为正式条目。',categories:['创作方法'],color:'#f5ddd2'},
{namespace:'Help',slug:'namespaces',title:'名字空间,内容的不同房间',summary:'条目、文件、分类、模板与草稿,各有自己的位置。',body:'Main:正式知识条目。\nFile:图片、视频、音频的说明页,现有素材包位于 /wiki/File:slug,同时保留 /p/ 兼容地址。\nCategory:跨名字空间的分类索引。\nTemplate:可复用的内容结构说明。\nDraft:待完善的草稿(当前内容公开,不用于私密信息)。\nHelp:使用指南。\n\n在 src/content/wiki.ts 添加内容,即可生成网页与 AI 正文。现有素材包也提供 /api/wiki-post/slug 的 Markdown。',categories:['使用指南'],color:'#dde8df'},
{namespace:'Template',slug:'idea',title:'一个想法的骨架',summary:'从问题、观察到表达,让创作有迹可循。',body:'## 问题\n你想回答什么?\n\n## 观察\n收集具体场景与可信来源。\n\n## 表达\n把结论写成独立的页面,再交给创作站制作。',categories:['创作方法'],color:'#e6def0'},
{namespace:'Draft',slug:'inbox',title:'还没成形,也值得留下',summary:'给正在生长的想法留一个位置。',body:'草稿用于公开孵化内容。补充来源、结构和分类后,可以迁移到 Main 名字空间。',categories:['创作方法'],color:'#f0e7ca'}];
+3 -3
View File
@@ -6,9 +6,9 @@ export const apiDocuments:Record<string,readonly string[]>={
"统一内容流",
"GET",
"查询参数:q(可选,最多 200 字符);category(可选,标签名称或命名空间);cursor(可选,上一页 nextCursor)。",
"JSON:entries 数组与 nextCursor;没有更多结果时 nextCursor 为 null。静态内容仅出现在第一页;已由相同 publicId 的数据库笔记接管时不重复展示。",
"JSON:entries、total、sort 与 nextCursor;entry.backlinkCount 为不同来源笔记数(重复链接和自引用不计);默认按引用数降序,搜索时先按标题/标签/简介/正文的匹配程度再按引用数排序,最后按新旧排序。q 支持空格分隔的多个关键词(全部匹配)及双引号短语,中英文不区分大小写。分类过滤发生在分页之前。没有更多结果时 nextCursor 为 null。静态文档与数据库笔记统一搜索与分页;已由相同 publicId 的数据库笔记接管时不重复展示。",
"GET /api/explore-feed?q=排版",
"503:素材库暂时无法连接。"
"400:游标无效或与搜索条件不符;503:素材库暂时无法连接。"
],
"/api/feed": [
"素材列表",
@@ -22,7 +22,7 @@ export const apiDocuments:Record<string,readonly string[]>={
"读取与编辑笔记",
"GET, PUT",
"路径参数:id,笔记稳定 ID(publicId 或存储 UUID)。PUT 使用 application/json,以下字段必填:title(1–200 字符)、description(最多 1000 字符)、markdown(最多 100000 字符)、tags(最多 50 个标签 UUID)、revision(GET 返回的 entry.revision,64 位十六进制)。可选 assets(最多 100 项 {id:媒体 UUID,role:content|caption},替换媒体关联,原二进制不删除);coverAssetId(图片 UUID 或 null,必须为本笔记 content 图片;null 清除显式封面)。静态代码页须先通过创建接口保存为数据库笔记,才可更新媒体。",
"GET 返回 {entry,tags},entry.assets 为媒体关联、entry.coverAssetId 为显式封面;PUT 返回更新后的 {entry}。先 GET 获取 revision,再 PUT;冲突后重新读取。",
"GET 返回 {entry,tags},entry.backlinks 为引用来源 {id,title} 数组,entry.backlinkCount 为其长度;只计算正文中本站 post 的 Markdown 链接(含引用式链接),排除代码块、图片、外站链接及自引用。entry.assets 为媒体关联、entry.coverAssetId 为显式封面;PUT 返回更新后的 {entry}。先 GET 获取 revision,再 PUT;冲突后重新读取。",
"GET /api/notes/{id}\nPUT /api/notes/{id}\n{\"title\":\"标题\",\"description\":\"简介\",\"markdown\":\"正文\",\"tags\":[],\"revision\":\"<GET 返回的 entry.revision>\"}",
"400:输入错误;404:笔记不存在;409:版本冲突。"
],
+42
View File
@@ -0,0 +1,42 @@
import {fromMarkdown} from 'mdast-util-from-markdown';
export type SearchDocument={id:string;aliases?:string[];title:string;description:string;markdown:string;categories:string[];namespace:string;createdAt:string};
export type Backlink={id:string;title:string};
const normalize=(value:string)=>value.normalize('NFKC').toLocaleLowerCase().replace(/\s+/g,' ').trim();
/** Markdown AST excludes images, code examples and unused link definitions. */
export function documentLinks(markdown:string):string[]{
const tree=fromMarkdown(markdown),definitions=new Map<string,string>(),links:string[]=[];
function visit(node:typeof tree|typeof tree.children[number],collect:boolean){
if(node.type==='definition'&&!collect)definitions.set(normalize(node.identifier),node.url);
if(collect&&node.type==='link')links.push(node.url);
if(collect&&node.type==='linkReference'){const url=definitions.get(normalize(node.identifier));if(url)links.push(url);}
if('children' in node)for(const child of node.children)visit(child as typeof tree.children[number],collect);
}
visit(tree,false);visit(tree,true);return links;
}
export function backlinksFor(documents:SearchDocument[]){
const targets=new Map(documents.flatMap(d=>[d.id,...(d.aliases||[])].map(id=>[id,d.id] as const))),result=new Map(documents.map(d=>[d.id,[] as Backlink[]]));
for(const source of documents){const seen=new Set<string>();for(const href of documentLinks(source.markdown)){
let url:URL;try{url=new URL(href,'http://8.211.154.134:18131/explore/'+source.id);}catch{continue;}
if(!['http:','https:'].includes(url.protocol)||url.host!=='8.211.154.134:18131')continue;
const match=url.pathname.match(/^\/(?:explore|api\/notes)\/([a-f0-9-]+)\/?$/),id=match&&targets.get(match[1]);
if(id&&id!==source.id&&!seen.has(id)){seen.add(id);result.get(id)!.push({id:source.id,title:source.title});}
}}
for(const refs of result.values())refs.sort((a,b)=>a.title.localeCompare(b.title)||a.id.localeCompare(b.id));return result;
}
export function searchTerms(query:string){return (normalize(query).match(/"[^"]+"|[^\s"]+/g)||[]).map(s=>s.replace(/^"|"$/g,''));}
export function searchScore(doc:SearchDocument,query:string):number{
const fields=[normalize(doc.title),normalize(doc.categories.join(' ')),normalize(doc.description),normalize(doc.markdown)],terms=searchTerms(query);
if(!terms.length)return 0;
if(!terms.every(t=>fields.some(f=>f.includes(t))))return -1;
return terms.reduce((score,t)=>score+fields.reduce((n,f,i)=>n+(f.includes(t)?[20,10,5,1][i]:0),0),0)+(fields[0]===normalize(query)?100:0);
}
export function rankDocuments(documents:SearchDocument[],q='',category=''){
const links=backlinksFor(documents);
return documents.map(doc=>({doc,score:searchScore(doc,q),backlinkCount:links.get(doc.id)!.length})).filter(x=>x.score>=0&&(!category||x.doc.categories.includes(category)||x.doc.namespace===category)).sort((a,b)=>b.score-a.score||b.backlinkCount-a.backlinkCount||b.doc.createdAt.localeCompare(a.doc.createdAt)||a.doc.id.localeCompare(b.doc.id));
}
export class InvalidDiscoveryCursor extends Error{}
export function discoveryPage<T extends {doc:{id:string}}>(ranked:T[],q:string,category:string,cursor?:string){
let start=0;if(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,'base64url').toString());if(parsed.q!==q||parsed.category!==category||typeof parsed.after!=='string')throw Error();const index=ranked.findIndex(x=>x.doc.id===parsed.after);if(index<0)throw Error();start=index+1;}catch{throw new InvalidDiscoveryCursor('无效的搜索游标,请重新搜索。');}}
const rows=ranked.slice(start,start+24),last=rows.at(-1);
return {rows,nextCursor:start+24<ranked.length&&last?Buffer.from(JSON.stringify({q,category,after:last.doc.id})).toString('base64url'):null,total:ranked.length};
}
+29 -5
View File
@@ -5,14 +5,15 @@ import {wikiPages,wikiMarkdown} from '@/content/wiki';
import {skillCatalog} from '@/content/skills/catalog';
import {publicPostId} from './model';
import {pageId,exploreUrl,guidanceUrl} from '@/content/page-links';
import {getPostById,feed,publishedPublicIds} from './library';
import {getPostById,discoveryDocuments,postsByPublicIds} from './library';
import {backlinksFor,rankDocuments,discoveryPage,type SearchDocument,type Backlink} from './discovery';
import {applyStaticEdit,staticEdits,withRevision} from './note-edits';
export type ExploreMedia={kind:'image'|'video'|'audio';url:string;title:string;poster?:string};
export type ExploreEntry={id:string;title:string;description:string;imageCount:number;namespace:string;categories:string[];markdown:string;media:ExploreMedia[];color:string;postSlug?:string;editableMarkdown?:string;revision?:string;assets?:{id:string;kind:string;role:string}[];coverAssetId?:string|null};
export type ExploreEntry={id:string;title:string;description:string;imageCount:number;namespace:string;categories:string[];markdown:string;media:ExploreMedia[];color:string;postSlug?:string;editableMarkdown?:string;revision?:string;assets?:{id:string;kind:string;role:string}[];coverAssetId?:string|null;backlinkCount?:number;backlinks?:Backlink[];searchExcerpt?:string};
export const staticEntries:ExploreEntry[]=[...guidanceDocuments.map(doc=>{const card=skillCatalog.find(c=>doc.path===c.id);return {id:pageId('guidance:'+doc.path),title:doc.title,description:noteDescriptions[doc.path]||doc.blocks.find(b=>b.type==='paragraph')?.text||doc.title,imageCount:new Set([...(card?[card.image]:[]),...doc.resources.filter(r=>r.kind==='image').map(r=>r.href)]).size,namespace:'Main',categories:[doc.collection],markdown:guidanceMarkdown(doc.path)!,media:Array.from(new Map([...(card?[{kind:'image' as const,url:card.image,title:card.alt}]:[]),...doc.resources.filter(r=>r.kind==='image').map(r=>({kind:'image' as const,url:r.href,title:r.title}))].map(m=>[m.url,m])).values()),color:'#eee5dc'};}),...wikiPages.map(page=>({id:pageId('wiki:'+page.namespace+':'+page.slug),title:page.title,description:page.summary,imageCount:0,namespace:page.namespace,categories:page.categories,markdown:wikiMarkdown(page),media:[],color:page.color}))];
// Canonicalize document references, including absolute links; pictures remain explicit links.
export function canonicalMarkdown(text:string){return text.replace(/\]\((?:http:\/\/8\.211\.154\.134:18131)?\/skills\/([^ )]+)\)/g,(whole,path:string)=>{const clean=path.replace(/\/index\.md$/,'').replace(/\.md$/,'');return pageId('guidance:'+clean)?']('+guidanceUrl(clean)+'?agent_mode=True)':whole;});}
export async function getEntry(id:string,client?:PoolClient):Promise<ExploreEntry|null>{
async function readEntry(id:string,client?:PoolClient):Promise<ExploreEntry|null>{
const validId=/^(?:[0-9a-f]{24}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/.test(id);
const post=validId&&(process.env.DATABASE_URL||client||id.length===36)?await getPostById(id,client):null;
if(!post){const page=staticEntries.find(e=>e.id===id);if(!page)return null;const edits=await staticEdits(client);return withRevision(applyStaticEdit({...page,markdown:canonicalMarkdown(page.markdown)},edits.find(e=>e.page_id===id)));}
@@ -22,5 +23,28 @@ export async function getEntry(id:string,client?:PoolClient):Promise<ExploreEntr
const body=editableMarkdown+'\n\n'+post.assets.filter(a=>a.derivation).map(a=>'['+({poster:'视频封面',audio_track:'独立音轨',silent_video:'静音视频'}[a.derivation||'']||a.derivation)+'](/api/media/'+a.id+')').join(' · ');
return withRevision({id:publicPostId(post),assets:post.assets.filter(a=>a.kind!=='text').map(a=>({id:a.id,kind:a.kind,role:a.role})),coverAssetId:post.cover_asset_id,title:post.title,editableMarkdown,description:post.description||body.slice(0,180)||post.title,imageCount:media.filter(m=>m.kind==='image').length,namespace:['image','video','audio'].includes(post.kind)?'File':'Main',categories:post.tags.map(t=>t.name),markdown:'# '+post.title+'\n\n'+body,media,color:'#eee5dc',postSlug:post.slug});
}
export async function exploreFeed(q='',category='',cursor?:string){const [data,edits,published]=await Promise.all([feed({q,cursor}),staticEdits(),publishedPublicIds()]);const pages=staticEntries.filter(e=>!published.includes(e.id)).map(e=>applyStaticEdit(e,edits.find(edit=>edit.page_id===e.id)));return {entries:[...(cursor?[]:pages.filter(e=>(!q||(e.title+e.description).includes(q)))),...data.posts.map(post=>{const cover=post.cover_asset_id||post.assets.find(a=>a.kind==='image'&&a.role==='content')?.id;const video=post.assets.find(a=>a.kind==='video');return {id:publicPostId(post),title:post.title,description:post.description||post.assets.find(a=>a.kind==='text')?.body?.slice(0,180)||post.title,imageCount:post.assets.filter(a=>a.kind==='image'&&a.role==='content').length,namespace:['image','video','audio'].includes(post.kind)?'File':'Main',categories:post.tags.map(t=>t.name),markdown:'',media:cover?[{kind:'image' as const,url:'/api/media/'+cover,title:post.title}]:video?.variants.includes('poster')?[{kind:'image' as const,url:'/api/media/'+post.assets.find(a=>a.source_asset_id===video.id&&a.derivation==='poster')?.id,title:post.title}]:[],color:'#eee5dc'};})].filter(e=>!category||e.categories.includes(category)||e.namespace===category),nextCursor:data.nextCursor};}
export function entryText(entry:ExploreEntry){return `${entry.markdown}\n\nDescription: ${entry.description}\nNamespace: ${entry.namespace}\nCategories: ${entry.categories.join(', ')}\n\n`+entry.media.map(m=>`- ${m.kind}: [${m.title}](${m.url})`).join('\n')+'\n\n[网页]('+exploreUrl(entry.id)+')\n';}
export async function discoveryCorpus(client?:PoolClient){
const [stored,edits]=await Promise.all([process.env.DATABASE_URL||client?discoveryDocuments(client):Promise.resolve([]),staticEdits(client)]);
const published=new Set(stored.map(p=>p.public_id));
const pages=staticEntries.filter(e=>!published.has(e.id)).map(e=>applyStaticEdit(e,edits.find(edit=>edit.page_id===e.id)));
const documents:SearchDocument[]=[...pages.map(e=>({id:e.id,title:e.title,description:e.description,markdown:canonicalMarkdown(e.markdown),categories:e.categories,namespace:e.namespace,createdAt:''})),...stored.map(p=>({id:p.public_id||p.id,aliases:[p.id],title:p.title,description:p.description,markdown:canonicalMarkdown(p.markdown),categories:p.categories,namespace:['image','video','audio'].includes(p.kind)?'File':'Main',createdAt:new Date(p.created_at).toISOString()}))];
return {documents,pages};
}
export async function getEntry(id:string,client?:PoolClient):Promise<ExploreEntry|null>{
const entry=await readEntry(id,client);if(!entry)return null;
const {documents}=await discoveryCorpus(client),refs=backlinksFor(documents).get(entry.id)||[];
return {...entry,backlinkCount:refs.length,backlinks:refs};
}
export async function exploreFeed(q='',category='',cursor?:string){
const {documents,pages}=await discoveryCorpus(),ranked=rankDocuments(documents,q,category),page=discoveryPage(ranked,q,category,cursor);
const staticIds=new Set(pages.map(e=>e.id)),posts=await postsByPublicIds(page.rows.filter(r=>!staticIds.has(r.doc.id)).map(r=>r.doc.id));
const entries:ExploreEntry[]=page.rows.map(({doc,backlinkCount})=>{
const original=pages.find(e=>e.id===doc.id);const post=posts.find(p=>publicPostId(p)===doc.id);
if(original)return {...original,backlinkCount,...(q?{searchExcerpt:excerpt(doc.markdown,q)}:{})};
if(!post)throw Error('Search result disappeared');
const cover=post.cover_asset_id||post.assets.find(a=>a.kind==='image'&&a.role==='content')?.id,video=post.assets.find(a=>a.kind==='video'),poster=post.assets.find(a=>a.source_asset_id===video?.id&&a.derivation==='poster')?.id;
return {id:doc.id,title:doc.title,description:doc.description||doc.markdown.slice(0,180)||doc.title,imageCount:post.assets.filter(a=>a.kind==='image'&&a.role==='content').length,namespace:doc.namespace,categories:doc.categories,markdown:'',media:cover?[{kind:'image' as const,url:'/api/media/'+cover,title:doc.title}]:poster?[{kind:'image' as const,url:'/api/media/'+poster,title:doc.title}]:[],color:'#eee5dc',backlinkCount,...(q?{searchExcerpt:excerpt(doc.markdown,q)}:{})};
});return {entries,nextCursor:page.nextCursor,total:page.total,sort:q?'relevance,backlinks,newest':'backlinks,newest'};
}
function excerpt(markdown:string,q:string){const clean=markdown.replace(/[`#*_[\]<>]/g,'').replace(/\s+/g,' '),term=q.trim().replace(/^"|"$/g,'').split(/\s+/)[0]||'',at=clean.toLocaleLowerCase().indexOf(term.toLocaleLowerCase());return (at>50?'…':'')+clean.slice(Math.max(0,at-50),Math.max(0,at-50)+180);}
export function entryText(entry:ExploreEntry){return `${entry.markdown}\n\nDescription: ${entry.description}\nBacklinks: ${entry.backlinkCount??0}\n${(entry.backlinks||[]).map(b=>'引用来源:['+b.title+']('+exploreUrl(b.id)+')').join('\n')}\nNamespace: ${entry.namespace}\nCategories: ${entry.categories.join(', ')}\n\n`+entry.media.map(m=>`- ${m.kind}: [${m.title}](${m.url})`).join('\n')+'\n\n[网页]('+exploreUrl(entry.id)+')\n';}
+12
View File
@@ -33,3 +33,15 @@ export async function feed(options: {kind?: PostKind; path?: string; cursor?: st
}
export async function publishedPublicIds():Promise<string[]>{return (await db().query("SELECT public_id FROM posts WHERE public_id IS NOT NULL")).rows.map(p=>p.public_id);}
/** Lightweight text corpus: no image bodies or media files are loaded. */
export async function discoveryDocuments(client?:PoolClient){
return (await (client||db()).query(`SELECT p.id,p.public_id,p.title,p.description,p.kind,p.created_at,
COALESCE((SELECT string_agg(a.body,E'\n\n' ORDER BY pa.position) FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id AND a.kind='text'),'') AS markdown,
COALESCE((SELECT jsonb_agg(t.name) FROM tags t JOIN post_tags pt ON pt.tag_id=t.id WHERE pt.post_id=p.id),'[]') AS categories
FROM posts p WHERE EXISTS(SELECT 1 FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=p.id AND pa.role IN ('content','caption') AND ((a.storage_key IS NOT NULL AND a.byte_size>0) OR (a.kind='text' AND a.body IS NOT NULL)))`)).rows;
}
export async function postsByPublicIds(ids:string[],client?:PoolClient):Promise<Post[]>{
if(!ids.length)return [];const rows=(await (client||db()).query(`${expand} WHERE COALESCE(p.public_id,p.id::text)=ANY($1::text[])`,[ids])).rows;
return serialize(rows,await tags(client));
}
+2 -1
View File
@@ -1,5 +1,6 @@
import {serveApiDocumentation} from '@/lib/api-documentation';
import type {NextApiRequest,NextApiResponse} from 'next';
import {InvalidDiscoveryCursor} from '@/lib/discovery';
import {exploreFeed} from '@/lib/explore';
export default async function handler(req:NextApiRequest,res:NextApiResponse){
if(serveApiDocumentation(req,res,'/api/explore-feed'))return;if(req.method!=='GET')return res.status(405).end();try{return res.json(await exploreFeed(String(req.query.q||'').slice(0,200),String(req.query.category||''),String(req.query.cursor||'')||undefined));}catch{return res.status(503).json({error:'素材库暂时无法连接'});}}
if(serveApiDocumentation(req,res,'/api/explore-feed'))return;if(req.method!=='GET')return res.status(405).end();try{return res.json(await exploreFeed(String(req.query.q||'').slice(0,200),String(req.query.category||''),String(req.query.cursor||'')||undefined));}catch(e){if(e instanceof InvalidDiscoveryCursor)return res.status(400).json({error:e.message});return res.status(503).json({error:'素材库暂时无法连接'});}}
+1 -1
View File
@@ -9,6 +9,6 @@ export default function handler(req:NextApiRequest,res:NextApiResponse){
const plain=typeof req.query.agent_mode==='string'&&req.query.agent_mode.toLowerCase()==='true';
res.setHeader('Content-Type',plain?'text/plain; charset=utf-8':'application/json; charset=utf-8');
if(req.method==='HEAD')return res.status(200).end();
if(plain)return res.send('# PROMPT 业务 API\n\n各接口使用 GET + agent_mode=True 读取说明;已有参数时用 & 拼接。动态路径允许保留占位符。业务调用请移除该参数。\n\n'+entries.map(e=>`- ${e.title}(${e.methods}):${e.documentation}`).join('\n')+'\n');
if(plain)return res.send('# waterfall-wiki 业务 API\n\n各接口使用 GET + agent_mode=True 读取说明;已有参数时用 & 拼接。动态路径允许保留占位符。业务调用请移除该参数。\n\n'+entries.map(e=>`- ${e.title}(${e.methods}):${e.documentation}`).join('\n')+'\n');
return res.json({entries});
}
+1 -1
View File
@@ -3,4 +3,4 @@ import {publishedPublicIds} from '@/lib/library';
import {staticEntries} from '@/lib/explore';
import {applyStaticEdit,staticEdits} from '@/lib/note-edits';
import {exploreUrl} from '@/content/page-links';
export default async function handler(_:NextApiRequest,res:NextApiResponse){const [edits,published]=await Promise.all([staticEdits(),process.env.DATABASE_URL?publishedPublicIds():Promise.resolve([])]);const entries=staticEntries.filter(e=>!published.includes(e.id)).map(e=>applyStaticEdit(e,edits.find(edit=>edit.page_id===e.id)));res.setHeader('Content-Type','text/plain; charset=utf-8');res.send('# PROMPT\n\n'+entries.map(e=>`- [${e.title}](${exploreUrl(e.id)}?agent_mode=True)`).join('\n')+'\n\n素材分页索引:/api/explore-feed(使用 nextCursor 翻页)。所有内容均使用 /explore/{id}?agent_mode=True 读取纯文本。\n');}
export default async function handler(_:NextApiRequest,res:NextApiResponse){const [edits,published]=await Promise.all([staticEdits(),process.env.DATABASE_URL?publishedPublicIds():Promise.resolve([])]);const entries=staticEntries.filter(e=>!published.includes(e.id)).map(e=>applyStaticEdit(e,edits.find(edit=>edit.page_id===e.id)));res.setHeader('Content-Type','text/plain; charset=utf-8');res.send('# waterfall-wiki\n\n'+entries.map(e=>`- [${e.title}](${exploreUrl(e.id)}?agent_mode=True)`).join('\n')+'\n\n素材分页索引:/api/explore-feed(使用 nextCursor 翻页)。所有内容均使用 /explore/{id}?agent_mode=True 读取纯文本。\n');}
+2 -2
View File
@@ -5,5 +5,5 @@ import {Shell} from '@/components/Shell';
import {ExploreFeed} from '@/components/ExploreFeed';
import {staticEntries,exploreFeed,type ExploreEntry} from '@/lib/explore';
import {tags} from '@/lib/library';
export default function Categories({categories,category,entries,cursor,q}:{categories:string[];category:string;entries:ExploreEntry[];cursor:string|null;q:string}){return <Shell><Head><title>分类 · PROMPT</title></Head><div className="discovery-tabs"><Link href="/categories" className={!category?'selected':''}>全部</Link>{categories.map(c=><Link className={c===category?'selected':''} href={'/categories?category='+encodeURIComponent(c)} key={c}>{c}</Link>)}</div><ExploreFeed key={category+q} initial={entries} cursor={cursor} q={q} category={category}/></Shell>}
export const getServerSideProps:GetServerSideProps=async({query})=>{const category=String(query.category||'');const q=String(query.q||'').slice(0,200);const categories=new Set(['Main','File','Template','Draft','Help',...staticEntries.flatMap(e=>e.categories)]);try{(await tags()).forEach(t=>categories.add(t.name));const data=await exploreFeed(q,category);return {props:{categories:[...categories],category,q,entries:data.entries,cursor:data.nextCursor}};}catch{return {props:{categories:[...categories],category,q,entries:staticEntries.filter(e=>(!category||e.categories.includes(category)||e.namespace===category)&&(!q||(e.title+e.description).includes(q))),cursor:null}}}};
export default function Categories({categories,category,entries,cursor,q,total}:{categories:string[];category:string;entries:ExploreEntry[];cursor:string|null;q:string;total?:number}){return <Shell><Head><title>分类 · waterfall-wiki</title></Head><div className="discovery-tabs"><Link href="/categories" className={!category?'selected':''}>全部</Link>{categories.map(c=><Link className={c===category?'selected':''} href={'/categories?category='+encodeURIComponent(c)} key={c}>{c}</Link>)}</div><ExploreFeed key={category+q} initial={entries} cursor={cursor} q={q} category={category} total={total}/></Shell>}
export const getServerSideProps:GetServerSideProps=async({query})=>{const category=String(query.category||'');const q=String(query.q||'').slice(0,200);const categories=new Set(['Main','File','Template','Draft','Help',...staticEntries.flatMap(e=>e.categories)]);try{(await tags()).forEach(t=>categories.add(t.name));const data=await exploreFeed(q,category);return {props:{categories:[...categories],category,q,entries:data.entries,cursor:data.nextCursor,total:data.total}};}catch{return {props:{categories:[...categories],category,q,entries:staticEntries.filter(e=>(!category||e.categories.includes(category)||e.namespace===category)&&(!q||(e.title+e.description).includes(q))),cursor:null}}}};
+2 -3
View File
@@ -1,8 +1,7 @@
import type {GetServerSideProps} from 'next';
import Head from 'next/head';
import Link from 'next/link';
import {Shell} from '@/components/Shell';
import {ExploreFeed} from '@/components/ExploreFeed';
import {exploreFeed,staticEntries,type ExploreEntry} from '@/lib/explore';
export default function Home({entries,cursor,q,unavailable=false}:{entries:ExploreEntry[];cursor:string|null;q:string;unavailable?:boolean}){return <Shell><Head><title>PROMPT · 发现</title></Head><div className="discovery-tabs"><Link href="/" className="selected">发现</Link><Link href="/categories">分类</Link></div>{unavailable&&<p role="status">素材库暂时无法连接,先看看这些公开笔记。</p>}<ExploreFeed key={q} initial={entries} cursor={cursor} q={q}/></Shell>}
export const getServerSideProps:GetServerSideProps=async({query})=>{const q=String(query.q||'').slice(0,200);try{const data=await exploreFeed(q);return {props:{entries:data.entries,cursor:data.nextCursor,q}}}catch{return {props:{entries:staticEntries.filter(e=>!q||(e.title+e.description).includes(q)),cursor:null,q,unavailable:true}}}};
export default function Home({entries,cursor,q,total,unavailable=false}:{entries:ExploreEntry[];cursor:string|null;q:string;total?:number;unavailable?:boolean}){return <Shell><Head><title>waterfall-wiki · 发现</title></Head>{unavailable&&<p role="status">素材库暂时无法连接,先看看这些公开笔记。</p>}<ExploreFeed key={q} initial={entries} cursor={cursor} q={q} total={total}/></Shell>}
export const getServerSideProps:GetServerSideProps=async({query})=>{const q=String(query.q||'').slice(0,200);try{const data=await exploreFeed(q);return {props:{entries:data.entries,cursor:data.nextCursor,total:data.total,q}}}catch{return {props:{entries:staticEntries.filter(e=>!q||(e.title+e.description).includes(q)),cursor:null,q,unavailable:true}}}};
+1 -1
View File
@@ -12,7 +12,7 @@ export default function Import({allTags}:{allTags:Tag[]}){
const [files,setFiles]=useState<File[]>([]);const [title,setTitle]=useState('');const [description,setDescription]=useState('');const [selected,setSelected]=useState<string[]>([]);const [busy,setBusy]=useState(false);const [error,setError]=useState('');
function choose(list:FileList|null){if(!list)return;const items=Array.from(list);setFiles(items);if(!title&&items[0])setTitle(items[0].name.replace(/\.[^.]+$/,''));}
async function submit(e:FormEvent){e.preventDefault();setError('');setBusy(true);try{const data=new FormData();data.set('kind',kind);data.set('title',title);data.set('description',description);data.set('tags',JSON.stringify(selected));files.forEach(f=>data.append('files',f));const res=await fetch('/api/upload',{method:'POST',body:data});const result=await res.json();if(!res.ok)throw new Error(result.error);await router.push('/explore/'+result.id);}catch(e){setError(e instanceof Error?e.message:'上传失败');}finally{setBusy(false);}}
return <Shell><Head><title>素材入库 · PROMPT</title></Head><header className="page-header"><div><span className="eyebrow">MAKE ROOM FOR INSPIRATION</span><h1>导入素材</h1><p>支持多文件导入。同一组素材收录为一个素材包,每份文件都可以再次引用。</p></div></header><form className="editor-panel" onSubmit={submit}>
return <Shell><Head><title>素材入库 · waterfall-wiki</title></Head><header className="page-header"><div><span className="eyebrow">MAKE ROOM FOR INSPIRATION</span><h1>导入素材</h1><p>支持多文件导入。同一组素材收录为一个素材包,每份文件都可以再次引用。</p></div></header><form className="editor-panel" onSubmit={submit}>
<div className="kind-picker">{[{id:'image',name:'图片',Icon:Image},{id:'video',name:'视频',Icon:Film},{id:'audio',name:'声音',Icon:AudioLines}].map(t=><button type="button" key={t.id} disabled={busy} className={kind===t.id?'selected':''} onClick={()=>{setKind(t.id);setFiles([]);}}><t.Icon size={19}/>{t.name}</button>)}</div>
<label className="drop-zone" onDragOver={e=>e.preventDefault()} onDrop={e=>{e.preventDefault();if(!busy)choose(e.dataTransfer.files);}}><input type="file" multiple disabled={busy} accept={kind==='image'?'image/jpeg,image/png,image/webp,image/gif,image/avif':kind+'/*'} onChange={e=>choose(e.target.files)}/><span className="upload-circle"><Upload size={24}/></span><strong>选择文件或拖放到这里</strong><span>最多 16 个文件,单个不超过 250 MB</span></label>
{files.length>0&&<ul className="file-list">{files.map((f,i)=><li key={i}><Check size={15}/><span>{f.name}</span><small>{(f.size/1024/1024).toFixed(1)} MB</small><button type="button" aria-label={`移除 ${f.name}`} disabled={busy} onClick={()=>setFiles(a=>a.filter((_,j)=>i!==j))}><X size={14}/></button></li>)}</ul>}
+1 -1
View File
@@ -16,5 +16,5 @@ export default function Doodle(){
const [selected,setSelected]=useState(0);const [color,setColor]=useState('#fffaf0');const [copied,setCopied]=useState(false);
const svg=()=>`<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><path d="${strokes[selected].path}" fill="none" stroke="${color}" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
function download(){const url=URL.createObjectURL(new Blob([svg()],{type:'image/svg+xml'}));const a=document.createElement('a');a.href=url;a.download=`prompt-doodle-${selected+1}.svg`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
return <Shell><Head><title>线条灵感 · PROMPT</title></Head><header className="page-header"><div><span className="eyebrow">SMALL LINES, LITTLE STORIES</span><h1>线条工具</h1><p>选择图形、调整颜色,下载后用于照片涂鸦。</p></div><span className="pill"><Sparkles size={14}/>照片涂鸦工具箱</span></header><div className="doodle-layout"><section className="doodle-catalog">{strokes.map((s,i)=><button key={s.name} onClick={()=>{setSelected(i);setCopied(false);}} className={`doodle-card ${i===selected?'selected':''}`}><div><svg viewBox="0 0 128 128"><path d={s.path} fill="none" stroke={color} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/></svg></div><strong>{s.name}</strong><small>{s.hint}</small></button>)}</section><aside className="surface doodle-inspector"><span className="eyebrow">A LITTLE MARK</span><div className="doodle-large"><svg viewBox="0 0 128 128"><path d={strokes[selected].path} fill="none" stroke={color} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/></svg></div><h2>{strokes[selected].name}</h2><p>{strokes[selected].hint}</p><div className="swatches">{['#fffaf0','#332c28','#ef6954','#ecc75b'].map(c=><button aria-label={`线条颜色 ${c}`} key={c} style={{background:c}} className={c===color?'selected':''} onClick={()=>setColor(c)}/>)}</div><button className="primary-button" onClick={download}><Download size={16}/>下载透明底 SVG</button><button className="secondary-button" onClick={async()=>{await navigator.clipboard.writeText(svg());setCopied(true);}}><Copy size={16}/>{copied?'已复制':'复制线条'}</button><p className="form-note">小图用来挑选造型与记录想法。正式画进照片时,位置、比例与笔触仍需要顺着画面调整。</p></aside></div></Shell>;
return <Shell><Head><title>线条灵感 · waterfall-wiki</title></Head><header className="page-header"><div><span className="eyebrow">SMALL LINES, LITTLE STORIES</span><h1>线条工具</h1><p>选择图形、调整颜色,下载后用于照片涂鸦。</p></div><span className="pill"><Sparkles size={14}/>照片涂鸦工具箱</span></header><div className="doodle-layout"><section className="doodle-catalog">{strokes.map((s,i)=><button key={s.name} onClick={()=>{setSelected(i);setCopied(false);}} className={`doodle-card ${i===selected?'selected':''}`}><div><svg viewBox="0 0 128 128"><path d={s.path} fill="none" stroke={color} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/></svg></div><strong>{s.name}</strong><small>{s.hint}</small></button>)}</section><aside className="surface doodle-inspector"><span className="eyebrow">A LITTLE MARK</span><div className="doodle-large"><svg viewBox="0 0 128 128"><path d={strokes[selected].path} fill="none" stroke={color} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/></svg></div><h2>{strokes[selected].name}</h2><p>{strokes[selected].hint}</p><div className="swatches">{['#fffaf0','#332c28','#ef6954','#ecc75b'].map(c=><button aria-label={`线条颜色 ${c}`} key={c} style={{background:c}} className={c===color?'selected':''} onClick={()=>setColor(c)}/>)}</div><button className="primary-button" onClick={download}><Download size={16}/>下载透明底 SVG</button><button className="secondary-button" onClick={async()=>{await navigator.clipboard.writeText(svg());setCopied(true);}}><Copy size={16}/>{copied?'已复制':'复制线条'}</button><p className="form-note">小图用来挑选造型与记录想法。正式画进照片时,位置、比例与笔触仍需要顺着画面调整。</p></aside></div></Shell>;
}
+1
View File
@@ -44,3 +44,4 @@
.note-editor .note-editor-body{font-family:ui-monospace,SFMono-Regular,monospace;font-size:13px;min-height:260px;tab-size:2}.note-editor details{margin:16px 0}.note-editor summary{cursor:pointer;font-size:13px;color:#526c80}
.note-editor-actions{display:flex;justify-content:flex-end;gap:12px;position:sticky;bottom:-28px;padding:14px 0;background:#fff;border-top:1px solid #eee;margin-top:24px}
.note-editor .tag-input-row input{width:0}.note-editor .tag-input-selected button,.note-editor .tag-input-suggestions button{font:inherit;font-size:12px}
.brand strong{font-size:17px;letter-spacing:-.6px;overflow-wrap:anywhere}.global-search .search-submit{font-size:13px;white-space:nowrap;padding:7px 12px;border-radius:18px;background:#fff;color:#444}.backlink-count{display:inline-flex;align-items:center;gap:5px;color:#737b79;font-size:12px;margin:0 2px 10px}.backlink-count:hover{color:#315775;text-decoration:underline}.search-results-heading{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;margin:0 0 24px;font-size:15px}.search-results-heading span{color:#888;font-size:12px}.discovery-card .search-excerpt{font-size:12px;line-height:1.7;color:#6a746c;border-left:2px solid #ccd5ce;padding-left:9px;margin:0 2px 12px;overflow-wrap:anywhere}.note-backlinks{border-top:1px solid #eee;margin-top:26px;padding-top:18px}.note-backlinks h2{font-size:15px;font-weight:600}.note-backlinks ul{list-style:none;padding:0;display:grid;gap:12px}.note-backlinks a{font-size:13px;line-height:1.7}.note-backlinks p{font-size:13px;color:#888}
+21
View File
@@ -0,0 +1,21 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {backlinksFor,documentLinks,rankDocuments,discoveryPage,InvalidDiscoveryCursor,type SearchDocument} from '../src/lib/discovery';
const doc=(id:string,patch:Partial<SearchDocument>={}):SearchDocument=>({id,title:'普通笔记 '+id,description:'',markdown:'',categories:[],namespace:'Main',createdAt:'2026-01-01',...patch});
test('backlinks count distinct documents, resolve UUID aliases and ignore self/external/image/code links',()=>{
const a=doc('a',{aliases:['aaaa-1111'],markdown:'[self](/explore/a)'}),b=doc('b',{markdown:'[inline](/explore/a) [again](http://8.211.154.134:18131/explore/aaaa-1111?agent_mode=True#x)\n\n[reference][target]\n\n[target]: /api/notes/a\n\n![image](/explore/c)\n\n`[code](/explore/c)`\n\n```md\n[fenced](/explore/c)\n```\n[external](https://example.com/explore/c)'}),c=doc('c',{markdown:'[a](/explore/a)'});
const refs=backlinksFor([a,b,c]);assert.deepEqual(refs.get('a')?.map(r=>r.id),['b','c']);assert.equal(refs.get('c')?.length,0);assert.equal(documentLinks(b.markdown).length,4);
});
test('search includes body, tags and descriptions; matches all terms, casefolds and ranks title above body',()=>{
const documents=[doc('a',{markdown:'正文专属关键词 React 实践',categories:['课程']}),doc('b',{title:'REACT 实践',description:'正文专属关键词'}),doc('c',{description:'React 介绍'})];
assert.deepEqual(rankDocuments(documents,'react 实践').map(r=>r.doc.id),['b','a']);
assert.deepEqual(rankDocuments(documents,'课程 正文专属关键词').map(r=>r.doc.id),['a']);
assert.deepEqual(rankDocuments(documents,'"react 实践"').map(r=>r.doc.id),['b','a']);assert.equal(rankDocuments(documents,'不存在').length,0);
});
test('default order favors inbound links and filters the entire corpus before paginating',()=>{
const documents=Array.from({length:52},(_,i)=>doc(i.toString(16).padStart(3,'0'),{categories:i%2?['wanted']:[],markdown:i?'[target](/explore/000)':''}));
const ranked=rankDocuments(documents);assert.equal(ranked[0].doc.id,'000');assert.equal(ranked[0].backlinkCount,51);
const filtered=rankDocuments(documents,'','wanted'),first=discoveryPage(filtered,'','wanted'),second=discoveryPage(filtered,'','wanted',first.nextCursor!);
assert.equal(first.total,26);assert.equal(first.rows.length,24);assert.equal(second.rows.length,2);assert.equal(second.nextCursor,null);assert.equal(new Set([...first.rows,...second.rows].map(r=>r.doc.id)).size,26);
assert.throws(()=>discoveryPage(filtered,'different','wanted',first.nextCursor!),InvalidDiscoveryCursor);assert.throws(()=>discoveryPage(filtered,'','wanted','bad'),InvalidDiscoveryCursor);
});
+10
View File
@@ -36,6 +36,16 @@ test('real PostgreSQL + S3 notes, flat tags, resource sharing and video processi
const reused=await request('/api/posts',{kind:'image',title:'同一张图的另一种用法',description:'同一素材的独立说明',assets:[{id:first.assets[0]}],tags:[root.id]});
assert.equal((await db().query('SELECT count(*)::integer AS n FROM post_assets WHERE asset_id=$1',[first.assets[0]])).rows[0].n,2);
const filtered=await request('/api/feed?section=images&path=lines');assert.equal(filtered.posts.length,1);assert.equal(filtered.posts.find((p:{id:string})=>p.id===reused.id).description,'同一素材的独立说明');assert.equal((await request('/api/feed?section=images&path=white')).posts.length,1);
// A real stored body-only match and backlinks must update through the public API.
const targetNote=await request('/api/posts',{kind:'article',title:'引用目标',text:'仅在正文中的索引验证 OrchidLexicon',tags:[root.id]});
const referring=await request('/api/posts',{kind:'article',title:'引用来源',text:`[目标](${targetNote.url}) [重复](${targetNote.url}?agent_mode=True)`,tags:[]});
const targetEntry=(await request('/api/notes/'+targetNote.id)).entry;
assert.equal(targetEntry.backlinkCount,1);assert.equal(targetEntry.backlinks[0].id,referring.id);
const bodySearch=await request('/api/explore-feed?q=orchidlexicon');assert.equal(bodySearch.total,1);assert.equal(bodySearch.entries[0].id,targetNote.id);
const mixedSearch=await request('/api/explore-feed?q='+encodeURIComponent('OrchidLexicon 线条'));assert.equal(mixedSearch.total,1);
const removeReference=await request('/api/notes/'+referring.id);
const editResponse=await fetch(base+'/api/notes/'+referring.id,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({title:'引用来源',description:'更新后撤回引用',markdown:'引用已经移除',tags:[],revision:removeReference.entry.revision})});assert.equal(editResponse.status,200);
assert.equal((await request('/api/notes/'+targetNote.id)).entry.backlinkCount,0);
const empty=randomUUID();await db().query("INSERT INTO posts(id,slug,kind,title) VALUES($1,$2,'image','空对象')",[empty,empty]);assert.equal((await request('/api/feed')).posts.length,2);
assert.equal((await request('/api/feed')).contributions.length,0,'Import does not invent contribution rules');
await db().query("INSERT INTO contribution_events(id,kind,subject_type,amount) VALUES($1,'test.import','asset',2),($2,'test.edit','post',3)",[randomUUID(),randomUUID()]);assert.equal((await request('/api/feed')).contributions.reduce((n:number,c:{total:number})=>n+c.total,0),5);