fix(xiaoyi): align 20-template intake, package docs, and font manifest consumption

This commit is contained in:
WuYongJie 2026-12-04 21:41:31 +08:00
parent 0c9cbdcf2f
commit 9359d836d9
4 changed files with 329 additions and 11 deletions

View File

@ -460,7 +460,9 @@ export function intakeMetadata(value, warnings) {
}
return normalized;
};
return {version:1,productFields:readFields(value.productFields),barcodeFields:readFields(value.barcodeFields)};
const barcodeHelp = typeof value.barcodeHelp === 'string' && value.barcodeHelp.trim() ? value.barcodeHelp : undefined;
return {version:1,productFields:readFields(value.productFields),barcodeFields:readFields(value.barcodeFields),
...(barcodeHelp !== undefined && {barcodeHelp})};
}
function sourceAssetsOf(doc) {
@ -557,8 +559,13 @@ export async function xiaoyiPacks(input, {signal,fetch,onProgress} = {}) {
if (!binding.original && pages.length !== mapping.screens.length) {
addWarning(componentWarnings, '模板页面数量与绑定记录略有差异,已自动兼容加载');
}
if (binding.fontManifest && !files.has(binding.fontManifest)) {
addWarning(componentWarnings, '模板字体清单文件缺失,已自动兼容加载');
}
const descriptor = {component,mappingVersion:mapping.mapping_version,mappingAssetId:binding.mapping,
sourceInventoryAssetId:binding.inventory,originalAssetIds:originals.map(({id})=>id)};
sourceInventoryAssetId:binding.inventory,
...(binding.fontManifest ? {fontManifestAssetId:binding.fontManifest} : {}),
originalAssetIds:originals.map(({id})=>id)};
const pack = componentPack({version:manifest.version,template:{
templateId,name:input.name || raw.template_name || templateId,brand:raw.brand,category:raw.category,
components:[descriptor],assets:originals.map(({id,file})=>({...file,declaredId:id,assetId:id,revision:manifest.version})),

View File

@ -22,9 +22,11 @@ const dimensionUnit = value => units.get(fieldText(value).trim().toLowerCase())
const materialKeys = ['material', 'materialtype', '材质', '材质类型'];
const boardKeys = ['boardtype', '板材类型', '板材'];
function barcodeEntry(barcode, { colorName, dimensions, material, boardType }) {
function barcodeEntry(barcode, { colorName, variantName, dimensions, material, boardType }) {
const spec = fieldText(variantName);
return {
barcode, colorName: fieldText(colorName),
...(spec ? { variantName: spec } : {}),
dimensions: { length: fieldText(dimensions?.length), width: fieldText(dimensions?.width),
height: fieldText(dimensions?.height), unit: dimensionUnit(dimensions?.unit) },
material: fieldText(material), boardType: fieldText(boardType),
@ -112,8 +114,12 @@ export function briefBarcodeEntries(brief = {}) {
dimensions.push(brief.dimensions, normalized?.specs?.dimensions, shared?.dimensions);
}
return barcodeEntry(barcode, {
colorName: answers.colorName ?? (row?.colorName || facts?.colorName || legacy?.colorName
|| owner?.colorName || variant?.colorName || brief.colorName),
colorName: (fieldText(answers.colorName) ? answers.colorName : undefined)
?? (fieldText(answers.variantColor) ? answers.variantColor : undefined)
?? (row?.colorName || facts?.colorName || legacy?.colorName
|| owner?.colorName || variant?.colorName || brief.colorName),
variantName: (fieldText(answers.variantName) ? answers.variantName : undefined)
?? (row?.variantName || facts?.variantName || legacy?.variantName),
dimensions: legacyDimensions(dimensions, answers, intakeFields, brief.dimensions?.unit),
material: answers.material ?? (row?.material || facts?.material || legacy?.material
|| legacyAttribute(row, materialKeys) || legacyAttribute(facts, materialKeys) || owner?.materialName
@ -196,18 +202,19 @@ function briefImages(brief, scope) {
export function canonicalProductBrief(brief = {}, scope, entries = briefBarcodeEntries(brief)) {
const identity = brief.normalizedProduct?.identity;
const persisted = Array.isArray(brief.barcodeEntries);
const name = persisted ? brief.name ?? identity?.productName : brief.name || identity?.productName;
const brand = persisted ? brief.brandName ?? identity?.platformBrand : brief.brandName || identity?.platformBrand;
const category = persisted ? brief.categoryName ?? identity?.platformCategory : brief.categoryName || identity?.platformCategory;
const intake = record(brief.intake);
const productValues = record(intake.productValues);
const barcodeValues = record(intake.barcodeValues);
const name = persisted ? brief.name ?? identity?.productName ?? productValues.productName : brief.name || identity?.productName || productValues.productName;
const brand = persisted ? brief.brandName ?? identity?.platformBrand ?? productValues.brandName : brief.brandName || identity?.platformBrand || productValues.brandName;
const category = persisted ? brief.categoryName ?? identity?.platformCategory ?? productValues.categoryLabel ?? productValues.productCategory : brief.categoryName || identity?.platformCategory || productValues.categoryLabel || productValues.productCategory;
return {
name: fieldText(name), spu: projectSpu(brief) ?? '',
brand: fieldText(brief.brand ?? brand), category: fieldText(brief.category ?? category),
note: fieldText(brief.note),
barcodeEntries: scope ? entries.filter(row => scope.barcodes.includes(row.barcode)) : entries,
images: briefImages(brief, scope),
intake: { ...intake, productValues: record(intake.productValues), barcodeValues: scope
intake: { ...intake, productValues, barcodeValues: scope
? Object.fromEntries(scope.barcodes.filter(code => Object.hasOwn(barcodeValues, code)).map(code => [code, barcodeValues[code]]))
: barcodeValues },
};

View File

@ -269,16 +269,41 @@ export async function openXiaoyiSkills(store, templateId, signal, finishedGoal,
fileId:item.sha256, sha256:item.sha256, revision:manifest.knowledgeVersion, path:item.path, kind:item.type,
},
]));
const entryDir = path.posix.dirname(manifest.entrypoint);
const entryPrefix = entryDir === '.' ? '' : entryDir + '/';
const docPaths = manifest.files
.map(item => item.path)
.filter(filePath => filePath.endsWith('.md') && filePath !== manifest.entrypoint && filePath !== manifest.supplement)
.sort();
const packageDocs = entryPrefix
? docPaths.filter(filePath => filePath.startsWith(entryPrefix))
: docPaths.filter(filePath => !filePath.includes('/'));
const fontManifests = Object.fromEntries(
Object.entries(manifest.bindings ?? {})
.filter(([, binding]) => typeof binding?.fontManifest === 'string' && binding.fontManifest.trim())
.map(([component, binding]) => [component, binding.fontManifest]),
);
const localAssets = manifest.assets.map(item => ({...item,localPath:fileAt(root,item.path)}));
const componentFonts = Object.fromEntries(
Object.keys(manifest.bindings ?? {}).map(component => [
component,
localAssets.filter(item => item.type === 'font' && (!item.component || item.component === component || item.component === 'shared')),
]),
);
const execution = {
knowledgeVersion:manifest.knowledgeVersion, entrypoint:manifest.entrypoint,
supplement:manifest.supplement, overrides:manifest.overrides,
instruction:'按锁定的知识库根相对路径读取资料。共享章节有覆盖声明时,以对应补充章节为准,其余共享内容继续适用。',
...(packageDocs.length ? {packageDocs} : {}),
...(docPaths.length ? {docPaths} : {}),
instruction:'按锁定的知识库根相对路径读取资料(packageDocs/docPaths 为已索引文档路径,按需用 read 读取)。共享章节有覆盖声明时,以对应补充章节为准,其余共享内容继续适用。',
};
const sources = [...documents.values()];
return {
knowledgeVersion:manifest.knowledgeVersion, execution, productionProfiles, snapshot:{manifest,root},
productionBinding:{templateId, knowledgeVersion:manifest.knowledgeVersion, productionProfiles,
assets:manifest.assets.map(item => ({...item,localPath:fileAt(root,item.path)}))},
...(Object.keys(fontManifests).length ? {fontManifests} : {}),
...(Object.values(componentFonts).some(list => list.length) ? {componentFonts} : {}),
assets:localAssets},
filesRoot:root, resource, documents, sources,
files:[...documents].map(([file, source]) => ({...source,path:file})),
resolveFile:async file => documents.has(file),

View File

@ -0,0 +1,279 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { zipSync } from 'fflate';
import { intakeMetadata, xiaoyiPacks } from '../src/enterprise-templates.mjs';
import { canonicalProductBrief } from '../src/product-brief.mjs';
import { scopedProductionBrief } from '../src/production-repository.mjs';
import { productContext } from '../src/project-context.mjs';
import { openXiaoyiSkills } from '../src/xiaoyi-release.mjs';
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
const describe = bytes => ({ size: bytes.length, sha256: sha256(bytes) });
function minimalMapping(templateId, component, screenId, assetId, originalBytes) {
return JSON.stringify({
template_id: templateId,
component,
mapping_version: '2026-12-04.1',
canvas: [800, 800],
source: {
sha256: sha256(originalBytes),
assets: [{ asset_id: assetId, ps_sha256: sha256(originalBytes), canvas_px: [800, 800] }],
},
screens: [{ screen_id: screenId, title: `${component}首屏`, bounds: [0, 0, 800, 800], asset_id: assetId }],
fields: [{
field_id: `${component}_title`,
name: '标题',
role: 'title',
type: '文案',
screen_id: screenId,
asset_id: assetId,
raw_text: '示例标题',
ps_location: { path: '标题', name: '标题' },
ps_style: { bounds: [20, 20, 400, 120], coverage_rect: [20, 20, 400, 120], style_runs: [{ font_name: 'OPPOSans-B', font_size: 36 }] },
}],
});
}
test('intake dynamic schema preserves barcodeHelp, boolean/select/number/multiline, variantColor, and same-color multi-spec variantName', () => {
const warnings = [];
const rawIntake = {
version: 1,
barcodeHelp: '同一花色如有不同尺寸规格,请按条码分别填写 variantName 与尺寸。',
productFields: [
{ id: 'productName', label: '产品名称', type: 'text', required: true },
{ id: 'brandName', label: '商品品牌', type: 'text', required: true },
{ id: 'categoryLabel', label: '正式品类', type: 'select', options: ['书桌', '餐桌', '电脑桌'], required: true },
{ id: 'hasCableTray', label: '是否带走线槽', type: 'boolean', required: false },
{ id: 'sellingPoints', label: '核心卖点', type: 'text', multiline: true, required: true },
{ id: 'desktopThickness', label: '桌板厚度', type: 'number', unit: 'mm', required: true },
],
barcodeFields: [
{ id: 'variantName', label: '条码对应的规格或款式', type: 'text', required: true },
{ id: 'variantColor', label: '颜色或花色', type: 'text', required: true },
{ id: 'length', label: '桌面长度', type: 'number', unit: 'cm', required: true },
{ id: 'depth', label: '桌面进深', type: 'number', unit: 'cm', required: true },
{ id: 'height', label: '桌面总高', type: 'number', unit: 'cm', required: true },
{ id: 'secondaryHeight', label: '副高度', type: 'number', unit: 'cm', required: false },
{ id: 'comboDesktopLength', label: '双人组合整体长度', type: 'number', unit: 'cm', required: false },
],
};
const schema = intakeMetadata(rawIntake, warnings);
assert.deepEqual(warnings, []);
assert.equal(schema.barcodeHelp, rawIntake.barcodeHelp);
assert.equal(schema.productFields.length, 6);
assert.equal(schema.barcodeFields.length, 7);
const skuStandard = 'DNZ0385-120-WALNUT';
const skuDeep = 'DNZ0385-140-WALNUT';
const brief = {
variants: [{ id: 'walnut', colorName: '胡桃木色', images: [] }],
barcodeBindings: { walnut: `${skuStandard}\n${skuDeep}` },
detailBarcode: skuStandard,
intake: {
schema,
productValues: {
productName: '实木书桌Pro',
brandName: '顾家家居',
categoryLabel: '电脑桌',
hasCableTray: true,
sellingPoints: '1. 加厚实木\n2. 隐藏走线',
desktopThickness: 25,
},
barcodeValues: {
[skuStandard]: {
variantName: '1.2米标准款',
variantColor: '胡桃木色',
length: 120,
depth: 60,
height: 75,
secondaryHeight: 90,
comboDesktopLength: 240,
},
[skuDeep]: {
variantName: '1.4米加深款',
variantColor: '胡桃木色',
length: 140,
depth: 70,
height: 75,
secondaryHeight: 90,
comboDesktopLength: 280,
},
},
},
};
const canonical = canonicalProductBrief(brief);
assert.equal(canonical.name, '实木书桌Pro');
assert.equal(canonical.brand, '顾家家居');
assert.equal(canonical.category, '电脑桌');
assert.equal(canonical.intake.productValues.hasCableTray, true);
assert.equal(canonical.intake.productValues.desktopThickness, 25);
assert.equal(canonical.barcodeEntries.length, 2);
const [entry1, entry2] = canonical.barcodeEntries;
assert.equal(entry1.colorName, '胡桃木色');
assert.equal(entry1.variantName, '1.2米标准款');
assert.equal(entry2.colorName, '胡桃木色');
assert.equal(entry2.variantName, '1.4米加深款');
assert.equal(canonical.intake.barcodeValues[skuDeep].depth, 70);
assert.equal(canonical.intake.barcodeValues[skuDeep].comboDesktopLength, 280);
const ctx = productContext(
{ accountScope: 'acc', project: 'proj', documentId: 7, brief },
{ scope: 'acc', project: 'proj', documentId: 7 },
);
assert.equal(ctx.product.name, '实木书桌Pro');
assert.equal(ctx.barcodeEntries.length, 2);
const { brief: detailBrief } = scopedProductionBrief(brief, 'walnut', 'detail');
assert.deepEqual(detailBrief.barcodes, [skuStandard]);
assert.deepEqual(Object.keys(detailBrief.intake.barcodeValues), [skuStandard]);
const { brief: skuBrief } = scopedProductionBrief(brief, 'walnut', 'sku_images');
assert.deepEqual(skuBrief.barcodes, [skuStandard, skuDeep]);
assert.equal(skuBrief.barcodeEntries[0].variantName, '1.2米标准款');
assert.equal(skuBrief.barcodeEntries[1].variantName, '1.4米加深款');
});
test('openXiaoyiSkills and xiaoyiPacks index self-contained package docs, overrides, fontManifests, and shared/component fonts', async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xiaoyi-20tpl-contract-'));
try {
const templateId = 'SFY-MATTRESS-002';
const version = '2026-12-04.1';
const knowledgeVersion = `${templateId}@${version}`;
const baseDir = '新品出图自动化知识库/企业知识库/Skills/家具详情页设计/template-adapter/assets/索菲亚/床垫/SFY-MATTRESS-002';
const entryDir = `${baseDir}/小壹`;
const entrypoint = `${entryDir}/SKILL.md`;
const supplement = `${entryDir}/无人值守补充说明.md`;
const brandSpec = `${entryDir}/品牌视觉规范.md`;
const sizeCheck = `${entryDir}/尺寸数字核对.md`;
const nestedSource = `${entryDir}/资料/来源与母表.md`;
const sharedGuide = '新品出图自动化知识库/企业知识库/Skills/小壹共用/模板原图换商品.md';
const sharedSectionDoc = '新品出图自动化知识库/企业知识库/Skills/通用详情页制作与PS模板验证/references/04-模板与工作簿/03-模板输入与制作衔接.md';
const productionConfig = `${entryDir}/production.json`;
const detailOriginal = Buffer.from('detail-psd');
const mainOriginal = Buffer.from('main-psd');
const skuOriginal = Buffer.from('sku-psd');
const sharedFont = Buffer.from('shared-font-bytes');
const detailFont = Buffer.from('detail-font-bytes');
const mainFont = Buffer.from('main-font-bytes');
const detailOrigPath = `${baseDir}/详情/D01.psb`;
const mainOrigPath = `${baseDir}/主图/M01.psd`;
const skuOrigPath = `${baseDir}/SKU/K01.psd`;
const sharedFontPath = '新品出图自动化知识库/企业知识库/Skills/家具详情页设计/template-adapter/assets/索菲亚/字体/OPPOSans-B.ttf';
const detailFontPath = '新品出图自动化知识库/企业知识库/Skills/家具详情页设计/template-adapter/assets/索菲亚/字体/OPPOSans-R.ttf';
const mainFontPath = '新品出图自动化知识库/企业知识库/Skills/家具详情页设计/template-adapter/assets/索菲亚/字体/SourceHanSansSC-Medium.otf';
const detailMappingPath = `${baseDir}/详情/字段映射.json`;
const mainMappingPath = `${baseDir}/主图/字段映射.json`;
const skuMappingPath = `${baseDir}/SKU/字段映射.json`;
const detailInvPath = `${baseDir}/详情/完整图层清单.json`;
const mainInvPath = `${baseDir}/主图/完整图层清单.json`;
const skuInvPath = `${baseDir}/SKU/完整图层清单.json`;
const detailFontManifest = `${baseDir}/详情/字体清单.json`;
const mainFontManifest = `${baseDir}/主图/字体清单.json`;
const skuFontManifest = `${baseDir}/SKU/字体清单.json`;
const filesMap = {
[entrypoint]: Buffer.from('---\nname: xiaoyi-sfy-mattress-002\ndescription: 小壹模板制作入口\n---\n通读[品牌视觉规范](品牌视觉规范.md)、[无人值守补充说明](无人值守补充说明.md)与[尺寸数字核对](尺寸数字核对.md)。\n'),
[supplement]: Buffer.from('# 无人值守补充说明\n按图位证据核对。'),
[brandSpec]: Buffer.from('# 品牌视觉规范\n' + '超长品牌规范正文'.repeat(500)),
[sizeCheck]: Buffer.from('# 尺寸数字核对\n逐屏核对长宽高。'),
[nestedSource]: Buffer.from('# 来源与母表\n母表映射依据。'),
[sharedGuide]: Buffer.from('# 模板原图换商品\n使用模板原图替换商品主体。'),
[sharedSectionDoc]: Buffer.from('# 模板输入与制作衔接\n公共参考规范。'),
[productionConfig]: Buffer.from(JSON.stringify({ productionProfiles: { detail: { pages: { D01: {} } } } })),
[detailMappingPath]: Buffer.from(minimalMapping(templateId, 'detail', 'D01', 'D01', detailOriginal)),
[mainMappingPath]: Buffer.from(minimalMapping(templateId, 'main_images', 'M01', 'M01', mainOriginal)),
[skuMappingPath]: Buffer.from(minimalMapping(templateId, 'sku_images', 'K01', 'K01', skuOriginal)),
[detailInvPath]: Buffer.from(JSON.stringify({ template_id: templateId, component: 'detail', mapping_version: '2026-12-04.1' })),
[mainInvPath]: Buffer.from(JSON.stringify({ template_id: templateId, component: 'main_images', mapping_version: '2026-12-04.1' })),
[skuInvPath]: Buffer.from(JSON.stringify({ template_id: templateId, component: 'sku_images', mapping_version: '2026-12-04.1' })),
[detailFontManifest]: Buffer.from(JSON.stringify({ fonts: ['OPPOSans-B.ttf', 'OPPOSans-R.ttf'] })),
[mainFontManifest]: Buffer.from(JSON.stringify({ fonts: ['OPPOSans-B.ttf', 'SourceHanSansSC-Medium.otf'] })),
[skuFontManifest]: Buffer.from(JSON.stringify({ fonts: ['OPPOSans-B.ttf'] })),
};
const bundle = zipSync(filesMap);
const assetsMap = {
[detailOrigPath]: { type: 'original', component: 'detail', bytes: detailOriginal },
[mainOrigPath]: { type: 'original', component: 'main_images', bytes: mainOriginal },
[skuOrigPath]: { type: 'original', component: 'sku_images', bytes: skuOriginal },
[sharedFontPath]: { type: 'font', component: 'shared', bytes: sharedFont },
[detailFontPath]: { type: 'font', component: 'detail', bytes: detailFont },
[mainFontPath]: { type: 'font', component: 'main_images', bytes: mainFont },
};
const overrides = [{
sharedPath: sharedSectionDoc,
section: '新品图片是否参考原 PS 构图',
supplementPath: sharedGuide,
supplementSection: '新品图片使用模板原图',
}];
const manifest = Buffer.from(JSON.stringify({
schemaVersion: 1,
templateId,
version,
knowledgeVersion,
entrypoint,
supplement,
productionConfig,
overrides,
bindings: {
detail: { mapping: detailMappingPath, inventory: detailInvPath, original: detailOrigPath, fontManifest: detailFontManifest },
main_images: { mapping: mainMappingPath, inventory: mainInvPath, pages: { M01: { original: mainOrigPath, assetId: 'M01' } }, fontManifest: mainFontManifest },
sku_images: { mapping: skuMappingPath, inventory: skuInvPath, original: skuOrigPath, fontManifest: skuFontManifest },
},
assets: Object.entries(assetsMap).map(([p, meta]) => ({ path: p, type: meta.type, component: meta.component, ...describe(meta.bytes) })),
bundle: describe(bundle),
files: Object.entries(filesMap).map(([p, bytes]) => ({
path: p,
type: p === entrypoint ? 'skill' : p.endsWith('字段映射.json') ? 'mapping' : p.endsWith('完整图层清单.json') ? 'inventory' : 'attachment',
...describe(bytes),
})),
}));
const blobBySha = new Map(Object.values(assetsMap).map(meta => [sha256(meta.bytes), meta.bytes]));
const fetch = async url => {
if (url.pathname.endsWith('/current')) return Response.json({ version, manifestSha256: sha256(manifest) });
if (url.pathname.endsWith('/manifest')) return new Response(manifest);
if (url.pathname.endsWith('/bundle')) return new Response(bundle);
const blobMatch = /\/blobs\/([a-f0-9]{64})$/.exec(url.pathname);
if (blobMatch && blobBySha.has(blobMatch[1])) return new Response(blobBySha.get(blobMatch[1]));
throw Error('Unexpected route: ' + url.pathname);
};
const skills = await openXiaoyiSkills({ dir: path.join(dir, 'store') }, templateId, undefined, undefined, fetch, undefined, false);
assert.deepEqual(skills.execution.packageDocs, [brandSpec, sizeCheck, nestedSource].sort());
assert.deepEqual(skills.execution.docPaths, [brandSpec, sizeCheck, nestedSource, sharedGuide, sharedSectionDoc].sort());
assert.deepEqual(skills.execution.overrides, overrides);
// Low-noise: execution indexes paths without injecting the full 品牌视觉规范.md body
assert.ok(!JSON.stringify(skills.execution).includes('超长品牌规范正文'));
assert.deepEqual(skills.productionBinding.fontManifests, {
detail: detailFontManifest,
main_images: mainFontManifest,
sku_images: skuFontManifest,
});
assert.deepEqual(skills.productionBinding.componentFonts.detail.map(f => f.path), [sharedFontPath, detailFontPath]);
assert.deepEqual(skills.productionBinding.componentFonts.main_images.map(f => f.path), [sharedFontPath, mainFontPath]);
assert.deepEqual(skills.productionBinding.componentFonts.sku_images.map(f => f.path), [sharedFontPath]);
const result = await xiaoyiPacks({ templateId, projectDir: path.join(dir, 'proj'), cache: path.join(dir, 'cache') }, { fetch });
assert.deepEqual(result.warnings, []);
assert.equal(result.packs.detail.enterprise.components.detail.originals.length, 1);
assert.deepEqual(result.packs.detail.xiaoyi.fontManifests, skills.productionBinding.fontManifests);
assert.equal(result.packs.main_images.xiaoyi.componentFonts.main_images.length, 2);
} finally {
await fs.rm(dir, { recursive: true, force: true });
}
});