Publish reference layouts as API-authored text and image notes
wiki CI and deployment / verify-and-deploy (push) Successful in 16m28s

This commit is contained in:
2026-10-26 17:20:57 +08:00
parent dd09ae3485
commit 38ec492ca3
669 changed files with 819 additions and 11326 deletions
+28
View File
@@ -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));
});
-13
View File
@@ -15,16 +15,3 @@ test('independent notes expose their own description, tags and complete image co
const workflow=(await getEntry(pageId('guidance:shadow-puppet/workflow')))!;
assert.notEqual(workflow.description,note.description);assert.notEqual(workflow.id,note.id);
});
test('agent text preserves tutorial HTML and TSX code without returning an HTML page',async()=>{
const entry=(await getEntry(pageId('guidance:premium-layout/ref-01')))!;
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.startsWith('# '+entry.title));
assert.match(body,/```\n<!doctype html>\n<html lang="zh-CN">/);
assert.ok(body.includes('export default function Example'));
assert.ok(body.includes('app/designs/ref-01/page.tsx'));
assert.equal(body,entryText(entry));
});
+25
View File
@@ -100,6 +100,31 @@ test('real PostgreSQL + S3 notes, flat tags, resource sharing and video processi
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('# '));
-47
View File
@@ -1,47 +0,0 @@
import React from 'react';
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {readFile} from 'node:fs/promises';
import {createHash} from 'node:crypto';
import path from 'node:path';
import sharp from 'sharp';
import {renderToStaticMarkup} from 'react-dom/server';
import {transformSync} from 'esbuild';
import manifest from '../src/content/layouts/reference/manifest.json';
import ReferenceLayout,{layoutIds,validateReplacements} from '../src/content/layouts/reference/ReferenceLayout';
import {textMergeTarget} from '../src/content/layouts/reference/group-text';
import {layoutDocuments,htmlExample,reactExample,nextExample,legacyLayoutIds} from '../src/content/layouts/documents';
import {getServerSideProps} from '../src/pages/explore/[id]';
const publicRoot=path.resolve(import.meta.dirname,'../public');
const asset=(url:string)=>path.join(publicRoot,url);
test('27 source layouts have stable row-major IDs, 5/5/5/6/6 positions and scoped components',async()=>{
assert.deepEqual(manifest.map(l=>l.id),[...layoutIds]);assert.equal(layoutDocuments.length,28);
assert.deepEqual([1,2,3,4,5].map(row=>manifest.filter(l=>l.source.row===row).length),[5,5,5,6,6]);
const hash=createHash('sha256').update(await readFile(asset('/layout-reference/source.png'))).digest('hex');
for(const l of manifest){assert.equal(l.source.sha256,hash);assert.equal(new Set(l.elements.map(e=>e.id)).size,l.elements.length);for(const e of l.elements){assert.ok(e.asset.startsWith('/layout-reference/'+l.id+'/'));assert.ok(e.pixels>0);assert.equal(e.id[0],{text:'T',image:'I',decoration:'D'}[e.kind]);if(e.reading==='unreadable')assert.equal(e.text,null)}}
});
test('all 27 extracted layer composites equal their original source crops at every RGB pixel',async()=>{
for(const l of manifest){
const result=await sharp(asset(l.background)).composite(l.elements.map(e=>({input:asset(e.asset),left:e.box[0],top:e.box[1]}))).removeAlpha().raw().toBuffer();
const reference=await sharp(asset(l.reference)).removeAlpha().raw().toBuffer();assert.ok(result.equals(reference),l.id+' physical layer composite must match');
}
});
test('a residual end glyph stays in T01 instead of creating a second word; other columns stay independent',()=>{
assert.equal(textMergeTarget([38,24,6,6],[{box:[2,20,38,15],direction:'horizontal'}]),0);
assert.equal(textMergeTarget([90,24,6,6],[{box:[2,20,38,15],direction:'horizontal'}]),-1);
const first=manifest[0];assert.deepEqual(first.elements.filter(e=>e.kind==='text').map(e=>e.id),['T01','T02']);
assert.ok(first.elements.find(e=>e.id==='T01')!.box[0]+first.elements.find(e=>e.id==='T01')!.box[2]>=44);
const date=manifest.find(l=>l.id==='ref-21')!.elements.find(e=>e.id==='T03')!;assert.equal(date.text,'03');assert.equal(date.kind,'text');
const grayWord=manifest.find(l=>l.id==='ref-23')!.elements.find(e=>e.text==='BULUBLUE')!;assert.equal(grayWord.kind,'text');
});
test('component replacement rejects foreign IDs and wrong kinds; default React renders exact source assets',()=>{
assert.throws(()=>validateReplacements('ref-01',{text:{'ref-02/T01':'wrong'}}));
assert.throws(()=>validateReplacements('ref-01',{text:{'ref-01/I01':'wrong'}}));
assert.throws(()=>validateReplacements('missing',{}));
for(const id of layoutIds){const html=renderToStaticMarkup(<ReferenceLayout id={id}/>);assert.ok(html.includes('data-layout-id="'+id+'"'));assert.equal((html.match(/data-component=/g)||[]).length,manifest.find(l=>l.id===id)!.elements.length)}
const edited=renderToStaticMarkup(<ReferenceLayout id="ref-01" text={{'ref-01/T01':'我的品牌'}} images={{'ref-01/I01':'/my-photo.jpg'}}/>);assert.ok(edited.includes('我的品牌'));assert.ok(edited.includes('mask-image'));assert.ok(edited.includes('T01-underlay.png'));
});
test('HTML, React and Next.js examples bind each source ID and retired approximate posts redirect to Router',async()=>{
for(const l of manifest){assert.ok(htmlExample(l.id).includes("const id='"+l.id+"'"));transformSync(reactExample(l.id),{loader:'tsx'});transformSync(nextExample(l.id),{loader:'tsx'});const html=await readFile(asset('/layout-reference/'+l.id+'/index.html'),'utf8');assert.ok(html.includes('data-toggle="text"'));assert.ok(html.includes('data-toggle="image"'));assert.ok(html.includes('manifest='+JSON.stringify(l).replaceAll('<','\\u003c')))}
for(const id of legacyLayoutIds){const response=await getServerSideProps({params:{id},query:{},res:{},req:{}} as never);assert.ok('redirect' in response)}
});