From 7f37aa4c9368279794c3a165bad507b76283212b Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 26 Oct 2026 20:20:55 +0800 Subject: [PATCH] Add full-content discovery search and backlink ranking to waterfall-wiki --- apps/wiki/package.json | 5 +-- apps/wiki/pnpm-lock.yaml | 3 ++ apps/wiki/src/components/ExploreDetail.tsx | 4 +-- apps/wiki/src/components/ExploreFeed.tsx | 11 +++--- apps/wiki/src/components/Feed.tsx | 4 +-- apps/wiki/src/components/GuidanceIndex.tsx | 2 +- apps/wiki/src/components/Shell.tsx | 4 +-- apps/wiki/src/components/SkillDocs.tsx | 2 +- apps/wiki/src/content/skills/guidance.ts | 2 +- apps/wiki/src/content/wiki.ts | 2 +- apps/wiki/src/lib/api-documentation.ts | 6 ++-- apps/wiki/src/lib/discovery.ts | 42 ++++++++++++++++++++++ apps/wiki/src/lib/explore.ts | 34 +++++++++++++++--- apps/wiki/src/lib/library.ts | 12 +++++++ apps/wiki/src/pages/api/explore-feed.ts | 3 +- apps/wiki/src/pages/api/index.ts | 2 +- apps/wiki/src/pages/api/wiki-index.ts | 2 +- apps/wiki/src/pages/categories.tsx | 4 +-- apps/wiki/src/pages/index.tsx | 5 ++- apps/wiki/src/pages/library/import.tsx | 2 +- apps/wiki/src/pages/tools/doodle.tsx | 2 +- apps/wiki/src/styles/globals.css | 1 + apps/wiki/tests/discovery.test.ts | 21 +++++++++++ apps/wiki/tests/integration.test.ts | 10 ++++++ 24 files changed, 150 insertions(+), 35 deletions(-) create mode 100644 apps/wiki/src/lib/discovery.ts create mode 100644 apps/wiki/tests/discovery.test.ts diff --git a/apps/wiki/package.json b/apps/wiki/package.json index 4833b0a..fd071c0 100644 --- a/apps/wiki/package.json +++ b/apps/wiki/package.json @@ -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", diff --git a/apps/wiki/pnpm-lock.yaml b/apps/wiki/pnpm-lock.yaml index 6c669c6..9d6e89a 100644 --- a/apps/wiki/pnpm-lock.yaml +++ b/apps/wiki/pnpm-lock.yaml @@ -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) diff --git a/apps/wiki/src/components/ExploreDetail.tsx b/apps/wiki/src/components/ExploreDetail.tsx index 5269ba3..3e2b883 100644 --- a/apps/wiki/src/components/ExploreDetail.tsx +++ b/apps/wiki/src/components/ExploreDetail.tsx @@ -31,7 +31,7 @@ export function ExploreDetail({entry:initial,background}:{entry:ExploreEntry;bac setCopied(mode);setCopyError(''); }catch{setCopied('');setCopyError('复制失败,请重试。')} } - return {entry.title} · PROMPT + return {entry.title} · waterfall-wiki
{if(!editing)close()}}>
e.stopPropagation()}> @@ -39,7 +39,7 @@ export function ExploreDetail({entry:initial,background}:{entry:ExploreEntry;bac {media?.kind==='image'?{media.title}:media?.kind==='video'?
; } diff --git a/apps/wiki/src/components/ExploreFeed.tsx b/apps/wiki/src/components/ExploreFeed.tsx index 2ea69da..63030db 100644 --- a/apps/wiki/src/components/ExploreFeed.tsx +++ b/apps/wiki/src/components/ExploreFeed.tsx @@ -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 <>
{entries.map((entry,i)=>
+ return <>{q&&
搜索「{q}」{total!==undefined?` · ${total} 篇`:""}按匹配程度、被引用数排序
}
{entries.map((entry,i)=>
{entry.media[0]?{entry.media[0].title}:<>{entry.namespace.toUpperCase()}{entry.title}记录 · 连接 · 灵感} {entry.imageCount>1&&{entry.imageCount}} -

{entry.title}

{entry.description}

+

{entry.title}

{entry.description}

{q&&entry.searchExcerpt&&

{entry.searchExcerpt}

} + 被引用 {entry.backlinkCount??0} {entry.categories.length>0&&
{entry.categories.map(tag=>#{tag})}
} -
)}
{!entries.length&&

这个分类还没有内容。

}{cursor&&
}; + )}{!entries.length&&

{q?'没有匹配的内容,试试更短的关键词。':'这个分类还没有内容。'}

}{cursor&&
}; } diff --git a/apps/wiki/src/components/Feed.tsx b/apps/wiki/src/components/Feed.tsx index 9849683..d0435d0 100644 --- a/apps/wiki/src/components/Feed.tsx +++ b/apps/wiki/src/components/Feed.tsx @@ -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 {target?.name||current?.name||'灵感首页'} · PROMPT + return {target?.name||current?.name||'灵感首页'} · waterfall-wiki {current&&

{target?.name||current.name}

{current.hint}

} {tagPath&&
全部{current?.name}{tagPath.split('/').map((_,i)=>{const path=tagPath.split('/').slice(0,i+1).join('/');return / {initial.tags.find(t=>t.path===path)?.name};})}
}
{!section?<>全部{sections.map(s=>{s.name})}:<>全部{children.map(t=>{t.name})}}
最近收录
{initial.unavailable?

素材库暂时没有连接上

请稍后刷新,已保存的内容不会因此丢失。

:(posts.length||(!section&&skillCatalog.some(s=>(s.title+s.description+s.category).toLowerCase().includes(String(router.query.q||'').toLowerCase()))))?:
A LITTLE SPACE FOR SOMETHING GOOD

{router.query.q?'还没有找到这份灵感':'这里还没有内容'}

{router.query.q?'换一个词试试看。':'导入图片、视频或声音,开始整理你的素材。'}

导入素材图文和动态作品通过代码加入,自由决定每一个像素。
} {cursor&&
} -
PROMPT · PROBABLY RENDERING ONE MORE PIXEL TONIGHT
+
waterfall-wiki · PROBABLY RENDERING ONE MORE PIXEL TONIGHT
; } diff --git a/apps/wiki/src/components/GuidanceIndex.tsx b/apps/wiki/src/components/GuidanceIndex.tsx index 8af6d8a..151e559 100644 --- a/apps/wiki/src/components/GuidanceIndex.tsx +++ b/apps/wiki/src/components/GuidanceIndex.tsx @@ -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 指导文档 · PROMPT +export function GuidanceIndex(){return 指导文档 · waterfall-wiki

指导文档

每篇都有独立地址,网页与 Markdown 一一对应。沿着引用,找到需要的方法。

全部文档

这些分组只帮助浏览。任何一篇都可以独立进入,也可以引用其他文档。

{guidanceDocuments.map(doc=>
{doc.title}{doc.collection}Markdown ↗
)}

按创作主题浏览

diff --git a/apps/wiki/src/components/Shell.tsx b/apps/wiki/src/components/Shell.tsx index 3be8cc2..9c81560 100644 --- a/apps/wiki/src/components/Shell.tsx +++ b/apps/wiki/src/components/Shell.tsx @@ -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
-
{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()}:{})}});}}>setQuery(e.target.value)}/>{query&&}
{children}
{open&&
; } diff --git a/apps/wiki/src/components/SkillDocs.tsx b/apps/wiki/src/components/SkillDocs.tsx index 1a52684..3d2b6e0 100644 --- a/apps/wiki/src/components/SkillDocs.tsx +++ b/apps/wiki/src/components/SkillDocs.tsx @@ -26,7 +26,7 @@ export function SkillDocs({documentPath,documentId='index',skillId='street-peopl setCopied(true); }catch{setCopied(false)} } - return {doc.title} · 指导文档 · PROMPT + return {doc.title} · 指导文档 · waterfall-wiki
← 全部指导文档
{doc.collection} / 指导文档

{doc.title}

diff --git a/apps/wiki/src/content/skills/guidance.ts b/apps/wiki/src/content/skills/guidance.ts index ed8c258..7fc4fc8 100644 --- a/apps/wiki/src/content/skills/guidance.ts +++ b/apps/wiki/src/content/skills/guidance.ts @@ -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'; } diff --git a/apps/wiki/src/content/wiki.ts b/apps/wiki/src/content/wiki.ts index 97d0c55..896c64f 100644 --- a/apps/wiki/src/content/wiki.ts +++ b/apps/wiki/src/content/wiki.ts @@ -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'}]; diff --git a/apps/wiki/src/lib/api-documentation.ts b/apps/wiki/src/lib/api-documentation.ts index 2270fe5..1aabff9 100644 --- a/apps/wiki/src/lib/api-documentation.ts +++ b/apps/wiki/src/lib/api-documentation.ts @@ -6,9 +6,9 @@ export const apiDocuments:Record={ "统一内容流", "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={ "读取与编辑笔记", "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\":\"\"}", "400:输入错误;404:笔记不存在;409:版本冲突。" ], diff --git a/apps/wiki/src/lib/discovery.ts b/apps/wiki/src/lib/discovery.ts new file mode 100644 index 0000000..aca45a9 --- /dev/null +++ b/apps/wiki/src/lib/discovery.ts @@ -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(),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();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(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{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{ +async function readEntry(id:string,client?:PoolClient):Promise{ 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):Promisea.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{ + 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';} diff --git a/apps/wiki/src/lib/library.ts b/apps/wiki/src/lib/library.ts index 12220a6..b5a03fb 100644 --- a/apps/wiki/src/lib/library.ts +++ b/apps/wiki/src/lib/library.ts @@ -33,3 +33,15 @@ export async function feed(options: {kind?: PostKind; path?: string; cursor?: st } export async function publishedPublicIds():Promise{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{ + 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)); +} diff --git a/apps/wiki/src/pages/api/explore-feed.ts b/apps/wiki/src/pages/api/explore-feed.ts index d03c669..5945070 100644 --- a/apps/wiki/src/pages/api/explore-feed.ts +++ b/apps/wiki/src/pages/api/explore-feed.ts @@ -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:'素材库暂时无法连接'});}} diff --git a/apps/wiki/src/pages/api/index.ts b/apps/wiki/src/pages/api/index.ts index 5c5e7c4..be0c96e 100644 --- a/apps/wiki/src/pages/api/index.ts +++ b/apps/wiki/src/pages/api/index.ts @@ -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}); } diff --git a/apps/wiki/src/pages/api/wiki-index.ts b/apps/wiki/src/pages/api/wiki-index.ts index a12d7c1..2779579 100644 --- a/apps/wiki/src/pages/api/wiki-index.ts +++ b/apps/wiki/src/pages/api/wiki-index.ts @@ -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');} diff --git a/apps/wiki/src/pages/categories.tsx b/apps/wiki/src/pages/categories.tsx index 232186b..1a69b59 100644 --- a/apps/wiki/src/pages/categories.tsx +++ b/apps/wiki/src/pages/categories.tsx @@ -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 分类 · PROMPT
全部{categories.map(c=>{c})}
} -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 分类 · waterfall-wiki
全部{categories.map(c=>{c})}
} +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}}}}; diff --git a/apps/wiki/src/pages/index.tsx b/apps/wiki/src/pages/index.tsx index e88853a..3c42e65 100644 --- a/apps/wiki/src/pages/index.tsx +++ b/apps/wiki/src/pages/index.tsx @@ -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 PROMPT · 发现
发现分类
{unavailable&&

素材库暂时无法连接,先看看这些公开笔记。

}
} -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 waterfall-wiki · 发现{unavailable&&

素材库暂时无法连接,先看看这些公开笔记。

}
} +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}}}}; diff --git a/apps/wiki/src/pages/library/import.tsx b/apps/wiki/src/pages/library/import.tsx index 6f0a991..76fbd65 100644 --- a/apps/wiki/src/pages/library/import.tsx +++ b/apps/wiki/src/pages/library/import.tsx @@ -12,7 +12,7 @@ export default function Import({allTags}:{allTags:Tag[]}){ const [files,setFiles]=useState([]);const [title,setTitle]=useState('');const [description,setDescription]=useState('');const [selected,setSelected]=useState([]);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 素材入库 · PROMPT
MAKE ROOM FOR INSPIRATION

导入素材

支持多文件导入。同一组素材收录为一个素材包,每份文件都可以再次引用。

+ return 素材入库 · waterfall-wiki
MAKE ROOM FOR INSPIRATION

导入素材

支持多文件导入。同一组素材收录为一个素材包,每份文件都可以再次引用。

{[{id:'image',name:'图片',Icon:Image},{id:'video',name:'视频',Icon:Film},{id:'audio',name:'声音',Icon:AudioLines}].map(t=>)}
{files.length>0&&
    {files.map((f,i)=>
  • {f.name}{(f.size/1024/1024).toFixed(1)} MB
  • )}
} diff --git a/apps/wiki/src/pages/tools/doodle.tsx b/apps/wiki/src/pages/tools/doodle.tsx index 3cd5585..e163637 100644 --- a/apps/wiki/src/pages/tools/doodle.tsx +++ b/apps/wiki/src/pages/tools/doodle.tsx @@ -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=()=>``; 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 线条灵感 · PROMPT
SMALL LINES, LITTLE STORIES

线条工具

选择图形、调整颜色,下载后用于照片涂鸦。

照片涂鸦工具箱
{strokes.map((s,i)=>)}
; + return 线条灵感 · waterfall-wiki
SMALL LINES, LITTLE STORIES

线条工具

选择图形、调整颜色,下载后用于照片涂鸦。

照片涂鸦工具箱
{strokes.map((s,i)=>)}
; } diff --git a/apps/wiki/src/styles/globals.css b/apps/wiki/src/styles/globals.css index e289758..3b38203 100644 --- a/apps/wiki/src/styles/globals.css +++ b/apps/wiki/src/styles/globals.css @@ -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} diff --git a/apps/wiki/tests/discovery.test.ts b/apps/wiki/tests/discovery.test.ts new file mode 100644 index 0000000..15f411e --- /dev/null +++ b/apps/wiki/tests/discovery.test.ts @@ -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=>({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); +}); diff --git a/apps/wiki/tests/integration.test.ts b/apps/wiki/tests/integration.test.ts index cfa9176..e46daaf 100644 --- a/apps/wiki/tests/integration.test.ts +++ b/apps/wiki/tests/integration.test.ts @@ -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);