Restore PROMPT branding, rename waterfall-wiki, and add system tag workflows
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {test} from 'node:test';
|
||||
import type {NextApiRequest,NextApiResponse} from 'next';
|
||||
import {apiDocuments,serveApiDocumentation} from '../src/lib/api-documentation';
|
||||
import index from '../src/pages/api/index';
|
||||
|
||||
function response(){
|
||||
const state={status:0,headers:{} as Record<string,string>,body:undefined as unknown};
|
||||
const res={setHeader(name:string,value:string){state.headers[name]=value;return res;},status(code:number){state.status=code;return res;},send(body:unknown){state.body=body;return res;},json(body:unknown){state.body=body;return res;},end(){return res;}};
|
||||
return {state,res:res as unknown as NextApiResponse};
|
||||
}
|
||||
const request=(method:string,agent_mode:unknown)=>({method,query:{agent_mode}} as unknown as NextApiRequest);
|
||||
|
||||
test('every business handler serves documentation before validating parameters or accessing dependencies',async()=>{
|
||||
const routes:Record<string,string>={
|
||||
'/api/explore-feed':'explore-feed','/api/feed':'feed','/api/notes/{id}':'notes/[id]',
|
||||
'/api/posts':'posts/index','/api/tags':'tags','/api/upload':'upload',
|
||||
'/api/media/{id}':'media/[id]','/api/preview':'preview',
|
||||
'/api/skills/street-people':'skills/street-people','/api/health':'health','/api/ready':'ready',
|
||||
};
|
||||
for(const [path,route] of Object.entries(routes)){
|
||||
const {default:handler}=await import('../src/pages/api/'+route+'.ts');
|
||||
for(const method of ['GET','HEAD']){
|
||||
const {state,res}=response();
|
||||
await handler(request(method,'tRuE'),res);
|
||||
assert.equal(state.status,200,path);
|
||||
assert.equal(state.headers['Content-Type'],'text/plain; charset=utf-8',path);
|
||||
if(method==='HEAD')assert.equal(state.body,undefined);else {
|
||||
assert.ok(String(state.body).includes(path),path);
|
||||
assert.ok(String(state.body).includes('参数'),path);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.deepEqual(Object.keys(routes).sort(),Object.keys(apiDocuments).sort());
|
||||
});
|
||||
|
||||
test('normal calls and mutations do not enter documentation mode',()=>{
|
||||
for(const [method,value] of [['GET',undefined],['GET','false'],['GET',['True','false']],['POST','True'],['PUT','True'],['DELETE','True']]){
|
||||
const {state,res}=response();
|
||||
assert.equal(serveApiDocumentation(request(method as string,value),res,'/api/posts'),false);
|
||||
assert.equal(state.status,0);
|
||||
}
|
||||
});
|
||||
|
||||
test('index exposes every business endpoint and its text URL',()=>{
|
||||
const {state,res}=response();index(request('GET','True'),res);
|
||||
for(const path of [...Object.keys(apiDocuments),'/studio/api/export/{slug}','/studio/api/health'])assert.ok(String(state.body).includes(path+'?agent_mode=True'));
|
||||
});
|
||||
|
||||
test('health keeps its regular JSON response',async()=>{
|
||||
const {default:handler}=await import('../src/pages/api/health');
|
||||
const {state,res}=response();handler(request('GET',undefined),res);
|
||||
assert.equal(state.status,200);assert.equal((state.body as {status:string}).status,'ok');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {postInput} from '../src/lib/write';
|
||||
import {noteEditInput,withRevision} from '../src/lib/note-edits';
|
||||
import {publicPostId} from '../src/lib/model';
|
||||
import {entryText,type ExploreEntry} from '../src/lib/explore';
|
||||
test('generic API accepts stable public IDs while retaining UUID storage and rejecting invalid IDs',()=>{
|
||||
const publicId='0123456789abcdef01234567',stored=randomUUID();
|
||||
assert.equal(postInput.parse({kind:'article',title:'文本与图像',publicId}).publicId,publicId);
|
||||
for(const id of ['bad','ABCDEF0123456789abcdef01','1'.repeat(25)])assert.equal(postInput.safeParse({kind:'article',title:'x',publicId:id}).success,false);
|
||||
assert.equal(publicPostId({id:stored,public_id:publicId}),publicId);assert.equal(publicPostId({id:stored}),stored);
|
||||
});
|
||||
test('media/cover edits are optional and change optimistic revisions independently of the text',()=>{
|
||||
const a=randomUUID(),b=randomUUID();
|
||||
const entry:ExploreEntry={id:'0123456789abcdef01234567',title:'笔记',description:'说明',markdown:'# 笔记\n\n正文',namespace:'Main',categories:[],imageCount:1,media:[],color:'#fff',assets:[{id:a,kind:'image',role:'content'}],coverAssetId:a};
|
||||
const before=withRevision(entry).revision;
|
||||
assert.notEqual(withRevision({...entry,coverAssetId:b}).revision,before);
|
||||
assert.notEqual(withRevision({...entry,assets:[{id:b,kind:'image',role:'content'}]}).revision,before);
|
||||
const input={title:'笔记',description:'说明',markdown:'正文',tags:[],revision:before};
|
||||
assert.equal(noteEditInput.parse(input).assets,undefined);
|
||||
assert.equal(noteEditInput.parse({...input,assets:[{id:a}],coverAssetId:null}).assets?.[0].role,'content');
|
||||
});
|
||||
test('AI text preserves JSON, code and media links as ordinary modalities',()=>{
|
||||
const id=randomUUID(),markdown='# 文本说明\n\n```json\n{"type":"text","box":[1,2,3,4]}\n```\n\n```tsx\nexport default function Example(){return <div/>}\n```';
|
||||
const entry:ExploreEntry={id,title:'文本说明',description:'可访问',markdown,namespace:'Main',categories:[],imageCount:1,media:[{kind:'image',url:'/api/media/'+randomUUID(),title:'标注图'}],color:'#fff'};
|
||||
const text=entryText(entry);assert.ok(text.includes(markdown));assert.ok(text.includes(entry.media[0].url));assert.ok(text.includes('/explore/'+id));
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {base32,totp,matchingStep,newAuthConfig,signSession,validSession,sessionCookie,safeReturn,authConfig} from '../src/lib/auth';
|
||||
import {proxy} from '../src/proxy';
|
||||
import {NextRequest} from 'next/server';
|
||||
import {mkdtempSync,writeFileSync,rmSync} from 'node:fs';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {join} from 'node:path';
|
||||
test('TOTP matches RFC 6238 SHA-1 test vectors',()=>{
|
||||
const secret=base32(Buffer.from('12345678901234567890'));
|
||||
for(const [time,expected] of [[59,'94287082'],[1111111109,'07081804'],[1111111111,'14050471'],[1234567890,'89005924'],[2000000000,'69279037'],[20000000000,'65353130']] as const) assert.equal(totp(secret,Math.floor(time/30),8),expected);
|
||||
assert.equal(matchingStep(secret,totp(secret,100),3000000),100);
|
||||
assert.equal(matchingStep(secret,totp(secret,99),3000000),99);
|
||||
assert.equal(matchingStep(secret,totp(secret,98),3000000),null);
|
||||
assert.equal(matchingStep(secret,'123',3000000),null);
|
||||
});
|
||||
test('JWT rejects tampering, expiry, wrong keys and malformed values',()=>{
|
||||
const config=newAuthConfig(),token=signSession(config,1000);
|
||||
assert.equal(validSession(token,config,1000),true);
|
||||
assert.equal(validSession(token,config,1000+604800),false);
|
||||
assert.equal(validSession(token,config,900),false);
|
||||
assert.equal(validSession(token,newAuthConfig(),1000),false);
|
||||
assert.equal(validSession(token+'x',config,1000),false);
|
||||
assert.equal(validSession('eyJhbGciOiJub25lIn0.e30.',config,1000),false);
|
||||
assert.equal(validSession(undefined,config),false);
|
||||
});
|
||||
test('cookies are HTTP-only and secure by default; redirects stay local',()=>{
|
||||
assert.match(sessionCookie('test'),/HttpOnly; SameSite=Lax; Max-Age=604800; Secure$/);
|
||||
assert.match(sessionCookie('',true),/Max-Age=0/);
|
||||
for(const path of ['https://evil.test','//evil.test','/\\evil.test','/login?next=/','/\nLocation: bad']) assert.equal(safeReturn(path),'/');
|
||||
assert.equal(safeReturn('/explore/123?q=test'),'/explore/123?q=test');
|
||||
});
|
||||
test('proxy protects APIs, data routes, static content and Studio; fails closed',()=>{
|
||||
const temp=mkdtempSync(join(tmpdir(),'prompt-auth-')); const old=process.env.AUTH_CONFIG_FILE;
|
||||
try{
|
||||
const config=newAuthConfig(); process.env.AUTH_CONFIG_FILE=join(temp,'config.json'); writeFileSync(process.env.AUTH_CONFIG_FILE,JSON.stringify(config));
|
||||
for(const path of ['/','/library/import','/skills/example.png','/_next/data/build/index.json','/studio']) assert.equal(proxy(new NextRequest('http://wiki.test'+path)).status,307,path);
|
||||
for(const path of ['/api/upload','/studio/api/export','/api/feed']) assert.equal(proxy(new NextRequest('http://wiki.test'+path)).status,401,path);
|
||||
for(const path of ['/login','/_next/static/chunk.js','/api/health','/api/ready']) assert.equal(proxy(new NextRequest('http://wiki.test'+path)).status,200,path);
|
||||
const headers={cookie:'prompt_session='+signSession(config),host:'wiki.test'};
|
||||
assert.equal(proxy(new NextRequest('http://wiki.test/api/feed',{headers})).status,200);
|
||||
assert.equal(proxy(new NextRequest('http://wiki.test/api/posts',{method:'POST',headers:{...headers,origin:'http://evil.test'}})).status,403);
|
||||
assert.equal(proxy(new NextRequest('http://wiki.test/api/posts',{method:'POST',headers:{...headers,origin:'http://wiki.test'}})).status,200);
|
||||
writeFileSync(process.env.AUTH_CONFIG_FILE,'{}'); assert.throws(()=>authConfig()); assert.equal(proxy(new NextRequest('http://wiki.test/')).status,503);
|
||||
}finally{if(old===undefined)delete process.env.AUTH_CONFIG_FILE;else process.env.AUTH_CONFIG_FILE=old;rmSync(temp,{recursive:true,force:true});}
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
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\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);
|
||||
});
|
||||
|
||||
test('pasted full URLs count but disguised link labels and inline code do not',()=>{
|
||||
const source=doc('b',{markdown:'http://8.211.154.134:18131/explore/a。\n\n[http://8.211.154.134:18131/explore/c](https://example.com)\n\n`http://8.211.154.134:18131/explore/c`'});
|
||||
const refs=backlinksFor([doc('a'),source,doc('c')]);assert.equal(refs.get('a')?.length,1);assert.equal(refs.get('c')?.length,0);
|
||||
});
|
||||
|
||||
test('system categories filter independently of ordinary tags and are searchable',()=>{
|
||||
const ranked=rankDocuments([doc('a',{categories:['中国风'],systemTags:['文档入口','document-entry']}),doc('b',{categories:['中国风']})],'','document-entry');
|
||||
assert.deepEqual(ranked.map(r=>r.doc.id),['a']);assert.equal(rankDocuments([doc('a',{categories:['中国风'],systemTags:['文档入口']})],'中国风 文档入口').length,1);
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {staticEntries,getEntry,entryText} from '../src/lib/explore';
|
||||
import {pageId,previewUrl} from '../src/content/page-links';
|
||||
import {guidanceDocuments} from '../src/content/skills/guidance';
|
||||
import {getServerSideProps} from '../src/pages/explore/[id]';
|
||||
test('every public document has a distinct persisted ID and canonical entry',async()=>{assert.equal(new Set(staticEntries.map(e=>e.id)).size,staticEntries.length);for(const e of staticEntries){assert.match(e.id,/^[a-f0-9]{24}$/);assert.equal((await getEntry(e.id))?.title,e.title);}for(const doc of guidanceDocuments)assert.ok(pageId('guidance:'+doc.path));assert.equal(await getEntry('unknown'),null);});
|
||||
test('agent_mode on the canonical URL emits text with media links and no HTML',async()=>{const entry=staticEntries.find(e=>e.media.length)!;let body='';const headers:Record<string,string>={};const response={setHeader:(k:string,v:string)=>headers[k]=v,end:(value:string)=>{body=value}};await getServerSideProps({params:{id:entry.id},query:{agent_mode:'True'},res:response,req:{method:'GET'}} as never);assert.match(headers['Content-Type'],/text\/plain/);assert.ok(body.includes(entry.title));assert.ok(body.includes(entry.media[0].url));assert.ok(body.startsWith('# '+entry.title));assert.ok(!body.includes('!['));assert.equal(body,entryText((await getEntry(entry.id))!));});
|
||||
test('preview URLs always use bounded image endpoints',()=>{const url=new URL(previewUrl('/api/media/id?variant=poster',480),'http://test');assert.equal(url.pathname,'/api/preview');assert.equal(url.searchParams.get('source'),'/api/media/id?variant=poster');assert.equal(url.searchParams.get('width'),'480');});
|
||||
|
||||
test('independent notes expose their own description, tags and complete image counts',async()=>{
|
||||
for(const entry of staticEntries){assert.ok(entry.description.trim());assert.equal(entry.imageCount,entry.media.filter(m=>m.kind==='image').length);assert.equal(new Set(entry.media.map(m=>m.url)).size,entry.media.length);}
|
||||
const note=(await getEntry(pageId('guidance:shadow-puppet')))!;
|
||||
assert.equal(note.imageCount,2);assert.ok(note.categories.includes('照片入皮影'));assert.ok(entryText(note).includes('Description: '+note.description));
|
||||
const workflow=(await getEntry(pageId('guidance:shadow-puppet/workflow')))!;
|
||||
assert.notEqual(workflow.description,note.description);assert.notEqual(workflow.id,note.id);
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {db} from '../src/lib/db';
|
||||
export async function verifyFlatNoteMigration(){
|
||||
const client=await db().connect();const schema='migration_'+randomUUID().replaceAll('-','');
|
||||
try{
|
||||
await client.query(`CREATE SCHEMA ${schema}`);await client.query(`SET search_path TO ${schema}`);
|
||||
for(const name of ['001_library','002_page_snapshots','003_note_descriptions'])await client.query(await readFile(`db/${name}.sql`,'utf8'));
|
||||
const [video,picture,post,tag,duplicate,parent]=Array.from({length:6},()=>randomUUID());
|
||||
await client.query(`INSERT INTO assets(id,kind,storage_key,mime_type,byte_size) VALUES($1,'video','original','video/mp4',100),($2,'image','snapshot','image/png',50)`,[video,picture]);
|
||||
await client.query(`INSERT INTO posts(id,slug,kind,title,page_key) VALUES($1,'old-note','article','保留的笔记','old-code')`,[post]);
|
||||
await client.query(`INSERT INTO post_assets(post_id,asset_id,position) VALUES($1,$2,0)`,[post,video]);
|
||||
await client.query(`INSERT INTO page_snapshots(post_id,page_index,asset_id,revision) VALUES($1,1,$2,'old-revision')`,[post,picture]);
|
||||
await client.query(`INSERT INTO render_jobs(post_id,status,revision) VALUES($1,'pending','old-revision')`,[post]);
|
||||
await client.query(`INSERT INTO asset_variants(asset_id,role,storage_key,mime_type,byte_size) VALUES($1,'poster','old-poster','image/jpeg',20)`,[video]);
|
||||
await client.query(`INSERT INTO media_jobs(id,asset_id) VALUES($1,$2)`,[randomUUID(),video]);
|
||||
await client.query(`INSERT INTO tags(id,slug,name) VALUES($1,'parent','上级'),($2,'same','重复')`,[parent,tag]);
|
||||
await client.query(`INSERT INTO tags(id,parent_id,slug,name) VALUES($1,$2,'same','重复')`,[duplicate,parent]);
|
||||
await client.query(`INSERT INTO post_tags(post_id,tag_id) VALUES($1,$2),($1,$3)`,[post,tag,duplicate]);
|
||||
await client.query(`INSERT INTO asset_tags(asset_id,tag_id) VALUES($1,$2)`,[video,duplicate]);
|
||||
await client.query(await readFile('db/004_flat_notes.sql','utf8'));
|
||||
assert.equal((await client.query('SELECT count(*)::integer n FROM post_assets WHERE post_id=$1 AND asset_id=$2',[post,picture])).rows[0].n,1,'Previously generated image remains linked');
|
||||
const processed=(await client.query(`SELECT a.storage_key,pa.role FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=$1 AND a.derivation='poster'`,[post])).rows;
|
||||
assert.deepEqual(processed,[{storage_key:'old-poster',role:'poster'}],'Processed file uses its existing object and a normal resource link');
|
||||
assert.equal((await client.query('SELECT count(*)::integer n FROM post_tags WHERE post_id=$1',[post])).rows[0].n,1);
|
||||
assert.equal((await client.query('SELECT count(*)::integer n FROM asset_tags WHERE asset_id=$1',[video])).rows[0].n,1,'Merging equal tags retains asset associations');
|
||||
assert.equal((await client.query('SELECT count(*)::integer n FROM media_jobs')).rows[0].n,1,'Video processing queue survives');
|
||||
assert.equal((await client.query(`SELECT count(*)::integer n FROM information_schema.columns WHERE table_schema=$1 AND column_name IN ('parent_id','page_key')`,[schema])).rows[0].n,0);
|
||||
await client.query(await readFile('db/008_system_tags.sql','utf8'));
|
||||
assert.equal((await client.query("SELECT count(*)::integer n FROM tags WHERE kind='system'")).rows[0].n,2);
|
||||
assert.ok((await client.query("SELECT 1 FROM tags WHERE kind='normal'")).rowCount);
|
||||
assert.equal((await client.query('SELECT count(*)::integer n FROM post_tags WHERE post_id=$1',[post])).rows[0].n,1,'System tag migration retains ordinary associations');
|
||||
await assert.rejects(client.query("INSERT INTO tags(id,slug,name,kind) VALUES($1,'invalid-system','Invalid system','system')",[randomUUID()]));
|
||||
}finally{
|
||||
await client.query('ROLLBACK');await client.query('SET search_path TO public');await client.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);client.release();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { healthResponse } from "../src/lib/health";
|
||||
|
||||
test("health identifies the deployed release", () => {
|
||||
assert.deepEqual(healthResponse("GET", "abc123"), {
|
||||
statusCode: 200,
|
||||
body: { status: "ok", service: "prompt", release: "abc123" },
|
||||
});
|
||||
});
|
||||
|
||||
test("HEAD is supported and mutations are rejected", () => {
|
||||
assert.equal(healthResponse("HEAD").statusCode, 200);
|
||||
assert.equal(healthResponse("POST").statusCode, 405);
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {test} from 'node:test';
|
||||
import {spawn} from 'node:child_process';
|
||||
import {once} from 'node:events';
|
||||
import {createServer} from 'node:net';
|
||||
import {setTimeout} from 'node:timers/promises';
|
||||
import {mkdtemp,readFile,writeFile,rm} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {join} from 'node:path';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import sharp from 'sharp';
|
||||
import {db} from '../src/lib/db';
|
||||
import {probe,run} from '../src/lib/probe';
|
||||
import {verifyFlatNoteMigration} from './flat-note-migration';
|
||||
import {staticEntries} from '../src/lib/explore';
|
||||
import {publishLearningSeries} from '../src/lib/publish-learning-series';
|
||||
|
||||
test('real PostgreSQL + S3 notes, flat tags, resource sharing and video processing', {timeout:300000}, async()=>{
|
||||
assert.equal(process.env.PROMPT_INTEGRATION_TEST,'1','Run only against an explicitly isolated test database');
|
||||
const socket=createServer();socket.listen(0,'127.0.0.1');await once(socket,'listening');const address=socket.address();assert.ok(address&&typeof address!=='string');const port=address.port;await new Promise<void>(r=>socket.close(()=>r()));
|
||||
const external=process.env.PROMPT_TEST_BASE_URL;
|
||||
const base=external||`http://127.0.0.1:${port}`;
|
||||
const server=external?null:spawn(process.execPath,['.next/standalone/server.js'],{env:{...process.env,PORT:String(port),HOSTNAME:'127.0.0.1'},stdio:'inherit'});
|
||||
const worker=external?null:spawn(process.execPath,['dist/worker.cjs'],{env:process.env,stdio:'inherit'});const dir=await mkdtemp(join(tmpdir(),'prompt-test-'));
|
||||
const request=async(path:string,body?:unknown)=>{const res=await fetch(base+path,body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:undefined);assert.ok(res.ok,`${path}: ${res.status} ${res.ok?'':await res.text()}`);return res.json();};
|
||||
try{
|
||||
let ready=false;for(let i=0;i<60;i++){try{if((await fetch(base+'/api/health')).ok){ready=true;break;}}catch{}await setTimeout(250);}assert.ok(ready);
|
||||
for(const route of ['/','/images','/videos','/audio','/articles','/motion','/library/import','/tools/doodle','/tools/skills','/tools/skills/street-people','/tools/skills/shadow-puppet'])assert.equal((await fetch(base+route)).status,200,route);
|
||||
await verifyFlatNoteMigration();
|
||||
const root=await request('/api/tags',{name:'线条',slug:'lines'});const child=await request('/api/tags',{name:'白色',slug:'white'});
|
||||
const sameTag=await request('/api/tags',{name:'#线条'});assert.equal(sameTag.id,root.id,'Hashtag creation reuses the globally unique tag');
|
||||
assert.equal((await db().query("SELECT count(*)::integer AS n FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='tags' AND column_name='parent_id'")).rows[0].n,0);
|
||||
const a=await sharp({create:{width:160,height:220,channels:3,background:'#b8c9af'}}).png().toBuffer();
|
||||
const upload=async(kind:string,files:{data:Uint8Array;name:string;mime:string}[])=>{const form=new FormData();form.set('kind',kind);form.set('title','测试收藏 '+kind);form.set('description','可以复用的独立文字');form.set('tags',JSON.stringify([child.id]));files.forEach(f=>form.append('files',new Blob([new Uint8Array(f.data)],{type:f.mime}),f.name));const res=await fetch(base+'/api/upload',{method:'POST',body:form});assert.equal(res.status,201,await res.clone().text());return res.json();};
|
||||
const first=await upload('image',[{data:a,name:'a.png',mime:'image/png'},{data:a,name:'b.png',mime:'image/png'}]);
|
||||
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);
|
||||
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);
|
||||
const img=await fetch(base+'/api/media/'+first.assets[0],{headers:{Range:'bytes=0-9'}});assert.equal(img.status,206);assert.equal((await img.arrayBuffer()).byteLength,10);
|
||||
const lightweight=await fetch(base+'/api/preview?source='+encodeURIComponent('/api/media/'+first.assets[0])+'&width=480');assert.equal(lightweight.status,200);assert.match(lightweight.headers.get('content-type')||'',/image\/webp/);assert.ok((await lightweight.arrayBuffer()).byteLength<=100000);
|
||||
const textEntry=await fetch(base+'/explore/'+reused.id+'?agent_mode=True');assert.equal(textEntry.status,200);assert.match(textEntry.headers.get('content-type')||'',/text\/plain/);assert.ok((await textEntry.text()).includes(first.assets[0]));
|
||||
assert.equal((await fetch(base+'/images/lines/missing')).status,404);assert.equal((await fetch(base+'/p/'+reused.slug)).status,200);
|
||||
for(const sound of [true,false]){
|
||||
const path=join(dir,sound?'sound.mp4':'silent.mp4');const args=['-y','-v','error','-f','lavfi','-i','color=c=blue:s=160x120:r=10'];if(sound)args.push('-f','lavfi','-i','sine=frequency=440:sample_rate=44100');args.push('-t','0.5','-c:v','libx264','-pix_fmt','yuv420p');if(sound)args.push('-c:a','aac');args.push(path);await run('ffmpeg',args);
|
||||
const post=await upload('video',[{data:await readFile(path),name:'video.mp4',mime:'video/mp4'}]);let asset;
|
||||
for(let i=0;i<120;i++){asset=(await db().query('SELECT * FROM assets WHERE id=$1',[post.assets[0]])).rows[0];if(asset.processing_status==='ready'||asset.processing_status==='failed')break;await setTimeout(500);}
|
||||
assert.equal(asset.processing_status,'ready',asset.processing_error);assert.equal(asset.has_audio,sound);
|
||||
const variants:string[]=(await db().query('SELECT derivation AS role FROM assets WHERE source_asset_id=$1',[asset.id])).rows.map(r=>r.role);assert.ok(variants.includes('silent_video'));assert.ok(variants.includes('poster'));assert.equal(variants.includes('audio_track'),sound);
|
||||
const linked=(await request('/api/feed?section=videos')).posts.find((p:{id:string})=>p.id===post.id);assert.ok(linked.assets.some((a:{role:string})=>a.role==='poster'));
|
||||
const videoNote=await fetch(base+'/explore/'+post.id+'?agent_mode=True').then(r=>r.text());assert.ok(videoNote.includes('静音视频'));
|
||||
const reusedVideo=await request('/api/posts',{kind:'video',title:'复用已加工的视频',assets:[{id:asset.id}]});assert.ok((await db().query("SELECT 1 FROM post_assets WHERE post_id=$1 AND role='silent_video'",[reusedVideo.id])).rowCount);
|
||||
const clip:Response=await fetch(base+'/api/media/'+asset.id+'?variant=silent_video');assert.equal(clip.status,200);const derived=join(dir,'derived.mp4');await writeFile(derived,Buffer.from(await clip.arrayBuffer()));assert.equal((await probe(derived)).streams.some(s=>s.codec_type==='audio'),false);
|
||||
}
|
||||
assert.equal((await db().query("SELECT count(*)::integer AS n FROM assets WHERE kind='audio' AND derivation='audio_track'")).rows[0].n,1,'Video soundtracks are ordinary reusable assets');
|
||||
const audio=join(dir,'audio.wav');await run('ffmpeg',['-y','-v','error','-f','lavfi','-i','sine=frequency=220','-t','0.2',audio]);await upload('audio',[{data:await readFile(audio),name:'audio.wav',mime:'audio/wav'}]);assert.equal((await request('/api/feed?section=audio')).posts.length,1);
|
||||
for(const removed of ['/library/assets','/library/tags'])assert.equal((await fetch(base+removed)).status,404);
|
||||
const published=await publishLearningSeries();await publishLearningSeries();
|
||||
const articles=(await request('/api/feed?section=articles')).posts;
|
||||
assert.equal(articles.length,3,'Repeated publication must not duplicate posts');
|
||||
assert.equal(new Set(articles.map((p:{cover_asset_id:string})=>p.cover_asset_id)).size,1,'Three posts share one independent image asset');
|
||||
assert.equal((await db().query('SELECT count(*)::integer AS n FROM post_assets WHERE asset_id=$1',[published.coverId])).rows[0].n,3);
|
||||
for(const slug of published.published){const response=await fetch(base+'/p/'+slug);assert.equal(response.status,200);assert.ok((await response.text()).includes('内容 ID'))}
|
||||
assert.equal((await request('/api/feed?section=articles&path=learning-skills')).posts.length,3);
|
||||
const coverResponse=await fetch(base+'/api/media/'+published.coverId);assert.equal(coverResponse.headers.get('content-type'),'image/png');
|
||||
const coverInfo=await sharp(Buffer.from(await coverResponse.arrayBuffer())).metadata();assert.equal(coverInfo.width,1080);assert.equal(coverInfo.height,1440);
|
||||
assert.equal((await request('/api/feed')).contributions.reduce((n:number,c:{total:number})=>n+c.total,0),5,'Editorial publication does not invent contribution events');
|
||||
for(const slug of published.published){
|
||||
assert.equal((await fetch(base+`/api/posts/${slug}/snapshots`)).status,404);
|
||||
assert.equal((await fetch(base+`/p/${slug}/pages/1`)).status,404);
|
||||
}
|
||||
const article=await request('/api/posts',{kind:'article',title:'无代码页面的笔记',text:'普通正文与 [引用](https://example.com)'});
|
||||
const articlePage=await fetch(base+'/explore/'+article.id).then(r=>r.text());assert.ok(articlePage.includes('note-inline-link'));
|
||||
const remaining=(await db().query("SELECT to_regclass('asset_variants') AS variants,to_regclass('page_snapshots') AS snapshots,to_regclass('render_jobs') AS renders")).rows[0];assert.deepEqual(remaining,{variants:null,snapshots:null,renders:null});
|
||||
// Both file-backed Wiki pages and media notes can be edited on their stable IDs.
|
||||
const note=staticEntries.find(e=>e.namespace==='Main'&&!e.media.length)!;
|
||||
const editable=await request('/api/notes/'+note.id);
|
||||
const newTag=await request('/api/tags',{name:'#在线编辑'});
|
||||
const updatedBody='## 新内容\n\n- 项目一\n - 子项目\n- [相关笔记](/explore/'+reused.id+')';
|
||||
const edit=async(id:string,payload:unknown)=>fetch(base+'/api/notes/'+id,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
|
||||
const payload={title:'已编辑的 Wiki 笔记',description:'修改后的预览描述',markdown:updatedBody,tags:[newTag.id],revision:editable.entry.revision};
|
||||
const saved=await edit(note.id,payload);assert.equal(saved.status,200,await saved.clone().text());
|
||||
assert.equal((await request('/api/notes/'+note.id)).entry.title,payload.title);
|
||||
assert.equal((await edit(note.id,{...payload,title:'旧窗口写入'})).status,409,'Stale editor must not overwrite a newer save');
|
||||
const updatedText=await fetch(base+'/explore/'+note.id+'?agent_mode=True').then(r=>r.text());assert.ok(updatedText.includes(updatedBody));assert.ok(updatedText.includes('在线编辑'));
|
||||
const updatedHtml=await fetch(base+'/explore/'+note.id).then(r=>r.text());assert.ok(updatedHtml.includes('<ul>'));assert.ok(updatedHtml.includes('<li>'));assert.ok(updatedHtml.includes('复制网页链接'));assert.ok(updatedHtml.includes('复制纯文本链接'));assert.ok(!updatedHtml.includes('原文件 ↗'));
|
||||
const editedPreview=(await request('/api/explore-feed?category='+encodeURIComponent('在线编辑'))).entries.find((e:{id:string})=>e.id===note.id);assert.equal(editedPreview.description,payload.description);
|
||||
assert.ok((await fetch(base+'/api/wiki-index').then(r=>r.text())).includes(payload.title));
|
||||
const storedPost=(await request('/api/notes/'+first.id)).entry;
|
||||
const oldCaption=(await db().query("SELECT a.id FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=$1 AND a.kind='text'",[first.id])).rows[0].id;
|
||||
const captionReuse=await request('/api/posts',{kind:'article',title:'共享文本的笔记',assets:[{id:oldCaption,role:'caption'}]});
|
||||
const savedPost=await edit(first.id,{title:'修改后的图片笔记',description:'图片仍保留',markdown:'新的正文',tags:[newTag.id],revision:storedPost.revision});assert.equal(savedPost.status,200,await savedPost.clone().text());
|
||||
const updatedPost=await request('/api/notes/'+first.id);assert.equal(updatedPost.entry.imageCount,2);assert.equal(updatedPost.entry.editableMarkdown,'新的正文');
|
||||
assert.equal((await request('/api/notes/'+captionReuse.id)).entry.editableMarkdown,'可以复用的独立文字','Editing one note must not mutate shared text');
|
||||
const authored=(await request('/api/feed?section=articles')).posts.find((p:{slug:string})=>p.slug===published.published[0]);const authoredState=await request('/api/notes/'+authored.id);
|
||||
assert.equal((await edit(authored.id,{title:'保留用户修改',description:'部署不能覆盖',markdown:'手动修改的正文',tags:[newTag.id],revision:authoredState.entry.revision})).status,200);
|
||||
await publishLearningSeries();const retained=await request('/api/notes/'+authored.id);assert.equal(retained.entry.title,'保留用户修改');assert.equal(retained.entry.editableMarkdown,'手动修改的正文');
|
||||
assert.equal((await request('/api/notes/'+note.id)).entry.title,payload.title,'Static edits outlive content publication');
|
||||
assert.equal((await fetch(base+'/api/notes/missing')).status,404);
|
||||
assert.equal((await fetch(base+'/api/notes/'+note.id,{method:'DELETE'})).status,405);
|
||||
// API-only publication: upload independent assets, retain a stable public ID, then update cover.
|
||||
const postCountBefore=(await db().query('SELECT count(*)::integer AS n FROM posts')).rows[0].n;
|
||||
const assetsForm=new FormData();assetsForm.set('kind','image');assetsForm.set('assetOnly','true');
|
||||
assetsForm.append('files',new Blob([new Uint8Array(a)],{type:'image/png'}),'standalone-a.png');
|
||||
const secondImage=await sharp({create:{width:160,height:220,channels:3,background:'#d7c7b5'}}).png().toBuffer();
|
||||
assetsForm.append('files',new Blob([new Uint8Array(secondImage)],{type:'image/png'}),'standalone-b.png');
|
||||
const uploadedOnly=await fetch(base+'/api/upload',{method:'POST',body:assetsForm});assert.equal(uploadedOnly.status,201,await uploadedOnly.clone().text());
|
||||
const independent=await uploadedOnly.json();assert.equal(independent.assets.length,2);assert.equal(independent.files[0].filename,'standalone-a.png');
|
||||
assert.equal((await db().query('SELECT count(*)::integer AS n FROM posts')).rows[0].n,postCountBefore,'assetOnly never creates a post');
|
||||
const publicId=note.id;
|
||||
const apiBody='## 纯文本资料\n\n```json\n{"type":"text","box":[1,2,3,4]}\n```\n\n```tsx\nexport default function Demo(){return <div/>}\n```';
|
||||
const publishedNote=await request('/api/posts',{kind:'article',title:'API 发布资料',slug:'api-public-'+randomUUID(),publicId,text:apiBody,assets:independent.assets.map((id:string)=>({id})),coverAssetId:independent.assets[0],tags:[child.id]});
|
||||
assert.equal(publishedNote.publicId,publicId);assert.ok(!(await fetch(base+'/api/wiki-index').then(r=>r.text())).includes('['+payload.title+']'),'Migrated code entries are not listed under stale titles');assert.equal(publishedNote.url,'/explore/'+publicId);
|
||||
const publicEntry=(await request('/api/notes/'+publicId)).entry;assert.equal(publicEntry.id,publicId);assert.equal(publicEntry.postSlug,publishedNote.slug);assert.equal(publicEntry.coverAssetId,independent.assets[0]);
|
||||
assert.equal((await request('/api/explore-feed')).entries.filter((e:{id:string})=>e.id===publicId).length,1,'API note replaces rather than duplicates its static predecessor');
|
||||
const publicText=await fetch(base+'/explore/'+publicId+'?agent_mode=True').then(r=>r.text());assert.ok(publicText.includes(apiBody));assert.ok(publicText.includes(independent.assets[0]));
|
||||
const coverPayload={title:publicEntry.title,description:publicEntry.description,markdown:publicEntry.editableMarkdown,tags:[child.id],revision:publicEntry.revision,coverAssetId:independent.assets[1]};
|
||||
const coverSaved=await edit(publicId,coverPayload);assert.equal(coverSaved.status,200,await coverSaved.clone().text());
|
||||
const afterCover=(await request('/api/notes/'+publicId)).entry;assert.equal(afterCover.coverAssetId,independent.assets[1]);assert.equal(afterCover.media[0].url,'/api/media/'+independent.assets[1]);assert.notEqual(afterCover.revision,publicEntry.revision);
|
||||
assert.equal((await edit(publicId,coverPayload)).status,409,'Stale cover edits cannot overwrite current media');
|
||||
const replaceMedia=await edit(publicId,{...coverPayload,revision:afterCover.revision,assets:[{id:independent.assets[1],role:'content'},{id:independent.assets[0],role:'caption'}]});assert.equal(replaceMedia.status,200,await replaceMedia.clone().text());
|
||||
const finalPublic=(await request('/api/notes/'+publicId)).entry;assert.equal(finalPublic.imageCount,1);assert.equal(finalPublic.assets.length,2);assert.equal(finalPublic.editableMarkdown,apiBody);
|
||||
const duplicatePublic=await fetch(base+'/api/posts',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({kind:'article',title:'不覆盖已有 ID',publicId,text:'x'})});assert.equal(duplicatePublic.status,409);
|
||||
assert.equal((await fetch(base+'/p/'+publishedNote.slug,{redirect:'manual'})).headers.get('location'),'/explore/'+publicId);
|
||||
for(const removed of ['/layout-reference/index.html','/layout-reference/ref-01/index.html','/layout-reference/index.json'])assert.equal((await fetch(base+removed)).status,404,removed);
|
||||
for(const doc of ['SKILL','style','upload','checks']){const r=await fetch(base+`/skills/street-people/${doc}.md`);assert.equal(r.status,200);assert.ok(r.headers.get('content-type')?.includes('text/markdown'));const text=await r.text();assert.ok(text.startsWith('# '));assert.ok(!text.includes('<html'));}
|
||||
for(const doc of ['SKILL','workflow','visual-grammar','prompt','delivery']){
|
||||
const path=`/skills/shadow-puppet/${doc}.md`;const response=await fetch(base+path);assert.equal(response.status,200,path);assert.ok(response.headers.get('content-type')?.includes('text/markdown'));assert.ok((await response.text()).startsWith('# '));
|
||||
const head=await fetch(base+path,{method:'HEAD'});assert.equal(head.status,200);assert.equal(await head.text(),'');
|
||||
if(doc!=='SKILL')assert.equal((await fetch(base+'/tools/skills/shadow-puppet/'+doc)).status,200);
|
||||
}
|
||||
for(const image of ['egret-example','dancer-example'])assert.equal((await fetch(base+`/skills/shadow-puppet/${image}.png`,{method:'HEAD'})).status,200);
|
||||
for(const path of ['/skills/missing/SKILL.md','/skills/shadow-puppet/missing.md','/tools/skills/shadow-puppet/missing'])assert.equal((await fetch(base+path)).status,404,path);
|
||||
assert.equal((await fetch(base+'/api/skill-docs/shadow-puppet/SKILL',{method:'POST'})).status,405);
|
||||
const home=await fetch(base+'/').then(r=>r.text());assert.ok(home.includes('/explore/'));assert.ok(home.includes('分类'));assert.ok(home.includes('照片入皮影'));
|
||||
|
||||
const spec=await request('/api/skills/street-people');assert.equal(spec.generation.executor,'coding-agent');
|
||||
assert.equal((await fetch(base+'/api/skills/street-people?format=md')).headers.get('content-type'),'text/markdown; charset=utf-8');
|
||||
const skillUpload=async(bytes:Uint8Array,slug:string)=>{const f=new FormData();f.set('slug',slug);f.append('files',new Blob([new Uint8Array(bytes)],{type:'image/png'}),'person.png');return fetch(base+'/api/skills/street-people',{method:'POST',body:f});};
|
||||
const skillSlug='skill-'+randomUUID();
|
||||
assert.equal((await skillUpload(a,skillSlug)).status,400,'Opaque PNG rejected');
|
||||
const opaqueAlpha=await sharp({create:{width:64,height:64,channels:4,background:'#fff'}}).png().toBuffer();
|
||||
assert.equal((await skillUpload(opaqueAlpha,skillSlug)).status,400,'Unused alpha channel rejected');
|
||||
const transparent=await sharp({create:{width:64,height:64,channels:4,background:'#0000'}}).composite([{input:await sharp({create:{width:32,height:32,channels:4,background:'#faf4e5'}}).png().toBuffer(),left:16,top:16}]).png().toBuffer();
|
||||
const created=await skillUpload(transparent,skillSlug);assert.equal(created.status,201,await created.clone().text());const character=await created.json();assert.equal(character.slug,skillSlug);assert.equal(character.url,'/p/'+skillSlug);
|
||||
assert.equal((await skillUpload(transparent,skillSlug)).status,409,'Stable slug prevents duplicate posts');
|
||||
const stored=await fetch(base+'/api/media/'+character.assets[0]);assert.deepEqual(Buffer.from(await stored.arrayBuffer()),transparent,'PNG alpha and original bytes preserved in S3');
|
||||
assert.equal((await fetch(base+character.url)).status,200);
|
||||
// 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);
|
||||
// System labels have a closed catalogue; ordinary # labels remain user-created.
|
||||
const allLabels=await request('/api/tags'),systems=allLabels.filter((t:{kind:string})=>t.kind==='system');assert.equal(systems.length,2);
|
||||
const entryLabel=systems.find((t:{system_key:string})=>t.system_key==='document-entry');assert.ok(entryLabel);
|
||||
for(const body of [{name:'非法系统项',kind:'system'},{name:'#文档入口'}]){
|
||||
const response=await fetch(base+'/api/tags',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});assert.equal(response.status,400);
|
||||
}
|
||||
const plain=await request('/api/tags',{name:'#可随时添加'});assert.equal(plain.kind,'normal');
|
||||
const beforeTags=(await request('/api/notes/'+targetNote.id)).entry;
|
||||
const patchTags=(payload:unknown)=>fetch(base+'/api/notes/'+targetNote.id,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
|
||||
const assigned=await patchTags({tags:[plain.id,entryLabel.id],revision:beforeTags.revision});assert.equal(assigned.status,200,await assigned.clone().text());
|
||||
const afterTags=(await request('/api/notes/'+targetNote.id)).entry;assert.deepEqual(afterTags.categories,[plain.name]);assert.equal(afterTags.systemTags[0].system_key,'document-entry');assert.equal(afterTags.editableMarkdown,beforeTags.editableMarkdown);
|
||||
const systemFeed=await request('/api/explore-feed?category='+encodeURIComponent(entryLabel.name));assert.ok(systemFeed.entries.some((e:{id:string})=>e.id===targetNote.id));
|
||||
assert.equal((await patchTags({tags:[],revision:beforeTags.revision})).status,409);
|
||||
assert.equal((await patchTags({tags:[],revision:afterTags.revision})).status,200);
|
||||
const cleared=(await request('/api/notes/'+targetNote.id)).entry;assert.equal(cleared.categories.length,0);assert.equal(cleared.systemTags.length,0);
|
||||
const categoriesHtml=await fetch(base+'/categories').then(r=>r.text());const tabs=categoriesHtml.match(/aria-label="系统标签分类"[\s\S]*?<\/nav>/)?.[0]||'';assert.ok(tabs.includes('文档入口'));assert.ok(tabs.includes('参考图'));assert.ok(!tabs.includes(plain.name));
|
||||
}finally{
|
||||
for(const child of [worker,server])if(child&&child.exitCode===null&&child.signalCode===null){const stopped=once(child,'exit');child.kill('SIGTERM');await stopped;}
|
||||
await rm(dir,{recursive:true,force:true});await db().end();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { chapters, seriesCover } from "../src/content/learning-skills/data";
|
||||
|
||||
test("the authored series has three distinct chapters of ten sourced skills and one cover",()=>{
|
||||
assert.equal(chapters.length,3);assert.equal(new Set(chapters.map(c=>c.key)).size,3);
|
||||
assert.equal(new Set(chapters.map(c=>c.slug)).size,3);assert.equal(seriesCover,"/learning-skills/cover.png");
|
||||
for(const chapter of chapters){
|
||||
assert.equal(chapter.skills.length,10);assert.equal(new Set(chapter.skills.map(s=>s.source)).size,10);
|
||||
for(const skill of chapter.skills){
|
||||
const source=new URL(skill.source);assert.equal(source.protocol,"https:");assert.equal(source.hostname,"github.com");
|
||||
assert.ok(skill.title&&skill.input&&skill.output&&skill.prompt&&skill.note);
|
||||
assert.equal(skill.sample.length,3);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {test} from 'node:test';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {decodeCursor,encodeCursor,validSection} from '../src/lib/model';
|
||||
test('timeline cursor preserves timestamp and ID, rejects malformed values',()=>{
|
||||
const date='2026-10-22T00:00:00.000Z',id=randomUUID();assert.deepEqual(decodeCursor(encodeCursor(date,id)),[date,id]);assert.throws(()=>decodeCursor('invalid'));assert.equal(decodeCursor(),null);
|
||||
});
|
||||
test('only the five content sections are recognized',()=>{assert.equal(validSection('videos')?.kind,'video');assert.equal(validSection('unknown'),undefined);});
|
||||
@@ -0,0 +1,18 @@
|
||||
import React from 'react';
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {renderToStaticMarkup} from 'react-dom/server';
|
||||
import {NoteMarkdown} from '../src/components/NoteMarkdown';
|
||||
const render=(text:string)=>renderToStaticMarkup(<NoteMarkdown text={text}/>);
|
||||
test('Markdown renders nested bullets, numbered and task lists as semantic lists',()=>{
|
||||
const html=render('- 第一项\n - 子项目\n- 第二项\n\n3. 第三步\n4. 第四步\n\n- [x] 完成\n- [ ] 待办');
|
||||
assert.match(html,/<ul>/);assert.match(html,/<li>第一项\n<ul>/);assert.match(html,/<ol start="3">/);assert.match(html,/type="checkbox"/);assert.match(html,/checked/);assert.ok(!html.includes('- 第一项'));
|
||||
});
|
||||
test('Markdown keeps fenced code, tables, strong text and subtle links',()=>{
|
||||
const html=render('## 标题\n\n**重点** 和 [相关笔记](/explore/abc?agent_mode=True)\n\n| 名称 | 值 |\n| --- | --- |\n| 条目 | 1 |\n\n```ts\nconst items = [1, 2];\n```');
|
||||
assert.match(html,/<h2>标题/);assert.match(html,/<strong>重点/);assert.match(html,/<table>/);assert.match(html,/<pre><code class="language-ts">/);assert.match(html,/note-inline-link/);assert.match(html,/href="\/explore\/abc"/);
|
||||
});
|
||||
test('Untrusted Markdown cannot execute HTML or javascript links and images stay links',()=>{
|
||||
const html=render('<script>alert(1)</script>\n\n[unsafe](javascript:alert)\n\n');
|
||||
assert.ok(!html.includes('<script>'));assert.ok(!html.includes('href="javascript:'));assert.ok(!html.includes('<img'));assert.match(html,/href="\/api\/media\/example"/);
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import sharp from 'sharp';
|
||||
import {compressPreview,previewWidth,staticPreviewPath,cachedPreview} from '../src/lib/preview';
|
||||
test('preview input validation rejects traversal and arbitrary sizes',()=>{for(const value of [1,10000,'bad'])assert.equal(previewWidth(value),null);assert.equal(previewWidth(480),480);for(const source of ['https://example.com/x.png','/../secret.png','//remote/x.png','/x.svg','/x.png?foo=bar'])assert.throws(()=>staticPreviewPath(source,'/public'));assert.equal(staticPreviewPath('/images/a.png','/public'),'/public/images/a.png');});
|
||||
test('large PNG becomes a bounded WebP with no upscaling',async()=>{const original=await sharp({create:{width:2200,height:3000,channels:3,background:'#f0e2d2'}}).png().toBuffer();const preview=await compressPreview(original,480);const info=await sharp(preview).metadata();assert.equal(info.format,'webp');assert.equal(info.width,480);assert.ok(preview.length<=100000);});
|
||||
test('identical concurrent requests share one transform and reuse the disk result',async()=>{let loads=0;const input=await sharp({create:{width:40,height:40,channels:3,background:'#fff'}}).png().toBuffer();const identity='test-'+Date.now();const load=async()=>{loads++;return input};const [a,b]=await Promise.all([cachedPreview(identity,480,load),cachedPreview(identity,480,load)]);assert.deepEqual(a.bytes,b.bytes);assert.equal(loads,1);await cachedPreview(identity,480,load);assert.equal(loads,1);});
|
||||
@@ -0,0 +1,59 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {skillDocuments,skillResources,documentMarkdown,getSkill,skillDocumentMarkdown,skillCatalog} from '../src/content/skills/catalog';
|
||||
test('human and agent documents share a complete linked resource registry',()=>{
|
||||
for(const doc of skillDocuments){const md=documentMarkdown(doc.id)!;assert.ok(md.startsWith('# '+doc.title));for(const block of doc.blocks){if(block.text)assert.ok(md.includes(block.text));for(const id of block.refs||[])assert.ok(skillResources.some(r=>r.id===id))}assert.ok(!md.includes('/p/street-people-'));}
|
||||
assert.equal(documentMarkdown('missing'),null);assert.equal(new Set(skillResources.map(r=>r.id)).size,skillResources.length);
|
||||
for(const doc of skillDocuments)assert.ok(skillResources.some(r=>r.id===doc.id&&r.human&&r.href.endsWith('.md')));
|
||||
});
|
||||
|
||||
test('original collections retain their authored documents and API resources',()=>{
|
||||
for(const card of skillCatalog){
|
||||
const skill=getSkill(card.id)!;assert.ok(skill);assert.equal(skill.id,card.id);
|
||||
assert.equal(new Set(skill.resources.map(r=>r.id)).size,skill.resources.length);
|
||||
for(const doc of skill.documents){
|
||||
const md=skillDocumentMarkdown(card.id,doc.id)!;assert.ok(md.startsWith('# '+doc.title));
|
||||
assert.ok(skill.resources.some(r=>r.id===doc.id&&r.kind==='document'&&r.human));
|
||||
for(const block of doc.blocks){if(block.text)assert.ok(md.includes(block.text));for(const id of block.refs||[])assert.ok(skill.resources.some(r=>r.id===id),card.id+': '+id);}
|
||||
}
|
||||
}
|
||||
assert.equal(getSkill('__proto__'),undefined);assert.equal(skillDocumentMarkdown('missing','index'),null);assert.equal(skillDocumentMarkdown('shadow-puppet','missing'),null);
|
||||
const shadow=getSkill('shadow-puppet')!;
|
||||
assert.equal(shadow.resources.filter(r=>r.kind==='document').length,5);
|
||||
assert.equal(shadow.resources.filter(r=>r.kind==='image').length,2);
|
||||
assert.equal(shadow.resources.find(r=>r.id==='upload-api')?.href,'/api/upload');
|
||||
assert.equal(shadow.resources.find(r=>r.id==='media-api')?.template,true);
|
||||
});
|
||||
|
||||
test('every guidance page has a matching Markdown URL and all document links resolve globally',async()=>{
|
||||
const {guidanceDocuments,getGuidance,guidanceMarkdown,guidanceIndexMarkdown,humanDocumentUrl,markdownDocumentUrl,guidanceBacklinks}=await import('../src/content/skills/guidance');
|
||||
assert.equal(new Set(guidanceDocuments.map(d=>d.path)).size,guidanceDocuments.length);
|
||||
for(const doc of guidanceDocuments){
|
||||
for(const r of doc.resources)if(r.documentPath)assert.ok(getGuidance(r.documentPath),r.documentPath);
|
||||
const text=guidanceMarkdown(doc.path)!;
|
||||
assert.ok(text.startsWith('# '+doc.title));
|
||||
assert.equal(markdownDocumentUrl(doc.path),humanDocumentUrl(doc.path)+'?agent_mode=True');
|
||||
assert.ok(text.includes(humanDocumentUrl(doc.path)));
|
||||
for(const block of doc.blocks){
|
||||
if(block.text)assert.ok(text.includes(block.text));
|
||||
for(const id of block.refs||[]){const r=doc.resources.find(r=>r.id===id);assert.ok(r,doc.path+': '+id);if(r.documentPath){assert.ok(getGuidance(r.documentPath));assert.ok(text.includes(markdownDocumentUrl(r.documentPath)));}}
|
||||
}
|
||||
assert.ok(guidanceIndexMarkdown().includes(markdownDocumentUrl(doc.path)));
|
||||
}
|
||||
assert.ok(guidanceIndexMarkdown(true).includes('/skills/index.md'));
|
||||
assert.equal(getGuidance('__proto__'),undefined);assert.equal(guidanceMarkdown('missing'),null);
|
||||
const shared=guidanceBacklinks('image-delivery').map(d=>d.path);
|
||||
assert.ok(shared.includes('street-people/checks'));assert.ok(shared.includes('shadow-puppet/delivery'));
|
||||
assert.ok(guidanceMarkdown('image-delivery')!.includes(markdownDocumentUrl('street-people/checks')));
|
||||
assert.ok(guidanceMarkdown('image-delivery')!.includes(markdownDocumentUrl('shadow-puppet/delivery')));
|
||||
});
|
||||
|
||||
test('Markdown counterpart responses support GET and HEAD and reject writes or missing documents',async()=>{
|
||||
const {sendMarkdown}=await import('../src/lib/markdown-response');
|
||||
const {guidanceMarkdown}=await import('../src/content/skills/guidance');
|
||||
for(const [method,text,expected] of [['GET',guidanceMarkdown('shadow-puppet/prompt'),200],['HEAD',guidanceMarkdown('shadow-puppet/prompt'),200],['POST',guidanceMarkdown('shadow-puppet/prompt'),405],['GET',guidanceMarkdown('missing'),404]] as const){
|
||||
const result={code:0,body:null as string|null,headers:{} as Record<string,string>,setHeader(k:string,v:string){this.headers[k]=v;return this},status(code:number){this.code=code;return this},send(body:string){this.body=body;return this},end(){return this}};
|
||||
sendMarkdown({method} as import('next').NextApiRequest,result as unknown as import('next').NextApiResponse,text);
|
||||
assert.equal(result.code,expected);if(method==='GET'&&expected===200){assert.match(result.headers['Content-Type'],/text\/markdown/);assert.ok(result.body?.startsWith('# '));}else assert.equal(result.body,null);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {wikiPages,findWikiPage,wikiMarkdown,wikiPath} from '../src/content/wiki';
|
||||
test('every wiki card resolves to the same AI-visible page',()=>{for(const page of wikiPages){const key=page.namespace+':'+page.slug;assert.equal(findWikiPage(key),page);assert.ok(wikiMarkdown(page).includes(page.body));assert.equal(decodeURIComponent(wikiPath(page)),'/wiki/'+key);}});
|
||||
test('category membership crosses namespaces and rejects unknown categories',()=>{const page=findWikiPage('Category:创作方法');assert.ok(page?.body.includes('Main:'));assert.ok(page?.body.includes('Template:'));assert.equal(findWikiPage('Category:missing'),undefined);assert.equal(findWikiPage('Unknown:welcome'),undefined);});
|
||||
Reference in New Issue
Block a user