557 lines
32 KiB
JavaScript
557 lines
32 KiB
JavaScript
import {xiaoyiPacks,templateRequest} from '../src/enterprise-templates.mjs';
|
|
import {createServer} from 'node:http';
|
|
import {once} from 'node:events';
|
|
import {xiaoyiFixture} from './xiaoyi-fixture.mjs';
|
|
import {test} from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import os from 'node:os';
|
|
import {createHash} from 'node:crypto';
|
|
import {zipSync} from 'fflate';
|
|
import {acquireXiaoyiRelease,openXiaoyiSkills} from '../src/xiaoyi-release.mjs';
|
|
|
|
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
const describe = bytes => ({size:bytes.length,sha256:sha(bytes)});
|
|
|
|
async function fixture(t, {badHash = false,templateId = 'CHAIR',withBindings = false,intake,schemaVersion=1,configText='{"productionProfiles":{"detail":{"pages":{"D01":{}}}}}'} = {}) {
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-release-'));
|
|
t.after(() => fs.rm(dir,{recursive:true,force:true}));
|
|
const config = Buffer.from(configText);
|
|
const guide = Buffer.from(withBindings?'---\nname: chair\ndescription: Fixture template.\n---\n指南':'guide');
|
|
const blob = Buffer.from('original');
|
|
const mapping = Buffer.from(JSON.stringify({
|
|
template_id:templateId,component:'detail',mapping_version:'1',
|
|
canvas:[40,40],source:{sha256:sha(blob)},
|
|
fields:[{field_id:'D01-I01',type:'图片',name:'商品',screen_id:'D01',
|
|
ps_location:{path:'商品',name:'商品'},ps_style:{coverage_rect:[0,0,40,40]}}],
|
|
screens:[{screen_id:'D01',title:'商品页',bounds:[0,0,40,40]}],
|
|
}));
|
|
const inventory = Buffer.from(JSON.stringify({template_id:templateId,component:'detail',mapping_version:'1'}));
|
|
const extra = withBindings ? {'模板/mapping.json':mapping,'模板/inventory.json':inventory} : {};
|
|
const bundle = Buffer.from(zipSync({'规则/SKILL.md':guide,'小壹/production.json':config,...extra}));
|
|
const manifest = {
|
|
schemaVersion,templateId,version:'v1',knowledgeVersion:templateId+'@v1',
|
|
entrypoint:'规则/SKILL.md',supplement:'规则/SKILL.md',
|
|
productionConfig:'小壹/production.json',
|
|
...(intake ? {intake} : {}),
|
|
...(withBindings?{bindings:{detail:{mapping:'模板/mapping.json',inventory:'模板/inventory.json',original:'模板/original.psd'}}}:null),
|
|
bundle:describe(bundle),assets:[{path:'模板/original.psd',type:'original',component:'detail',...describe(blob)}],
|
|
files:[{path:'规则/SKILL.md',...describe(guide),...(badHash?{sha256:sha('wrong')}:null)},
|
|
{path:'小壹/production.json',...describe(config)},
|
|
...Object.entries(extra).map(([path,bytes])=>({path,type:path.endsWith('mapping.json')?'mapping':'inventory',...describe(bytes)}))],
|
|
};
|
|
const raw = Buffer.from(JSON.stringify(manifest));
|
|
const requests = [];
|
|
const pauses = [];
|
|
const options = {templateId,directory:path.join(dir,'project'),cache:path.join(dir,'cache'),
|
|
sleep:async ms => {pauses.push(ms);},
|
|
fetch:async (route,init) => {
|
|
requests.push([route,init.headers]);
|
|
if(route.endsWith('/current')) return Response.json({version:'v1',manifestSha256:sha(raw)});
|
|
if(route.endsWith('/manifest')) return new Response(raw,{headers:{etag:'"'+sha(raw)+'"'}});
|
|
const body = route.endsWith('/bundle') ? bundle : blob;
|
|
if (!init.headers?.range) return new Response(body);
|
|
const offset = Number(init.headers.range.slice(6,-1));
|
|
assert.equal(init.headers['if-range'],'"'+sha(body)+'"');
|
|
return new Response(body.subarray(offset),{status:206,headers:{
|
|
'content-range':`bytes ${offset}-${body.length-1}/${body.length}`,
|
|
}});
|
|
}};
|
|
return {options,manifest,requests,pauses,bundle,blob};
|
|
}
|
|
|
|
async function fastTemplate(t, inventoryVersion) {
|
|
const root = await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-fast-template-'));
|
|
t.after(() => fs.rm(root,{recursive:true,force:true}));
|
|
const templateId = 'QA-FAST-001';
|
|
const version = '2026-12-01.2';
|
|
const knowledgeVersion = `${templateId}@${version}`;
|
|
const components = {detail:[['S01','D01',640],['S02','D02',640]],main_images:[['M01','M01',512]],sku_images:[['K01','K01',512]]};
|
|
const entries = {'SKILL.md':Buffer.from('---\nname: fast\ndescription: Fixture template.\n---\n指南')};
|
|
const put = (name, value) => { entries[name] = Buffer.from(JSON.stringify(value)); };
|
|
const bindings = {}, assets = [];
|
|
const blobs = new Map();
|
|
put('production.json', {productionProfiles:{detail:{},main_images:{},sku_images:{}}});
|
|
for (const [component, pages] of Object.entries(components)) {
|
|
const files = pages.map(([screen, assetId, height]) => {
|
|
const original = `${component}/${assetId}.psd`;
|
|
const blob = Buffer.from(original);
|
|
const content = describe(blob);
|
|
blobs.set(content.sha256, blob);
|
|
assets.push({path:original, type:'original', component, ...content});
|
|
return {screen, assetId, height, original, sha256:content.sha256};
|
|
});
|
|
const source = {assets:files.map(({assetId,height,sha256}) => ({asset_id:assetId, ps_sha256:sha256, canvas_px:[512,height]}))};
|
|
const mapping = `${component}/mapping.json`, inventory = `${component}/inventory.json`;
|
|
const identity = {template_id:templateId,component};
|
|
put(mapping, {...identity,source,mapping_version:'20261201.1',
|
|
screens:files.map(({screen,assetId,height}) => ({screen_id:screen,asset_id:assetId,title:screen,bounds:[0,0,512,height]})),
|
|
fields:files.map(({screen,assetId,height}) => ({field_id:screen+'-I01',type:'图片',name:'商品',screen_id:screen,
|
|
ps_location:{asset_id:assetId,path:'商品',name:'商品'},ps_style:{coverage_rect:[0,0,512,height]}})),
|
|
});
|
|
put(inventory, {...identity,source,mapping_version:component==='sku_images' ? inventoryVersion : '20261201.1'});
|
|
bindings[component] = {mapping,inventory,...(files.length === 1 ? {original:files[0].original} :
|
|
{pages:Object.fromEntries(files.map(({screen,assetId,original}) => [screen,{assetId,original}]))})};
|
|
}
|
|
const bundle = Buffer.from(zipSync(entries));
|
|
const files = Object.entries(entries).map(([path,data]) => ({path,...describe(data),type:path.split('/').at(-1).split('.')[0]}));
|
|
const manifest = Buffer.from(JSON.stringify({schemaVersion:1,templateId,version,knowledgeVersion,
|
|
entrypoint:'SKILL.md',supplement:'SKILL.md',productionConfig:'production.json',bundle:describe(bundle),bindings,files,assets}));
|
|
const fetch = async url => {
|
|
const route = new URL(url).pathname;
|
|
if (route.endsWith('/current')) return Response.json({version,manifestSha256:sha(manifest)});
|
|
if (route.endsWith('/manifest')) return new Response(manifest,{headers:{etag:`"${sha(manifest)}"`}});
|
|
if (route.endsWith('/bundle')) return new Response(bundle);
|
|
const data = blobs.get(route.split('/').at(-1));
|
|
assert.ok(data,route);
|
|
return new Response(data);
|
|
};
|
|
return {input:{templateId,projectDir:path.join(root,'project'),cache:path.join(root,'blobs')},fetch};
|
|
}
|
|
|
|
test('the four-image template keeps both detail originals and the main and SKU outputs', async t => {
|
|
const {input,fetch} = await fastTemplate(t, '20261201.1');
|
|
const {packs} = await xiaoyiPacks(input,{fetch});
|
|
assert.deepEqual(Object.keys(packs), ['detail','main_images','sku_images']);
|
|
assert.deepEqual(packs.detail.outputs.map(({id,originalAssetId,top}) => [id,originalAssetId,top]), [['S01','D01',0],['S02','D02',640]]);
|
|
assert.deepEqual(packs.detail.enterprise.components.detail.originals.map(({assetId}) => assetId), ['D01','D02']);
|
|
assert.deepEqual(packs.main_images.outputs.map(({id,originalAssetId}) => [id,originalAssetId]), [['M01','M01']]);
|
|
assert.deepEqual(packs.sku_images.outputs.map(({id,originalAssetId}) => [id,originalAssetId]), [['K01','K01']]);
|
|
for (const pack of Object.values(packs)) {
|
|
for (const output of pack.outputs) {
|
|
assert.equal(output.slots[0].fieldId, `${output.id}-I01`);
|
|
assert.equal(output.slots[0].kind, 'image');
|
|
assert.equal(output.slots[0].psLayer.asset_id, output.originalAssetId);
|
|
}
|
|
}
|
|
});
|
|
|
|
for (const version of [undefined, 20261201.1, '20261201.2']) {
|
|
test(`tolerates an inconsistent SKU inventory version (${version}) with soft compatibilityWarnings`, async t => {
|
|
const {input,fetch} = await fastTemplate(t, version);
|
|
const result = await xiaoyiPacks(input,{fetch});
|
|
assert.deepEqual(Object.keys(result.packs), ['detail','main_images','sku_images']);
|
|
assert.ok(Array.isArray(result.compatibilityWarnings) && result.compatibilityWarnings.length > 0);
|
|
assert.deepEqual(result.warnings, result.compatibilityWarnings);
|
|
assert.ok(result.compatibilityWarnings.every(w => typeof w === 'string' && !/\.json|QA-FAST|mapping_version/i.test(w)));
|
|
assert.ok(result.packs.sku_images.compatibilityWarnings.includes(result.compatibilityWarnings[0]));
|
|
});
|
|
}
|
|
|
|
test('loads legacy QA-FAST-001@2026-12-01.1 shape (missing inventory version, ps_assets, mismatched pages/intake) with soft warnings', async t => {
|
|
const root = await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-legacy-fast-'));
|
|
t.after(() => fs.rm(root,{recursive:true,force:true}));
|
|
const templateId = 'QA-FAST-001';
|
|
const version = '2026-12-01.1';
|
|
const knowledgeVersion = `${templateId}@${version}`;
|
|
const components = {detail:[['S01','D01',640],['S02','D02',640]],main_images:[['M01','M01',512]],sku_images:[['K01','K01',512]]};
|
|
const entries = {'SKILL.md':Buffer.from('---\nname: legacy-fast\ndescription: Legacy fixture.\n---\n指南')};
|
|
const put = (name, value) => { entries[name] = Buffer.from(JSON.stringify(value)); };
|
|
const bindings = {}, assets = [], blobs = new Map();
|
|
put('production.json', {productionProfiles:{detail:{},main_images:{},sku_images:{}}});
|
|
for (const [component, pages] of Object.entries(components)) {
|
|
const files = pages.map(([screen, assetId, height]) => {
|
|
const original = `${component}/${assetId}.psd`;
|
|
const blob = Buffer.from('legacy-' + original);
|
|
const content = describe(blob);
|
|
blobs.set(content.sha256, blob);
|
|
assets.push({path:original, type:'original', component, ...content});
|
|
return {screen, assetId, height, original, sha256:content.sha256};
|
|
});
|
|
const psAssets = files.map(({assetId,height,sha256}) => ({asset_id:assetId, ps_sha256:sha256, canvas_px:[512,height]}));
|
|
const mapping = `templates/${templateId}/${component}/mapping.json`;
|
|
const inventory = `templates/${templateId}/${component}/inventory.json`;
|
|
put(mapping, {
|
|
template_id:templateId, component, mapping_version:'20261201.1',
|
|
ps_assets:psAssets,
|
|
screens:files.map(({screen,assetId,height}) => ({screen_id:screen,asset_id:assetId,title:screen,bounds:[0,0,512,height]})),
|
|
fields:files.map(({screen,assetId,height}) => ({field_id:screen+'-I01',type:'图片',name:'商品',screen_id:screen,
|
|
ps_location:{asset_id:assetId,path:'商品',name:'商品'},ps_style:{coverage_rect:[0,0,512,height]}})),
|
|
});
|
|
// Legacy inventory: missing mapping_version, mismatched component/template_id, and partial ps_assets
|
|
put(inventory, {
|
|
ps_assets:component === 'detail' ? psAssets.slice(0,1) : psAssets,
|
|
});
|
|
bindings[component] = {
|
|
mapping, inventory,
|
|
...(files.length === 1 ? {original:files[0].original} : {
|
|
pages:{[files[0].screen]:{assetId:files[0].assetId,original:files[0].original}},
|
|
}),
|
|
};
|
|
if (component === 'detail') {
|
|
// Include both originals in pages so both assets are bound, while intentionally omitting S02 or keeping extra mismatch on inventory
|
|
bindings[component].pages = Object.fromEntries(files.map(({screen,assetId,original}) => [screen,{assetId,original}]));
|
|
}
|
|
}
|
|
const legacyIntake = {
|
|
version:2,
|
|
productFields:[
|
|
{id:'material',label:'材质',type:'text',hint:123},
|
|
{id:'future_widget',label:'新控件',type:'rich_text'},
|
|
],
|
|
};
|
|
const bundle = Buffer.from(zipSync(entries));
|
|
const files = Object.entries(entries).map(([filePath,data]) => ({path:filePath,...describe(data),type:filePath.split('/').at(-1).split('.')[0]}));
|
|
const manifestObj = {schemaVersion:1,templateId,version,knowledgeVersion,
|
|
entrypoint:'SKILL.md',supplement:'SKILL.md',productionConfig:'production.json',
|
|
intake:legacyIntake,bundle:describe(bundle),bindings,files,assets};
|
|
const manifest = Buffer.from(JSON.stringify(manifestObj));
|
|
const catalog = {items:[{templateId,name:'老模板',brand:'Fixture',category:'Chair',
|
|
version,knowledgeVersion,components:[{id:'detail'},{id:'main_images'},{id:'sku_images'}],intake:legacyIntake}]};
|
|
const fetch = async url => {
|
|
const route = new URL(url).pathname;
|
|
if (route === '/api/xiaoyi/v1/templates') return Response.json(catalog);
|
|
if (route.endsWith('/current')) return Response.json({version,manifestSha256:sha(manifest)});
|
|
if (route.endsWith('/manifest')) return new Response(manifest,{headers:{etag:`"${sha(manifest)}"`}});
|
|
if (route.endsWith('/bundle')) return new Response(bundle);
|
|
const data = blobs.get(route.split('/').at(-1));
|
|
assert.ok(data,route);
|
|
return new Response(data);
|
|
};
|
|
const result = await xiaoyiPacks({templateId,projectDir:path.join(root,'project'),cache:path.join(root,'blobs')},{fetch});
|
|
assert.deepEqual(Object.keys(result.packs), ['detail','main_images','sku_images']);
|
|
assert.equal(result.packs.detail.xiaoyi.intake.productFields.length, 1);
|
|
assert.equal(result.packs.detail.xiaoyi.intake.productFields[0].id, 'material');
|
|
assert.deepEqual(result.packs.detail.xiaoyi.intake.barcodeFields, []);
|
|
assert.ok(result.compatibilityWarnings.length >= 3);
|
|
assert.equal(new Set(result.compatibilityWarnings).size, result.compatibilityWarnings.length);
|
|
assert.ok(result.compatibilityWarnings.every(w => !/\.json|QA-FAST|ps_assets|mapping_version/i.test(w)));
|
|
|
|
const catalogResult = await templateRequest({
|
|
root:path.join(root,'catalog-root'),action:'resource-component',
|
|
brandId:'ekb:brand:Fixture',brandName:'Fixture',categoryId:'ekb:category:Chair',categoryName:'Chair',
|
|
resourceSetId:templateId,componentId:'detail',
|
|
},{fetch});
|
|
assert.ok(catalogResult.compatibilityWarnings.length > 0);
|
|
assert.ok(catalogResult.items[0].issues.length > 0);
|
|
assert.ok(catalogResult.items[0].pack.compatibilityWarnings.length > 0);
|
|
});
|
|
|
|
test('still rejects when core original PSD/PSB asset is missing from manifest', async t => {
|
|
const {options,manifest} = await fixture(t,{withBindings:true});
|
|
const missingOriginalManifest = Buffer.from(JSON.stringify({
|
|
...manifest,
|
|
assets:[],
|
|
}));
|
|
const fetch = async (url,init) => {
|
|
const route = url.pathname;
|
|
if (route.endsWith('/current')) return Response.json({version:'v1',manifestSha256:sha(missingOriginalManifest)});
|
|
if (route.endsWith('/manifest')) return new Response(missingOriginalManifest,{headers:{etag:`"${sha(missingOriginalManifest)}"`}});
|
|
return options.fetch(route,init);
|
|
};
|
|
await assert.rejects(xiaoyiPacks({
|
|
templateId:options.templateId,projectDir:options.directory,cache:options.cache,
|
|
brandId:'fixture-brand',categoryId:'fixture-category',name:'Fixture chair',
|
|
},{fetch}), /缺少original/);
|
|
});
|
|
|
|
test('locks a verified release, resumes offline and repairs from the same bundle', async t => {
|
|
const {options,requests} = await fixture(t);
|
|
const first = await acquireXiaoyiRelease(options);
|
|
assert.equal(first.manifest.knowledgeVersion,'CHAIR@v1');
|
|
assert.deepEqual(first.productionProfiles.detail.pages,{D01:{}});
|
|
assert.equal(requests.length,4);
|
|
const noNetwork = {...options,fetch:() => assert.fail('attempted network')};
|
|
const original = await acquireXiaoyiRelease(noNetwork);
|
|
assert.equal(original.manifest.version,'v1');
|
|
assert.equal(original.memoryFiles.get('规则/SKILL.md').toString('utf8'),'guide');
|
|
await assert.rejects(fs.access(path.join(first.root,'规则','SKILL.md')),{code:'ENOENT'});
|
|
});
|
|
|
|
test('an unknown manifest schema and malformed optional production config still open with warnings', async t => {
|
|
const {options}=await fixture(t,{withBindings:true,schemaVersion:9,configText:'invalid json'});
|
|
const result=await xiaoyiPacks({
|
|
templateId:options.templateId,projectDir:options.directory,cache:options.cache,
|
|
},{fetch:(url,init)=>options.fetch(url.pathname,init)});
|
|
assert.deepEqual(Object.keys(result.packs),['detail']);
|
|
assert.deepEqual(result.packs.detail.xiaoyi.productionProfiles,{});
|
|
assert.match(result.warnings.join(' '),/知识清单版本.*默认设置/);
|
|
assert.ok(result.packs.detail.enterprise.components.detail.originals[0].sha256);
|
|
});
|
|
|
|
test('same-size tampering fails SHA-256 validation while the locked release stays available for repair', async t => {
|
|
const {options,manifest,bundle,blob}=await fixture(t);
|
|
await acquireXiaoyiRelease(options);
|
|
const cachedBundle=path.join(options.cache,manifest.bundle.sha256);
|
|
await fs.writeFile(cachedBundle,Buffer.alloc(bundle.length,120));
|
|
await assert.rejects(acquireXiaoyiRelease({...options,fetch:()=>{throw Error('fixture offline');}}),error => error.message.includes('缓存已损坏') && error.cause?.message === 'fixture offline');
|
|
const repairedBundle = await acquireXiaoyiRelease(options);
|
|
assert.equal(repairedBundle.memoryFiles.get('规则/SKILL.md').toString('utf8'),'guide');
|
|
const original=path.join(options.cache,sha(blob));
|
|
await fs.writeFile(original,Buffer.alloc(blob.length,120));
|
|
await assert.rejects(acquireXiaoyiRelease({...options,fetch:()=>{throw Error('fixture offline');}}),/fixture offline/);
|
|
assert.equal(JSON.parse(await fs.readFile(path.join(options.directory,'manifest.json'),'utf8')).knowledgeVersion,manifest.knowledgeVersion);
|
|
await acquireXiaoyiRelease(options);
|
|
assert.deepEqual(await fs.readFile(original),blob);
|
|
});
|
|
|
|
test('continues bundle and blob partials with matching If-Range', async t => {
|
|
const {options,requests,bundle,blob,manifest} = await fixture(t);
|
|
await fs.mkdir(options.directory);
|
|
await fs.mkdir(options.cache);
|
|
await fs.writeFile(path.join(options.cache,manifest.bundle.sha256+'.part'),bundle.subarray(0,5));
|
|
await fs.writeFile(path.join(options.cache,sha(blob)+'.part'),blob.subarray(0,3));
|
|
await acquireXiaoyiRelease(options);
|
|
assert.deepEqual(requests.filter(([,headers])=>headers).map(([,headers])=>headers.range), ['bytes=5-','bytes=3-']);
|
|
});
|
|
|
|
test('rejects a file hash mismatch without writing a lock', async t => {
|
|
const {options} = await fixture(t,{badHash:true});
|
|
await assert.rejects(acquireXiaoyiRelease(options),/校验失败/);
|
|
await assert.rejects(fs.access(path.join(options.directory,'manifest.json')),{code:'ENOENT'});
|
|
});
|
|
|
|
for (const [status,code,hint] of [[401,'authentication_required',/检测连接/],
|
|
[403,'forbidden',/联系知识库管理员/],[404,'not_published',/还没有发布/],[404,undefined,/没有提供小壹制作通道/],[410,'version_retired',/已撤回/]]) {
|
|
test(`stops on HTTP ${status}`, async t => {
|
|
const {options,pauses} = await fixture(t);
|
|
options.fetch = async () => Response.json({status,code,error:'failure',retryable:false},{status});
|
|
await assert.rejects(acquireXiaoyiRelease(options),hint);
|
|
assert.deepEqual(pauses,[]);
|
|
});
|
|
}
|
|
|
|
test('honors Retry-After before retrying', async t => {
|
|
const {options,pauses} = await fixture(t);
|
|
const fetch = options.fetch;
|
|
options.fetch = (...args) => {
|
|
options.fetch = fetch;
|
|
return Response.json({status:429,code:'usage_limit',retryable:true},{status:429,headers:{'retry-after':'7'}});
|
|
};
|
|
await acquireXiaoyiRelease(options);
|
|
assert.deepEqual(pauses,[7000]);
|
|
});
|
|
|
|
test('backs off twice with jitter and reports a network diagnosis', async t => {
|
|
const {options,pauses} = await fixture(t);
|
|
options.fetch = async () => {throw Object.assign(Error('offline'),{network:true});};
|
|
await assert.rejects(acquireXiaoyiRelease(options),/无法开工:连不上企业知识库服务器/);
|
|
assert.equal(pauses.length,2);
|
|
assert.ok(pauses[0] >= 200 && pauses[0] < 300);
|
|
assert.ok(pauses[1] >= 500 && pauses[1] < 600);
|
|
});
|
|
|
|
test('catalog retries a timeout and a 500, then preserves cached fields and the draft offline', async t => {
|
|
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'xiaoyi-catalog-offline-'));
|
|
t.after(() => fs.rm(root,{recursive:true,force:true}));
|
|
const fields = [
|
|
{id:'description',label:'产品说明',type:'text',placeholder:'填写产品亮点',multiline:true},
|
|
{id:'name',label:'名称',type:'text',placeholder:'',multiline:false},
|
|
{id:'legacy',label:'旧字段',type:'text'},
|
|
];
|
|
const input = {root,action:'catalog',brandName:'品牌',categoryName:'椅子'};
|
|
const draft = path.join(root,'draft.json');
|
|
await fs.writeFile(draft,'{"description":"手工填写"}');
|
|
let calls = 0;
|
|
const fetch = async () => {
|
|
calls++;
|
|
if (calls === 1) throw new DOMException('fixture timeout','TimeoutError');
|
|
if (calls === 2) return Response.json({}, {status:500});
|
|
return Response.json({items:[{templateId:'CHAIR',name:'椅子',brand:'品牌',category:'椅子',
|
|
intake:{version:1,productFields:fields,barcodeFields:[]}}]});
|
|
};
|
|
const online = await templateRequest(input,{fetch});
|
|
assert.equal(calls,3);
|
|
assert.deepEqual(online.items[0].intake.productFields,fields);
|
|
calls = 0;
|
|
const offline = await templateRequest(input,{fetch:async()=>{
|
|
calls++;
|
|
throw new TypeError('fetch failed',{cause:Object.assign(Error('reset'),{code:'ECONNRESET'})});
|
|
}});
|
|
assert.equal(calls,3);
|
|
assert.deepEqual(offline.items,online.items);
|
|
assert.match(offline.notice,/检查网络、VPN 或代理.*本机缓存模板.*草稿已保留/);
|
|
assert.equal(await fs.readFile(draft,'utf8'),'{"description":"手工填写"}');
|
|
for (const [status,code,diagnosis] of [
|
|
[401,'authentication_required',/重新登录/],
|
|
[401,'knowledge_upstream_session_rejected',/核对授权配置和服务器时间/],
|
|
[403,'forbidden',/无权/],
|
|
[503,'knowledge_session_misconfigured',/配置错误/],
|
|
[503,'knowledge_upstream_misconfigured',/连接地址配置错误/],
|
|
]) {
|
|
calls = 0;
|
|
await assert.rejects(templateRequest(input,{fetch:async()=>{
|
|
calls++;
|
|
return Response.json({code},{status});
|
|
}}),diagnosis);
|
|
assert.equal(calls,1);
|
|
}
|
|
});
|
|
|
|
test('a rejected range restarts the same bundle without a range header', async t => {
|
|
const {options,requests,manifest,bundle} = await fixture(t);
|
|
await fs.mkdir(options.directory);
|
|
await fs.mkdir(options.cache);
|
|
await fs.writeFile(path.join(options.cache,manifest.bundle.sha256+'.part'),bundle.subarray(0,5));
|
|
const fetch = options.fetch;
|
|
let rejected = false;
|
|
options.fetch = (route,init) => {
|
|
if (route.endsWith('/bundle') && !rejected) {
|
|
rejected = true;
|
|
assert.equal(init.headers.range,'bytes=5-');
|
|
return new Response(null,{status:416});
|
|
}
|
|
return fetch(route,init);
|
|
};
|
|
await acquireXiaoyiRelease(options);
|
|
assert.ok(rejected);
|
|
const [route,headers] = requests.find(([route])=>route.endsWith('/bundle'));
|
|
assert.match(route,/releases\/v1\/bundle$/);
|
|
assert.equal(headers,undefined);
|
|
});
|
|
|
|
test('a switched HTTP current is ignored on continuation and picked up by the next round', async t => {
|
|
const {options} = await fixture(t);
|
|
const entry = '规则/SKILL.md';
|
|
const documents = {[entry]:'---\nname: demo\ndescription: Demo production guide.\n---\n制作说明'};
|
|
let publish = xiaoyiFixture('CHAIR','v1',entry,documents);
|
|
const requests = [];
|
|
const server = createServer(async (request, response) => {
|
|
const url = new URL(request.url, 'http://localhost');
|
|
requests.push(url.pathname);
|
|
const reply = publish(url);
|
|
response.writeHead(reply.status,Object.fromEntries(reply.headers));
|
|
response.end(Buffer.from(await reply.arrayBuffer()));
|
|
});
|
|
server.listen(0,'127.0.0.1');
|
|
await once(server,'listening');
|
|
t.after(() => new Promise(resolve => server.close(resolve)));
|
|
const fetchLocal = (url,init) => fetch(new URL(url.pathname,`http://127.0.0.1:${server.address().port}`),init);
|
|
const store = {dir:options.directory};
|
|
const first = await openXiaoyiSkills(store,'CHAIR',undefined,undefined,fetchLocal);
|
|
assert.equal(first.knowledgeVersion,'CHAIR@v1');
|
|
publish = xiaoyiFixture('CHAIR','v2',entry,documents);
|
|
requests.length = 0;
|
|
const continued = await openXiaoyiSkills(store,'CHAIR',undefined,undefined,fetchLocal);
|
|
assert.equal(continued.knowledgeVersion,'CHAIR@v1');
|
|
assert.deepEqual(requests,[]);
|
|
const next = await openXiaoyiSkills(store,'CHAIR',undefined,'finished-first-round',fetchLocal);
|
|
assert.equal(next.knowledgeVersion,'CHAIR@v2');
|
|
assert.notEqual(next.filesRoot,first.filesRoot);
|
|
assert.equal(requests.filter(route=>route.endsWith('/current')).length,1);
|
|
});
|
|
|
|
test('repair of a missing uncached asset checks the pinned release and stops on retirement', async t => {
|
|
const {options,blob} = await fixture(t);
|
|
await acquireXiaoyiRelease(options);
|
|
await fs.rm(path.join(options.cache,sha(blob)));
|
|
const requested = [];
|
|
options.fetch = route => {
|
|
requested.push(route);
|
|
return Response.json({status:410,code:'version_retired',retryable:false},{status:410});
|
|
};
|
|
await assert.rejects(acquireXiaoyiRelease(options),{status:410,code:'version_retired'});
|
|
assert.deepEqual(requested,['/api/xiaoyi/v1/templates/CHAIR/releases/v1/manifest']);
|
|
});
|
|
|
|
test('a second template reuses an already verified blob by digest', async t => {
|
|
const first = await fixture(t);
|
|
const next = await fixture(t,{templateId:'TABLE'});
|
|
await acquireXiaoyiRelease(first.options);
|
|
const second = await acquireXiaoyiRelease({...next.options,cache:first.options.cache});
|
|
assert.equal(second.manifest.templateId,'TABLE');
|
|
assert.equal(next.requests.some(([route])=>route.includes('/blobs/')),false);
|
|
await assert.rejects(fs.access(path.join(second.root,'模板','original.psd')),{code:'ENOENT'});
|
|
const cached = await fs.stat(path.join(first.options.cache,sha(next.blob)),{bigint:true});
|
|
assert.equal(cached.nlink,1n);
|
|
});
|
|
|
|
test('a resumed project with a missing manifest uses its recorded version', async t => {
|
|
const {options,requests} = await fixture(t);
|
|
const first = await acquireXiaoyiRelease(options);
|
|
await fs.rm(path.join(options.directory,'manifest.json'));
|
|
requests.length = 0;
|
|
const recovered = await acquireXiaoyiRelease({...options,pinnedKnowledgeVersion:first.manifest.knowledgeVersion});
|
|
assert.equal(recovered.manifest.version,'v1');
|
|
assert.deepEqual(requests.map(([route])=>route),['/api/xiaoyi/v1/templates/CHAIR/releases/v1/manifest']);
|
|
});
|
|
|
|
test('first production prepares the component from only manifest bindings and release files', async t => {
|
|
const {options,requests} = await fixture(t,{withBindings:true});
|
|
const result = await xiaoyiPacks({
|
|
templateId:options.templateId,projectDir:options.directory,cache:options.cache,
|
|
brandId:'fixture-brand',categoryId:'fixture-category',name:'Fixture chair',
|
|
},{fetch:(url,init)=>options.fetch(url.pathname,init)});
|
|
const pack = result.packs.detail;
|
|
assert.equal(pack.enterprise.sourceKind,'xiaoyi-release');
|
|
assert.equal(pack.outputs[0].originalAssetId,'original');
|
|
assert.equal(pack.outputs[0].slots[0].fieldId,'D01-I01');
|
|
assert.deepEqual(pack.xiaoyi.productionProfiles.detail.pages,{D01:{}});
|
|
assert.ok(requests.every(([route])=>route.startsWith('/api/xiaoyi/v1/')));
|
|
});
|
|
|
|
test('catalog-only intake is retained when rebuilding the selected fixed version', async t => {
|
|
const intake = {version:1,productFields:[{id:'material',label:'材质',type:'text',required:true}],barcodeFields:[]};
|
|
const {options} = await fixture(t,{withBindings:true});
|
|
const root = path.join(options.directory,'catalog-root');
|
|
const catalog = {items:[{templateId:'CHAIR',name:'Fixture chair',brand:'Fixture',category:'Chair',
|
|
version:'v1',knowledgeVersion:'CHAIR@v1',components:[{id:'detail'}],intake}]};
|
|
const fetch = async (url,init) => url.pathname === '/api/xiaoyi/v1/templates'
|
|
? Response.json(catalog) : options.fetch(url.pathname,init);
|
|
const common = {root,brandId:'ekb:brand:Fixture',brandName:'Fixture',categoryId:'ekb:category:Chair',categoryName:'Chair'};
|
|
const choice = await templateRequest({...common,action:'resource-component',resourceSetId:'CHAIR',componentId:'detail'},{fetch});
|
|
const original = choice.items[0].pack;
|
|
const projectDir = path.join(root,'catalog',sha(JSON.stringify(['CHAIR','v1'])));
|
|
const recovered = await xiaoyiPacks({templateId:'CHAIR',projectDir,cache:path.join(root,'blobs'),
|
|
name:'Fixture chair',brandId:common.brandId,categoryId:common.categoryId,
|
|
knowledgeVersion:'CHAIR@v1',intake:original.xiaoyi.intake},{fetch});
|
|
assert.deepEqual(recovered.packs.detail, original);
|
|
});
|
|
|
|
|
|
test('production Key browses brands, categories, templates and component mappings without downloading originals', async t => {
|
|
const intake = {version:1,productFields:[{id:'material',label:'材质',type:'text',required:true}],
|
|
barcodeFields:[{id:'color',label:'颜色',type:'select',options:['浅色','深色']}]};
|
|
const {options,requests} = await fixture(t,{withBindings:true,intake});
|
|
const root = path.join(options.directory,'catalog-root');
|
|
const catalog = {items:[{templateId:'CHAIR',name:'Fixture chair',brand:'Fixture',category:'Chair',
|
|
version:'v1',knowledgeVersion:'CHAIR@v1',components:[{id:'detail'}],intake}]};
|
|
const fetch = async (url,init) => url.pathname === '/api/xiaoyi/v1/templates'
|
|
? Response.json(catalog) : options.fetch(url.pathname,init);
|
|
const common = {root,brandId:'ekb:brand:Fixture',brandName:'Fixture',
|
|
categoryId:'ekb:category:Chair',categoryName:'Chair'};
|
|
const brands = await templateRequest({...common,action:'choices',kind:'brands'},{fetch});
|
|
assert.equal(brands.catalog.items[0].name,'Fixture');
|
|
const categories = await templateRequest({...common,action:'choices',kind:'categories'},{fetch});
|
|
assert.equal(categories.catalog.items[0].name,'Chair');
|
|
const list = await templateRequest({...common,action:'catalog',query:'CHAIR'},{fetch});
|
|
assert.equal(list.items[0].id,'CHAIR');
|
|
assert.deepEqual(list.items[0].intake,intake);
|
|
const set = await templateRequest({...common,action:'resource-set',resourceSetId:'CHAIR'},{fetch});
|
|
assert.equal(set.items[0].id,'detail');
|
|
const part = await templateRequest({...common,action:'resource-component',resourceSetId:'CHAIR',componentId:'detail'},{fetch});
|
|
const pack = part.items[0].pack;
|
|
assert.equal(pack.enterprise.sourceKind,'xiaoyi-release');
|
|
assert.equal(pack.enterprise.resourceSetId,'CHAIR');
|
|
assert.equal(pack.enterprise.componentId,'detail');
|
|
assert.deepEqual(pack.xiaoyi.intake,intake);
|
|
assert.equal(pack.outputs[0].slots[0].fieldId,'D01-I01');
|
|
assert.equal(requests.some(([route])=>route.includes('/blobs/')),false);
|
|
assert.equal(requests.some(([route])=>route.endsWith('/bundle')),true);
|
|
const cachedProject = path.join(root,'catalog',createHash('sha256').update(JSON.stringify(['CHAIR','v1'])).digest('hex'));
|
|
const full = await xiaoyiPacks({templateId:'CHAIR',projectDir:cachedProject,cache:path.join(root,'blobs'),
|
|
name:'Fixture chair',brandId:common.brandId,categoryId:common.categoryId,knowledgeVersion:'CHAIR@v1'},{fetch});
|
|
assert.deepEqual(full.packs.detail.xiaoyi.intake,intake);
|
|
const withoutKnowledge = value => {const copy = structuredClone(value); delete copy.xiaoyi; return copy;};
|
|
assert.deepEqual(withoutKnowledge(full.packs.detail),withoutKnowledge(pack));
|
|
assert.equal(requests.filter(([route])=>route.includes('/blobs/')).length,1);
|
|
delete catalog.items[0].intake;
|
|
const legacy = await templateRequest({...common,action:'catalog'},{fetch});
|
|
assert.equal(legacy.items[0].intake,undefined);
|
|
catalog.items[0].intake = {...intake,productFields:[{id:'bad',label:'错误类型',type:'unknown'}]};
|
|
const toleratedCatalog = await templateRequest({...common,action:'catalog'},{fetch});
|
|
assert.deepEqual(toleratedCatalog.items[0].intake.productFields, []);
|
|
assert.ok(toleratedCatalog.compatibilityWarnings.length > 0);
|
|
assert.ok(toleratedCatalog.items[0].compatibilityWarnings.length > 0);
|
|
});
|
|
|
|
test('production catalog reports rejected keys without falling through to generic MCP', async t => {
|
|
const {options} = await fixture(t);
|
|
await assert.rejects(templateRequest({root:options.directory,action:'choices',kind:'brands'},
|
|
{fetch:async url => {
|
|
assert.equal(url.pathname,'/api/xiaoyi/v1/templates');
|
|
return Response.json({code:'authentication_required'},{status:401});
|
|
}}),/知识库连接已失效/);
|
|
});
|