dsh-ppt 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,113 @@
1
+ import { createDataMath } from './deck-data-math.mjs'
2
+ import { chartColors, renderChartSvg } from './deck-media.mjs'
3
+
4
+ /** Only referenced excerpts and arithmetic enter the offline HTML, not full sources. */
5
+ export function renderDataView(manifest, theme) {
6
+ if (!manifest.dataModel) return { css: '', body: '', script: '' }
7
+ const model = manifest.dataModel
8
+ const payload = { metrics:model.metrics.map(({source,...m})=>m),values:model.values,fingerprint:model.fingerprint,
9
+ deckId:manifest.deckId,revision:manifest.revision,language:manifest.language,theme,
10
+ slides:manifest.slides.map((s,i)=>({id:s.id,page:i+1,template:s.dataTemplate||{},chart:s.chart})) }
11
+ const json=JSON.stringify(payload).replace(/</g,'\\u003c').replace(/\u2028/g,'\\u2028').replace(/\u2029/g,'\\u2029')
12
+ return { css: DATA_CSS,body:'<dialog id="data-panel" aria-labelledby="data-title"></dialog>',
13
+ script:`<script>(()=>{const esc=value=>String(value??'').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;').replaceAll("'",'&#39;');const chartColors=${chartColors.toString()};const chart=${renderChartSvg.toString()};(${initDataView.toString()})(${json},(${createDataMath.toString()})(),chart);})();</script>` }
14
+ }
15
+
16
+ /** Embedded verbatim. All material text is written with DOM text APIs. */
17
+ function initDataView(data, math, chartRenderer) {
18
+ const en=data.language==='en',L=(zh,english)=>en?english:zh,byId=new Map(data.metrics.map(m=>[m.id,m]));
19
+ const panel=document.getElementById('data-panel'),controls=[],baseline=Object.fromEntries(data.metrics.filter(m=>m.kind==='input').map(m=>[m.id,m.value]));
20
+ let parameters={...baseline},values=math.solve(data.metrics),valid=true,dirty=false,selection=data.metrics[0]?.id;
21
+ for(const metric of data.metrics)if(metric.ast)math.inspect(metric.ast,new Set(byId.keys()));
22
+ function el(tag,text,parent,attributes={}){const node=document.createElement(tag);if(text!==undefined)node.textContent=text;for(const[key,value]of Object.entries(attributes))node.setAttribute(key,String(value));if(parent)parent.append(node);return node;}
23
+ function button(text,parent,click){const node=el('button',text,parent,{type:'button'});node.addEventListener('click',event=>{event.stopPropagation();click(event);});return node;}
24
+ const header=el('div',undefined,panel,{class:'data-head'});el('h2',L('数字溯源与现场推演','Data lineage and what-if'),header,{id:'data-title'});button(L('关闭','Close'),header,()=>panel.close());
25
+ el('p',L('来源表示数字如何得到,不代表事实已核验。推演参数均为用户假设。','Lineage explains how numbers were obtained, not whether they are true. Adjustable parameters are assumptions.'),panel,{class:'data-muted'});
26
+ const notice=el('div','',panel,{role:'status',class:'data-notice'}),error=el('div','',panel,{role:'alert',class:'data-error'});error.hidden=true;
27
+ const scenario=el('section',undefined,panel);el('h3',L('现场推演','What-if assumptions'),scenario);
28
+ for(const metric of data.metrics.filter(m=>m.kind==='input')){
29
+ const row=el('div',undefined,scenario,{class:'data-control'}),label=el('label',metric.label,row,{for:'data-input-'+metric.id}),formatted=el('output','',label);
30
+ const range=el('input',undefined,row,{type:'range',min:metric.min,max:metric.max,step:metric.step,value:metric.value,'aria-label':metric.label+' '+L('滑杆','slider')}),number=el('input',undefined,row,{type:'number',id:'data-input-'+metric.id,min:metric.min,max:metric.max,step:metric.step,value:metric.value});
31
+ controls.push({metric,range,number,formatted});
32
+ function change(event){const raw=event.target.value;const next={...parameters,[metric.id]:raw===''?NaN:Number(raw)};update(next);}
33
+ range.addEventListener('input',change);number.addEventListener('input',change);
34
+ if(metric.note)el('p',metric.note,row,{class:'data-muted'});
35
+ }
36
+ if(!controls.length)el('p',L('本工程没有可调假设,原始事实不会被滑杆修改。','No adjustable assumptions. Source facts cannot be changed with sliders.'),scenario);
37
+ const actions=el('div',undefined,scenario,{class:'data-actions'});button(L('恢复已保存参数','Reset to saved values'),actions,()=>update({...baseline}));
38
+ const save=button(L('保存推演参数','Save scenario parameters'),actions,()=>download('scenario.json',JSON.stringify({schemaVersion:1,deckId:data.deckId,revision:data.revision,fingerprint:data.fingerprint,parameters},null,2),'application/json'));
39
+ if(window.parent!==window){save.disabled=true;save.title=L('在 DSH 工作台中确认并保存静态 PPTX','Confirm and save the static PPTX in the DSH workbench');}
40
+ el('p',L('HTML 可离线推演。要生成对应的可编辑 PPTX,请在 DSH 工作台导入参数并确认保存。未保存推演时,旧 PPTX 的下载会暂缓。','HTML supports offline what-if. Import saved parameters into the DSH workbench and confirm to create the matching editable PPTX. Older PPTX downloads are blocked while values are unsaved.'),scenario,{class:'data-muted'});
41
+ el('h3',L('追问数字出处','Inspect a number'),panel);
42
+ const chooser=el('select',undefined,panel,{'aria-label':L('溯源指标','Trace metric')});data.metrics.forEach(m=>el('option',m.label,chooser,{value:m.id}));chooser.addEventListener('change',()=>{selection=chooser.value;showEvidence();});
43
+ const evidence=el('section',undefined,panel,{class:'data-evidence'});
44
+ const toggle=button(L('数字来源 / 推演','Sources / what-if'),document.getElementById('delivery-bar'),()=>open());toggle.id='data-toggle';
45
+ function open(id,missing){if(id&&byId.has(id)){selection=id;chooser.value=id;}showEvidence(missing);if(!panel.open)panel.showModal();if(id||missing)evidence.scrollIntoView({block:'nearest'});}
46
+ function showEvidence(missing){
47
+ evidence.replaceChildren();
48
+ if(missing){el('h3',L('此数字未关联原始材料','This number has no linked source'),evidence);el('p',L('请在 DSH 中提供来源,并用指标绑定替换固定数字。不能将相同数值自动当作同一来源。','Provide the source in DSH and bind a metric. Matching numeric values alone do not establish a common source.'),evidence);return;}
49
+ const metric=byId.get(selection);if(!metric)return;
50
+ el('h3',metric.label+' = '+math.format(values[metric.id],metric,data.language),evidence);
51
+ if(metric.kind==='source'){
52
+ el('strong',metric.evidence.name+' · '+metric.evidence.locator,evidence);el('pre',metric.evidence.excerpt,evidence);
53
+ const more=el('details',undefined,evidence);el('summary',L('来源快照校验值','Source snapshot checksum'),more);el('code','SHA-256: '+metric.evidence.sha256,more);
54
+ }else if(metric.kind==='input')el('p',L('用户假设;不是从源材料证明的事实。','User assumption, not a fact established by source material.')+(metric.note?' '+metric.note:''),evidence);
55
+ else{
56
+ el('pre','= '+metric.formula,evidence);el('p',L('计算输入(点击继续追问):','Inputs (click to trace further):'),evidence);
57
+ for(const id of metric.dependencies){const dependency=byId.get(id);button(dependency.label+' = '+math.format(values[id],dependency,data.language),evidence,()=>open(id));}
58
+ }
59
+ }
60
+ function fragment(template){
61
+ const result=document.createDocumentFragment(),pattern=/\{\{([A-Za-z][A-Za-z0-9]*)\}\}/g;let end=0;
62
+ for(const match of template.matchAll(pattern)){result.append(document.createTextNode(template.slice(end,match.index)));const metric=byId.get(match[1]);const number=el('button',math.format(values[metric.id],metric,data.language),result,{type:'button',class:'data-number','data-metric':metric.id,title:L('查看数字出处','Inspect source')});end=match.index+match[0].length;}
63
+ result.append(document.createTextNode(template.slice(end)));return result;
64
+ }
65
+ function fill(node,template){if(node&&typeof template==='string')node.replaceChildren(fragment(template));}
66
+ function graphFor(template,solved){const graph=structuredClone(template),text=value=>typeof value==='string'?value.replace(/\{\{([A-Za-z][A-Za-z0-9]*)\}\}/g,(_,id)=>math.format(solved[id],byId.get(id),data.language)):value;graph.categories=graph.categories.map(text);graph.series=graph.series.map(s=>({...s,name:text(s.name),values:s.values.map(v=>typeof v==='string'&&/^\{\{[A-Za-z][A-Za-z0-9]*\}\}$/.test(v)?solved[v.slice(2,-2)]:Number(v))}));graph.unit=text(graph.unit);graph.caption=text(graph.caption);if(graph.kind==='pie'&&(graph.series[0].values.some(v=>v<0)||graph.series[0].values.reduce((a,b)=>a+b,0)<=0))throw new Error(L('饼图数值需非负且总和大于零','Pie values must be non-negative with a positive total'));return graph;}
67
+ function missingNumbers(root){
68
+ const targets=root.querySelectorAll('h1,h2,.statement-title,.quote-text,.subtitle,.quote-attr,.deck-table th,.deck-table td,li,.media-body p,.media-caption');
69
+ const texts=[];for(const target of targets){const walker=document.createTreeWalker(target,NodeFilter.SHOW_TEXT);while(walker.nextNode()){const node=walker.currentNode;if(node.parentElement?.closest('.data-number,svg,.chart-data'))continue;texts.push(node);}}
70
+ for(const node of new Set(texts)){const pattern=/[-+]?(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?[%%]?/g,content=node.textContent,matches=[...content.matchAll(pattern)];if(!matches.length)continue;const output=document.createDocumentFragment();let end=0;for(const match of matches){output.append(document.createTextNode(content.slice(end,match.index)));el('button',match[0],output,{type:'button',class:'data-number data-unlinked','data-unlinked':'1',title:L('未关联来源','Source not linked')});end=match.index+match[0].length;}output.append(document.createTextNode(content.slice(end)));node.replaceWith(output);}
71
+ }
72
+ function redraw(){
73
+ for(const slide of data.slides){const root=document.querySelectorAll('.slide')[slide.page-1];if(!root)continue;const template=slide.template;
74
+ fill(root.querySelector('.media-title,h1,h2,.statement-title,.quote-text'),template.title);
75
+ fill(root.querySelector('.subtitle,.quote-attr,.media-body > p'),template.subtitle);fill(root.querySelector('.kicker'),template.kicker);
76
+ if(template.bullets)root.querySelectorAll('li').forEach((li,i)=>fill(li,template.bullets[i]));
77
+ if(template.rows)root.querySelectorAll('.deck-table tr').forEach((row,r)=>Array.from(row.children).forEach((cell,c)=>fill(cell,template.rows[r]?.[c])));
78
+ if(template.notes)root.dataset.notes=template.notes.replace(/\{\{([A-Za-z][A-Za-z0-9]*)\}\}/g,(_,id)=>math.format(values[id],byId.get(id),data.language));
79
+ if(template.chart){const graph=graphFor(template.chart,values),area=root.querySelector('.media-chart');if(area)area.innerHTML=chartRenderer(graph,data.theme);fill(root.querySelector('.media-caption'),template.chart.caption);}
80
+ if(slide.chart&&!root.querySelector('.data-chart-trace')){const link=button(L('图表数字来源','Chart sources'),root.querySelector('.media-canvas'),()=>{const id=Object.keys(template.chart||{}).length?[...JSON.stringify(template.chart).matchAll(/\{\{([A-Za-z][A-Za-z0-9]*)\}\}/g)][0]?.[1]:null;open(id,!id);});link.className='data-chart-trace';}
81
+ missingNumbers(root);
82
+ }
83
+ for(const {metric,range,number,formatted}of controls){range.value=String(parameters[metric.id]);number.value=String(parameters[metric.id]);formatted.textContent=' '+math.format(values[metric.id],metric,data.language);}
84
+ notice.textContent=dirty?L('当前为未保存推演,PPTX 尚未更新。','Unsaved what-if values. The PPTX has not been updated.'):L('当前显示已保存的静态基线;公式和假设随 PPTX 附上。','Showing saved values; formulas and assumptions accompany the PPTX.');
85
+ downloadState();
86
+ showEvidence();window.dispatchEvent(new Event('dsh-data-change'));
87
+ }
88
+ function downloadState(){save.disabled=window.parent!==window||!valid;document.querySelectorAll('a[download]').forEach(link=>{if(/\.(?:pptx|json)(?:[?#]|$)/i.test(link.href)){if(dirty||!valid)link.setAttribute('aria-disabled','true');else link.removeAttribute('aria-disabled');}});}
89
+ function notifyState(){window.__dshData.onChange?.({...parameters},dirty,valid);}
90
+ function update(next,notify=true){
91
+ try{const complete={...baseline,...next},solved=math.solve(data.metrics,complete);for(const slide of data.slides)if(slide.template.chart)graphFor(slide.template.chart,solved);parameters=complete;values=solved;valid=true;dirty=Object.keys(baseline).some(id=>parameters[id]!==baseline[id]);error.hidden=true;redraw();if(notify)notifyState();return true;}
92
+ catch(reason){valid=false;error.hidden=false;error.textContent=L('无法计算,请检查数值或恢复已保存参数:','Cannot calculate. Check values or reset: ')+reason.message;downloadState();if(notify)notifyState();return false;}
93
+ }
94
+ function download(name,text,type){if(!valid)return;const url=URL.createObjectURL(new Blob([text],{type})),link=document.createElement('a');link.href=url;link.download=name;document.body.append(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);}
95
+ document.getElementById('stage').addEventListener('click',event=>{const target=event.target.closest('[data-metric],[data-unlinked]');if(target){event.preventDefault();event.stopImmediatePropagation();open(target.dataset.metric,!!target.dataset.unlinked);}},true);
96
+ document.addEventListener('click',event=>{const link=event.target.closest('a[download]');if(link&&/\.(?:pptx|json)(?:[?#]|$)/i.test(link.href)&&(dirty||!valid)){event.preventDefault();event.stopImmediatePropagation();open();}},true);
97
+ panel.addEventListener('keydown',event=>event.stopPropagation());
98
+ for(const name of ['wheel','touchstart','touchend'])panel.addEventListener(name,event=>event.stopPropagation(),{passive:true});
99
+ document.addEventListener('keydown',event=>{if(event.key.toLowerCase()==='d'&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!event.target.closest('input,textarea,select')){event.preventDefault();open();}});
100
+ window.__dshData={getState:()=>({schemaVersion:1,deckId:data.deckId,revision:data.revision,fingerprint:data.fingerprint,parameters:{...parameters},dirty,valid}),setParameters:next=>update(next,false),onChange:null};redraw();
101
+ }
102
+
103
+ const DATA_CSS=`
104
+ .data-number{font:inherit!important;line-height:inherit!important;color:inherit!important;background:transparent!important;border:0!important;border-bottom:2px dotted var(--accent)!important;border-radius:0!important;padding:0!important;cursor:pointer;display:inline;white-space:inherit;letter-spacing:inherit}.data-number.data-unlinked{border-bottom-color:var(--muted)!important}
105
+ .data-chart-trace{position:absolute;right:6.4%;top:18%;font:12px var(--font-body);border:1px solid var(--muted);border-radius:9px;padding:6px 9px;background:var(--panel);color:var(--fg);cursor:pointer}
106
+ #data-panel{background:var(--panel);color:var(--fg);border:1px solid var(--muted);border-radius:18px;width:min(700px,calc(100vw - 24px));max-height:88vh;padding:24px;overflow:auto;font:15px/1.6 var(--font-body)}#data-panel::backdrop{background:#0009}
107
+ #data-panel h2{font-size:23px;margin:0;max-width:none}#data-panel h3{font-size:17px;margin:20px 0 8px}#data-panel p{font-size:14px}.data-head,.data-actions{display:flex;gap:10px;align-items:center;justify-content:space-between;flex-wrap:wrap}
108
+ #data-panel button,#data-panel select,#data-panel input[type=number]{font:inherit;background:var(--bg);color:var(--fg);border:1px solid var(--muted);border-radius:9px;padding:8px 11px}#data-panel button{cursor:pointer}#data-panel button:disabled{opacity:.45;cursor:default}#data-panel select{width:100%}
109
+ .data-muted{color:var(--muted)}.data-control{display:grid;grid-template-columns:minmax(0,1fr) 115px;gap:8px;margin:14px 0}.data-control label{grid-column:1/-1}.data-control p{grid-column:1/-1;margin:0}.data-control input{min-width:0;width:100%;accent-color:var(--accent)}.data-control output{font-variant-numeric:tabular-nums;color:var(--accent)}
110
+ .data-notice,.data-error{padding:10px 12px;border:1px solid var(--muted);border-radius:9px;margin:12px 0}.data-error{color:#e67878}.data-evidence pre,.data-evidence code{font:inherit;white-space:pre-wrap;overflow-wrap:anywhere}.data-evidence button{display:block;margin:7px 0;text-align:left}
111
+ a[aria-disabled=true]{opacity:.5;cursor:not-allowed}@media(max-width:640px){#data-panel{padding:16px}.data-control{grid-template-columns:minmax(0,1fr) 105px}#delivery-bar{flex-wrap:wrap;row-gap:5px}#delivery-bar button,#delivery-bar a{font-size:12px;padding:7px 9px}}
112
+ @media print{#data-panel,.data-chart-trace{display:none!important}.data-number{border:0!important}}
113
+ `
@@ -0,0 +1,190 @@
1
+ /** Data provenance and explicit what-if assumptions. File imports occur only in tool calls. */
2
+ import { createRequire } from 'node:module'
3
+ import { readFileSync, lstatSync } from 'node:fs'
4
+ import { basename, resolve, extname } from 'node:path'
5
+ import { createHash } from 'node:crypto'
6
+ import { createDataMath } from './deck-data-math.mjs'
7
+
8
+ const math = createDataMath(), MAX_BYTES = 1024 * 1024
9
+ const require = createRequire(import.meta.url)
10
+ function parser(name) { try { return require(name) } catch(error) { if(error.code==='MODULE_NOT_FOUND')fail('数据绑定需安装技能目录的依赖:npm install --ignore-scripts','Data binding requires skill dependencies: npm install --ignore-scripts');throw error } }
11
+ const identifier = value => typeof value === 'string' && /^[A-Za-z][A-Za-z0-9]{0,47}$/.test(value) && !['constructor','prototype','eval','Function','Math','process','window','globalThis'].includes(value)
12
+ const clone = value => structuredClone(value)
13
+ const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex')
14
+ const fail = (zh, en) => { throw new Error('dsh-ppt:' + zh + ' / ' + en) }
15
+ const token = /\{\{([A-Za-z][A-Za-z0-9]*)\}\}/g
16
+ const fields = ['title','subtitle','kicker','text','bullets','rows','notes','chart']
17
+ const numericPattern = /[-+]?(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?[%%]?/g
18
+ export const dataFingerprint = model => digest({ sources: model.sources, metrics: model.metrics.map(({ ast, dependencies, evidence, ...m }) => m) })
19
+
20
+ function boundedString(value, cap, label) {
21
+ if (typeof value !== 'string' || value.length > cap) fail(label + '过长或无效', 'Invalid or oversized ' + label)
22
+ return value
23
+ }
24
+ function sourceInput(input, cwd, allowFiles) {
25
+ if (!input || !identifier(input.id)) fail('数据源 ID 请使用字母开头的字母和数字', 'Source IDs must use letters and digits')
26
+ let format = input.format, content = input.content, name = input.name || input.id
27
+ if(format!==undefined&&!['csv','tsv','text'].includes(format)||input.kind!==undefined&&!['table','text'].includes(input.kind))fail('来源格式需为 CSV、TSV 或文本','Source format must be CSV, TSV or text')
28
+ if (input.path !== undefined) {
29
+ if (!allowFiles || typeof input.path !== 'string') fail('网页请求不能读取任意文件', 'Browser requests cannot read arbitrary files')
30
+ const path = resolve(cwd, input.path), stat = lstatSync(path)
31
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_BYTES) fail('源文件需为 1 MiB 内的普通文件', 'Source must be a regular file up to 1 MiB')
32
+ const suffix = extname(path).toLowerCase(); format ||= suffix === '.csv' ? 'csv' : suffix === '.tsv' ? 'tsv' : ['.md','.txt'].includes(suffix) ? 'text' : ''
33
+ if (!['csv','tsv','text'].includes(format)) fail('源文件支持 CSV、TSV、TXT 和 Markdown', 'Supported source files: CSV, TSV, TXT and Markdown')
34
+ content = readFileSync(path, 'utf8'); name = input.name || basename(path)
35
+ }
36
+ boundedString(String(name), 120, '数据源名称')
37
+ let source
38
+ if (format === 'csv' || format === 'tsv') {
39
+ boundedString(content, MAX_BYTES, '源数据')
40
+ const rows = parser('csv-parse/sync').parse(content, { bom: true, delimiter: format === 'tsv' ? '\t' : ',', skip_empty_lines: false, max_record_size: 100000 })
41
+ source = { id: input.id, name: String(name), kind: 'table', rows }
42
+ } else if (input.kind === 'table' || input.rows !== undefined) source = { id: input.id, name: String(name), kind: 'table', rows: clone(input.rows) }
43
+ else source = { id: input.id, name: String(name), kind: 'text', text: boundedString(content ?? input.text, MAX_BYTES, '材料') }
44
+ if (source.kind === 'table') {
45
+ const rows = source.rows
46
+ if (!Array.isArray(rows) || !rows.length || rows.length > 500 || !Array.isArray(rows[0]) || !rows[0].length || rows[0].length > 26 || rows.some(r => !Array.isArray(r) || r.length !== rows[0].length || r.some(v => !['string','number'].includes(typeof v) || typeof v === 'number' && !Number.isFinite(v) || String(v).length > 2000))) fail('表格需 1–500 行、1–26 列,行宽一致,单元格最多 2000 字符', 'Table limits: 500 rows, 26 columns, equal row widths, 2000 characters per cell')
47
+ }
48
+ source.sha256 = digest(source.kind === 'text' ? source.text : source.rows)
49
+ return source
50
+ }
51
+ function numeric(value) {
52
+ if (typeof value === 'number') return math.finite(value)
53
+ const text = String(value).trim()
54
+ if (!/^[-+]?(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?[%%]?$/.test(text)) fail('引用位置不是单个数值', 'The referenced location is not a single number')
55
+ return math.finite(Number(text.replaceAll(',', '').replace(/[%%]$/, '')) / (/[%%]$/.test(text) ? 100 : 1))
56
+ }
57
+ function evidenceOf(ref, sources) {
58
+ if (!ref || typeof ref !== 'object') fail('指标缺少来源', 'Metric source is missing')
59
+ const source = sources.find(s => s.id === ref.sourceId)
60
+ if (!source) fail('找不到数据源:' + ref.sourceId, 'Unknown source: ' + ref.sourceId)
61
+ let value, locator, excerpt, reference
62
+ if (source.kind === 'table') {
63
+ const cell = /^([A-Z])([1-9]\d{0,2})$/.exec(String(ref.cell || '').toUpperCase())
64
+ if (!cell) fail('单元格需使用 A1–Z500 地址', 'Use a cell address from A1 to Z500')
65
+ const row = Number(cell[2]) - 1, col = cell[1].charCodeAt(0) - 65
66
+ if (!source.rows[row] || col >= source.rows[row].length) fail('引用单元格超出数据源', 'Cell is outside the source table')
67
+ value = numeric(source.rows[row][col]); locator = cell[1] + cell[2]
68
+ excerpt = source.rows[row].map((c, i) => String.fromCharCode(65 + i) + ': ' + String(c)).join(' | ').slice(0,1000)
69
+ reference = { sourceId: source.id, cell: locator }
70
+ } else {
71
+ if (!Number.isInteger(ref.line) || ref.line < 1 || ref.line > 10000 || !Number.isInteger(ref.numberIndex ?? 0) || (ref.numberIndex ?? 0) < 0 || (ref.numberIndex ?? 0) > 100) fail('请指定材料行号与该行数值序号(从 0 开始)', 'Specify a line and zero-based numberIndex')
72
+ const line = source.text.split(/\r?\n/)[ref.line - 1]
73
+ if (line === undefined || line.length > 8000) fail('材料行不存在或超过 8000 字符', 'Source line missing or longer than 8000 characters')
74
+ const numbers = [...line.matchAll(numericPattern)], match = numbers[ref.numberIndex ?? 0]
75
+ if (!match) fail('该材料行没有指定的数值', 'Requested number not found on the source line')
76
+ value = numeric(match[0]); locator = 'L' + ref.line + ' #' + (Number(ref.numberIndex ?? 0) + 1); excerpt = line
77
+ reference = { sourceId: source.id, line: ref.line, numberIndex: ref.numberIndex ?? 0 }
78
+ }
79
+ return { value, reference, evidence: { sourceId: source.id, name: source.name, locator, excerpt, sha256: source.sha256 } }
80
+ }
81
+ export function normalizeDataModel(input, { cwd = '.', allowFiles = false } = {}) {
82
+ if (!input || input.schemaVersion !== undefined && input.schemaVersion !== 1 || !Array.isArray(input.sources) || input.sources.length > 8 || !Array.isArray(input.metrics) || !input.metrics.length || input.metrics.length > 80) fail('数据模型需包含最多 8 个来源和 1–80 个指标', 'Data model needs up to 8 sources and 1–80 metrics')
83
+ const sources = input.sources.map(s => sourceInput(s, cwd, allowFiles)), seen = new Set()
84
+ if (new Set(sources.map(s => s.id)).size !== sources.length || Buffer.byteLength(JSON.stringify(sources)) > MAX_BYTES) fail('数据源重复或总量超过 1 MiB', 'Duplicate sources or combined data exceeds 1 MiB')
85
+ const metrics = input.metrics.map(raw => {
86
+ if (!raw || !identifier(raw.id) || seen.has(raw.id) || !['source','input','formula'].includes(raw.kind)) fail('指标 ID 重复、无效或类型不受支持', 'Invalid, duplicate metric ID or unsupported kind')
87
+ seen.add(raw.id)
88
+ const format = raw.format || {}, style = format.style || 'number', digits = format.digits ?? 2
89
+ if (!['number','percent'].includes(style) || !Number.isInteger(digits) || digits < 0 || digits > 6) fail('显示格式只支持 number / percent 和 0–6 位小数', 'Use number/percent and 0–6 decimal places')
90
+ const metric = { id: raw.id, label: boundedString(raw.label || raw.id,120,'指标名称'), kind: raw.kind, format: { style, digits, ...(format.unit ? { unit: boundedString(format.unit,24,'单位') } : {}) }, ...(raw.note ? { note: boundedString(raw.note,1000,'假设说明') } : {}) }
91
+ if (raw.kind === 'source') { const result = evidenceOf(raw.source,sources); Object.assign(metric,{source:result.reference,value:result.value,evidence:result.evidence}) }
92
+ if (raw.kind === 'input') {
93
+ if ([raw.value,raw.min,raw.max,raw.step].some(v=>typeof v!=='number'||!Number.isFinite(v)||Math.abs(v)>1e15)||raw.min>=raw.max||raw.step<=0||(raw.max-raw.min)/raw.step>100000) fail('假设需提供数值、最小值、最大值和正步长(最多 100000 步)', 'Assumptions need finite value/min/max/positive step, at most 100000 steps')
94
+ Object.assign(metric,{value:raw.value,min:raw.min,max:raw.max,step:raw.step}); math.inputValue(metric,raw.value)
95
+ }
96
+ if (raw.kind === 'formula') { metric.formula = boundedString(raw.formula,512,'公式'); const jsep=parser('jsep');try { metric.ast = jsep(metric.formula) } catch { fail('公式无法解析:'+raw.id,'Formula cannot be parsed: '+raw.id) } }
97
+ return metric
98
+ })
99
+ if (metrics.filter(m=>m.kind==='input').length>12) fail('每个工程最多 12 个可调假设','At most 12 adjustable assumptions')
100
+ for (const metric of metrics) if (metric.ast) metric.dependencies = math.inspect(metric.ast, seen)
101
+ const values = math.solve(metrics)
102
+ return { schemaVersion:1,sources,metrics,values,fingerprint:dataFingerprint({sources,metrics}) }
103
+ }
104
+ export function substituteData(value, model, numericValue = false) {
105
+ if (typeof value !== 'string') return value
106
+ if (/\{\{|\}\}/.test(value.replace(token,''))) fail('数据占位符需使用 {{指标ID}}','Use {{metricId}} for data placeholders')
107
+ const match = /^\{\{([A-Za-z][A-Za-z0-9]*)\}\}$/.exec(value)
108
+ if (numericValue && match) {
109
+ if (!Object.hasOwn(model.values,match[1])) fail('未知指标:'+match[1],'Unknown metric: '+match[1])
110
+ return model.values[match[1]]
111
+ }
112
+ if (numericValue && value.includes('{{')) fail('图表数值需为完整的 {{指标ID}}','Chart values require an exact {{metricId}}')
113
+ return value.replace(token,(_,id)=>{
114
+ const metric=model.metrics.find(m=>m.id===id);if(!metric)fail('未知指标:'+id,'Unknown metric: '+id)
115
+ return math.format(model.values[id],metric)
116
+ })
117
+ }
118
+ function chartTemplate(chart) {
119
+ if (!chart || !chart.rows) return clone(chart)
120
+ return { ...chart, rows:undefined,categories:chart.rows.slice(1).map(r=>r[0]),series:chart.rows[0].slice(1).map((name,c)=>({name,values:chart.rows.slice(1).map(r=>r[c+1])})) }
121
+ }
122
+ export function resolveTemplate(template, model) {
123
+ const next=clone(template)
124
+ for (const key of ['title','subtitle','kicker','text','notes']) if(typeof next[key]==='string')next[key]=substituteData(next[key],model)
125
+ if(Array.isArray(next.bullets))next.bullets=next.bullets.map(v=>substituteData(v,model))
126
+ if(Array.isArray(next.rows))next.rows=next.rows.map(row=>row.map(v=>substituteData(v,model)))
127
+ if(next.chart){next.chart=chartTemplate(next.chart);next.chart.categories=next.chart.categories?.map(v=>substituteData(v,model));next.chart.series=next.chart.series?.map(s=>({...s,name:substituteData(s.name,model),values:s.values.map(v=>substituteData(v,model,true))}));for(const k of ['unit','caption'])if(next.chart[k])next.chart[k]=substituteData(next.chart[k],model)}
128
+ return next
129
+ }
130
+ function hasBinding(value){return typeof value==='string'?/\{\{[A-Za-z][A-Za-z0-9]*\}\}/.test(value):Array.isArray(value)?value.some(hasBinding):value&&typeof value==='object'?Object.values(value).some(hasBinding):false}
131
+ export function prepareDataSlides(rawSlides, model, normalize, language='zh') {
132
+ return rawSlides.flatMap(raw=>{
133
+ if(raw.dataTemplate && (typeof raw.dataTemplate!=='object'||Array.isArray(raw.dataTemplate)||Object.keys(raw.dataTemplate).some(key=>!fields.includes(key))))fail('数据模板只允许文本、表格和图表字段','Data templates only support text, table and chart fields')
134
+ const original={...raw,...raw.dataTemplate};delete original.dataTemplate
135
+ if(original.chart)original.chart=chartTemplate(original.chart)
136
+ const resolved=resolveTemplate(original,model), actual=normalize([resolved],120,language)
137
+ // Normalize text/table templates using the same pagination as real output.
138
+ // Charts are normalized with real values, then their canonical bindings restored.
139
+ const textTemplate={...original,...(original.chart?{chart:resolved.chart}:{})},templates=normalize([textTemplate],120,language)
140
+ if(templates.length!==actual.length)fail('数据绑定改变了页数,请先将表格分页','Binding changes pagination; split the table first')
141
+ return actual.map((slide,i)=>{
142
+ const candidate={...templates[i],...(original.chart?{chart:original.chart}:{})},dataTemplate={}
143
+ for(const key of fields)if(hasBinding(candidate[key]))dataTemplate[key]=candidate[key]
144
+ return {...slide,...(Object.keys(dataTemplate).length?{dataTemplate}:{})}
145
+ })
146
+ })
147
+ }
148
+ export function refreshDataSlides(slides, model, normalize, language) {
149
+ return slides.map(slide=>{const refreshed=prepareDataSlides([slide],model,normalize,language);if(refreshed.length!==1)fail('更新后页数发生变化,请分拆该页','Data refresh must preserve slide count');return{...refreshed[0],id:slide.id}})
150
+ }
151
+ /** Reject stale materialized values and unsafe persisted file references. */
152
+ export function validateDataSnapshot(manifest, normalize) {
153
+ if(!manifest.dataModel){if(manifest.slides.some(s=>s.dataTemplate))fail('数据模板缺少模型','Data templates require a data model');return}
154
+ const model=normalizeDataModel(manifest.dataModel)
155
+ if(JSON.stringify(model)!==JSON.stringify(manifest.dataModel))fail('数据模型快照不一致,请从原始材料重新生成','Data snapshot is inconsistent; rebuild from source material')
156
+ const refreshed=refreshDataSlides(manifest.slides,model,normalize,manifest.language)
157
+ for(let i=0;i<refreshed.length;i++)for(const key of [...fields,'dataTemplate'])if(JSON.stringify(refreshed[i][key])!==JSON.stringify(manifest.slides[i][key]))fail('第 '+(i+1)+' 页与数据绑定不一致','Slide '+(i+1)+' differs from its data bindings')
158
+ }
159
+ export function dataReferences(slide) {return [...new Set([...JSON.stringify(slide.dataTemplate||{}).matchAll(token)].map(match=>match[1]))]}
160
+ export function dataDependencies(model, ids) {
161
+ const found=new Set(),byId=new Map(model.metrics.map(m=>[m.id,m]))
162
+ function visit(id){if(found.has(id))return;const metric=byId.get(id);if(!metric)fail('未知指标:'+id,'Unknown metric: '+id);found.add(id);metric.dependencies?.forEach(visit)}
163
+ ids.forEach(visit);return model.metrics.filter(m=>found.has(m.id))
164
+ }
165
+ export function dataNotes(manifest, slide) {
166
+ if(!manifest.dataModel||!slide.dataTemplate)return slide.notes||''
167
+ const model=manifest.dataModel,en=manifest.language==='en',metrics=dataDependencies(model,dataReferences(slide))
168
+ const lines=[slide.notes||'',en?'--- Data and assumptions (confirmed static snapshot) ---':'--- 数据、公式与假设(已确认的静态快照) ---',...metrics.map(m=>m.label+' ['+m.id+'] = '+math.format(model.values[m.id],m,manifest.language)+'\n'+(m.kind==='formula'?'= '+m.formula:m.kind==='input'?(en?'User assumption':'用户假设')+(m.note?': '+m.note:''):m.evidence.name+' · '+m.evidence.locator+'\n'+m.evidence.excerpt+'\nSHA-256: '+m.evidence.sha256))]
169
+ return lines.join('\n\n')
170
+ }
171
+ export function dataReport(manifest) {
172
+ const en=manifest.language==='en',heading=String(manifest.title).replace(/[\r\n]/g,' '),lines=['# '+heading,en?'Data lineage and assumptions; source links are not factual verification.':'数据溯源与假设;关联到原文不代表事实已被核验。']
173
+ manifest.slides.forEach((slide,i)=>{if(slide.dataTemplate)lines.push('## '+(i+1)+'. '+slide.title,dataNotes(manifest,slide))})
174
+ return lines.join('\n\n')+'\n'
175
+ }
176
+ export function previewDataChange(manifest, options, normalize) {
177
+ if(!manifest.dataModel)fail('工程尚未配置数据模型','This project has no data model')
178
+ const raw=clone(manifest.dataModel),updates=options.sourceUpdates??[],parameters=options.parameters??{}
179
+ if(!Array.isArray(updates)||updates.length>8||!parameters||typeof parameters!=='object'||Array.isArray(parameters))fail('数据更新格式无效','Invalid data update')
180
+ const updated=new Set()
181
+ for(const update of updates){const index=raw.sources.findIndex(s=>s.id===update?.id);if(index<0||updated.has(update.id))fail('来源不存在或重复','Unknown or duplicate source');updated.add(update.id);const source=raw.sources[index];const next=sourceInput({...update,name:source.name},options.cwd||'.',options.allowFiles===true);if(next.kind!==source.kind)fail('替换材料需保持表格或文本类型','Keep the same source type');raw.sources[index]=next}
182
+ for(const [id,value]of Object.entries(parameters)){const metric=raw.metrics.find(m=>m.id===id);if(metric?.kind!=='input')fail('仅可更改明确声明的假设','Only declared assumptions can change');math.inputValue(metric,value);metric.value=value}
183
+ const model=normalizeDataModel(raw),slides=refreshDataSlides(manifest.slides,model,normalize,manifest.language)
184
+ const changes=model.metrics.filter(m=>model.values[m.id]!==manifest.dataModel.values[m.id]||JSON.stringify(m.evidence)!==JSON.stringify(manifest.dataModel.metrics.find(old=>old.id===m.id)?.evidence)).map(m=>({id:m.id,label:m.label,before:manifest.dataModel.values[m.id],after:model.values[m.id],beforeText:math.format(manifest.dataModel.values[m.id],m,manifest.language),afterText:math.format(model.values[m.id],m,manifest.language),kind:m.kind}))
185
+ const changedIds=new Set(changes.map(m=>m.id))
186
+ const affectedSlides=slides.flatMap((slide,i)=>JSON.stringify(slide)!==JSON.stringify(manifest.slides[i])||dataDependencies(model,dataReferences(slide)).some(m=>changedIds.has(m.id))?[{id:slide.id,page:i+1,title:slide.title,fields:fields.filter(key=>JSON.stringify(slide[key])!==JSON.stringify(manifest.slides[i][key])).map(key=>({field:key,before:manifest.slides[i][key]??'',after:slide[key]??''})),evidenceChanged:dataDependencies(model,dataReferences(slide)).some(m=>m.kind==='source'&&changedIds.has(m.id))}]:[])
187
+ // Include the full saved state, so hand edits that omit revision updates also invalidate confirmation.
188
+ const token=digest({state:digest(manifest),after:model.fingerprint,slides:slides.map(s=>({id:s.id,dataTemplate:s.dataTemplate}))})
189
+ return {model,slides,preview:{token,changes,affectedSlides,sourceChanges:[...updated],changed:model.fingerprint!==manifest.dataModel.fingerprint}}
190
+ }