@agile-team/mach-report 2.25.0 → 2.25.1
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.
- package/README.md +4 -2
- package/dist/{ExcelBindingWizard-NQ_v396s.js → ExcelBindingWizard-bs3F4dD8.js} +3 -3
- package/dist/{ExcelBindingWizard-BgJG-T6k.cjs → ExcelBindingWizard-jSdjBtWw.cjs} +1 -1
- package/dist/{ParamEditor-Z-3yodp5.js → ParamEditor-B7YVD28E.js} +1 -1
- package/dist/{ParamEditor-DEP38mBp.cjs → ParamEditor-CGfaweYX.cjs} +1 -1
- package/dist/{ReportBatchPanel-D33LjMrA.cjs → ReportBatchPanel-BRJt0TXp.cjs} +1 -1
- package/dist/{ReportBatchPanel-DG8FV-5X.js → ReportBatchPanel-BTKHtLTW.js} +1 -1
- package/dist/{ReportLabelStudio-Bz-xAayk.cjs → ReportLabelStudio-BvK_WBke.cjs} +1 -1
- package/dist/{ReportLabelStudio-BZp23_hA.js → ReportLabelStudio-CZwqyO3t.js} +2 -2
- package/dist/{ReportPreview-CilFAS9U.js → ReportPreview-CnxaDTCO.js} +4 -4
- package/dist/{ReportPreview-dOOzPts2.cjs → ReportPreview-DqFBcsJQ.cjs} +2 -2
- package/dist/{ReportTemplateLibrary-DpSGgvFa.js → ReportTemplateLibrary-C7sB0Jay.js} +1 -1
- package/dist/{ReportTemplateLibrary-uG1gENaW.cjs → ReportTemplateLibrary-ClwxhnC0.cjs} +1 -1
- package/dist/{RuleEditor-BONALh1Q.js → RuleEditor-CsDGFaWz.js} +3 -3
- package/dist/{RuleEditor-bLXiRcxL.cjs → RuleEditor-D-OdaGdR.cjs} +1 -1
- package/dist/{TemplateOutlinePanel-JGBKeF3e.js → TemplateOutlinePanel-CXOT7d1r.js} +1 -1
- package/dist/{TemplateOutlinePanel-C3nfHuaR.cjs → TemplateOutlinePanel-DAqR9zQi.cjs} +1 -1
- package/dist/{TemplateReusePanel-DXQUO6nQ.js → TemplateReusePanel-Dcfx3Hba.js} +2 -2
- package/dist/{TemplateReusePanel-BKhgp6kg.cjs → TemplateReusePanel-ygIi-Ajz.cjs} +1 -1
- package/dist/{TemplateReviewPanel-DhL7Hapy.js → TemplateReviewPanel-COU8FqPq.js} +1 -1
- package/dist/{TemplateReviewPanel-5RWFUUEf.cjs → TemplateReviewPanel-DyGULVxr.cjs} +1 -1
- package/dist/analytics.cjs +1 -1
- package/dist/analytics.js +2 -2
- package/dist/artifact-integrity.json +71 -71
- package/dist/{auto-umW_ozwr.js → auto-D7x7QsWD.js} +4 -4
- package/dist/{auto-D-eDZa_V.cjs → auto-mPK9W0y5.cjs} +1 -1
- package/dist/{designer-CCyj5WYS.js → designer-B597ZdC0.js} +4 -4
- package/dist/{designer-Cj7fn4Hh.cjs → designer-DFIdv_n7.cjs} +1 -1
- package/dist/designer.cjs +1 -1
- package/dist/designer.js +1 -1
- package/dist/{encoding-CEkBtlUP.js → encoding-Amq3XrtU.js} +2 -2
- package/dist/{encoding-Cipno7dq.cjs → encoding-DRVXs5xm.cjs} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +8 -8
- package/dist/{json-snapshot-x0JpllWL.js → json-snapshot-CBVWZvyC.js} +661 -614
- package/dist/json-snapshot-DCFEtfFw.cjs +2 -0
- package/dist/matrix-DUYPRL7t.cjs +1 -0
- package/dist/{matrix-C6e_r_vp.js → matrix-b6T291xo.js} +120 -104
- package/dist/{plugin-CttO46hc.js → plugin-BdCplNe1.js} +1 -1
- package/dist/{plugin-B_k23hut.cjs → plugin-DHe8y5pD.cjs} +1 -1
- package/dist/{prefill-BkF9Fw_p.js → prefill-Buy4NJ15.js} +1 -1
- package/dist/{prefill-BvkuwooY.cjs → prefill-Cw4ZYGXZ.cjs} +1 -1
- package/dist/{prepared-CSywIEAZ.cjs → prepared-BlNeOjoO.cjs} +1 -1
- package/dist/{prepared-Cyuh61fJ.js → prepared-CBJ7BkK0.js} +1 -1
- package/dist/{protocol-BwbJNVZl.cjs → protocol-BU_4sXP0.cjs} +1 -1
- package/dist/{protocol-DwtxjXzO.js → protocol-CB19KXGr.js} +2 -2
- package/dist/{region-binding-workflow-D8I4QWRh.js → region-binding-workflow-EYxvUYJ-.js} +1 -1
- package/dist/{region-binding-workflow-COD8nISZ.cjs → region-binding-workflow-NdkMSFCh.cjs} +1 -1
- package/dist/report-encoding-worker.cjs +1 -1
- package/dist/report-encoding-worker.js +1 -1
- package/dist/{runtime-BE30icyB.js → runtime-B5d_lQNQ.js} +3 -3
- package/dist/{runtime-DRSuy_SQ.cjs → runtime-BRx8Agqr.cjs} +1 -1
- package/dist/sbom.cdx.json +1 -1
- package/dist/server-node.cjs +5 -5
- package/dist/server-node.js +1686 -1622
- package/dist/server.cjs +1 -1
- package/dist/server.js +6 -6
- package/dist/{template-catalog-D_gl93va.js → template-catalog-CM6U_RlD.js} +2 -2
- package/dist/{template-catalog-C0riwrx7.cjs → template-catalog-Cj66M84u.cjs} +1 -1
- package/dist/{template-fragments-D94ZZmPc.js → template-fragments-BDxdCuMD.js} +1 -1
- package/dist/{template-fragments-CgzPdFKB.cjs → template-fragments-DbKdxI1z.cjs} +1 -1
- package/dist/template-registry-B-AK1oam.cjs +1 -0
- package/dist/{template-registry-DZOtRY7t.js → template-registry-DeVgwEZj.js} +143 -142
- package/dist/vue-async.cjs +1 -1
- package/dist/vue-async.js +3 -3
- package/dist/vue.cjs +1 -1
- package/dist/vue.js +4 -4
- package/dist/{workbook-session-SzfILBJJ.js → workbook-session-B6hRjTyX.js} +1 -1
- package/dist/{workbook-session-DR2j6Hxm.cjs → workbook-session-BclW7KKH.cjs} +1 -1
- package/dist/worker.cjs +1 -1
- package/dist/worker.js +4 -4
- package/dist/xlsx.cjs +1 -1
- package/dist/xlsx.js +3 -3
- package/package.json +1 -1
- package/dist/json-snapshot-DQdkA_At.cjs +0 -2
- package/dist/matrix-B8QWbsGM.cjs +0 -1
- package/dist/template-registry-BMScUmM4.cjs +0 -1
package/dist/server.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const H=require("./runtime-DRSuy_SQ.cjs"),p=require("./sha256-DgZAKXqI.cjs"),C=require("./json-snapshot-DQdkA_At.cjs"),h=require("./batch-DYcokH4v.cjs"),ce=require("./template-catalog-C0riwrx7.cjs"),O=require("./template-registry-BMScUmM4.cjs"),M=require("./prepared-CSywIEAZ.cjs"),fe=require("./param-validation-C-8sRJLq.cjs"),de=require("./record-bindings-B7djSjNs.cjs"),ue=require("./dataset-IrlXbUvh.cjs"),le=require("./media-B7vnpD8k.cjs"),Ee=require("./diagnostic-collector-wASg6Fzs.cjs");function Ae(e={}){const t=e.concurrency??1,r=e.maxQueued??20;if(!Number.isSafeInteger(t)||t<1||!Number.isSafeInteger(r)||r<0)throw new p.ReportRuntimeError("budget","队列并发应为正整数,排队上限应为非负整数");const n=[],o=new Set,s=new Set;let a=!1,u=0;const f=()=>{for(;!a&&o.size<t&&n.length;)n.shift().start()};return{get active(){return o.size},get pending(){return n.length},enqueue:(i,d={})=>{if(a)throw new p.ReportRuntimeError("closed","任务队列已关闭");if(p.throwIfAborted(d.signal),o.size>=t&&n.length>=r)throw new p.ReportRuntimeError("queue-full","报表任务队列已满");const l=d.id??`report-${++u}`;if(s.has(l))throw new p.ReportRuntimeError("queue-full","任务 ID 正在执行或排队");const w=new AbortController;let m="queued",b,y,g,R;const P=new Promise((S,A)=>{g=S,R=A}),N=()=>{d.signal?.removeEventListener("abort",$),s.delete(l)},E=S=>{if(m!=="queued"&&m!=="running")return;const A=m==="queued";m="cancelled",w.abort(S);try{p.throwIfAborted(w.signal)}catch(q){R(q)}if(A){const q=n.indexOf(x);q>=0&&n.splice(q,1),N(),f()}},$=()=>E(d.signal?.reason),K=(S,A)=>{m==="running"&&(!Number.isFinite(S)||S<0||A!==void 0&&(!Number.isFinite(A)||A<S)||(b={completed:S,...A===void 0?{}:{total:A}}))},T=S=>{m!=="running"||w.signal.aborted||(y={...S,taskId:l},S.completed!==void 0&&K(S.completed,S.total),C.notifyReportTaskEvent(d.onEvent,y,w.signal))},x={cancel:E,start:()=>{m==="queued"&&(m="running",o.add(x),Promise.resolve().then(()=>(p.throwIfAborted(w.signal),i({taskId:l,signal:w.signal,reportProgress:K,onEvent:T}))).then(S=>{m==="running"&&(m="completed",g(S))},S=>{m==="running"&&(m="failed",R(S))}).finally(()=>{o.delete(x),N(),f()}))}};return s.add(l),d.signal?.addEventListener("abort",$,{once:!0}),d.signal?.aborted?E(d.signal.reason):o.size<t?x.start():n.push(x),{id:l,get status(){return m},get progress(){return b},get event(){return y},result:P,cancel:E}},close:(i={})=>{a=!0;for(const d of[...n])d.cancel(new p.ReportRuntimeError("closed","任务队列已关闭"));if(i.cancelRunning)for(const d of o)d.cancel(new p.ReportRuntimeError("closed","任务队列已关闭"))}}}function ke(e){let t,r;const n=new Promise((o,s)=>{t=o,r=s});return n.catch(()=>{}),{progress:e,promise:n,resolve:t,reject:r}}function Q(e){const t=Promise.reject(e);return t.catch(()=>{}),t}function Oe(e,t){let r,n,o=!0,s;function a(c){s??=c??new Error("任务心跳更新失败"),n?.reject(s),n=void 0,t(s)}function u(c){const i=Promise.resolve().then(()=>e(c?.progress)).then(()=>c?.resolve(),d=>{c?.reject(d),a(d)}).finally(()=>{r=void 0;const d=n;n=void 0,d&&s===void 0&&u(d)});r=i,i.catch(d=>{a(d)})}function f(c){if(!o)return Q(new h.ReportJobError("closed","任务进度上报已结束"));if(s!==void 0)return Q(s);n?n.progress=c:n=ke(c);const i=n;return r||(n=void 0,u(i)),i.promise}return{progress:f,pulse(){o&&!r&&s===void 0&&u()},async finish(){for(o=!1;r;)await r;if(s!==void 0)throw s}}}class W extends h.ReportJobError{constructor(){super("capacity","任务结果超过独立预算,请保存文件引用")}}function Je(e){const t=e.concurrency??1,r=e.leaseMs??3e4,n=e.heartbeatMs??1e4,o=e.maxResultBytes??256*1024;if(![t,r,n,o].every(a=>Number.isSafeInteger(a)&&a>0)||n*2>r)throw new h.ReportJobError("input","并发、租约、心跳应为正整数,租约至少为心跳的两倍");if(n>2147483647)throw new h.ReportJobError("input","心跳间隔超过平台定时器上限(2147483647毫秒)");return{concurrency:t,leaseMs:r,heartbeatMs:n,maxResultBytes:o,now:()=>{const a=(e.now??Date.now)();if(!Number.isSafeInteger(a)||a<0)throw new h.ReportJobError("input","任务时钟应返回非负整数毫秒");return a}}}async function L(e,t,r){h.checkJobIdentity(t,r);const n=await e.read(t,r);if(!n)throw new h.ReportJobError("missing","报表任务不存在");return n}async function D(e,t,r,n=[]){const o={...t,...r,revision:t.revision+1};for(const s of n)delete o[s];if(!await e.compareAndSwap(t.scope,t.id,t.revision,o))throw new h.ReportJobError("conflict","报表任务已被其他请求更新");return h.cloneJob(o)}async function Pe(e,t,r,n){if(!t.trim()||t.length>128)throw new h.ReportJobError("input","workerId应为1–128位标识");for(const o of await e.store.candidates(n,100)){const s=o.cancelRequested?{...o,revision:o.revision+1,status:"cancelled",updatedAt:n}:{...o,revision:o.revision+1,status:"running",attempt:o.attempt+1,updatedAt:n,lease:{owner:t,expiresAt:n+r}};if(s.status==="cancelled"&&delete s.lease,await e.store.compareAndSwap(o.scope,o.id,o.revision,s))return s}}function Y(e,t,r,n){return e.status==="running"&&e.attempt===n&&e.lease?.owner===t&&e.lease.expiresAt>r}async function Te(e,t,r,n){const{scope:o,id:s}=r,a=r.lease.owner;let u;const f=Oe(async y=>{const g=await L(e.store,o,s),R=t.now();if(!Y(g,a,R,r.attempt))throw new h.ReportJobError("lease","报表任务租约已失效");if(g.cancelRequested){n.abort(new h.ReportJobError("closed","任务已请求取消"));return}await D(e.store,g,{updatedAt:R,lease:{owner:a,expiresAt:R+t.leaseMs},...y?{progress:y}:{}})},y=>{u=y,n.abort(y)}),c=(y,g)=>!Number.isFinite(y)||y<0||g!==void 0&&(!Number.isFinite(g)||g<y)?Promise.reject(new h.ReportJobError("input","任务进度无效")):f.progress({completed:y,...g===void 0?{}:{total:g}}),i=setInterval(()=>{f.pulse()},t.heartbeatMs);let d,l;try{const y=Object.prototype.hasOwnProperty.call(e.handlers,r.request.kind)?e.handlers[r.request.kind]:void 0;if(!y)throw new h.ReportJobError("input","报表任务处理器未注册");if(!n.signal.aborted){const g=await y(h.cloneJob(r.request.payload),{scope:o,taskId:s,attempt:r.attempt,executionToken:JSON.stringify([o,s,r.attempt]),signal:n.signal,reportProgress:c});if(d=JSON.parse(h.serializeJobJson(g)),h.jobByteLength(d)>t.maxResultBytes)throw new W}}catch(y){l=y??new Error("报表任务执行失败")}finally{clearInterval(i),await f.finish().catch(()=>{})}const w=await L(e.store,o,s),m=t.now();if(!Y(w,a,m,r.attempt))throw new h.ReportJobError("lease","任务租约已失效,迟到结果不会写回");const b={...w,updatedAt:m};delete b.lease,l??=u,w.cancelRequested||n.signal.aborted&&u===void 0?b.status="cancelled":l!==void 0?(b.status="failed",b.error={code:l instanceof W?"result-budget":l instanceof h.ReportJobError?l.code:"execution",message:l instanceof Error?l.message.slice(0,500):"报表任务执行失败"}):(b.status="completed",b.result=d);try{h.serializeJobJson(b)}catch{delete b.result,b.status="failed",b.error={code:"result-budget",message:"任务结果与请求的组合超过存储预算,请保存文件引用而非文件内容"}}return je(e.store,w,b)}async function je(e,t,r){try{return await D(e,t,r,["lease"])}catch(n){if(!(n instanceof h.ReportJobError)||n.code!=="capacity"||r.status!=="completed")throw n;return delete r.result,r.status="failed",r.error={code:"result-budget",message:"任务结果超过存储剩余预算,请保存文件引用而非文件内容"},D(e,t,r,["lease","result"])}}async function ee(e,t,r,n){const o=await e.readTombstone?.(t,r);if(o){if(o.requestHash!==await h.jobRequestHash(n))throw new h.ReportJobError("conflict","相同任务ID不能提交不同内容(幂等保留期内)");return{scope:t,id:r,revision:o.revision,request:h.cloneJob(n),status:o.status,createdAt:o.createdAt,updatedAt:o.updatedAt,attempt:o.attempt,archived:!0}}}function Ne(e){e={...e,handlers:{...e.handlers}};const t=Je(e),r=new Set,n=new Set;let o=!1,s=0;const a=(c,i)=>(h.checkJobIdentity(c,i),e.store.read(c,i));return{submit:async c=>{if(c={...c},h.checkJobIdentity(c.scope,c.id),!Object.prototype.hasOwnProperty.call(e.handlers,c.kind)||typeof e.handlers[c.kind]!="function")throw new h.ReportJobError("input","报表任务处理器未注册");const i={kind:c.kind,payload:JSON.parse(h.serializeJobJson(c.payload,{maxNodes:19e3,maxCharacters:75e4}))},d=await a(c.scope,c.id);if(d){if(h.serializeJobJson(d.request)!==h.serializeJobJson(i))throw new h.ReportJobError("conflict","相同任务ID不能提交不同内容");return d}const l=await ee(e.store,c.scope,c.id,i);if(l)return l;const w=t.now(),m={scope:c.scope,id:c.id,revision:1,request:i,status:"queued",createdAt:w,updatedAt:w,attempt:0};if(!await e.store.compareAndSwap(c.scope,c.id,null,m)){const b=await a(c.scope,c.id);if(b&&h.serializeJobJson(b.request)===h.serializeJobJson(i))return b;const y=await ee(e.store,c.scope,c.id,i);if(y)return y;throw new h.ReportJobError("conflict","报表任务提交发生冲突")}return h.cloneJob(m)},get:a,runNext:c=>{if(o)return Promise.reject(new h.ReportJobError("closed","报表任务服务已关闭"));if(s>=t.concurrency)return Promise.reject(new h.ReportJobError("capacity","报表任务执行槽位已满"));s++;const i=new AbortController;r.add(i);const d=(async()=>{try{const l=await Pe(e,c,t.leaseMs,t.now());return l?.status==="running"?await Te(e,t,l,i):l}finally{s--,r.delete(i)}})();return n.add(d),d.then(()=>n.delete(d),()=>n.delete(d)),d},get active(){return s},cancel:async(c,i)=>{const d=await L(e.store,c,i);return d.status!=="queued"&&d.status!=="running"?d:D(e.store,d,{updatedAt:t.now(),...d.status==="queued"?{status:"cancelled"}:{cancelRequested:!0}})},retry:async(c,i,d)=>{const l=await L(e.store,c,i);if(l.revision!==d||l.status!=="failed")throw new h.ReportJobError("conflict","仅可重试当前修订的失败任务");const w={...l,status:"queued",updatedAt:t.now()};return delete w.error,delete w.progress,D(e.store,l,w,["error","progress"])},prune:async c=>{if(!e.store.prune||!e.store.readTombstone)throw new h.ReportJobError("input","当前任务适配器未实现可选终态保留能力");return e.store.prune({...c,now:t.now()})},close:async()=>{o=!0;for(const c of r)c.abort(new h.ReportJobError("closed","任务服务正在关闭"));await Promise.allSettled([...n])}}}function pe(e,t){const r=e.assets,n=e[t];if(!(!r&&!n?.assetRenderers&&!n?.assetRegistry))return{...r,...n?.assetFailure===void 0?{}:{assetFailure:n.assetFailure},...n?.onDiagnostic===void 0?{}:{onDiagnostic:n.onDiagnostic},assetRegistry:n?.assetRegistry??r?.assetRegistry,assetRenderers:{...r?.assetRenderers,...n?.assetRenderers},assetBudget:{...r?.assetBudget,...n?.assetBudget}}}function te(e,t){if(!e||e.code!=="missing-image"||e.format!=="pdf"&&e.format!=="xlsx")return!1;const r=pe(t,e.format);return typeof r?.assetRenderers?.[e.kind]=="function"||!!(e.extension&&r?.assetRegistry?.hasExtension(e.extension.id,e.extension.version,e.kind))}function Be(e,t){const r=ce.reviewReportTemplate(e,t),n=r.issues.filter(s=>!te(s.diagnostic,t)),o=r.samples.map(s=>({...s,diagnostics:s.diagnostics.filter(a=>!te(a,t))}));return{...r,issues:n,samples:o,ok:n.every(s=>s.severity!=="error"),artifacts:[]}}async function $e(e,t,r,n,o){const s=H.createReportRuntime({reports:{sample:{template:r,datasets:e.datasets}},assets:pe(n,t),budget:{maxRows:n.maxSampleRows??1e3,maxPages:n.maxPages??100,maxCells:n.maxCells??25e4,maxOutputBytes:n.maxOutputBytes??2e7,maxDurationMs:n.maxDurationMs??3e4}});try{const{result:a,digest:u}=await p.controlled(n.signal,n.maxDurationMs??3e4,async f=>{const c=await s.export({reportIds:["sample"],params:e.params,format:t,signal:f,fidelity:n.strictOutputs?"strict":"warn",pdf:n.pdf,xlsx:n.xlsx}),i=c.diagnostics.filter(l=>l.severity!=="info");if(n.strictOutputs&&i.length)throw new Error(`Strict ${t} encoding found fidelity issues: ${i.slice(0,3).map(l=>l.message).join("; ")}`);const d=await n.digest?.(c.bytes);return p.throwIfAborted(f),await n.onArtifact?.(e.name,c),p.throwIfAborted(f),{result:c,digest:d}});o.artifacts.push({fixture:e.name,format:t,bytes:a.bytes.byteLength,pages:a.stats.pages,...u?{digest:u}:{}}),o.issues.push(...a.diagnostics.map(f=>({code:"output",severity:n.strictOutputs||f.severity==="error"?"error":"warning",path:"$.template",fixture:e.name,message:`${t}: ${f.message}`})))}catch(a){p.throwIfAborted(n.signal),o.issues.push({code:"output",severity:"error",path:"$.template",fixture:e.name,message:`${t}: ${a instanceof Error?a.message:String(a)}`})}}async function Me(e,t={}){p.throwIfAborted(t.signal);const r=Be(e,t);if(!r.ok)return r;const n=O.parseReportTemplate(e).template,o=[...new Set(t.formats??["pdf","xlsx"])];if(!o.length||o.some(s=>s!=="pdf"&&s!=="xlsx"))return r.issues.push({code:"output",severity:"error",path:"$.formats",message:"真实文件验收应至少选择PDF/XLSX之一"}),r.ok=!1,r;for(const s of t.fixtures??[])for(const a of o)p.throwIfAborted(t.signal),!(a!=="pdf"&&a!=="xlsx")&&await $e(s,a,n,t,r);return r.ok=r.issues.every(s=>s.severity!=="error"),r}class v extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportInstanceError"}}function j(e,t){if(typeof e!="string"||!e.trim()||e.length>256||typeof t!="string"||t!==t.trim()||!/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/.test(t))throw new v("input","实例范围应非空,ID 应为安全标识")}function De(e,t){const r=Object.getPrototypeOf(e);if(r!==(t?Array.prototype:Object.prototype)&&!(r===null&&!t)||Object.getOwnPropertySymbols(e).length)throw new v("input","实例应为普通 JSON 对象");if(t&&Object.keys(e).some(o=>o!==String(Number(o))||!Number.isSafeInteger(Number(o))||Number(o)<0||Number(o)>=e.length))throw new v("input","实例数组不能包含额外属性");if(Object.getOwnPropertyNames(e).filter(o=>!(t&&o==="length")).length!==Object.keys(e).length)throw new v("input","实例不能包含不可枚举属性")}function Ce(e){if(!Number.isSafeInteger(e.revision)||e.revision<1||typeof e.title!="string"||!e.title.trim()||e.title.length>512)throw new v("input","实例修订或标题无效");if(typeof e.generatedAt!="string"||!Number.isFinite(Date.parse(e.generatedAt))||new Date(e.generatedAt).toISOString()!==e.generatedAt)throw new v("input","实例生成时间应为 ISO UTC 字符串");if(!Array.isArray(e.reportIds)||!e.reportIds.length||e.reportIds.length>100||e.reportIds.some(t=>typeof t!="string"||!t.trim())||new Set(e.reportIds).size!==e.reportIds.length)throw new v("input","实例报表 ID 应非空且唯一")}function qe(e){return e===null||typeof e=="boolean"||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function we(e,t){if(!Number.isSafeInteger(t)||t<1)throw new v("input","实例快照字节预算应为正安全整数");let r=0,n=0;const o=new Set;function s(u,f){if(++r>1e6||f>64)throw new v("capacity","实例节点或嵌套深度超过预算");if(typeof u=="string"&&(n+=u.length,n>t))throw new v("capacity","实例文本超过预算");if(qe(u))return u;if(!u||typeof u!="object"||o.has(u))throw new v("input","实例只允许无循环的有限 JSON 值");const c=Array.isArray(u);De(u,c),o.add(u);const i=Object.create(null);for(const d of Object.keys(u)){if(n+=d.length,n>t)throw new v("capacity","实例文本超过预算");const l=Object.getOwnPropertyDescriptor(u,d);if(l.get||l.set||["__proto__","constructor","prototype"].includes(d))throw new v("input","实例不能包含访问器或危险键");l.value!==void 0&&(i[d]=s(l.value,f+1))}if(o.delete(u),c){if(Object.keys(i).length!==u.length)throw new v("input","实例数组不能稀疏或包含额外属性");return Array.from({length:u.length},(d,l)=>i[String(l)])}return i}const a=JSON.stringify(s(e,0));if(new TextEncoder().encode(a).byteLength>t)throw new v("capacity","实例快照超过单条字节预算");return a}function F(e,t=8e6){const r=JSON.parse(we(e,t));j(r.scope,r.id);const n=new Set(["scope","id","revision","title","generatedAt","reportIds","params","templateRevisions","sourceRevisions","plan","artifacts","output"]);if(Object.keys(r).some(s=>!n.has(s)))throw new v("input","实例包含未知字段");Ce(r);for(const s of[r.params,r.templateRevisions,r.sourceRevisions])if(!s||typeof s!="object"||Array.isArray(s)||Object.values(s).some(a=>typeof a!="string"))throw new v("input","实例参数和修订应为字符串字典");if(r.reportIds.some(s=>!r.templateRevisions[s]))throw new v("input","每张报表都应记录生成时的模板修订");const o=O.validateRenderPlan(r.plan);if(!o.ok)throw new v("input",`实例渲染计划无效:${o.errors[0]?.path}`);if(r.output!==void 0){if(!r.output||Object.keys(r.output).some(s=>!["stats","diagnostics","layout","sources"].includes(s)))throw new v("input","实例输出元数据只允许统计、诊断和字体度量;不保存来源令牌");if(M.validatePreparedMetadata({...r.output,plan:r.plan,revisions:{}}),r.output.sources?.some(s=>"sourceToken"in s))throw new v("input","实例来源清单不保存来源令牌")}return r.artifacts!==void 0&&ze(r.artifacts),r}function ze(e){if(!Array.isArray(e)||e.length>100)throw new v("input","实例文件列表无效");const t=new Set;for(const r of e){if(!r||typeof r.key!="string"||!r.key.trim()||r.key.length>1024||t.has(r.key)||!["pdf","xlsx"].includes(r.format)||!Number.isSafeInteger(r.bytes)||r.bytes<0||r.sha256!==void 0&&(typeof r.sha256!="string"||r.sha256.length!==64||!/^[a-f0-9]{64}$/i.test(r.sha256)))throw new v("input","实例文件应包含唯一存储键、格式、大小和可选 SHA256");t.add(r.key)}}function me(e){const{scope:t,id:r,revision:n,title:o,generatedAt:s,reportIds:a,params:u,templateRevisions:f,sourceRevisions:c}=e;return JSON.parse(JSON.stringify({scope:t,id:r,revision:n,title:o,generatedAt:s,reportIds:a,params:u,templateRevisions:f,sourceRevisions:c}))}function _e(e){const t={maxInstances:100,maxRevisions:20,maxBytes:64e6,maxSnapshotBytes:8e6,...e};if(Object.values(t).some(r=>!Number.isSafeInteger(r)||r<1))throw new v("input","实例存储预算应为正安全整数");return t}function Le(e={}){const t=_e(e),r=new Map;let n=0;return{read:async(o,s,a,u)=>{p.throwIfAborted(u),j(o,s);const f=r.get(JSON.stringify([o,s])),c=f?.get(a??f.size);return c?F(c,t.maxSnapshotBytes):void 0},list:async(o,s={})=>{p.throwIfAborted(s.signal),j(o,"list");const a=s.limit??25;if(!Number.isSafeInteger(a)||a<1||a>100)throw new v("input","实例每页数量应为 1–100");const u=Array.from(r.values(),f=>f.get(f.size)).filter(f=>f.scope===o&&(!s.after||f.id>s.after)&&(!s.reportId||f.reportIds.includes(s.reportId))).sort((f,c)=>f.id<c.id?-1:1).slice(0,a+1);return{items:u.slice(0,a).map(me),...u.length>a?{next:u[a-1].id}:{}}},compareAndSwap:async(o,s,a,u,f)=>{p.throwIfAborted(f),j(o,s);const c=F(u,t.maxSnapshotBytes);if(c.scope!==o||c.id!==s||c.revision!==(a??0)+1)throw new v("input","实例身份或修订不一致");const i=JSON.stringify([o,s]),d=r.get(i)??new Map;if((d.size||null)!==a)return!1;const l=new TextEncoder().encode(JSON.stringify(c)).byteLength;if(d.size>=t.maxRevisions||n+l>t.maxBytes||!d.size&&r.size>=t.maxInstances)throw new v("capacity","实例存储达到预算,请使用持久化归档策略或显式调整容量");return d.set(c.revision,c),r.set(i,d),n+=l,!0}}}function ye(e,t={}){const r=t.maxSnapshotBytes??8e6;if(!Number.isSafeInteger(r)||r<1)throw new v("input","实例快照字节预算应为正安全整数");return{read:e.read.bind(e),list:e.list.bind(e),save:async(n,o)=>{const s=o.expectedRevision;if(s!==null&&(!Number.isSafeInteger(s)||s<1||s>=Number.MAX_SAFE_INTEGER))throw new v("input","实例预期修订无效");const a=JSON.parse(we(n,r)),u=F({...a,revision:(s??0)+1},r);if(p.throwIfAborted(o.signal),!await e.compareAndSwap(u.scope,u.id,s,u,o.signal))throw new v("conflict","实例已存在或已变化,请显式确认修订后保存");return u}}}function Fe(e,t){return h.serializeJobJson({reportIds:e,params:t})}function Ve(e){if(!e||typeof e!="object"||Object.getOwnPropertySymbols(e).length)throw new v("input","生成请求应为普通对象");const t=Object.create(null);let r;const n=new Set(["scope","id","title","reportIds","params","expectedRevision","signal"]);for(const o of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,o);if(!n.has(o)||!s.enumerable||s.get||s.set)throw new v("input","生成请求不能包含未知字段或访问器");o==="signal"?r=s.value:s.value!==void 0&&(t[o]=s.value)}return{signal:r,request:JSON.parse(h.serializeJobJson(t))}}function he(e){const t=JSON.parse(h.serializeJobJson(e.templateRevisions)),r=M.snapshotPdfFonts(e.pdf),n=ye(e.instances,{maxSnapshotBytes:e.maxSnapshotBytes});return{async generate(o){const{signal:s,request:a}=Ve(o);if(j(a.scope,a.id),a.expectedRevision!==null&&(!Number.isSafeInteger(a.expectedRevision)||a.expectedRevision<1))throw new v("input","实例预期修订无效");const u=e.runtime.validate(a);if(!u.ok)throw new fe.ReportParamValidationError(u.issues);const f=Object.create(null);for(const g of a.reportIds){if(typeof t[g]!="string"||!t[g])throw new TypeError(`报表 ${g} 缺少生成时的模板修订`);f[g]=t[g]}if(p.throwIfAborted(s),((await e.instances.read(a.scope,a.id,void 0,s))?.revision??null)!==a.expectedRevision)throw new v("conflict","实例已存在或已变化,请显式确认修订后生成");const i=await e.runtime.prepare({reportIds:a.reportIds,params:u.values,pdf:r,signal:s});p.throwIfAborted(s);const d=Object.create(null);for(const[g,R]of Object.entries(i.revisions))R.revision!==void 0&&(d[g]=R.revision);const{plan:l,revisions:w,sources:m,...b}=i,y={...b,...m?{sources:m.map(({sourceToken:g,...R})=>R)}:{}};return n.save({scope:a.scope,id:a.id,title:a.title,reportIds:a.reportIds,params:u.values,templateRevisions:f,sourceRevisions:d,generatedAt:(e.now?.()??new Date).toISOString(),plan:l,output:y},{expectedRevision:a.expectedRevision,signal:s})},read:n.read,list:n.list,async exportInstance(o){const{scope:s,id:a,revision:u,signal:f,format:c,fidelity:i,taskId:d,correlationId:l,onEvent:w}=o,m=M.snapshotPdfFonts(o.pdf??r),b=M.snapshotXlsxOptions(o.xlsx);j(s,a),p.throwIfAborted(f);const y=await n.read(s,a,u,f);if(!y)throw new v("input","报表实例不存在");const g={plan:y.plan,revisions:Object.fromEntries(y.reportIds.map(R=>[R,{revision:y.sourceRevisions[R]}])),diagnostics:[{code:"instance-row-count",severity:"info",message:"历史实例未保存原始取数行数;本次 rows 统计为 0,页面及单元格数由已保存计划校验。"}],stats:{rows:0,pages:y.plan.pages.length,cells:0,durationMs:0},...y.output};return e.runtime.exportPrepared({prepared:g,format:c,fidelity:i,pdf:m,xlsx:b,signal:f,taskId:d,correlationId:l,onEvent:w})},save:n.save}}function z(e,t,r){if(!Number.isSafeInteger(e)||e<1||e>t)throw new RangeError(`${r} 应为 1–${t} 的安全整数`);return e}function re(e){if(!e||typeof e.key!="string"||!e.key.trim()||e.key.length>1024||!["pdf","xlsx"].includes(e.format)||!Number.isSafeInteger(e.bytes)||e.bytes<0||e.sha256!==void 0&&!/^[a-f0-9]{64}$/i.test(e.sha256))throw new TypeError("分批归档回执应包含存储键、格式、大小和可选 SHA256");return{key:e.key,format:e.format,bytes:e.bytes,...e.sha256?{sha256:e.sha256}:{}}}function He(e){if(!O.validateReportTemplate(e).ok||!e.repeat)throw new TypeError("分批生成仅支持有效的逐记录固定标签模板");return JSON.parse(JSON.stringify(e))}function Ue(e){const t=new Set,r=e.repeat;r.rowKey&&t.add(r.rowKey),typeof r.copies=="object"&&t.add(r.copies.field);const n=o=>{o.binding&&t.add(o.binding.field);for(const s of o.grid?.cells??[])for(const a of s)a?.children?.forEach(n)};return e.pages.forEach(o=>o.components.forEach(s=>n(s))),[...t]}function Ke(e,t,r,n){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError(`标签记录 ${n} 应为对象`);const o=Object.create(null);for(const s of t){const a=de.readRecordScalar(e,s,{dataset:r,rowIndex:n});if(typeof a=="string"&&a.length>1e6)throw new p.ReportRuntimeError("budget","标签字段超过 1 MB 字符预算",`$.datasets.${r}[${n}].${s}`);a!==void 0&&(o[s]=a)}return o}function Ze(e,t,r,n){const o=t.repeat;if(!o.rowKey)return;const s=de.readRecordScalar(e,o.rowKey,{rowIndex:n,dataset:o.dataset});if(!(typeof s=="string"&&s.trim()||typeof s=="number"&&Number.isFinite(s)))throw new TypeError(`标签记录 ${n} 的业务主键无效`);const a=JSON.stringify([typeof s,s]);if(r.keys.has(a))throw new TypeError(`标签记录 ${n} 的业务主键重复(包含先前批次)`);r.bytes+=a.length*2+64,r.keys.add(a)}function Xe(e){return Object.entries(e).reduce((t,[r,n])=>t+64+r.length*2+(typeof n=="string"?n.length*2:8),0)}function Ge(e,t){if(!t)return e;for(const r of e.plan.pages){const n=r.meta?.record;n&&typeof n=="object"&&"rowIndex"in n&&typeof n.rowIndex=="number"&&(n.rowIndex+=t)}return e}async function Qe(e,t){if(!e.return)return;const r=Promise.resolve(e.return());if(t.aborted){r.catch(()=>{});return}await p.controlled(t,void 0,()=>r)}async function ne(e,t,r){const n=Promise.resolve().then(()=>e.onReceipt?.(t,r));n.catch(()=>{}),await p.controlled(r.signal,void 0,()=>n)}function We(e,t,r){return new Promise((n,o)=>{let s=!1,a=!1,u;const f=()=>{clearTimeout(u),t.removeEventListener("abort",c)},c=()=>{s||u!==void 0||(u=setTimeout(()=>{if(!s){s=!0,a=!0,f();try{p.throwIfAborted(t)}catch(i){o(i)}}},0))};e.then(i=>{if(a){Promise.resolve().then(()=>r(i)).catch(()=>{});return}s||(s=!0,f(),n(i))},i=>{s||(s=!0,f(),o(i))}),t.addEventListener("abort",c,{once:!0}),t.aborted&&c()})}async function Ye(e,t){const r=z(t.batchSize??100,1e3,"batchSize"),n=z(t.maxRows??1e5,1e6,"maxRows"),o=z(t.maxChunks??1e3,1e4,"maxChunks"),s=z(t.maxRetainedBytes??16e6,64e6,"maxRetainedBytes"),a=He(t.template),u=Ue(a);if(!e||typeof e[Symbol.asyncIterator]!="function")throw new TypeError("标签来源应为 AsyncIterable");return p.controlled(t.signal,t.runtime?.budget?.maxDurationMs??12e4,async f=>{const c={rows:0,chunks:[]},i={keys:new Set,bytes:0},d=e[Symbol.asyncIterator]();let l=!1,w=!1,m;const b=()=>m??=Qe(d,f),y=()=>{l||b().catch(()=>{})};f.addEventListener("abort",y,{once:!0});try{for(;!l;){p.throwIfAborted(f);const g=[];let R=0;for(;g.length<r;){const x=await p.controlled(f,void 0,()=>Promise.resolve(d.next()));if(x.done){l=!0;break}if(c.rows+g.length>=n)throw new p.ReportRuntimeError("budget","标签来源行数超过预算","$.maxRows");if(c.chunks.length>=o)throw new p.ReportRuntimeError("budget","标签分块数量超过预算","$.maxChunks");const S=Ke(x.value,u,a.repeat.dataset,c.rows+g.length);if(Ze(S,a,i,c.rows+g.length),R+=Xe(S),i.bytes+R>s)throw new p.ReportRuntimeError("budget","标签当前块字段与全局主键索引超过内存预算","$.maxRetainedBytes");g.push(S)}if(!g.length)break;const P=H.createReportRuntime({...t.runtime,reports:{labels:{template:a,datasets:{[a.repeat.dataset]:g}}}});let N;const E={index:c.chunks.length,rowOffset:c.rows,rowCount:g.length,signal:f,export:x=>P.exportPrepared({pdf:t.pdf,...x,prepared:N,signal:f})};let $;const T=(await h.runReportBatch([{id:`labels-${E.index}`,params:{}}],async()=>{try{N=Ge(await P.prepare({reportIds:["labels"],pdf:t.pdf,signal:f}),E.rowOffset),p.throwIfAborted(f);const x=Promise.resolve(t.execute(N,E)),S=await We(x,f,A=>ne(t,re(A),E));return re(S)}catch(x){throw $=x,x}},{concurrency:1,signal:f,failure:"stop"}))[0];if(T.status==="cancelled")throw p.throwIfAborted(f),new Error("标签分批任务已取消");if(T.status==="failed")throw $??new Error(T.error.message);c.chunks.push({...T.value,index:E.index,rowOffset:E.rowOffset,rowCount:E.rowCount}),c.rows+=g.length,await ne(t,T.value,E)}return c}catch(g){throw w=!0,g}finally{f.removeEventListener("abort",y),l||await b().catch(g=>{if(!w)throw g})}})}async function ge(e,t){const r=t.document().id,n=()=>t.editor.saving||t.editor.blocked;if(n())throw new Error("草稿尚未保存,请处理设计器提示后再发布");if(t.editor.pendingLocalChanges){const s=t.successfulSaves();if(await t.editor.save(),await t.afterSave(),t.successfulSaves()===s||t.editor.pendingLocalChanges||n())throw new Error("草稿尚未保存,请处理设计器提示后再发布")}const o=t.document();if(o.id!==r)throw new v("conflict","当前模板已切换,请重新确认后发布");return e.publish(o.id,{expectedRevision:o.revision??null})}function be(e,t){return{async search(r){p.throwIfAborted(r.signal);const n=await e.list(r.signal);if(n.length>1e3)throw new RangeError("本地模板连接目录最多 1000 项;更大目录请使用宿主分页查询适配器");const o=[];for(const s of n){p.throwIfAborted(r.signal);const[a,u]=await Promise.all([e.get(s.id,{draft:!0,signal:r.signal}),e.get(s.id,{signal:r.signal})]),f=a??u;f&&o.push({document:f,published:u,draftRevision:a?.revision,publishedRevision:u?.revision,...t?.(O.parseReportTemplate(f))})}return ce.createLocalTemplateCatalog(o).search(r)},async get(r,n){return n.mode==="published"?e.get(r,{signal:n.signal}):await e.get(r,{draft:!0,signal:n.signal})??e.get(r,{signal:n.signal})}}}function ve(e=1e3){if(!Number.isSafeInteger(e)||e<1||e>1e3)throw new RangeError("本地生成意图上限应为 1–1000");const t=new Map,r=globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;return{forCase(n,o){if(![n,o].every(f=>typeof f=="string"&&f.length>0&&f.length<=256))throw new TypeError("模板与参数组标识无效");const s=JSON.stringify([n,o]),a=t.get(s);if(a)return a;if(t.size>=e)throw new RangeError("本地生成意图已达上限,请使用持久化任务服务");const u=`instance-${r}-${(t.size+1).toString(36)}`;return t.set(s,u),u}}}function et(e,t,r){const n=Object.keys(r);return e.reportIds.length===1&&e.reportIds[0]===t.id&&Object.keys(e.templateRevisions).length===1&&e.templateRevisions[t.id]===t.revision&&Object.keys(e.params).length===n.length&&n.every(o=>r[o]===e.params[o])}function oe(e){return{instanceId:e.id,label:e.title}}function tt(e,t,r){const n=O.parseReportTemplate(e);if(!n.revision)throw new Error("请先发布该模板");const o=typeof t.data=="function"?t.data(O.parseReportTemplate(n)):t.data,s=H.createReportRuntime({...t.runtime,reports:{[n.id]:{...o,template:n.template}}}),a=he({runtime:s,instances:t.instances,templateRevisions:{[n.id]:n.revision},pdf:t.pdf});async function u(f,c,i){p.throwIfAborted(i);const d=await t.instances.read(t.scope,f,void 0,i);if(p.throwIfAborted(i),!!d){if(!et(d,n,c))throw new v("conflict","此参数组已用于其他参数或发布修订,请复制为新任务生成");return oe(d)}}return{document:O.parseReportTemplate(n),async execute(f,{signal:c}){p.throwIfAborted(c);const i=s.validate({reportIds:[n.id],params:f.params});if(!i.ok)throw new Error(i.issues[0]?.message??"生成参数无效");const d=r(n.id,f.id),l=await u(d,i.values,c);if(l)return l;try{return oe(await a.generate({scope:t.scope,id:d,title:(t.title?.(O.parseReportTemplate(n),f,i.values)??`${n.name} · ${f.id}`).slice(0,512),reportIds:[n.id],params:i.values,expectedRevision:null,signal:c}))}catch(w){if(w instanceof v&&w.code==="conflict"){const m=await u(d,i.values,c);if(m)return m}throw w}}}}function rt(e){e={...e};const t=ve(),r=e.instanceId??t.forCase;return{catalog:e.catalog??be(e.templates,e.catalogMetadata),publish:n=>ge(e.templates,n),async batch(n,o={}){const{expectedRevision:s,signal:a}=o,u=await e.templates.get(n,{signal:a});if(p.throwIfAborted(a),!u?.revision)throw new Error("请先发布该模板");if(s!==void 0&&u.revision!==s)throw new v("conflict","模板发布版本已变化,请重新打开后生成");return tt(u,e,r)}}}const Re="2.25.0";function U(e,t){const r=t?.componentPath;if(!Number.isSafeInteger(t?.pageIndex)||t.pageIndex<0||!Array.isArray(r)||r.length<1||r.length>31||r.length%3!==1||r.some(o=>!Number.isSafeInteger(o)||o<0))throw new TypeError("模板包图片位置无效");let n=e.template.pages[t.pageIndex]?.components[r[0]];for(let o=1;n&&o<r.length;o+=3)n=n.grid?.cells[r[o]]?.[r[o+1]]?.children?.[r[o+2]];if(!n||n.kind!=="image"||n.binding)throw new TypeError("模板包图片位置应指向静态图片组件");return n}function nt(e){const t=["id","kind","mediaType","bytes","sha256","license","font","targets"];if(!e||Object.keys(e).some(r=>!t.includes(r)))throw new TypeError("模板资源包含未知字段");if(typeof e.id!="string"||!/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/.test(e.id))throw new TypeError("模板资源ID应为安全标识");if(!Number.isSafeInteger(e.bytes)||e.bytes<1||e.bytes>32e6||!/^[a-f0-9]{64}$/.test(e.sha256))throw new TypeError("模板资源大小或SHA256无效");if(e.license!==void 0&&(typeof e.license!="string"||e.license.length>512))throw new TypeError("模板资源许可说明无效")}function ot(e,t){if(nt(e),e.kind==="font"){if(!["font/ttf","font/otf"].includes(e.mediaType)||e.targets!==void 0)throw new TypeError("字体资源类型无效");const r=e.font;if(!r||typeof r.family!="string"||!r.family.trim()||r.family.length>128||!["regular","bold","italic","boldItalic"].includes(r.face)||Object.keys(r).some(n=>!["family","face"].includes(n)))throw new TypeError("字体资源需要family和face");return}if(e.kind!=="image"||!["image/png","image/jpeg"].includes(e.mediaType)||e.font!==void 0)throw new TypeError("模板图片仅支持PNG/JPEG");if(!Array.isArray(e.targets)||!e.targets.length||e.targets.length>1e3)throw new TypeError("模板图片需要1–1000个位置");for(const r of e.targets){if(Object.keys(r).some(n=>!["pageIndex","componentPath"].includes(n)))throw new TypeError("模板图片位置包含未知字段");U(t,r)}}function st(e,t){const r=n=>n.every((o,s)=>e[s]===o);return t==="image/png"?r([137,80,78,71,13,10,26,10]):t==="image/jpeg"?r([255,216,255]):t==="font/otf"?r([79,84,84,79]):r([0,1,0,0])||r([116,114,117,101])}function Ie(e){if(!(e instanceof Uint8Array)||!e.byteLength||e.byteLength>32e6)throw new RangeError("资源摘要只接受1–32MB字节");return p.portableSha256Hex(e)}function Se(e,t,r=le.createImageMediaInspector()){const n=new Set(t.flatMap(a=>(a.targets??[]).map(u=>U(e,u)))),o=new Map,s=a=>{if(a.imageData&&!n.has(a)){const u=r(a.imageData);o.set(u.dataUrl,u.bytes.byteLength)}for(const u of a.grid?.cells??[])for(const f of u)for(const c of f?.children??[])s(c)};for(const a of e.template.pages)for(const u of a.components)s(u);return[...o.values()].reduce((a,u)=>a+u,0)}function at(e,t){let r="";for(let n=0;n<e.length;n+=16384)r+=String.fromCharCode(...e.subarray(n,n+16384));return`data:${t};base64,${btoa(r)}`}async function it(e,t,r,n,o=3e4){if(!Number.isFinite(o)||o<1||o>2147483647)throw new RangeError("模板资源加载超时应为1–2147483647毫秒");return p.controlled(n,o,async s=>{const a=[],u=le.createImageMediaInspector();Se(e,t,u);for(const f of t){p.throwIfAborted(s);const c=await p.controlled(s,void 0,()=>Promise.resolve(r(JSON.parse(JSON.stringify(f)),{signal:s})));if(p.throwIfAborted(s),!c||!(c.bytes instanceof Uint8Array)||c.mediaType!==f.mediaType||c.bytes.byteLength!==f.bytes)throw new TypeError(`资源 ${f.id} 的类型或大小与清单不一致`);const i=new Uint8Array(c.bytes);if(!st(i,f.mediaType)||Ie(i)!==f.sha256)throw new TypeError(`资源 ${f.id} 的文件标识或SHA256与清单不一致`);if(f.kind==="font")a.push({id:f.id,family:f.font.family,face:f.font.face,bytes:i});else{const d=u(at(i,f.mediaType)).dataUrl;for(const l of f.targets)U(e,l).imageData=d}}return a})}function se(e){if(typeof e!="string"||!/^(0|[1-9]\d{0,5})\.(0|[1-9]\d{0,5})\.(0|[1-9]\d{0,5})$/.test(e))throw new TypeError("模板包最低版本与运行版本应为正式版本x.y.z");return e.split(".").map(Number)}function ct(e,t){const r=se(e),n=se(t);for(let o=0;o<3;o++){if(n[o]>r[o])return;if(n[o]<r[o])throw new Error(`模板包需要MachReport ${e}或更新版本`)}}function X(e,t,r){const n=e??t;if(!Number.isSafeInteger(n)||n<1||n>r)throw new RangeError("模板包字节预算无效");return n}function ft(e){if(e.contracts!==void 0){if(!e.contracts||typeof e.contracts!="object"||Array.isArray(e.contracts)||Object.keys(e.contracts).length>100)throw new TypeError("模板包字段契约应为最多100个数据集");for(const[t,r]of Object.entries(e.contracts)){if(!t.trim()||t.length>256)throw new TypeError("模板包数据集名称无效");ue.validateDatasetRows([],r)}}}function dt(e,t){if(!e||e.deidentified!==!0||typeof e.name!="string"||!e.name.trim()||e.name.length>128)throw new TypeError("样例需要名称和明确的deidentified:true确认");if(Object.keys(e).some(n=>!["name","deidentified","datasets","params"].includes(n)))throw new TypeError("模板包样例包含未知字段");if(!e.datasets||typeof e.datasets!="object"||Array.isArray(e.datasets))throw new TypeError("模板包样例数据集无效");if(ut(e,t),!fe.validateReportParams(t.document.template.params??[],e.params).ok)throw new TypeError(`样例 ${e.name} 的参数不符合模板定义`)}function ut(e,t){let r=0;for(const o of Object.values(e.datasets))if(!Array.isArray(o)||o.some(s=>!s||typeof s!="object"||Array.isArray(s)))throw new TypeError("模板包样例应为对象行数组");const n=C.templateValidationDatasets(t.document.template,e.datasets,{maxRows:1e3});for(const[o,s]of Object.entries(n)){if(r+=s.length,r>1e3)throw new RangeError("模板包每个样例最多1000行");const a=t.contracts?.[o];if(a&&!ue.validateDatasetRows(s,a).ok)throw new TypeError(`样例 ${e.name} 不符合 ${o} 字段契约`)}for(const o of Object.keys(t.contracts??{}))if(!Object.prototype.hasOwnProperty.call(e.datasets,o))throw new TypeError(`样例 ${e.name} 缺少 ${o} 数据集`)}function lt(e){if(e.fixtures===void 0)return;if(!Array.isArray(e.fixtures)||e.fixtures.length>20)throw new RangeError("模板包最多20个脱敏样例");const t=new Set;for(const r of e.fixtures){if(dt(r,e),t.has(r.name))throw new TypeError("模板包样例名称重复");t.add(r.name)}}function pt(e,t){if(!Array.isArray(e.resources)||e.resources.length>64)throw new RangeError("模板包最多64个资源依赖");const r=new Set,n=new Set,o=new Set;let s=0;for(const a of e.resources){if(ot(a,e.document),r.has(a.id))throw new TypeError("模板资源ID重复");if(r.add(a.id),s+=a.bytes,s>t)throw new RangeError("模板包资源总大小超过预算");const u=a.font&&JSON.stringify([a.font.family,a.font.face]);if(u&&o.has(u))throw new TypeError("模板包字体family/face重复");u&&o.add(u);for(const f of a.targets??[]){const c=JSON.stringify([f.pageIndex,f.componentPath]);if(n.has(c))throw new TypeError("同一图片位置不能绑定多个资源");n.add(c)}}if(s+Se(e.document,e.resources)>t)throw new RangeError("模板包内嵌与外部资源总大小超过预算")}function G(e,t={}){p.throwIfAborted(t.signal);const r=X(t.maxBytes,8e6,32e6);if(typeof e=="string"){if(e.length>r||new TextEncoder().encode(e).byteLength>r)throw new RangeError("模板包JSON超过预算");e=JSON.parse(e)}const n=C.snapshotReportJson(e,{maxBytes:r,check:()=>p.throwIfAborted(t.signal),error:(o,s)=>new TypeError(s)});if(!n||typeof n!="object"||Array.isArray(n)||n.schemaVersion!=="1.0"||Object.keys(n).some(o=>!["schemaVersion","minimumVersion","document","contracts","resources","fixtures"].includes(o)))throw new TypeError("模板包结构或版本无效");return ct(n.minimumVersion,t.runtimeVersion??Re),n.document=O.parseReportTemplate(n.document),ft(n),lt(n),pt(n,X(t.maxResourceBytes,32e6,64e6)),n}function wt(e,t={}){const r=C.snapshotReportJson(e,{maxBytes:X(t.maxBytes,8e6,32e6),check:()=>p.throwIfAborted(t.signal),error:(o,s)=>new TypeError(s)}),n=G({schemaVersion:"1.0",...r,minimumVersion:r.minimumVersion??Re,resources:r.resources??[]},t);for(const o of n.resources)for(const s of o.targets??[])delete U(n.document,s).imageData;return n}async function mt(e,t){const{resolve:r,signal:n,maxDurationMs:o}=t,s=G(e,t),a=await it(s.document,s.resources,r,n,o);return{document:s.document,fonts:a,contracts:s.contracts,fixtures:s.fixtures??[]}}class I extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportDocumentError"}}function yt(e={}){const t={maxDocuments:e.maxDocuments??32,maxBytes:e.maxBytes??64e6,maxPages:e.maxPages??1e4,maxPageBytes:e.maxPageBytes??4e6,maxManifestBytes:e.maxManifestBytes??1e6};if(Object.values(t).some(r=>!Number.isSafeInteger(r)||r<1))throw new I("input","文档预算应为正安全整数");return t}function J(e,t,r){if([e,t,...r===void 0?[]:[r]].some(n=>typeof n!="string"||!n.trim()||n.length>256))throw new I("input","文档 scope、id、version 应为 1–256 位非空字符串");return JSON.stringify([e,t])}function k(e,t,r){return C.snapshotReportJson(e,{maxBytes:t,maxNodes:t,check:()=>p.throwIfAborted(r),error:(n,o)=>new I(n==="budget"?"capacity":"input",o)})}function B(e){return new TextEncoder().encode(JSON.stringify(e)).byteLength}function ae(e){if(!e||e.schemaVersion!==Ee.RENDER_PLAN_SCHEMA_VERSION||"pages"in e||e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean")throw new I("input","文档计划头应使用当前版本,且不得携带 pages")}function _(e,t){e.bytes=0;for(let r=0;r<8;r++){const n=t+B(e);if(n===e.bytes)return;e.bytes=n}throw new I("capacity","文档容量统计无效")}function ht(e,t,r=[]){const n=new Map;let o=0,s=Promise.resolve();for(const i of r){const d=J(i.scope,i.id,i.version);if(ae(i.plan),n.has(d)||!Number.isSafeInteger(i.bytes)||i.bytes<0||!Number.isSafeInteger(i.pageCount)||i.pageCount<0||i.pageCount>t.maxPages||!["building","complete","failed"].includes(i.state)||i.revision!==i.pageCount+(i.state==="building"?0:1))throw new I("input","文档清单无效");n.set(d,k(i,t.maxManifestBytes)),o+=i.bytes}function a(i,d){if(o-(d?.bytes??0)+i.bytes>t.maxBytes||!d&&n.size>=t.maxDocuments)throw new I("capacity","文档存储容量已满,请显式清理旧文档")}if(n.size>t.maxDocuments||o>t.maxBytes)throw new I("capacity","已存文档超过预算");const u=i=>{const d=s.then(i);return s=d.then(()=>{},()=>{}),d},f=(i,d,l,w)=>{const m=n.get(J(i,d,l));if(!m)throw new I("missing","文档不存在");if(m.version!==l||w!==void 0&&m.revision!==w)throw new I("conflict","文档已变化,请重新读取清单");return m},c=async(i,d,l)=>{const w=k(i,t.maxManifestBytes);return a(w,d),await e.write(w,l),n.set(J(i.scope,i.id),w),o+=i.bytes-(d?.bytes??0),k(w,t.maxManifestBytes)};return{create:(i,d)=>{const l=k(i,t.maxManifestBytes,d),w=J(l.scope,l.id,l.version);return ae(l.plan),u(async()=>{if(p.throwIfAborted(d),n.has(w))throw new I("conflict","文档已存在,不可覆盖");const m={...l,revision:0,state:"building",pageCount:0,bytes:0};return _(m,0),c(m)})},append:(i,d,l,w,m,b)=>{const y=k(m,t.maxPageBytes,b),g=O.validateRenderPlan({pages:[y]});if(!g.ok)throw new I("input",g.errors[0].message);return u(async()=>{p.throwIfAborted(b);const R=f(i,d,l,w);if(R.state!=="building")throw new I("conflict","已完成文档不可追加");if(R.pageCount>=t.maxPages)throw new I("capacity","文档页数超过预算");const P={...R,revision:w+1,pageCount:R.pageCount+1};return _(P,R.bytes-B(R)+B(y)),c(P,R,{index:R.pageCount,value:y})})},complete:(i,d,l,w,m,b)=>{const y=m===void 0?void 0:k(m,t.maxManifestBytes,b);return y&&M.validatePreparedMetadata({...y}),u(async()=>{p.throwIfAborted(b);const g=f(i,d,l,w);if(g.state!=="building")throw new I("conflict","文档已完成");if(y&&y.stats.pages!==g.pageCount)throw new I("input","准备结果页数与文档页数不一致");const R={...g,revision:w+1,state:"complete",...y?{metadata:y}:{}};return _(R,g.bytes-B(g)),c(R,g)})},fail:(i,d,l,w,m)=>{const b=k(m,4096);if(!b||!["cancelled","generation"].includes(b.code)||typeof b.message!="string"||!b.message.trim()||b.message.length>1024)throw new I("input","文档失败状态无效");return u(async()=>{const y=f(i,d,l,w);if(y.state!=="building")throw new I("conflict","终态文档不可变更");const g={...y,state:"failed",revision:w+1,failure:b};return _(g,y.bytes-B(y)),c(g,y)})},read:async(i,d,l)=>{p.throwIfAborted(l);const w=J(i,d);await s,p.throwIfAborted(l);const m=n.get(w);return m?k(m,t.maxManifestBytes):void 0},readPage:(i,d,l,w,m)=>u(async()=>{p.throwIfAborted(m);const b=f(i,d,l);if(!Number.isSafeInteger(w)||w<0)throw new I("input","页索引应为非负安全整数");if(w>=b.pageCount)return;const y=await e.readPage(i,d,w);if(p.throwIfAborted(m),!y)throw new I("missing","已提交的文档页缺失");return k(y,t.maxPageBytes,m)}),remove:(i,d,l,w)=>u(async()=>{p.throwIfAborted(w);const m=J(i,d,l),b=n.get(m);return b?(f(i,d,l),await e.remove(b),n.delete(m),o-=b.bytes,!0):!1})}}function gt(e={}){const t=new Map;return ht({write:async(r,n)=>{if(!n)return;const o=J(r.scope,r.id),s=t.get(o)??[];s[n.index]=n.value,t.set(o,s)},readPage:async(r,n,o)=>t.get(J(r,n))?.[o],remove:async r=>{t.delete(J(r.scope,r.id))}},yt(e))}async function bt(e,t){const r=t.fromPage??0,n=t.limit??4,o=t.maxBytes??8e6;if(!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(n)||n<1||n>32||!Number.isSafeInteger(o)||o<1)throw new I("input","页窗口参数无效;每次最多读取 32 页");const s=await e.read(t.scope,t.id,t.signal);if(!s)throw new I("missing","文档不存在");if(s.version!==t.version)throw new I("conflict","文档版本已变化");const a=[];let u=0,f=Math.min(r,s.pageCount);for(;f<Math.min(s.pageCount,r+n);f++){const c=await e.readPage(t.scope,t.id,t.version,f,t.signal);if(!c)throw new I("missing","文档页缺失");const i=B(c);if(u+i>o){if(!a.length)throw new I("capacity","单页超过读取窗口预算");break}a.push(c),u+=i}return{manifest:s,pages:a,nextPage:f}}async function vt(e,t){const{scope:r,id:n,version:o,signal:s,pages:a}=t,u=t.metadata===void 0?void 0:k(t.metadata,1e6,s);let f=await e.create({scope:r,id:n,version:o,plan:t.plan},s),c;try{const i=Symbol.asyncIterator in a?a[Symbol.asyncIterator]():a[Symbol.iterator]();for(c=i;;){const d=await p.controlled(s,void 0,()=>Promise.resolve(i.next()));if(d.done)break;f=await e.append(r,n,o,f.revision,d.value,s)}return await e.complete(r,n,o,f.revision,u,s)}catch(i){throw Promise.resolve(c?.return?.()).catch(()=>{}),await e.fail(r,n,o,f.revision,s?.aborted?{code:"cancelled",message:"报表文档生成已取消"}:{code:"generation",message:"报表文档生成失败"}).catch(()=>{}),i}}const xe="1.0",ie=Object.freeze({params:422,validate:422,fetch:502,config:400,input:400,budget:413,capacity:413,timeout:504,"queue-full":429,closed:503,cancelled:499,"output-fidelity":422,conflict:409,missing:404});function V(e){return e&&typeof e=="object"?e:{}}function Rt(e){if(Array.isArray(e))return e.slice(0,100).map(t=>Object.fromEntries(["code","path","field","message"].flatMap(r=>typeof V(t)[r]=="string"?[[r,V(t)[r].slice(0,4096)]]:[])))}function It(e,t){const r=V(e),n=r.name==="AbortError"?"cancelled":r.code,o=typeof n=="string"&&Object.prototype.hasOwnProperty.call(ie,n)?n:"internal",s=o==="internal"?void 0:Rt(r.issues??V(r.cause).issues);return{status:ie[o]??500,body:{error:{code:o,message:o==="internal"?"Report execution failed":typeof r.message=="string"?r.message.slice(0,4096):"Report request failed",correlationId:t.slice(0,128),...o!=="internal"&&typeof r.path=="string"?{path:r.path.slice(0,4096)}:{},...s?{issues:s}:{}}}}}function Z(e,t,r){return{description:r,headers:{"X-Request-Id":{schema:{type:"string"},description:"Request correlation identity"}},content:{[e]:{schema:t}}}}function St(e){return{type:"object",additionalProperties:!1,properties:Object.fromEntries(e.params.map(t=>[t.field,{type:"string"}])),required:e.params.filter(t=>t.required&&t.defaultValue===void 0).map(t=>t.field),"x-report-typedSchema":e.paramsSchema}}function xt(e,t={}){const r=t.basePath??"/reports";if(!/^\/[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(r))throw new Error("OpenAPI basePath 应为不含查询串、参数和尾斜线的绝对路径");const n={[r]:{get:{operationId:"describeReports",responses:{200:Z("application/json",{type:"array",items:{type:"object"}},"Authorized report descriptions")}}}},o=new Set;for(const s of e){if(!s.id.trim()||o.has(s.id)||[".",".."].includes(s.id))throw new Error("OpenAPI 报表 ID 应非空、唯一且不是路径跳转段");o.add(s.id);for(const a of["prepare","pdf","xlsx"]){const u=a==="prepare"?"prepare":`export/${a}`,f=a!=="prepare",c={200:Z(f?a==="pdf"?"application/pdf":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"application/json",f?{type:"string",format:"binary"}:{type:"object",required:["plan","stats","diagnostics","revisions"]},f?"Report file":"Prepared report snapshot")};for(const i of[400,413,422,429,499,500,502,503,504])c[String(i)]=Z("application/json",{$ref:"#/components/schemas/ReportError"},"Structured report error");n[`${r}/${encodeURIComponent(s.id)}/${u}`]={post:{operationId:`report_${o.size}_${a}`,parameters:[{in:"header",name:"X-Request-Id",schema:{type:"string",pattern:"^[A-Za-z0-9._-]{1,80}$"}}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["params"],additionalProperties:!1,properties:{params:St(s)}}}}},responses:c,"x-report-datasets":s.datasetsSchema}}}}return{openapi:"3.1.0",info:{title:t.title??"MachReport HTTP",version:t.version??xe},paths:n,components:{schemas:{ReportError:{type:"object",required:["error"],properties:{error:{type:"object",required:["code","message","correlationId"],properties:{code:{type:"string"},message:{type:"string"},correlationId:{type:"string"},path:{type:"string"},issues:{type:"array",items:{type:"object",additionalProperties:{type:"string"}}}}}}}}}}}exports.createReportRuntime=H.createReportRuntime;exports.ReportRuntimeError=p.ReportRuntimeError;exports.ReportJobError=h.ReportJobError;exports.checkJobIdentity=h.checkJobIdentity;exports.cloneJob=h.cloneJob;exports.createMemoryReportJobStore=h.createMemoryReportJobStore;exports.runReportBatch=h.runReportBatch;exports.runnableJob=h.runnableJob;exports.serializeJobJson=h.serializeJobJson;exports.snapshotReportBatchCases=h.snapshotReportBatchCases;exports.validateJobRecord=h.validateJobRecord;exports.validateJobTransition=h.validateJobTransition;exports.REPORT_HTTP_CONTRACT_VERSION=xe;exports.ReportDocumentError=I;exports.ReportInstanceError=v;exports.checkInstanceIdentity=j;exports.createManagerTemplateCatalog=be;exports.createMemoryReportDocumentStore=gt;exports.createMemoryReportInstanceIds=ve;exports.createMemoryReportInstanceStore=Le;exports.createReportGenerationService=he;exports.createReportInstanceManager=ye;exports.createReportJobService=Ne;exports.createReportOpenApi=xt;exports.createReportTaskQueue=Ae;exports.createReportTemplatePackage=wt;exports.createReportWorkflow=rt;exports.parseReportTemplatePackage=G;exports.readReportDocumentPages=bt;exports.reportHttpError=It;exports.reportInstanceParameterKey=Fe;exports.reportInstanceSummary=me;exports.reportPackageResourceDigest=Ie;exports.resolveReportTemplatePackage=mt;exports.reviewReportPublication=Me;exports.runLabelStream=Ye;exports.saveAndPublishReportTemplate=ge;exports.snapshotReportInstance=F;exports.writeReportDocument=vt;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const H=require("./runtime-BRx8Agqr.cjs"),p=require("./sha256-DgZAKXqI.cjs"),C=require("./json-snapshot-DCFEtfFw.cjs"),h=require("./batch-DYcokH4v.cjs"),ce=require("./template-catalog-Cj66M84u.cjs"),O=require("./template-registry-B-AK1oam.cjs"),M=require("./prepared-BlNeOjoO.cjs"),fe=require("./param-validation-C-8sRJLq.cjs"),de=require("./record-bindings-B7djSjNs.cjs"),ue=require("./dataset-IrlXbUvh.cjs"),le=require("./media-B7vnpD8k.cjs"),Ee=require("./diagnostic-collector-wASg6Fzs.cjs");function Ae(e={}){const t=e.concurrency??1,r=e.maxQueued??20;if(!Number.isSafeInteger(t)||t<1||!Number.isSafeInteger(r)||r<0)throw new p.ReportRuntimeError("budget","队列并发应为正整数,排队上限应为非负整数");const n=[],o=new Set,s=new Set;let a=!1,u=0;const f=()=>{for(;!a&&o.size<t&&n.length;)n.shift().start()};return{get active(){return o.size},get pending(){return n.length},enqueue:(i,d={})=>{if(a)throw new p.ReportRuntimeError("closed","任务队列已关闭");if(p.throwIfAborted(d.signal),o.size>=t&&n.length>=r)throw new p.ReportRuntimeError("queue-full","报表任务队列已满");const l=d.id??`report-${++u}`;if(s.has(l))throw new p.ReportRuntimeError("queue-full","任务 ID 正在执行或排队");const w=new AbortController;let m="queued",b,y,g,R;const P=new Promise((S,A)=>{g=S,R=A}),N=()=>{d.signal?.removeEventListener("abort",$),s.delete(l)},E=S=>{if(m!=="queued"&&m!=="running")return;const A=m==="queued";m="cancelled",w.abort(S);try{p.throwIfAborted(w.signal)}catch(q){R(q)}if(A){const q=n.indexOf(x);q>=0&&n.splice(q,1),N(),f()}},$=()=>E(d.signal?.reason),K=(S,A)=>{m==="running"&&(!Number.isFinite(S)||S<0||A!==void 0&&(!Number.isFinite(A)||A<S)||(b={completed:S,...A===void 0?{}:{total:A}}))},T=S=>{m!=="running"||w.signal.aborted||(y={...S,taskId:l},S.completed!==void 0&&K(S.completed,S.total),C.notifyReportTaskEvent(d.onEvent,y,w.signal))},x={cancel:E,start:()=>{m==="queued"&&(m="running",o.add(x),Promise.resolve().then(()=>(p.throwIfAborted(w.signal),i({taskId:l,signal:w.signal,reportProgress:K,onEvent:T}))).then(S=>{m==="running"&&(m="completed",g(S))},S=>{m==="running"&&(m="failed",R(S))}).finally(()=>{o.delete(x),N(),f()}))}};return s.add(l),d.signal?.addEventListener("abort",$,{once:!0}),d.signal?.aborted?E(d.signal.reason):o.size<t?x.start():n.push(x),{id:l,get status(){return m},get progress(){return b},get event(){return y},result:P,cancel:E}},close:(i={})=>{a=!0;for(const d of[...n])d.cancel(new p.ReportRuntimeError("closed","任务队列已关闭"));if(i.cancelRunning)for(const d of o)d.cancel(new p.ReportRuntimeError("closed","任务队列已关闭"))}}}function ke(e){let t,r;const n=new Promise((o,s)=>{t=o,r=s});return n.catch(()=>{}),{progress:e,promise:n,resolve:t,reject:r}}function Q(e){const t=Promise.reject(e);return t.catch(()=>{}),t}function Oe(e,t){let r,n,o=!0,s;function a(c){s??=c??new Error("任务心跳更新失败"),n?.reject(s),n=void 0,t(s)}function u(c){const i=Promise.resolve().then(()=>e(c?.progress)).then(()=>c?.resolve(),d=>{c?.reject(d),a(d)}).finally(()=>{r=void 0;const d=n;n=void 0,d&&s===void 0&&u(d)});r=i,i.catch(d=>{a(d)})}function f(c){if(!o)return Q(new h.ReportJobError("closed","任务进度上报已结束"));if(s!==void 0)return Q(s);n?n.progress=c:n=ke(c);const i=n;return r||(n=void 0,u(i)),i.promise}return{progress:f,pulse(){o&&!r&&s===void 0&&u()},async finish(){for(o=!1;r;)await r;if(s!==void 0)throw s}}}class W extends h.ReportJobError{constructor(){super("capacity","任务结果超过独立预算,请保存文件引用")}}function Je(e){const t=e.concurrency??1,r=e.leaseMs??3e4,n=e.heartbeatMs??1e4,o=e.maxResultBytes??256*1024;if(![t,r,n,o].every(a=>Number.isSafeInteger(a)&&a>0)||n*2>r)throw new h.ReportJobError("input","并发、租约、心跳应为正整数,租约至少为心跳的两倍");if(n>2147483647)throw new h.ReportJobError("input","心跳间隔超过平台定时器上限(2147483647毫秒)");return{concurrency:t,leaseMs:r,heartbeatMs:n,maxResultBytes:o,now:()=>{const a=(e.now??Date.now)();if(!Number.isSafeInteger(a)||a<0)throw new h.ReportJobError("input","任务时钟应返回非负整数毫秒");return a}}}async function L(e,t,r){h.checkJobIdentity(t,r);const n=await e.read(t,r);if(!n)throw new h.ReportJobError("missing","报表任务不存在");return n}async function D(e,t,r,n=[]){const o={...t,...r,revision:t.revision+1};for(const s of n)delete o[s];if(!await e.compareAndSwap(t.scope,t.id,t.revision,o))throw new h.ReportJobError("conflict","报表任务已被其他请求更新");return h.cloneJob(o)}async function Pe(e,t,r,n){if(!t.trim()||t.length>128)throw new h.ReportJobError("input","workerId应为1–128位标识");for(const o of await e.store.candidates(n,100)){const s=o.cancelRequested?{...o,revision:o.revision+1,status:"cancelled",updatedAt:n}:{...o,revision:o.revision+1,status:"running",attempt:o.attempt+1,updatedAt:n,lease:{owner:t,expiresAt:n+r}};if(s.status==="cancelled"&&delete s.lease,await e.store.compareAndSwap(o.scope,o.id,o.revision,s))return s}}function Y(e,t,r,n){return e.status==="running"&&e.attempt===n&&e.lease?.owner===t&&e.lease.expiresAt>r}async function Te(e,t,r,n){const{scope:o,id:s}=r,a=r.lease.owner;let u;const f=Oe(async y=>{const g=await L(e.store,o,s),R=t.now();if(!Y(g,a,R,r.attempt))throw new h.ReportJobError("lease","报表任务租约已失效");if(g.cancelRequested){n.abort(new h.ReportJobError("closed","任务已请求取消"));return}await D(e.store,g,{updatedAt:R,lease:{owner:a,expiresAt:R+t.leaseMs},...y?{progress:y}:{}})},y=>{u=y,n.abort(y)}),c=(y,g)=>!Number.isFinite(y)||y<0||g!==void 0&&(!Number.isFinite(g)||g<y)?Promise.reject(new h.ReportJobError("input","任务进度无效")):f.progress({completed:y,...g===void 0?{}:{total:g}}),i=setInterval(()=>{f.pulse()},t.heartbeatMs);let d,l;try{const y=Object.prototype.hasOwnProperty.call(e.handlers,r.request.kind)?e.handlers[r.request.kind]:void 0;if(!y)throw new h.ReportJobError("input","报表任务处理器未注册");if(!n.signal.aborted){const g=await y(h.cloneJob(r.request.payload),{scope:o,taskId:s,attempt:r.attempt,executionToken:JSON.stringify([o,s,r.attempt]),signal:n.signal,reportProgress:c});if(d=JSON.parse(h.serializeJobJson(g)),h.jobByteLength(d)>t.maxResultBytes)throw new W}}catch(y){l=y??new Error("报表任务执行失败")}finally{clearInterval(i),await f.finish().catch(()=>{})}const w=await L(e.store,o,s),m=t.now();if(!Y(w,a,m,r.attempt))throw new h.ReportJobError("lease","任务租约已失效,迟到结果不会写回");const b={...w,updatedAt:m};delete b.lease,l??=u,w.cancelRequested||n.signal.aborted&&u===void 0?b.status="cancelled":l!==void 0?(b.status="failed",b.error={code:l instanceof W?"result-budget":l instanceof h.ReportJobError?l.code:"execution",message:l instanceof Error?l.message.slice(0,500):"报表任务执行失败"}):(b.status="completed",b.result=d);try{h.serializeJobJson(b)}catch{delete b.result,b.status="failed",b.error={code:"result-budget",message:"任务结果与请求的组合超过存储预算,请保存文件引用而非文件内容"}}return je(e.store,w,b)}async function je(e,t,r){try{return await D(e,t,r,["lease"])}catch(n){if(!(n instanceof h.ReportJobError)||n.code!=="capacity"||r.status!=="completed")throw n;return delete r.result,r.status="failed",r.error={code:"result-budget",message:"任务结果超过存储剩余预算,请保存文件引用而非文件内容"},D(e,t,r,["lease","result"])}}async function ee(e,t,r,n){const o=await e.readTombstone?.(t,r);if(o){if(o.requestHash!==await h.jobRequestHash(n))throw new h.ReportJobError("conflict","相同任务ID不能提交不同内容(幂等保留期内)");return{scope:t,id:r,revision:o.revision,request:h.cloneJob(n),status:o.status,createdAt:o.createdAt,updatedAt:o.updatedAt,attempt:o.attempt,archived:!0}}}function Ne(e){e={...e,handlers:{...e.handlers}};const t=Je(e),r=new Set,n=new Set;let o=!1,s=0;const a=(c,i)=>(h.checkJobIdentity(c,i),e.store.read(c,i));return{submit:async c=>{if(c={...c},h.checkJobIdentity(c.scope,c.id),!Object.prototype.hasOwnProperty.call(e.handlers,c.kind)||typeof e.handlers[c.kind]!="function")throw new h.ReportJobError("input","报表任务处理器未注册");const i={kind:c.kind,payload:JSON.parse(h.serializeJobJson(c.payload,{maxNodes:19e3,maxCharacters:75e4}))},d=await a(c.scope,c.id);if(d){if(h.serializeJobJson(d.request)!==h.serializeJobJson(i))throw new h.ReportJobError("conflict","相同任务ID不能提交不同内容");return d}const l=await ee(e.store,c.scope,c.id,i);if(l)return l;const w=t.now(),m={scope:c.scope,id:c.id,revision:1,request:i,status:"queued",createdAt:w,updatedAt:w,attempt:0};if(!await e.store.compareAndSwap(c.scope,c.id,null,m)){const b=await a(c.scope,c.id);if(b&&h.serializeJobJson(b.request)===h.serializeJobJson(i))return b;const y=await ee(e.store,c.scope,c.id,i);if(y)return y;throw new h.ReportJobError("conflict","报表任务提交发生冲突")}return h.cloneJob(m)},get:a,runNext:c=>{if(o)return Promise.reject(new h.ReportJobError("closed","报表任务服务已关闭"));if(s>=t.concurrency)return Promise.reject(new h.ReportJobError("capacity","报表任务执行槽位已满"));s++;const i=new AbortController;r.add(i);const d=(async()=>{try{const l=await Pe(e,c,t.leaseMs,t.now());return l?.status==="running"?await Te(e,t,l,i):l}finally{s--,r.delete(i)}})();return n.add(d),d.then(()=>n.delete(d),()=>n.delete(d)),d},get active(){return s},cancel:async(c,i)=>{const d=await L(e.store,c,i);return d.status!=="queued"&&d.status!=="running"?d:D(e.store,d,{updatedAt:t.now(),...d.status==="queued"?{status:"cancelled"}:{cancelRequested:!0}})},retry:async(c,i,d)=>{const l=await L(e.store,c,i);if(l.revision!==d||l.status!=="failed")throw new h.ReportJobError("conflict","仅可重试当前修订的失败任务");const w={...l,status:"queued",updatedAt:t.now()};return delete w.error,delete w.progress,D(e.store,l,w,["error","progress"])},prune:async c=>{if(!e.store.prune||!e.store.readTombstone)throw new h.ReportJobError("input","当前任务适配器未实现可选终态保留能力");return e.store.prune({...c,now:t.now()})},close:async()=>{o=!0;for(const c of r)c.abort(new h.ReportJobError("closed","任务服务正在关闭"));await Promise.allSettled([...n])}}}function pe(e,t){const r=e.assets,n=e[t];if(!(!r&&!n?.assetRenderers&&!n?.assetRegistry))return{...r,...n?.assetFailure===void 0?{}:{assetFailure:n.assetFailure},...n?.onDiagnostic===void 0?{}:{onDiagnostic:n.onDiagnostic},assetRegistry:n?.assetRegistry??r?.assetRegistry,assetRenderers:{...r?.assetRenderers,...n?.assetRenderers},assetBudget:{...r?.assetBudget,...n?.assetBudget}}}function te(e,t){if(!e||e.code!=="missing-image"||e.format!=="pdf"&&e.format!=="xlsx")return!1;const r=pe(t,e.format);return typeof r?.assetRenderers?.[e.kind]=="function"||!!(e.extension&&r?.assetRegistry?.hasExtension(e.extension.id,e.extension.version,e.kind))}function Be(e,t){const r=ce.reviewReportTemplate(e,t),n=r.issues.filter(s=>!te(s.diagnostic,t)),o=r.samples.map(s=>({...s,diagnostics:s.diagnostics.filter(a=>!te(a,t))}));return{...r,issues:n,samples:o,ok:n.every(s=>s.severity!=="error"),artifacts:[]}}async function $e(e,t,r,n,o){const s=H.createReportRuntime({reports:{sample:{template:r,datasets:e.datasets}},assets:pe(n,t),budget:{maxRows:n.maxSampleRows??1e3,maxPages:n.maxPages??100,maxCells:n.maxCells??25e4,maxOutputBytes:n.maxOutputBytes??2e7,maxDurationMs:n.maxDurationMs??3e4}});try{const{result:a,digest:u}=await p.controlled(n.signal,n.maxDurationMs??3e4,async f=>{const c=await s.export({reportIds:["sample"],params:e.params,format:t,signal:f,fidelity:n.strictOutputs?"strict":"warn",pdf:n.pdf,xlsx:n.xlsx}),i=c.diagnostics.filter(l=>l.severity!=="info");if(n.strictOutputs&&i.length)throw new Error(`Strict ${t} encoding found fidelity issues: ${i.slice(0,3).map(l=>l.message).join("; ")}`);const d=await n.digest?.(c.bytes);return p.throwIfAborted(f),await n.onArtifact?.(e.name,c),p.throwIfAborted(f),{result:c,digest:d}});o.artifacts.push({fixture:e.name,format:t,bytes:a.bytes.byteLength,pages:a.stats.pages,...u?{digest:u}:{}}),o.issues.push(...a.diagnostics.map(f=>({code:"output",severity:n.strictOutputs||f.severity==="error"?"error":"warning",path:"$.template",fixture:e.name,message:`${t}: ${f.message}`})))}catch(a){p.throwIfAborted(n.signal),o.issues.push({code:"output",severity:"error",path:"$.template",fixture:e.name,message:`${t}: ${a instanceof Error?a.message:String(a)}`})}}async function Me(e,t={}){p.throwIfAborted(t.signal);const r=Be(e,t);if(!r.ok)return r;const n=O.parseReportTemplate(e).template,o=[...new Set(t.formats??["pdf","xlsx"])];if(!o.length||o.some(s=>s!=="pdf"&&s!=="xlsx"))return r.issues.push({code:"output",severity:"error",path:"$.formats",message:"真实文件验收应至少选择PDF/XLSX之一"}),r.ok=!1,r;for(const s of t.fixtures??[])for(const a of o)p.throwIfAborted(t.signal),!(a!=="pdf"&&a!=="xlsx")&&await $e(s,a,n,t,r);return r.ok=r.issues.every(s=>s.severity!=="error"),r}class v extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportInstanceError"}}function j(e,t){if(typeof e!="string"||!e.trim()||e.length>256||typeof t!="string"||t!==t.trim()||!/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/.test(t))throw new v("input","实例范围应非空,ID 应为安全标识")}function De(e,t){const r=Object.getPrototypeOf(e);if(r!==(t?Array.prototype:Object.prototype)&&!(r===null&&!t)||Object.getOwnPropertySymbols(e).length)throw new v("input","实例应为普通 JSON 对象");if(t&&Object.keys(e).some(o=>o!==String(Number(o))||!Number.isSafeInteger(Number(o))||Number(o)<0||Number(o)>=e.length))throw new v("input","实例数组不能包含额外属性");if(Object.getOwnPropertyNames(e).filter(o=>!(t&&o==="length")).length!==Object.keys(e).length)throw new v("input","实例不能包含不可枚举属性")}function Ce(e){if(!Number.isSafeInteger(e.revision)||e.revision<1||typeof e.title!="string"||!e.title.trim()||e.title.length>512)throw new v("input","实例修订或标题无效");if(typeof e.generatedAt!="string"||!Number.isFinite(Date.parse(e.generatedAt))||new Date(e.generatedAt).toISOString()!==e.generatedAt)throw new v("input","实例生成时间应为 ISO UTC 字符串");if(!Array.isArray(e.reportIds)||!e.reportIds.length||e.reportIds.length>100||e.reportIds.some(t=>typeof t!="string"||!t.trim())||new Set(e.reportIds).size!==e.reportIds.length)throw new v("input","实例报表 ID 应非空且唯一")}function qe(e){return e===null||typeof e=="boolean"||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function we(e,t){if(!Number.isSafeInteger(t)||t<1)throw new v("input","实例快照字节预算应为正安全整数");let r=0,n=0;const o=new Set;function s(u,f){if(++r>1e6||f>64)throw new v("capacity","实例节点或嵌套深度超过预算");if(typeof u=="string"&&(n+=u.length,n>t))throw new v("capacity","实例文本超过预算");if(qe(u))return u;if(!u||typeof u!="object"||o.has(u))throw new v("input","实例只允许无循环的有限 JSON 值");const c=Array.isArray(u);De(u,c),o.add(u);const i=Object.create(null);for(const d of Object.keys(u)){if(n+=d.length,n>t)throw new v("capacity","实例文本超过预算");const l=Object.getOwnPropertyDescriptor(u,d);if(l.get||l.set||["__proto__","constructor","prototype"].includes(d))throw new v("input","实例不能包含访问器或危险键");l.value!==void 0&&(i[d]=s(l.value,f+1))}if(o.delete(u),c){if(Object.keys(i).length!==u.length)throw new v("input","实例数组不能稀疏或包含额外属性");return Array.from({length:u.length},(d,l)=>i[String(l)])}return i}const a=JSON.stringify(s(e,0));if(new TextEncoder().encode(a).byteLength>t)throw new v("capacity","实例快照超过单条字节预算");return a}function F(e,t=8e6){const r=JSON.parse(we(e,t));j(r.scope,r.id);const n=new Set(["scope","id","revision","title","generatedAt","reportIds","params","templateRevisions","sourceRevisions","plan","artifacts","output"]);if(Object.keys(r).some(s=>!n.has(s)))throw new v("input","实例包含未知字段");Ce(r);for(const s of[r.params,r.templateRevisions,r.sourceRevisions])if(!s||typeof s!="object"||Array.isArray(s)||Object.values(s).some(a=>typeof a!="string"))throw new v("input","实例参数和修订应为字符串字典");if(r.reportIds.some(s=>!r.templateRevisions[s]))throw new v("input","每张报表都应记录生成时的模板修订");const o=O.validateRenderPlan(r.plan);if(!o.ok)throw new v("input",`实例渲染计划无效:${o.errors[0]?.path}`);if(r.output!==void 0){if(!r.output||Object.keys(r.output).some(s=>!["stats","diagnostics","layout","sources"].includes(s)))throw new v("input","实例输出元数据只允许统计、诊断和字体度量;不保存来源令牌");if(M.validatePreparedMetadata({...r.output,plan:r.plan,revisions:{}}),r.output.sources?.some(s=>"sourceToken"in s))throw new v("input","实例来源清单不保存来源令牌")}return r.artifacts!==void 0&&ze(r.artifacts),r}function ze(e){if(!Array.isArray(e)||e.length>100)throw new v("input","实例文件列表无效");const t=new Set;for(const r of e){if(!r||typeof r.key!="string"||!r.key.trim()||r.key.length>1024||t.has(r.key)||!["pdf","xlsx"].includes(r.format)||!Number.isSafeInteger(r.bytes)||r.bytes<0||r.sha256!==void 0&&(typeof r.sha256!="string"||r.sha256.length!==64||!/^[a-f0-9]{64}$/i.test(r.sha256)))throw new v("input","实例文件应包含唯一存储键、格式、大小和可选 SHA256");t.add(r.key)}}function me(e){const{scope:t,id:r,revision:n,title:o,generatedAt:s,reportIds:a,params:u,templateRevisions:f,sourceRevisions:c}=e;return JSON.parse(JSON.stringify({scope:t,id:r,revision:n,title:o,generatedAt:s,reportIds:a,params:u,templateRevisions:f,sourceRevisions:c}))}function _e(e){const t={maxInstances:100,maxRevisions:20,maxBytes:64e6,maxSnapshotBytes:8e6,...e};if(Object.values(t).some(r=>!Number.isSafeInteger(r)||r<1))throw new v("input","实例存储预算应为正安全整数");return t}function Le(e={}){const t=_e(e),r=new Map;let n=0;return{read:async(o,s,a,u)=>{p.throwIfAborted(u),j(o,s);const f=r.get(JSON.stringify([o,s])),c=f?.get(a??f.size);return c?F(c,t.maxSnapshotBytes):void 0},list:async(o,s={})=>{p.throwIfAborted(s.signal),j(o,"list");const a=s.limit??25;if(!Number.isSafeInteger(a)||a<1||a>100)throw new v("input","实例每页数量应为 1–100");const u=Array.from(r.values(),f=>f.get(f.size)).filter(f=>f.scope===o&&(!s.after||f.id>s.after)&&(!s.reportId||f.reportIds.includes(s.reportId))).sort((f,c)=>f.id<c.id?-1:1).slice(0,a+1);return{items:u.slice(0,a).map(me),...u.length>a?{next:u[a-1].id}:{}}},compareAndSwap:async(o,s,a,u,f)=>{p.throwIfAborted(f),j(o,s);const c=F(u,t.maxSnapshotBytes);if(c.scope!==o||c.id!==s||c.revision!==(a??0)+1)throw new v("input","实例身份或修订不一致");const i=JSON.stringify([o,s]),d=r.get(i)??new Map;if((d.size||null)!==a)return!1;const l=new TextEncoder().encode(JSON.stringify(c)).byteLength;if(d.size>=t.maxRevisions||n+l>t.maxBytes||!d.size&&r.size>=t.maxInstances)throw new v("capacity","实例存储达到预算,请使用持久化归档策略或显式调整容量");return d.set(c.revision,c),r.set(i,d),n+=l,!0}}}function ye(e,t={}){const r=t.maxSnapshotBytes??8e6;if(!Number.isSafeInteger(r)||r<1)throw new v("input","实例快照字节预算应为正安全整数");return{read:e.read.bind(e),list:e.list.bind(e),save:async(n,o)=>{const s=o.expectedRevision;if(s!==null&&(!Number.isSafeInteger(s)||s<1||s>=Number.MAX_SAFE_INTEGER))throw new v("input","实例预期修订无效");const a=JSON.parse(we(n,r)),u=F({...a,revision:(s??0)+1},r);if(p.throwIfAborted(o.signal),!await e.compareAndSwap(u.scope,u.id,s,u,o.signal))throw new v("conflict","实例已存在或已变化,请显式确认修订后保存");return u}}}function Fe(e,t){return h.serializeJobJson({reportIds:e,params:t})}function Ve(e){if(!e||typeof e!="object"||Object.getOwnPropertySymbols(e).length)throw new v("input","生成请求应为普通对象");const t=Object.create(null);let r;const n=new Set(["scope","id","title","reportIds","params","expectedRevision","signal"]);for(const o of Object.getOwnPropertyNames(e)){const s=Object.getOwnPropertyDescriptor(e,o);if(!n.has(o)||!s.enumerable||s.get||s.set)throw new v("input","生成请求不能包含未知字段或访问器");o==="signal"?r=s.value:s.value!==void 0&&(t[o]=s.value)}return{signal:r,request:JSON.parse(h.serializeJobJson(t))}}function he(e){const t=JSON.parse(h.serializeJobJson(e.templateRevisions)),r=M.snapshotPdfFonts(e.pdf),n=ye(e.instances,{maxSnapshotBytes:e.maxSnapshotBytes});return{async generate(o){const{signal:s,request:a}=Ve(o);if(j(a.scope,a.id),a.expectedRevision!==null&&(!Number.isSafeInteger(a.expectedRevision)||a.expectedRevision<1))throw new v("input","实例预期修订无效");const u=e.runtime.validate(a);if(!u.ok)throw new fe.ReportParamValidationError(u.issues);const f=Object.create(null);for(const g of a.reportIds){if(typeof t[g]!="string"||!t[g])throw new TypeError(`报表 ${g} 缺少生成时的模板修订`);f[g]=t[g]}if(p.throwIfAborted(s),((await e.instances.read(a.scope,a.id,void 0,s))?.revision??null)!==a.expectedRevision)throw new v("conflict","实例已存在或已变化,请显式确认修订后生成");const i=await e.runtime.prepare({reportIds:a.reportIds,params:u.values,pdf:r,signal:s});p.throwIfAborted(s);const d=Object.create(null);for(const[g,R]of Object.entries(i.revisions))R.revision!==void 0&&(d[g]=R.revision);const{plan:l,revisions:w,sources:m,...b}=i,y={...b,...m?{sources:m.map(({sourceToken:g,...R})=>R)}:{}};return n.save({scope:a.scope,id:a.id,title:a.title,reportIds:a.reportIds,params:u.values,templateRevisions:f,sourceRevisions:d,generatedAt:(e.now?.()??new Date).toISOString(),plan:l,output:y},{expectedRevision:a.expectedRevision,signal:s})},read:n.read,list:n.list,async exportInstance(o){const{scope:s,id:a,revision:u,signal:f,format:c,fidelity:i,taskId:d,correlationId:l,onEvent:w}=o,m=M.snapshotPdfFonts(o.pdf??r),b=M.snapshotXlsxOptions(o.xlsx);j(s,a),p.throwIfAborted(f);const y=await n.read(s,a,u,f);if(!y)throw new v("input","报表实例不存在");const g={plan:y.plan,revisions:Object.fromEntries(y.reportIds.map(R=>[R,{revision:y.sourceRevisions[R]}])),diagnostics:[{code:"instance-row-count",severity:"info",message:"历史实例未保存原始取数行数;本次 rows 统计为 0,页面及单元格数由已保存计划校验。"}],stats:{rows:0,pages:y.plan.pages.length,cells:0,durationMs:0},...y.output};return e.runtime.exportPrepared({prepared:g,format:c,fidelity:i,pdf:m,xlsx:b,signal:f,taskId:d,correlationId:l,onEvent:w})},save:n.save}}function z(e,t,r){if(!Number.isSafeInteger(e)||e<1||e>t)throw new RangeError(`${r} 应为 1–${t} 的安全整数`);return e}function re(e){if(!e||typeof e.key!="string"||!e.key.trim()||e.key.length>1024||!["pdf","xlsx"].includes(e.format)||!Number.isSafeInteger(e.bytes)||e.bytes<0||e.sha256!==void 0&&!/^[a-f0-9]{64}$/i.test(e.sha256))throw new TypeError("分批归档回执应包含存储键、格式、大小和可选 SHA256");return{key:e.key,format:e.format,bytes:e.bytes,...e.sha256?{sha256:e.sha256}:{}}}function He(e){if(!O.validateReportTemplate(e).ok||!e.repeat)throw new TypeError("分批生成仅支持有效的逐记录固定标签模板");return JSON.parse(JSON.stringify(e))}function Ue(e){const t=new Set,r=e.repeat;r.rowKey&&t.add(r.rowKey),typeof r.copies=="object"&&t.add(r.copies.field);const n=o=>{o.binding&&t.add(o.binding.field);for(const s of o.grid?.cells??[])for(const a of s)a?.children?.forEach(n)};return e.pages.forEach(o=>o.components.forEach(s=>n(s))),[...t]}function Ke(e,t,r,n){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError(`标签记录 ${n} 应为对象`);const o=Object.create(null);for(const s of t){const a=de.readRecordScalar(e,s,{dataset:r,rowIndex:n});if(typeof a=="string"&&a.length>1e6)throw new p.ReportRuntimeError("budget","标签字段超过 1 MB 字符预算",`$.datasets.${r}[${n}].${s}`);a!==void 0&&(o[s]=a)}return o}function Ze(e,t,r,n){const o=t.repeat;if(!o.rowKey)return;const s=de.readRecordScalar(e,o.rowKey,{rowIndex:n,dataset:o.dataset});if(!(typeof s=="string"&&s.trim()||typeof s=="number"&&Number.isFinite(s)))throw new TypeError(`标签记录 ${n} 的业务主键无效`);const a=JSON.stringify([typeof s,s]);if(r.keys.has(a))throw new TypeError(`标签记录 ${n} 的业务主键重复(包含先前批次)`);r.bytes+=a.length*2+64,r.keys.add(a)}function Xe(e){return Object.entries(e).reduce((t,[r,n])=>t+64+r.length*2+(typeof n=="string"?n.length*2:8),0)}function Ge(e,t){if(!t)return e;for(const r of e.plan.pages){const n=r.meta?.record;n&&typeof n=="object"&&"rowIndex"in n&&typeof n.rowIndex=="number"&&(n.rowIndex+=t)}return e}async function Qe(e,t){if(!e.return)return;const r=Promise.resolve(e.return());if(t.aborted){r.catch(()=>{});return}await p.controlled(t,void 0,()=>r)}async function ne(e,t,r){const n=Promise.resolve().then(()=>e.onReceipt?.(t,r));n.catch(()=>{}),await p.controlled(r.signal,void 0,()=>n)}function We(e,t,r){return new Promise((n,o)=>{let s=!1,a=!1,u;const f=()=>{clearTimeout(u),t.removeEventListener("abort",c)},c=()=>{s||u!==void 0||(u=setTimeout(()=>{if(!s){s=!0,a=!0,f();try{p.throwIfAborted(t)}catch(i){o(i)}}},0))};e.then(i=>{if(a){Promise.resolve().then(()=>r(i)).catch(()=>{});return}s||(s=!0,f(),n(i))},i=>{s||(s=!0,f(),o(i))}),t.addEventListener("abort",c,{once:!0}),t.aborted&&c()})}async function Ye(e,t){const r=z(t.batchSize??100,1e3,"batchSize"),n=z(t.maxRows??1e5,1e6,"maxRows"),o=z(t.maxChunks??1e3,1e4,"maxChunks"),s=z(t.maxRetainedBytes??16e6,64e6,"maxRetainedBytes"),a=He(t.template),u=Ue(a);if(!e||typeof e[Symbol.asyncIterator]!="function")throw new TypeError("标签来源应为 AsyncIterable");return p.controlled(t.signal,t.runtime?.budget?.maxDurationMs??12e4,async f=>{const c={rows:0,chunks:[]},i={keys:new Set,bytes:0},d=e[Symbol.asyncIterator]();let l=!1,w=!1,m;const b=()=>m??=Qe(d,f),y=()=>{l||b().catch(()=>{})};f.addEventListener("abort",y,{once:!0});try{for(;!l;){p.throwIfAborted(f);const g=[];let R=0;for(;g.length<r;){const x=await p.controlled(f,void 0,()=>Promise.resolve(d.next()));if(x.done){l=!0;break}if(c.rows+g.length>=n)throw new p.ReportRuntimeError("budget","标签来源行数超过预算","$.maxRows");if(c.chunks.length>=o)throw new p.ReportRuntimeError("budget","标签分块数量超过预算","$.maxChunks");const S=Ke(x.value,u,a.repeat.dataset,c.rows+g.length);if(Ze(S,a,i,c.rows+g.length),R+=Xe(S),i.bytes+R>s)throw new p.ReportRuntimeError("budget","标签当前块字段与全局主键索引超过内存预算","$.maxRetainedBytes");g.push(S)}if(!g.length)break;const P=H.createReportRuntime({...t.runtime,reports:{labels:{template:a,datasets:{[a.repeat.dataset]:g}}}});let N;const E={index:c.chunks.length,rowOffset:c.rows,rowCount:g.length,signal:f,export:x=>P.exportPrepared({pdf:t.pdf,...x,prepared:N,signal:f})};let $;const T=(await h.runReportBatch([{id:`labels-${E.index}`,params:{}}],async()=>{try{N=Ge(await P.prepare({reportIds:["labels"],pdf:t.pdf,signal:f}),E.rowOffset),p.throwIfAborted(f);const x=Promise.resolve(t.execute(N,E)),S=await We(x,f,A=>ne(t,re(A),E));return re(S)}catch(x){throw $=x,x}},{concurrency:1,signal:f,failure:"stop"}))[0];if(T.status==="cancelled")throw p.throwIfAborted(f),new Error("标签分批任务已取消");if(T.status==="failed")throw $??new Error(T.error.message);c.chunks.push({...T.value,index:E.index,rowOffset:E.rowOffset,rowCount:E.rowCount}),c.rows+=g.length,await ne(t,T.value,E)}return c}catch(g){throw w=!0,g}finally{f.removeEventListener("abort",y),l||await b().catch(g=>{if(!w)throw g})}})}async function ge(e,t){const r=t.document().id,n=()=>t.editor.saving||t.editor.blocked;if(n())throw new Error("草稿尚未保存,请处理设计器提示后再发布");if(t.editor.pendingLocalChanges){const s=t.successfulSaves();if(await t.editor.save(),await t.afterSave(),t.successfulSaves()===s||t.editor.pendingLocalChanges||n())throw new Error("草稿尚未保存,请处理设计器提示后再发布")}const o=t.document();if(o.id!==r)throw new v("conflict","当前模板已切换,请重新确认后发布");return e.publish(o.id,{expectedRevision:o.revision??null})}function be(e,t){return{async search(r){p.throwIfAborted(r.signal);const n=await e.list(r.signal);if(n.length>1e3)throw new RangeError("本地模板连接目录最多 1000 项;更大目录请使用宿主分页查询适配器");const o=[];for(const s of n){p.throwIfAborted(r.signal);const[a,u]=await Promise.all([e.get(s.id,{draft:!0,signal:r.signal}),e.get(s.id,{signal:r.signal})]),f=a??u;f&&o.push({document:f,published:u,draftRevision:a?.revision,publishedRevision:u?.revision,...t?.(O.parseReportTemplate(f))})}return ce.createLocalTemplateCatalog(o).search(r)},async get(r,n){return n.mode==="published"?e.get(r,{signal:n.signal}):await e.get(r,{draft:!0,signal:n.signal})??e.get(r,{signal:n.signal})}}}function ve(e=1e3){if(!Number.isSafeInteger(e)||e<1||e>1e3)throw new RangeError("本地生成意图上限应为 1–1000");const t=new Map,r=globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;return{forCase(n,o){if(![n,o].every(f=>typeof f=="string"&&f.length>0&&f.length<=256))throw new TypeError("模板与参数组标识无效");const s=JSON.stringify([n,o]),a=t.get(s);if(a)return a;if(t.size>=e)throw new RangeError("本地生成意图已达上限,请使用持久化任务服务");const u=`instance-${r}-${(t.size+1).toString(36)}`;return t.set(s,u),u}}}function et(e,t,r){const n=Object.keys(r);return e.reportIds.length===1&&e.reportIds[0]===t.id&&Object.keys(e.templateRevisions).length===1&&e.templateRevisions[t.id]===t.revision&&Object.keys(e.params).length===n.length&&n.every(o=>r[o]===e.params[o])}function oe(e){return{instanceId:e.id,label:e.title}}function tt(e,t,r){const n=O.parseReportTemplate(e);if(!n.revision)throw new Error("请先发布该模板");const o=typeof t.data=="function"?t.data(O.parseReportTemplate(n)):t.data,s=H.createReportRuntime({...t.runtime,reports:{[n.id]:{...o,template:n.template}}}),a=he({runtime:s,instances:t.instances,templateRevisions:{[n.id]:n.revision},pdf:t.pdf});async function u(f,c,i){p.throwIfAborted(i);const d=await t.instances.read(t.scope,f,void 0,i);if(p.throwIfAborted(i),!!d){if(!et(d,n,c))throw new v("conflict","此参数组已用于其他参数或发布修订,请复制为新任务生成");return oe(d)}}return{document:O.parseReportTemplate(n),async execute(f,{signal:c}){p.throwIfAborted(c);const i=s.validate({reportIds:[n.id],params:f.params});if(!i.ok)throw new Error(i.issues[0]?.message??"生成参数无效");const d=r(n.id,f.id),l=await u(d,i.values,c);if(l)return l;try{return oe(await a.generate({scope:t.scope,id:d,title:(t.title?.(O.parseReportTemplate(n),f,i.values)??`${n.name} · ${f.id}`).slice(0,512),reportIds:[n.id],params:i.values,expectedRevision:null,signal:c}))}catch(w){if(w instanceof v&&w.code==="conflict"){const m=await u(d,i.values,c);if(m)return m}throw w}}}}function rt(e){e={...e};const t=ve(),r=e.instanceId??t.forCase;return{catalog:e.catalog??be(e.templates,e.catalogMetadata),publish:n=>ge(e.templates,n),async batch(n,o={}){const{expectedRevision:s,signal:a}=o,u=await e.templates.get(n,{signal:a});if(p.throwIfAborted(a),!u?.revision)throw new Error("请先发布该模板");if(s!==void 0&&u.revision!==s)throw new v("conflict","模板发布版本已变化,请重新打开后生成");return tt(u,e,r)}}}const Re="2.25.1";function U(e,t){const r=t?.componentPath;if(!Number.isSafeInteger(t?.pageIndex)||t.pageIndex<0||!Array.isArray(r)||r.length<1||r.length>31||r.length%3!==1||r.some(o=>!Number.isSafeInteger(o)||o<0))throw new TypeError("模板包图片位置无效");let n=e.template.pages[t.pageIndex]?.components[r[0]];for(let o=1;n&&o<r.length;o+=3)n=n.grid?.cells[r[o]]?.[r[o+1]]?.children?.[r[o+2]];if(!n||n.kind!=="image"||n.binding)throw new TypeError("模板包图片位置应指向静态图片组件");return n}function nt(e){const t=["id","kind","mediaType","bytes","sha256","license","font","targets"];if(!e||Object.keys(e).some(r=>!t.includes(r)))throw new TypeError("模板资源包含未知字段");if(typeof e.id!="string"||!/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/.test(e.id))throw new TypeError("模板资源ID应为安全标识");if(!Number.isSafeInteger(e.bytes)||e.bytes<1||e.bytes>32e6||!/^[a-f0-9]{64}$/.test(e.sha256))throw new TypeError("模板资源大小或SHA256无效");if(e.license!==void 0&&(typeof e.license!="string"||e.license.length>512))throw new TypeError("模板资源许可说明无效")}function ot(e,t){if(nt(e),e.kind==="font"){if(!["font/ttf","font/otf"].includes(e.mediaType)||e.targets!==void 0)throw new TypeError("字体资源类型无效");const r=e.font;if(!r||typeof r.family!="string"||!r.family.trim()||r.family.length>128||!["regular","bold","italic","boldItalic"].includes(r.face)||Object.keys(r).some(n=>!["family","face"].includes(n)))throw new TypeError("字体资源需要family和face");return}if(e.kind!=="image"||!["image/png","image/jpeg"].includes(e.mediaType)||e.font!==void 0)throw new TypeError("模板图片仅支持PNG/JPEG");if(!Array.isArray(e.targets)||!e.targets.length||e.targets.length>1e3)throw new TypeError("模板图片需要1–1000个位置");for(const r of e.targets){if(Object.keys(r).some(n=>!["pageIndex","componentPath"].includes(n)))throw new TypeError("模板图片位置包含未知字段");U(t,r)}}function st(e,t){const r=n=>n.every((o,s)=>e[s]===o);return t==="image/png"?r([137,80,78,71,13,10,26,10]):t==="image/jpeg"?r([255,216,255]):t==="font/otf"?r([79,84,84,79]):r([0,1,0,0])||r([116,114,117,101])}function Ie(e){if(!(e instanceof Uint8Array)||!e.byteLength||e.byteLength>32e6)throw new RangeError("资源摘要只接受1–32MB字节");return p.portableSha256Hex(e)}function Se(e,t,r=le.createImageMediaInspector()){const n=new Set(t.flatMap(a=>(a.targets??[]).map(u=>U(e,u)))),o=new Map,s=a=>{if(a.imageData&&!n.has(a)){const u=r(a.imageData);o.set(u.dataUrl,u.bytes.byteLength)}for(const u of a.grid?.cells??[])for(const f of u)for(const c of f?.children??[])s(c)};for(const a of e.template.pages)for(const u of a.components)s(u);return[...o.values()].reduce((a,u)=>a+u,0)}function at(e,t){let r="";for(let n=0;n<e.length;n+=16384)r+=String.fromCharCode(...e.subarray(n,n+16384));return`data:${t};base64,${btoa(r)}`}async function it(e,t,r,n,o=3e4){if(!Number.isFinite(o)||o<1||o>2147483647)throw new RangeError("模板资源加载超时应为1–2147483647毫秒");return p.controlled(n,o,async s=>{const a=[],u=le.createImageMediaInspector();Se(e,t,u);for(const f of t){p.throwIfAborted(s);const c=await p.controlled(s,void 0,()=>Promise.resolve(r(JSON.parse(JSON.stringify(f)),{signal:s})));if(p.throwIfAborted(s),!c||!(c.bytes instanceof Uint8Array)||c.mediaType!==f.mediaType||c.bytes.byteLength!==f.bytes)throw new TypeError(`资源 ${f.id} 的类型或大小与清单不一致`);const i=new Uint8Array(c.bytes);if(!st(i,f.mediaType)||Ie(i)!==f.sha256)throw new TypeError(`资源 ${f.id} 的文件标识或SHA256与清单不一致`);if(f.kind==="font")a.push({id:f.id,family:f.font.family,face:f.font.face,bytes:i});else{const d=u(at(i,f.mediaType)).dataUrl;for(const l of f.targets)U(e,l).imageData=d}}return a})}function se(e){if(typeof e!="string"||!/^(0|[1-9]\d{0,5})\.(0|[1-9]\d{0,5})\.(0|[1-9]\d{0,5})$/.test(e))throw new TypeError("模板包最低版本与运行版本应为正式版本x.y.z");return e.split(".").map(Number)}function ct(e,t){const r=se(e),n=se(t);for(let o=0;o<3;o++){if(n[o]>r[o])return;if(n[o]<r[o])throw new Error(`模板包需要MachReport ${e}或更新版本`)}}function X(e,t,r){const n=e??t;if(!Number.isSafeInteger(n)||n<1||n>r)throw new RangeError("模板包字节预算无效");return n}function ft(e){if(e.contracts!==void 0){if(!e.contracts||typeof e.contracts!="object"||Array.isArray(e.contracts)||Object.keys(e.contracts).length>100)throw new TypeError("模板包字段契约应为最多100个数据集");for(const[t,r]of Object.entries(e.contracts)){if(!t.trim()||t.length>256)throw new TypeError("模板包数据集名称无效");ue.validateDatasetRows([],r)}}}function dt(e,t){if(!e||e.deidentified!==!0||typeof e.name!="string"||!e.name.trim()||e.name.length>128)throw new TypeError("样例需要名称和明确的deidentified:true确认");if(Object.keys(e).some(n=>!["name","deidentified","datasets","params"].includes(n)))throw new TypeError("模板包样例包含未知字段");if(!e.datasets||typeof e.datasets!="object"||Array.isArray(e.datasets))throw new TypeError("模板包样例数据集无效");if(ut(e,t),!fe.validateReportParams(t.document.template.params??[],e.params).ok)throw new TypeError(`样例 ${e.name} 的参数不符合模板定义`)}function ut(e,t){let r=0;for(const o of Object.values(e.datasets))if(!Array.isArray(o)||o.some(s=>!s||typeof s!="object"||Array.isArray(s)))throw new TypeError("模板包样例应为对象行数组");const n=C.templateValidationDatasets(t.document.template,e.datasets,{maxRows:1e3});for(const[o,s]of Object.entries(n)){if(r+=s.length,r>1e3)throw new RangeError("模板包每个样例最多1000行");const a=t.contracts?.[o];if(a&&!ue.validateDatasetRows(s,a).ok)throw new TypeError(`样例 ${e.name} 不符合 ${o} 字段契约`)}for(const o of Object.keys(t.contracts??{}))if(!Object.prototype.hasOwnProperty.call(e.datasets,o))throw new TypeError(`样例 ${e.name} 缺少 ${o} 数据集`)}function lt(e){if(e.fixtures===void 0)return;if(!Array.isArray(e.fixtures)||e.fixtures.length>20)throw new RangeError("模板包最多20个脱敏样例");const t=new Set;for(const r of e.fixtures){if(dt(r,e),t.has(r.name))throw new TypeError("模板包样例名称重复");t.add(r.name)}}function pt(e,t){if(!Array.isArray(e.resources)||e.resources.length>64)throw new RangeError("模板包最多64个资源依赖");const r=new Set,n=new Set,o=new Set;let s=0;for(const a of e.resources){if(ot(a,e.document),r.has(a.id))throw new TypeError("模板资源ID重复");if(r.add(a.id),s+=a.bytes,s>t)throw new RangeError("模板包资源总大小超过预算");const u=a.font&&JSON.stringify([a.font.family,a.font.face]);if(u&&o.has(u))throw new TypeError("模板包字体family/face重复");u&&o.add(u);for(const f of a.targets??[]){const c=JSON.stringify([f.pageIndex,f.componentPath]);if(n.has(c))throw new TypeError("同一图片位置不能绑定多个资源");n.add(c)}}if(s+Se(e.document,e.resources)>t)throw new RangeError("模板包内嵌与外部资源总大小超过预算")}function G(e,t={}){p.throwIfAborted(t.signal);const r=X(t.maxBytes,8e6,32e6);if(typeof e=="string"){if(e.length>r||new TextEncoder().encode(e).byteLength>r)throw new RangeError("模板包JSON超过预算");e=JSON.parse(e)}const n=C.snapshotReportJson(e,{maxBytes:r,check:()=>p.throwIfAborted(t.signal),error:(o,s)=>new TypeError(s)});if(!n||typeof n!="object"||Array.isArray(n)||n.schemaVersion!=="1.0"||Object.keys(n).some(o=>!["schemaVersion","minimumVersion","document","contracts","resources","fixtures"].includes(o)))throw new TypeError("模板包结构或版本无效");return ct(n.minimumVersion,t.runtimeVersion??Re),n.document=O.parseReportTemplate(n.document),ft(n),lt(n),pt(n,X(t.maxResourceBytes,32e6,64e6)),n}function wt(e,t={}){const r=C.snapshotReportJson(e,{maxBytes:X(t.maxBytes,8e6,32e6),check:()=>p.throwIfAborted(t.signal),error:(o,s)=>new TypeError(s)}),n=G({schemaVersion:"1.0",...r,minimumVersion:r.minimumVersion??Re,resources:r.resources??[]},t);for(const o of n.resources)for(const s of o.targets??[])delete U(n.document,s).imageData;return n}async function mt(e,t){const{resolve:r,signal:n,maxDurationMs:o}=t,s=G(e,t),a=await it(s.document,s.resources,r,n,o);return{document:s.document,fonts:a,contracts:s.contracts,fixtures:s.fixtures??[]}}class I extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportDocumentError"}}function yt(e={}){const t={maxDocuments:e.maxDocuments??32,maxBytes:e.maxBytes??64e6,maxPages:e.maxPages??1e4,maxPageBytes:e.maxPageBytes??4e6,maxManifestBytes:e.maxManifestBytes??1e6};if(Object.values(t).some(r=>!Number.isSafeInteger(r)||r<1))throw new I("input","文档预算应为正安全整数");return t}function J(e,t,r){if([e,t,...r===void 0?[]:[r]].some(n=>typeof n!="string"||!n.trim()||n.length>256))throw new I("input","文档 scope、id、version 应为 1–256 位非空字符串");return JSON.stringify([e,t])}function k(e,t,r){return C.snapshotReportJson(e,{maxBytes:t,maxNodes:t,check:()=>p.throwIfAborted(r),error:(n,o)=>new I(n==="budget"?"capacity":"input",o)})}function B(e){return new TextEncoder().encode(JSON.stringify(e)).byteLength}function ae(e){if(!e||e.schemaVersion!==Ee.RENDER_PLAN_SCHEMA_VERSION||"pages"in e||e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean")throw new I("input","文档计划头应使用当前版本,且不得携带 pages")}function _(e,t){e.bytes=0;for(let r=0;r<8;r++){const n=t+B(e);if(n===e.bytes)return;e.bytes=n}throw new I("capacity","文档容量统计无效")}function ht(e,t,r=[]){const n=new Map;let o=0,s=Promise.resolve();for(const i of r){const d=J(i.scope,i.id,i.version);if(ae(i.plan),n.has(d)||!Number.isSafeInteger(i.bytes)||i.bytes<0||!Number.isSafeInteger(i.pageCount)||i.pageCount<0||i.pageCount>t.maxPages||!["building","complete","failed"].includes(i.state)||i.revision!==i.pageCount+(i.state==="building"?0:1))throw new I("input","文档清单无效");n.set(d,k(i,t.maxManifestBytes)),o+=i.bytes}function a(i,d){if(o-(d?.bytes??0)+i.bytes>t.maxBytes||!d&&n.size>=t.maxDocuments)throw new I("capacity","文档存储容量已满,请显式清理旧文档")}if(n.size>t.maxDocuments||o>t.maxBytes)throw new I("capacity","已存文档超过预算");const u=i=>{const d=s.then(i);return s=d.then(()=>{},()=>{}),d},f=(i,d,l,w)=>{const m=n.get(J(i,d,l));if(!m)throw new I("missing","文档不存在");if(m.version!==l||w!==void 0&&m.revision!==w)throw new I("conflict","文档已变化,请重新读取清单");return m},c=async(i,d,l)=>{const w=k(i,t.maxManifestBytes);return a(w,d),await e.write(w,l),n.set(J(i.scope,i.id),w),o+=i.bytes-(d?.bytes??0),k(w,t.maxManifestBytes)};return{create:(i,d)=>{const l=k(i,t.maxManifestBytes,d),w=J(l.scope,l.id,l.version);return ae(l.plan),u(async()=>{if(p.throwIfAborted(d),n.has(w))throw new I("conflict","文档已存在,不可覆盖");const m={...l,revision:0,state:"building",pageCount:0,bytes:0};return _(m,0),c(m)})},append:(i,d,l,w,m,b)=>{const y=k(m,t.maxPageBytes,b),g=O.validateRenderPlan({pages:[y]});if(!g.ok)throw new I("input",g.errors[0].message);return u(async()=>{p.throwIfAborted(b);const R=f(i,d,l,w);if(R.state!=="building")throw new I("conflict","已完成文档不可追加");if(R.pageCount>=t.maxPages)throw new I("capacity","文档页数超过预算");const P={...R,revision:w+1,pageCount:R.pageCount+1};return _(P,R.bytes-B(R)+B(y)),c(P,R,{index:R.pageCount,value:y})})},complete:(i,d,l,w,m,b)=>{const y=m===void 0?void 0:k(m,t.maxManifestBytes,b);return y&&M.validatePreparedMetadata({...y}),u(async()=>{p.throwIfAborted(b);const g=f(i,d,l,w);if(g.state!=="building")throw new I("conflict","文档已完成");if(y&&y.stats.pages!==g.pageCount)throw new I("input","准备结果页数与文档页数不一致");const R={...g,revision:w+1,state:"complete",...y?{metadata:y}:{}};return _(R,g.bytes-B(g)),c(R,g)})},fail:(i,d,l,w,m)=>{const b=k(m,4096);if(!b||!["cancelled","generation"].includes(b.code)||typeof b.message!="string"||!b.message.trim()||b.message.length>1024)throw new I("input","文档失败状态无效");return u(async()=>{const y=f(i,d,l,w);if(y.state!=="building")throw new I("conflict","终态文档不可变更");const g={...y,state:"failed",revision:w+1,failure:b};return _(g,y.bytes-B(y)),c(g,y)})},read:async(i,d,l)=>{p.throwIfAborted(l);const w=J(i,d);await s,p.throwIfAborted(l);const m=n.get(w);return m?k(m,t.maxManifestBytes):void 0},readPage:(i,d,l,w,m)=>u(async()=>{p.throwIfAborted(m);const b=f(i,d,l);if(!Number.isSafeInteger(w)||w<0)throw new I("input","页索引应为非负安全整数");if(w>=b.pageCount)return;const y=await e.readPage(i,d,w);if(p.throwIfAborted(m),!y)throw new I("missing","已提交的文档页缺失");return k(y,t.maxPageBytes,m)}),remove:(i,d,l,w)=>u(async()=>{p.throwIfAborted(w);const m=J(i,d,l),b=n.get(m);return b?(f(i,d,l),await e.remove(b),n.delete(m),o-=b.bytes,!0):!1})}}function gt(e={}){const t=new Map;return ht({write:async(r,n)=>{if(!n)return;const o=J(r.scope,r.id),s=t.get(o)??[];s[n.index]=n.value,t.set(o,s)},readPage:async(r,n,o)=>t.get(J(r,n))?.[o],remove:async r=>{t.delete(J(r.scope,r.id))}},yt(e))}async function bt(e,t){const r=t.fromPage??0,n=t.limit??4,o=t.maxBytes??8e6;if(!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(n)||n<1||n>32||!Number.isSafeInteger(o)||o<1)throw new I("input","页窗口参数无效;每次最多读取 32 页");const s=await e.read(t.scope,t.id,t.signal);if(!s)throw new I("missing","文档不存在");if(s.version!==t.version)throw new I("conflict","文档版本已变化");const a=[];let u=0,f=Math.min(r,s.pageCount);for(;f<Math.min(s.pageCount,r+n);f++){const c=await e.readPage(t.scope,t.id,t.version,f,t.signal);if(!c)throw new I("missing","文档页缺失");const i=B(c);if(u+i>o){if(!a.length)throw new I("capacity","单页超过读取窗口预算");break}a.push(c),u+=i}return{manifest:s,pages:a,nextPage:f}}async function vt(e,t){const{scope:r,id:n,version:o,signal:s,pages:a}=t,u=t.metadata===void 0?void 0:k(t.metadata,1e6,s);let f=await e.create({scope:r,id:n,version:o,plan:t.plan},s),c;try{const i=Symbol.asyncIterator in a?a[Symbol.asyncIterator]():a[Symbol.iterator]();for(c=i;;){const d=await p.controlled(s,void 0,()=>Promise.resolve(i.next()));if(d.done)break;f=await e.append(r,n,o,f.revision,d.value,s)}return await e.complete(r,n,o,f.revision,u,s)}catch(i){throw Promise.resolve(c?.return?.()).catch(()=>{}),await e.fail(r,n,o,f.revision,s?.aborted?{code:"cancelled",message:"报表文档生成已取消"}:{code:"generation",message:"报表文档生成失败"}).catch(()=>{}),i}}const xe="1.0",ie=Object.freeze({params:422,validate:422,fetch:502,config:400,input:400,budget:413,capacity:413,timeout:504,"queue-full":429,closed:503,cancelled:499,"output-fidelity":422,conflict:409,missing:404});function V(e){return e&&typeof e=="object"?e:{}}function Rt(e){if(Array.isArray(e))return e.slice(0,100).map(t=>Object.fromEntries(["code","path","field","message"].flatMap(r=>typeof V(t)[r]=="string"?[[r,V(t)[r].slice(0,4096)]]:[])))}function It(e,t){const r=V(e),n=r.name==="AbortError"?"cancelled":r.code,o=typeof n=="string"&&Object.prototype.hasOwnProperty.call(ie,n)?n:"internal",s=o==="internal"?void 0:Rt(r.issues??V(r.cause).issues);return{status:ie[o]??500,body:{error:{code:o,message:o==="internal"?"Report execution failed":typeof r.message=="string"?r.message.slice(0,4096):"Report request failed",correlationId:t.slice(0,128),...o!=="internal"&&typeof r.path=="string"?{path:r.path.slice(0,4096)}:{},...s?{issues:s}:{}}}}}function Z(e,t,r){return{description:r,headers:{"X-Request-Id":{schema:{type:"string"},description:"Request correlation identity"}},content:{[e]:{schema:t}}}}function St(e){return{type:"object",additionalProperties:!1,properties:Object.fromEntries(e.params.map(t=>[t.field,{type:"string"}])),required:e.params.filter(t=>t.required&&t.defaultValue===void 0).map(t=>t.field),"x-report-typedSchema":e.paramsSchema}}function xt(e,t={}){const r=t.basePath??"/reports";if(!/^\/[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(r))throw new Error("OpenAPI basePath 应为不含查询串、参数和尾斜线的绝对路径");const n={[r]:{get:{operationId:"describeReports",responses:{200:Z("application/json",{type:"array",items:{type:"object"}},"Authorized report descriptions")}}}},o=new Set;for(const s of e){if(!s.id.trim()||o.has(s.id)||[".",".."].includes(s.id))throw new Error("OpenAPI 报表 ID 应非空、唯一且不是路径跳转段");o.add(s.id);for(const a of["prepare","pdf","xlsx"]){const u=a==="prepare"?"prepare":`export/${a}`,f=a!=="prepare",c={200:Z(f?a==="pdf"?"application/pdf":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"application/json",f?{type:"string",format:"binary"}:{type:"object",required:["plan","stats","diagnostics","revisions"]},f?"Report file":"Prepared report snapshot")};for(const i of[400,413,422,429,499,500,502,503,504])c[String(i)]=Z("application/json",{$ref:"#/components/schemas/ReportError"},"Structured report error");n[`${r}/${encodeURIComponent(s.id)}/${u}`]={post:{operationId:`report_${o.size}_${a}`,parameters:[{in:"header",name:"X-Request-Id",schema:{type:"string",pattern:"^[A-Za-z0-9._-]{1,80}$"}}],requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["params"],additionalProperties:!1,properties:{params:St(s)}}}}},responses:c,"x-report-datasets":s.datasetsSchema}}}}return{openapi:"3.1.0",info:{title:t.title??"MachReport HTTP",version:t.version??xe},paths:n,components:{schemas:{ReportError:{type:"object",required:["error"],properties:{error:{type:"object",required:["code","message","correlationId"],properties:{code:{type:"string"},message:{type:"string"},correlationId:{type:"string"},path:{type:"string"},issues:{type:"array",items:{type:"object",additionalProperties:{type:"string"}}}}}}}}}}}exports.createReportRuntime=H.createReportRuntime;exports.ReportRuntimeError=p.ReportRuntimeError;exports.ReportJobError=h.ReportJobError;exports.checkJobIdentity=h.checkJobIdentity;exports.cloneJob=h.cloneJob;exports.createMemoryReportJobStore=h.createMemoryReportJobStore;exports.runReportBatch=h.runReportBatch;exports.runnableJob=h.runnableJob;exports.serializeJobJson=h.serializeJobJson;exports.snapshotReportBatchCases=h.snapshotReportBatchCases;exports.validateJobRecord=h.validateJobRecord;exports.validateJobTransition=h.validateJobTransition;exports.REPORT_HTTP_CONTRACT_VERSION=xe;exports.ReportDocumentError=I;exports.ReportInstanceError=v;exports.checkInstanceIdentity=j;exports.createManagerTemplateCatalog=be;exports.createMemoryReportDocumentStore=gt;exports.createMemoryReportInstanceIds=ve;exports.createMemoryReportInstanceStore=Le;exports.createReportGenerationService=he;exports.createReportInstanceManager=ye;exports.createReportJobService=Ne;exports.createReportOpenApi=xt;exports.createReportTaskQueue=Ae;exports.createReportTemplatePackage=wt;exports.createReportWorkflow=rt;exports.parseReportTemplatePackage=G;exports.readReportDocumentPages=bt;exports.reportHttpError=It;exports.reportInstanceParameterKey=Fe;exports.reportInstanceSummary=me;exports.reportPackageResourceDigest=Ie;exports.resolveReportTemplatePackage=mt;exports.reviewReportPublication=Me;exports.runLabelStream=Ye;exports.saveAndPublishReportTemplate=ge;exports.snapshotReportInstance=F;exports.writeReportDocument=vt;
|
package/dist/server.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { c as W } from "./runtime-
|
|
1
|
+
import { c as W } from "./runtime-B5d_lQNQ.js";
|
|
2
2
|
import { R as A, t as h, c as T, p as Re } from "./sha256-BDQ1Qk7A.js";
|
|
3
|
-
import { H as Se, s as Y, I as Ie } from "./json-snapshot-
|
|
3
|
+
import { H as Se, s as Y, I as Ie } from "./json-snapshot-CBVWZvyC.js";
|
|
4
4
|
import { R, c as X, s as P, a as H, j as Ee, b as ke, r as Oe } from "./batch-DGCt44XM.js";
|
|
5
5
|
import { d as rr, e as nr, f as sr, v as ar, g as or } from "./batch-DGCt44XM.js";
|
|
6
|
-
import { r as Ae, a as Pe } from "./template-catalog-
|
|
7
|
-
import { p as $, b as le, v as je } from "./template-registry-
|
|
8
|
-
import { v as pe, s as ee, a as Te } from "./prepared-
|
|
6
|
+
import { r as Ae, a as Pe } from "./template-catalog-CM6U_RlD.js";
|
|
7
|
+
import { p as $, b as le, v as je } from "./template-registry-DeVgwEZj.js";
|
|
8
|
+
import { v as pe, s as ee, a as Te } from "./prepared-CBJ7BkK0.js";
|
|
9
9
|
import { R as Ne, l as Be } from "./param-validation-CnDEd2l-.js";
|
|
10
10
|
import { k as we } from "./record-bindings-Cv7lFiof.js";
|
|
11
11
|
import { v as ye } from "./dataset-DL83majE.js";
|
|
@@ -916,7 +916,7 @@ function Ut(e) {
|
|
|
916
916
|
}
|
|
917
917
|
};
|
|
918
918
|
}
|
|
919
|
-
const be = "2.25.
|
|
919
|
+
const be = "2.25.1";
|
|
920
920
|
function U(e, t) {
|
|
921
921
|
const r = t?.componentPath;
|
|
922
922
|
if (!Number.isSafeInteger(t?.pageIndex) || t.pageIndex < 0 || !Array.isArray(r) || r.length < 1 || r.length > 31 || r.length % 3 !== 1 || r.some((s) => !Number.isSafeInteger(s) || s < 0)) throw new TypeError("模板包图片位置无效");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { y as O, J as k, I as j } from "./json-snapshot-
|
|
1
|
+
import { y as O, J as k, I as j } from "./json-snapshot-CBVWZvyC.js";
|
|
2
2
|
import { i as P } from "./capabilities-CN_kSVjO.js";
|
|
3
3
|
import { v as L } from "./dataset-DL83majE.js";
|
|
4
|
-
import { p as h } from "./template-registry-
|
|
4
|
+
import { p as h } from "./template-registry-DeVgwEZj.js";
|
|
5
5
|
import { b as S } from "./template-serialization-CWmHq7lX.js";
|
|
6
6
|
import { l as N } from "./param-validation-CnDEd2l-.js";
|
|
7
7
|
function $(e) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const w=require("./json-snapshot-DQdkA_At.cjs"),j=require("./capabilities-D4nfhcvB.cjs"),L=require("./dataset-IrlXbUvh.cjs"),h=require("./template-registry-BMScUmM4.cjs"),E=require("./template-serialization-CqQY4zDg.cjs"),P=require("./param-validation-C-8sRJLq.cjs");function R(e){if(e===void 0)return;const t=typeof e=="string"?e:JSON.stringify(e);return t.length>160?t.slice(0,157)+"…":t}function N(e){return/\.(?:repeat|binding)(?:\.|$)/.test(e)?/\.format(?:\.|$)/.test(e)?"format":"binding":/\.tree\.(?:idField|parentField|childrenField|labelField|input)$/.test(e)?"binding":/\.tree\.parentValues$/.test(e)?"calculation":/\.tree\.indentMm$/.test(e)?"format":/\.(?:computed|computeOptions|groups|groupBy|aggregates|grandTotal)(?:\.|\[|$)/.test(e)?"calculation":/\.(?:dataset|field|rowKey|revisionField|sourceTokenField|foreignKey|parentKey)$/.test(e)?"binding":/\.(?:style|headerStyle|format|rules|align|headerAlign|semanticRole|unit)(?:\.|\[|$)/.test(e)?"format":e.startsWith("$.template")?"structure":"metadata"}function T(e){const t=new Map;for(const r of e){if(!r||typeof r!="object"||!("field"in r)||typeof r.field!="string"||t.has(r.field))return;t.set(r.field,r)}return t}function D(e,t,r){return!e.startsWith("$.template.params")||t==="moved"?!1:/\.(?:type|required|min|max|minLength|maxLength|options|defaultValue)(?:\[|$)/.test(e)?!0:t!=="added"?!1:Array.isArray(r)?r.some(a=>!!a&&typeof a=="object"&&"required"in a&&a.required===!0):!!r&&typeof r=="object"&&"required"in r&&r.required===!0}function A(e,t,r={}){const a=h.parseReportTemplate(e),n=h.parseReportTemplate(t),o=r.maxChanges??500;if(!Number.isSafeInteger(o)||o<1||o>1e4)throw new RangeError("maxChanges must be between 1 and 10000");const s={changes:[],totalChanges:0,breakingChanges:0,truncated:!1};function d(c,l,u,m){const f=N(l),y=c!=="moved"&&(f==="binding"||l==="$.id"||c==="removed"&&f==="structure"||D(l,c,m));s.totalChanges++,y&&s.breakingChanges++,s.changes.length<o&&s.changes.push({kind:c,category:f,path:l,before:R(u),after:R(m),breaking:y})}function p(c,l,u){const m=T(c),f=T(l);if(!m||!f)return!1;const y=new Map(l.map((g,b)=>[g.field,b]));Array.from(m).forEach(([g,b],$)=>{const x=`${u}[${JSON.stringify(g)}]`;f.has(g)?(y.get(g)!==$&&d("moved",x,$,y.get(g)),i(b,f.get(g),x)):d("removed",x,b,void 0)});for(const[g,b]of f)m.has(g)||d("added",`${u}[${JSON.stringify(g)}]`,void 0,b);return!0}function i(c,l,u){if(!(Object.is(c,l)||u==="$.revision")){if(c===void 0||l===void 0){d(c===void 0?"added":"removed",u,c,l);return}if(Array.isArray(c)&&Array.isArray(l)){if((u.endsWith(".columns")||u.endsWith(".params"))&&p(c,l,u))return;for(let m=0;m<Math.max(c.length,l.length);m++)i(c[m],l[m],`${u}[${m}]`)}else if(c&&l&&typeof c=="object"&&typeof l=="object"&&!Array.isArray(c)&&!Array.isArray(l)){const m=c,f=l;for(const y of new Set([...Object.keys(m),...Object.keys(f)]))i(m[y],f[y],`${u}.${y}`)}else d("modified",u,c,l)}}return i(a,n,"$"),s.truncated=s.totalChanges>s.changes.length,s}function M(e,t,r){for(const a of E.collectTemplateDatasetBindings(e)){const n=Object.prototype.hasOwnProperty.call(t,a.dataset)?t[a.dataset]:void 0;if(!n){r.push({code:"dataset",severity:"error",path:`${a.path}.dataset`,message:`未声明数据集 ${a.dataset}`});continue}const o=new Set(n.fields.map(s=>s.field));a.fields.forEach(({field:s,path:d,summary:p})=>{!o.has(s)&&!a.generated.has(s)&&!(p&&a.summaries.has(s))&&r.push({code:"field",severity:"error",path:d,field:s,message:`数据集 ${a.dataset} 缺少字段 ${s}`})})}}function q(e,t,r,a){const n=r.maxSampleRows??1e3;let o;try{o=w.templateValidationDatasets(t,e.datasets,{maxRows:n})}catch(p){return a.push({code:"sample",severity:"error",path:"$.fixtures",fixture:e.name,message:p instanceof Error?p.message:String(p)}),!1}const s=Object.values(o).reduce((p,i)=>p+i.length,0);if(s>n)return a.push({code:"sample",severity:"error",path:"$.fixtures",fixture:e.name,message:`样例 ${s} 行超过预算 ${n},请显式选择验收样例`}),!1;const d=new Set(E.collectTemplateDatasetBindings(t).map(p=>p.dataset));for(const[p,i]of Object.entries(r.dataSchemas??{}).filter(([c])=>d.has(c)))try{const c=L.validateDatasetRows(o[p],i,{path:`$.datasets.${p}`,maxRows:n});if(a.push(...c.issues.map(l=>({...l,code:"sample",severity:"error",fixture:e.name}))),!c.ok)return!1}catch(c){return a.push({code:"dataset",severity:"error",path:`$.dataSchemas.${p}`,message:String(c)}),!1}return!0}function F(e,t){const r=e.pages[t.pageIndex]?.components[t.componentIndex]?.meta?.labelSource;if(r&&typeof r=="object"&&"pageIndex"in r&&"componentIndex"in r&&typeof r.pageIndex=="number"&&typeof r.componentIndex=="number")return{path:`$.template.pages[${r.pageIndex}].components[${r.componentIndex}]`,pageIndex:r.pageIndex,componentIndex:r.componentIndex};const a=e.pages[t.pageIndex]?.meta?.record;if(a&&typeof a=="object"&&"templatePageIndex"in a&&typeof a.templatePageIndex=="number")return{path:`$.template.pages[${a.templatePageIndex}].components[${t.componentIndex}]`,pageIndex:a.templatePageIndex,componentIndex:t.componentIndex}}function B(e,t,r){const a=F(t,r);if(a)return a;const n=t.pages[r.pageIndex]?.components[r.componentIndex],o=/^table:(\d+):(\d+)(?::|$)/.exec(n?.table?.id??"");if(o)return{path:`$.template.pages[${o[1]}].components[${o[2]}]`,pageIndex:Number(o[1]),componentIndex:Number(o[2])};for(const[s,d]of e.pages.entries()){const p=d.components.findIndex(i=>i===n||n?.nid!==void 0&&"nid"in i&&i.nid===n.nid);if(p>=0)return{path:`$.template.pages[${s}].components[${p}]`,pageIndex:s,componentIndex:p}}return{path:"$.template"}}function J(e,t,r,a,n){const o=P.validateReportParams(e.template.params??[],t.params??{});if(n.issues.push(...o.issues.map(s=>({...s,code:"params",severity:"error",fixture:t.name,path:s.path.replace(/^\$\.params/,`$.fixtures[${r}].params`)}))),!!o.ok&&q(t,e.template,a,n.issues))try{const{plan:s,warnings:d}=w.paginateTemplate(e.template,t.datasets,{maxPages:a.maxPages??100,maxCells:a.maxCells??25e4}),p=(a.formats??["pdf","xlsx"]).flatMap(i=>j.inspectOutputCapabilities(s,i));n.issues.push(...d.map(i=>({code:"layout",severity:"warning",path:"$.template",fixture:t.name,message:i}))),n.issues.push(...p.map(i=>({code:"output",severity:a.strictOutputs?"error":"warning",...B(e.template,s,i),fixture:t.name,message:`${i.format}: ${i.message}`,diagnostic:i}))),n.samples.push({name:t.name,pages:s.pages.length,rows:w.templateDatasetRowCount(e.template,t.datasets),diagnostics:p})}catch(s){n.issues.push({code:"layout",severity:"error",path:"$.template",fixture:t.name,message:s instanceof Error?s.message:String(s)})}}function V(e){for(const[r,a]of[["maxPages",e.maxPages],["maxCells",e.maxCells],["maxSampleRows",e.maxSampleRows]])if(a!==void 0&&(!Number.isSafeInteger(a)||a<1))throw new RangeError(`${r} must be a positive safe integer`);if((e.fixtures?.length??0)>20)throw new RangeError("At most 20 review fixtures are allowed");const t=new Set;for(const r of e.fixtures??[]){if(typeof r.name!="string"||!r.name.trim()||r.name.length>120||t.has(r.name))throw new Error("Review fixtures require unique non-empty names of at most 120 characters");t.add(r.name)}}function*C(e,t,r){let a;yield{stage:"template",run:()=>{V(t),a=h.parseReportTemplate(e)}};const n=t.previous;n&&(yield{stage:"baseline",run:()=>{r.changes=A(n,a),r.changes.breakingChanges&&!t.allowBreakingChanges&&r.issues.push({code:"compatibility",severity:"error",path:"$.template",message:`${r.changes.breakingChanges} 项字段或结构变更需要明确确认兼容性`})}}),t.dataSchemas&&(yield{stage:"bindings",run:()=>M(a.template,t.dataSchemas,r.issues)});for(const[o,s]of(t.fixtures??[]).entries())yield{stage:"fixture",fixture:s.name,run:()=>J(a,s,o,t,r)};t.fixtures?.length||r.issues.push({code:"sample",severity:"warning",path:"$.fixtures",message:"未提供验收样例,仅完成结构和字段检查,尚未验证排版与输出"})}function O(e){return e.ok=e.issues.every(t=>t.severity!=="error"),e}function k(e,t){e.issues.push({code:"template",severity:"error",path:"$",message:t instanceof Error?t.message:String(t)})}function W(e,t={}){const r={ok:!1,issues:[],samples:[]};try{for(const a of C(e,t,r))a.run()}catch(a){k(r,a)}return O(r)}function v(e){if(e?.aborted)throw e.reason??new DOMException("Template review was aborted","AbortError")}function K(e){return v(e),new Promise((t,r)=>{const a=()=>{clearTimeout(n),e?.removeEventListener("abort",a),r(e?.reason??new DOMException("Template review was aborted","AbortError"))},n=setTimeout(()=>{e?.removeEventListener("abort",a),t()},0);e?.addEventListener("abort",a,{once:!0}),e?.aborted&&a()})}function I(e,t){try{e.onProgress?.(t)}catch{}}async function _(e,t={}){const r={ok:!1,issues:[],samples:[]},a=t.fixtures?.length??0;let n=0;v(t.signal);try{const o=C(e,t,r),s=o.next();s.done||(s.value.run(),I(t,{completed:n,total:a,stage:s.value.stage})),v(t.signal);for(const d of o)await K(t.signal),v(t.signal),d.run(),d.stage==="fixture"&&n++,I(t,{completed:n,total:a,stage:d.stage,...d.fixture?{fixture:d.fixture}:{}}),v(t.signal)}catch(o){v(t.signal),k(r,o)}return O(r)}function z(e,t){const r=e.publishedRevision??e.published?.revision;for(const a of[e.draftRevision,r])if(a!==void 0&&(typeof a!="string"||!a.trim()))throw new TypeError("模板生命周期修订应为非空字符串");if(e.draftRevision!==void 0&&e.draftRevision!==t.revision)throw new TypeError("可编辑文档应与草稿修订一致");if(e.published&&(e.published.id!==t.id||e.published.revision!==r))throw new TypeError("发布文档身份或修订不一致");if(!e.published&&r!==void 0&&r!==t.revision)throw new TypeError("发布修订需要对应的独立文档");return{...e.draftRevision===void 0?{}:{draftRevision:e.draftRevision},...r===void 0?{}:{publishedRevision:r}}}function G(e,t){const r=h.parseReportTemplate(e);if(t.id===r.id)throw new Error("复制模板应使用新的 ID");const{revision:a,...n}=r;return h.parseReportTemplate({...n,id:t.id,name:t.name})}function H(e){if(!Array.isArray(e)||e.length>1e3)throw new RangeError("本地模板目录最多 1000 项");const t=new Map,r=new Map,a=[];for(const n of e){const o=h.parseReportTemplate(n.document);if(t.has(o.id))throw new Error(`模板 ID 重复:${o.id}`);if(n.category!==void 0&&(typeof n.category!="string"||n.category.length>128)||n.tags!==void 0&&(!Array.isArray(n.tags)||n.tags.length>20||n.tags.some(i=>typeof i!="string"||i.length>128)))throw new TypeError("模板分类和标签无效");const s=z(n,o),{template:d,...p}=o;t.set(o.id,o),n.published?r.set(o.id,h.parseReportTemplate(n.published)):s.publishedRevision&&r.set(o.id,h.parseReportTemplate(o)),a.push({...p,...s,...n.category?{category:n.category}:{},...n.tags?{tags:[...n.tags]}:{}})}return a.sort((n,o)=>n.id<o.id?-1:1),{search:async n=>{S(n.signal);const o=n.limit??30;if(!Number.isSafeInteger(o)||o<1||o>100)throw new RangeError("模板每页数量应为 1–100");const s=n.query?.trim().toLocaleLowerCase()??"",d=a.filter(i=>(!n.category||i.category===n.category)&&(!n.cursor||i.id>n.cursor)&&(!s||[i.id,i.name,i.description,...i.tags??[]].some(c=>c?.toLocaleLowerCase().includes(s)))),p=new Map;for(const i of a)i.category&&p.set(i.category,(p.get(i.category)??0)+1);return JSON.parse(JSON.stringify({items:d.slice(0,o),...d.length>o?{next:d[o-1].id}:{},categories:Array.from(p,([i,c])=>({id:i,label:i,count:c}))}))},get:async(n,o)=>{S(o.signal);const s=o.mode==="published"?r.get(n):t.get(n);return s?h.parseReportTemplate(s):void 0}}}function S(e){if(!e?.aborted)return;const t=new Error("模板目录操作已取消");throw t.name="AbortError",t}exports.cloneReportTemplate=G;exports.createLocalTemplateCatalog=H;exports.diffReportTemplates=A;exports.reviewReportTemplate=W;exports.reviewReportTemplateAsync=_;
|
|
1
|
+
"use strict";const w=require("./json-snapshot-DCFEtfFw.cjs"),j=require("./capabilities-D4nfhcvB.cjs"),L=require("./dataset-IrlXbUvh.cjs"),h=require("./template-registry-B-AK1oam.cjs"),E=require("./template-serialization-CqQY4zDg.cjs"),P=require("./param-validation-C-8sRJLq.cjs");function R(e){if(e===void 0)return;const t=typeof e=="string"?e:JSON.stringify(e);return t.length>160?t.slice(0,157)+"…":t}function N(e){return/\.(?:repeat|binding)(?:\.|$)/.test(e)?/\.format(?:\.|$)/.test(e)?"format":"binding":/\.tree\.(?:idField|parentField|childrenField|labelField|input)$/.test(e)?"binding":/\.tree\.parentValues$/.test(e)?"calculation":/\.tree\.indentMm$/.test(e)?"format":/\.(?:computed|computeOptions|groups|groupBy|aggregates|grandTotal)(?:\.|\[|$)/.test(e)?"calculation":/\.(?:dataset|field|rowKey|revisionField|sourceTokenField|foreignKey|parentKey)$/.test(e)?"binding":/\.(?:style|headerStyle|format|rules|align|headerAlign|semanticRole|unit)(?:\.|\[|$)/.test(e)?"format":e.startsWith("$.template")?"structure":"metadata"}function T(e){const t=new Map;for(const r of e){if(!r||typeof r!="object"||!("field"in r)||typeof r.field!="string"||t.has(r.field))return;t.set(r.field,r)}return t}function D(e,t,r){return!e.startsWith("$.template.params")||t==="moved"?!1:/\.(?:type|required|min|max|minLength|maxLength|options|defaultValue)(?:\[|$)/.test(e)?!0:t!=="added"?!1:Array.isArray(r)?r.some(a=>!!a&&typeof a=="object"&&"required"in a&&a.required===!0):!!r&&typeof r=="object"&&"required"in r&&r.required===!0}function A(e,t,r={}){const a=h.parseReportTemplate(e),n=h.parseReportTemplate(t),o=r.maxChanges??500;if(!Number.isSafeInteger(o)||o<1||o>1e4)throw new RangeError("maxChanges must be between 1 and 10000");const s={changes:[],totalChanges:0,breakingChanges:0,truncated:!1};function d(c,l,u,m){const f=N(l),y=c!=="moved"&&(f==="binding"||l==="$.id"||c==="removed"&&f==="structure"||D(l,c,m));s.totalChanges++,y&&s.breakingChanges++,s.changes.length<o&&s.changes.push({kind:c,category:f,path:l,before:R(u),after:R(m),breaking:y})}function p(c,l,u){const m=T(c),f=T(l);if(!m||!f)return!1;const y=new Map(l.map((g,b)=>[g.field,b]));Array.from(m).forEach(([g,b],$)=>{const x=`${u}[${JSON.stringify(g)}]`;f.has(g)?(y.get(g)!==$&&d("moved",x,$,y.get(g)),i(b,f.get(g),x)):d("removed",x,b,void 0)});for(const[g,b]of f)m.has(g)||d("added",`${u}[${JSON.stringify(g)}]`,void 0,b);return!0}function i(c,l,u){if(!(Object.is(c,l)||u==="$.revision")){if(c===void 0||l===void 0){d(c===void 0?"added":"removed",u,c,l);return}if(Array.isArray(c)&&Array.isArray(l)){if((u.endsWith(".columns")||u.endsWith(".params"))&&p(c,l,u))return;for(let m=0;m<Math.max(c.length,l.length);m++)i(c[m],l[m],`${u}[${m}]`)}else if(c&&l&&typeof c=="object"&&typeof l=="object"&&!Array.isArray(c)&&!Array.isArray(l)){const m=c,f=l;for(const y of new Set([...Object.keys(m),...Object.keys(f)]))i(m[y],f[y],`${u}.${y}`)}else d("modified",u,c,l)}}return i(a,n,"$"),s.truncated=s.totalChanges>s.changes.length,s}function M(e,t,r){for(const a of E.collectTemplateDatasetBindings(e)){const n=Object.prototype.hasOwnProperty.call(t,a.dataset)?t[a.dataset]:void 0;if(!n){r.push({code:"dataset",severity:"error",path:`${a.path}.dataset`,message:`未声明数据集 ${a.dataset}`});continue}const o=new Set(n.fields.map(s=>s.field));a.fields.forEach(({field:s,path:d,summary:p})=>{!o.has(s)&&!a.generated.has(s)&&!(p&&a.summaries.has(s))&&r.push({code:"field",severity:"error",path:d,field:s,message:`数据集 ${a.dataset} 缺少字段 ${s}`})})}}function q(e,t,r,a){const n=r.maxSampleRows??1e3;let o;try{o=w.templateValidationDatasets(t,e.datasets,{maxRows:n})}catch(p){return a.push({code:"sample",severity:"error",path:"$.fixtures",fixture:e.name,message:p instanceof Error?p.message:String(p)}),!1}const s=Object.values(o).reduce((p,i)=>p+i.length,0);if(s>n)return a.push({code:"sample",severity:"error",path:"$.fixtures",fixture:e.name,message:`样例 ${s} 行超过预算 ${n},请显式选择验收样例`}),!1;const d=new Set(E.collectTemplateDatasetBindings(t).map(p=>p.dataset));for(const[p,i]of Object.entries(r.dataSchemas??{}).filter(([c])=>d.has(c)))try{const c=L.validateDatasetRows(o[p],i,{path:`$.datasets.${p}`,maxRows:n});if(a.push(...c.issues.map(l=>({...l,code:"sample",severity:"error",fixture:e.name}))),!c.ok)return!1}catch(c){return a.push({code:"dataset",severity:"error",path:`$.dataSchemas.${p}`,message:String(c)}),!1}return!0}function F(e,t){const r=e.pages[t.pageIndex]?.components[t.componentIndex]?.meta?.labelSource;if(r&&typeof r=="object"&&"pageIndex"in r&&"componentIndex"in r&&typeof r.pageIndex=="number"&&typeof r.componentIndex=="number")return{path:`$.template.pages[${r.pageIndex}].components[${r.componentIndex}]`,pageIndex:r.pageIndex,componentIndex:r.componentIndex};const a=e.pages[t.pageIndex]?.meta?.record;if(a&&typeof a=="object"&&"templatePageIndex"in a&&typeof a.templatePageIndex=="number")return{path:`$.template.pages[${a.templatePageIndex}].components[${t.componentIndex}]`,pageIndex:a.templatePageIndex,componentIndex:t.componentIndex}}function B(e,t,r){const a=F(t,r);if(a)return a;const n=t.pages[r.pageIndex]?.components[r.componentIndex],o=/^table:(\d+):(\d+)(?::|$)/.exec(n?.table?.id??"");if(o)return{path:`$.template.pages[${o[1]}].components[${o[2]}]`,pageIndex:Number(o[1]),componentIndex:Number(o[2])};for(const[s,d]of e.pages.entries()){const p=d.components.findIndex(i=>i===n||n?.nid!==void 0&&"nid"in i&&i.nid===n.nid);if(p>=0)return{path:`$.template.pages[${s}].components[${p}]`,pageIndex:s,componentIndex:p}}return{path:"$.template"}}function J(e,t,r,a,n){const o=P.validateReportParams(e.template.params??[],t.params??{});if(n.issues.push(...o.issues.map(s=>({...s,code:"params",severity:"error",fixture:t.name,path:s.path.replace(/^\$\.params/,`$.fixtures[${r}].params`)}))),!!o.ok&&q(t,e.template,a,n.issues))try{const{plan:s,warnings:d}=w.paginateTemplate(e.template,t.datasets,{maxPages:a.maxPages??100,maxCells:a.maxCells??25e4}),p=(a.formats??["pdf","xlsx"]).flatMap(i=>j.inspectOutputCapabilities(s,i));n.issues.push(...d.map(i=>({code:"layout",severity:"warning",path:"$.template",fixture:t.name,message:i}))),n.issues.push(...p.map(i=>({code:"output",severity:a.strictOutputs?"error":"warning",...B(e.template,s,i),fixture:t.name,message:`${i.format}: ${i.message}`,diagnostic:i}))),n.samples.push({name:t.name,pages:s.pages.length,rows:w.templateDatasetRowCount(e.template,t.datasets),diagnostics:p})}catch(s){n.issues.push({code:"layout",severity:"error",path:"$.template",fixture:t.name,message:s instanceof Error?s.message:String(s)})}}function V(e){for(const[r,a]of[["maxPages",e.maxPages],["maxCells",e.maxCells],["maxSampleRows",e.maxSampleRows]])if(a!==void 0&&(!Number.isSafeInteger(a)||a<1))throw new RangeError(`${r} must be a positive safe integer`);if((e.fixtures?.length??0)>20)throw new RangeError("At most 20 review fixtures are allowed");const t=new Set;for(const r of e.fixtures??[]){if(typeof r.name!="string"||!r.name.trim()||r.name.length>120||t.has(r.name))throw new Error("Review fixtures require unique non-empty names of at most 120 characters");t.add(r.name)}}function*C(e,t,r){let a;yield{stage:"template",run:()=>{V(t),a=h.parseReportTemplate(e)}};const n=t.previous;n&&(yield{stage:"baseline",run:()=>{r.changes=A(n,a),r.changes.breakingChanges&&!t.allowBreakingChanges&&r.issues.push({code:"compatibility",severity:"error",path:"$.template",message:`${r.changes.breakingChanges} 项字段或结构变更需要明确确认兼容性`})}}),t.dataSchemas&&(yield{stage:"bindings",run:()=>M(a.template,t.dataSchemas,r.issues)});for(const[o,s]of(t.fixtures??[]).entries())yield{stage:"fixture",fixture:s.name,run:()=>J(a,s,o,t,r)};t.fixtures?.length||r.issues.push({code:"sample",severity:"warning",path:"$.fixtures",message:"未提供验收样例,仅完成结构和字段检查,尚未验证排版与输出"})}function O(e){return e.ok=e.issues.every(t=>t.severity!=="error"),e}function k(e,t){e.issues.push({code:"template",severity:"error",path:"$",message:t instanceof Error?t.message:String(t)})}function W(e,t={}){const r={ok:!1,issues:[],samples:[]};try{for(const a of C(e,t,r))a.run()}catch(a){k(r,a)}return O(r)}function v(e){if(e?.aborted)throw e.reason??new DOMException("Template review was aborted","AbortError")}function K(e){return v(e),new Promise((t,r)=>{const a=()=>{clearTimeout(n),e?.removeEventListener("abort",a),r(e?.reason??new DOMException("Template review was aborted","AbortError"))},n=setTimeout(()=>{e?.removeEventListener("abort",a),t()},0);e?.addEventListener("abort",a,{once:!0}),e?.aborted&&a()})}function I(e,t){try{e.onProgress?.(t)}catch{}}async function _(e,t={}){const r={ok:!1,issues:[],samples:[]},a=t.fixtures?.length??0;let n=0;v(t.signal);try{const o=C(e,t,r),s=o.next();s.done||(s.value.run(),I(t,{completed:n,total:a,stage:s.value.stage})),v(t.signal);for(const d of o)await K(t.signal),v(t.signal),d.run(),d.stage==="fixture"&&n++,I(t,{completed:n,total:a,stage:d.stage,...d.fixture?{fixture:d.fixture}:{}}),v(t.signal)}catch(o){v(t.signal),k(r,o)}return O(r)}function z(e,t){const r=e.publishedRevision??e.published?.revision;for(const a of[e.draftRevision,r])if(a!==void 0&&(typeof a!="string"||!a.trim()))throw new TypeError("模板生命周期修订应为非空字符串");if(e.draftRevision!==void 0&&e.draftRevision!==t.revision)throw new TypeError("可编辑文档应与草稿修订一致");if(e.published&&(e.published.id!==t.id||e.published.revision!==r))throw new TypeError("发布文档身份或修订不一致");if(!e.published&&r!==void 0&&r!==t.revision)throw new TypeError("发布修订需要对应的独立文档");return{...e.draftRevision===void 0?{}:{draftRevision:e.draftRevision},...r===void 0?{}:{publishedRevision:r}}}function G(e,t){const r=h.parseReportTemplate(e);if(t.id===r.id)throw new Error("复制模板应使用新的 ID");const{revision:a,...n}=r;return h.parseReportTemplate({...n,id:t.id,name:t.name})}function H(e){if(!Array.isArray(e)||e.length>1e3)throw new RangeError("本地模板目录最多 1000 项");const t=new Map,r=new Map,a=[];for(const n of e){const o=h.parseReportTemplate(n.document);if(t.has(o.id))throw new Error(`模板 ID 重复:${o.id}`);if(n.category!==void 0&&(typeof n.category!="string"||n.category.length>128)||n.tags!==void 0&&(!Array.isArray(n.tags)||n.tags.length>20||n.tags.some(i=>typeof i!="string"||i.length>128)))throw new TypeError("模板分类和标签无效");const s=z(n,o),{template:d,...p}=o;t.set(o.id,o),n.published?r.set(o.id,h.parseReportTemplate(n.published)):s.publishedRevision&&r.set(o.id,h.parseReportTemplate(o)),a.push({...p,...s,...n.category?{category:n.category}:{},...n.tags?{tags:[...n.tags]}:{}})}return a.sort((n,o)=>n.id<o.id?-1:1),{search:async n=>{S(n.signal);const o=n.limit??30;if(!Number.isSafeInteger(o)||o<1||o>100)throw new RangeError("模板每页数量应为 1–100");const s=n.query?.trim().toLocaleLowerCase()??"",d=a.filter(i=>(!n.category||i.category===n.category)&&(!n.cursor||i.id>n.cursor)&&(!s||[i.id,i.name,i.description,...i.tags??[]].some(c=>c?.toLocaleLowerCase().includes(s)))),p=new Map;for(const i of a)i.category&&p.set(i.category,(p.get(i.category)??0)+1);return JSON.parse(JSON.stringify({items:d.slice(0,o),...d.length>o?{next:d[o-1].id}:{},categories:Array.from(p,([i,c])=>({id:i,label:i,count:c}))}))},get:async(n,o)=>{S(o.signal);const s=o.mode==="published"?r.get(n):t.get(n);return s?h.parseReportTemplate(s):void 0}}}function S(e){if(!e?.aborted)return;const t=new Error("模板目录操作已取消");throw t.name="AbortError",t}exports.cloneReportTemplate=G;exports.createLocalTemplateCatalog=H;exports.diffReportTemplates=A;exports.reviewReportTemplate=W;exports.reviewReportTemplateAsync=_;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const f=require("./template-registry-
|
|
1
|
+
"use strict";const f=require("./template-registry-B-AK1oam.cjs"),T=require("./template-serialization-CqQY4zDg.cjs"),g=require("./diagnostic-collector-wASg6Fzs.cjs");function p(t){return JSON.parse(JSON.stringify(t))}function u(t){return{...t.repeatDataset?{repeat:{dataset:t.repeatDataset}}:{},pages:[{widthMm:4999,heightMm:4999,components:t.components}]}}function y(t){if(!t.id.trim()||!t.name.trim()||!t.revision.trim())throw new Error("Fragment identity, name and revision are required");if(!t.components.length||t.components.length>200)throw new RangeError("A fragment must contain 1–200 components");f.parseReportTemplate({schemaVersion:"1.0",id:t.id,name:t.name,template:u(t)})}function E(t,n,e,a){const r=f.parseReportTemplate(t).template.pages[n];if(!r||!e.length||e.some(o=>!Number.isSafeInteger(o)||!r.components[o]))throw new Error("Select existing components to capture a fragment");const s=[...new Set(e)].map(o=>r.components[o]),l=Math.min(...s.map(o=>o.leftMm)),i=Math.min(...s.map(o=>o.topMm)),m={...a,...t.template.repeat?{repeatDataset:t.template.repeat.dataset}:{},components:p(s).map(o=>({...o,leftMm:o.leftMm-l,topMm:o.topMm-i}))};return y(m),m}function b(t){y(t);const n=new Map;for(const e of T.collectTemplateDatasetBindings(u(t))){const a=n.get(e.dataset)??new Set;for(const r of e.fields)!e.generated.has(r.field)&&!e.summaries.has(r.field)&&a.add(r.field);n.set(e.dataset,a)}return[...n].map(([e,a])=>({dataset:e,fields:[...a]}))}function S(t,n,e){const a=n.replace(/^\$\.template\./,"").replace(/\[(\d+)\]/g,".$1").split(".");let r=t;for(const s of a.slice(0,-1))r=r[s];r[a[a.length-1]]=e}function F(t,n,e={}){const a=u({...t,components:n});for(const r of T.collectTemplateDatasetBindings(a)){for(const l of r.fields){const i=e.fields?.[r.dataset]?.[l.field];i!==void 0&&S(a,l.path,i)}const s=e.datasets?.[r.dataset];s!==void 0&&S(a,`${r.path}.dataset`,s)}}function h(t){if(!t||typeof t!="object")return;if(Array.isArray(t)){t.forEach(h);return}const n=t;for(const e of["nid","rkey","table","source"])delete n[e];if(n.kind==="list"&&delete n.id,n.meta&&typeof n.meta=="object")for(const e of["fragment","labelSource","record"])delete n.meta[e];Object.values(n).forEach(h)}function D(t){const n=new Set(t.template.pages.flatMap(a=>a.components.map(r=>r.meta?.fragment?.instance)));let e=1;for(;n.has(`fragment-${e}`);)e++;return`fragment-${e}`}function R(t,n,e){const a=e?t.components.flatMap((s,l)=>s.meta?.fragment?.instance===e?[l]:[]):[];if(e&&!a.length)throw new Error("Fragment instance no longer exists");const r=a.map(s=>t.components[s]);if(r.some(s=>s.meta?.fragment?.id!==n.id))throw new Error("An upgrade must use the same fragment identity");return{replacing:a,left:r.length?Math.min(...r.map(s=>s.leftMm)):t.marginLeftMm??0,top:r.length?Math.min(...r.map(s=>s.topMm)):t.marginTopMm??0}}function x(t,n){if(n.some(e=>e.leftMm<0||e.topMm<0||e.leftMm+e.widthMm>t.widthMm+.001||e.topMm+(e.kind==="list"?e.rowHeightMm??7:e.heightMm)>t.heightMm+.001))throw new Error("Fragment exceeds the target page; choose a larger page or adjust its placement")}function k(t,n,e){y(n);const a=f.parseReportTemplate(t),r=a.template.pages[e.pageIndex];if(!r||r.flow)throw new Error("Choose a fixed page before inserting a fragment");const s=R(r,n,e.replaceInstance),l=s.replacing,i=e.leftMm??s.left,m=e.topMm??s.top,o=p(n.components),M=e.replaceInstance??D(a);if(n.repeatDataset&&a.template.repeat?.dataset!==(e.bindings?.datasets?.[n.repeatDataset]??n.repeatDataset))throw new Error("Bind this label fragment to the current record dataset");F(n,o,e.bindings),o.forEach(h),o.forEach((c,d)=>{c.leftMm+=i,c.topMm+=m,c.meta={...c.meta,fragment:{id:n.id,revision:n.revision,instance:M,slot:d}}}),x(r,o);const w=l[0]??r.components.length;return r.components=r.components.filter((c,d)=>!l.includes(d)),r.components.splice(w,0,...o),{document:f.parseReportTemplate(a),componentIndices:o.map((c,d)=>w+d),instance:M}}function C(t,n,e,a){const r=f.parseReportTemplate(t),s=r.template.pages[n];if(!s)throw new Error("Page no longer exists");for(const l of e){const i=s.components[l];if(!i)throw new Error("Component no longer exists");i.kind==="list"?a.target==="header"?I(i,a.style):i.columns.forEach(m=>{m.style=g.mergeComponentStyles(m.style,p(a.style)),a.style.align&&(m.align=a.style.align)}):i.style=g.mergeComponentStyles(i.style,p(a.style))}return f.parseReportTemplate(r)}function I(t,n){if(t.headerStyle=g.mergeComponentStyles(t.headerStyle,p(n)),t.columns.forEach(e=>{e.headerStyle=g.mergeComponentStyles(e.headerStyle,p(n)),n.align&&(e.headerAlign=n.align)}),t.headerGrid)for(const e of t.headerGrid.cells)for(const a of e)a&&(a.style=g.mergeComponentStyles(a.style,p(n)))}exports.applyReportDocumentStyle=C;exports.captureTemplateFragment=E;exports.insertTemplateFragment=k;exports.inspectTemplateFragmentBindings=b;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const P=require("./computed-DK6BruFz.cjs"),fe=require("./matrix-DUYPRL7t.cjs"),k=require("./diagnostic-collector-wASg6Fzs.cjs"),de=require("./code-options-BUTChiZZ.cjs"),W=require("./param-validation-C-8sRJLq.cjs"),w=require("./template-serialization-CqQY4zDg.cjs");function ce(e,i,t){e!==void 0&&(typeof e!="string"||!e.trim()||e.length>4096)&&t.push({path:i,message:"来源范围应为不超过 4096 字符的非空字符串"})}function G(e,i,t){e.editable!==void 0&&typeof e.editable!="boolean"&&t.push({path:`${i}.editable`,message:"编辑控制应为布尔值"}),e.valueType!==void 0&&!["text","number","boolean"].includes(e.valueType)&&t.push({path:`${i}.valueType`,message:"编辑类型应为 text、number 或 boolean"})}function ue(e,i,t){G(e,i,t),e.indentMm!==void 0&&(typeof e.indentMm!="number"||!Number.isFinite(e.indentMm)||e.indentMm<0)&&t.push({path:`${i}.indentMm`,message:"单元格缩进应为有限非负数"}),e.derived!==void 0&&typeof e.derived!="boolean"&&t.push({path:`${i}.derived`,message:"派生结果标记应为布尔值"}),U(e.source,`${i}.source`,t,!0),e.formula!==void 0&&typeof e.formula!="string"&&t.push({path:`${i}.formula`,message:"单元格公式应为字符串"})}function U(e,i,t,s=!1){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e)){t.push({path:i,message:"业务来源应为对象"});return}const n=e;ce(n.sourceScope,`${i}.sourceScope`,t);for(const a of["datasetId",...s?["field"]:[]])(typeof n[a]!="string"||!n[a].trim())&&t.push({path:`${i}.${a}`,message:"业务标识应为非空字符串"});for(const a of["rowKey","revision"]){const o=n[a];o===void 0&&!(s&&a==="rowKey")||typeof o!="string"&&!(typeof o=="number"&&Number.isFinite(o))&&t.push({path:`${i}.${a}`,message:"业务键及修订号应为字符串或有限数字"})}n.sourceToken!==void 0&&typeof n.sourceToken!="string"&&t.push({path:`${i}.sourceToken`,message:"来源令牌应为字符串"})}const he=new Set(["text","image","barcode","qrcode","chart","line","rect","ellipse"]);function p(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function R(e){return e===null?"null":typeof e=="string"?JSON.stringify(e.slice(0,120)):["number","boolean","undefined"].includes(typeof e)?String(e):`[${typeof e}]`}function me(e,i,t,s){const n=e[i];(typeof n!="number"||!Number.isFinite(n))&&s.push({path:`${t}.${i}`,message:`应为有限数字,实际 ${R(n)}`})}function ge(e,i,t){if(e!==void 0){const s=`${i}.table`;if(!p(e))t.push({path:s,message:"逻辑表来源应为对象"});else{U(e.source,`${s}.source`,t),(typeof e.id!="string"||!e.id.trim())&&t.push({path:`${s}.id`,message:"逻辑表 ID 应为非空字符串"});const n=e.role;["header","body","group-header","subtotal","grand-total"].includes(n)||t.push({path:`${s}.role`,message:"未知逻辑表行角色"});const a=e.rowIndex;(typeof a!="number"||!Number.isInteger(a)||(n==="header"?a!==-1:a<0))&&t.push({path:`${s}.rowIndex`,message:"表头索引应为 -1,内容行索引应为非负整数"}),(!Array.isArray(e.columnKeys)||e.columnKeys.some(o=>typeof o!="string"))&&t.push({path:`${s}.columnKeys`,message:"逻辑列字段应为字符串数组"}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&t.push({path:`${s}.layout`,message:"布局应为 page 或 wide"}),e.title!==void 0&&typeof e.title!="string"&&t.push({path:`${s}.title`,message:"逻辑表名称应为字符串"})}}}function pe(e,i,t,s){if(e!==void 0)if(!p(e)||!Array.isArray(e.cells))t.push({path:`${i}.grid.cells`,message:"grid.cells 应为二维数组"});else{const n=e.paddingMm;n!==void 0&&(typeof n!="number"||!Number.isFinite(n)||n<0)&&t.push({path:`${i}.grid.paddingMm`,message:"单元格内距应为有限非负数"}),e.cells.forEach((a,o)=>{if(!Array.isArray(a)){t.push({path:`${i}.grid.cells.${o}`,message:"行应为数组"});return}a.forEach((r,f)=>{if(r==null)return;const d=`${i}.grid.cells.${o}.${f}`;if(!p(r)){t.push({path:d,message:"网格单元格应为对象或 null"});return}ue(r,d,t),r.dataBar!==void 0&&!k.validDataBar(r.dataBar)&&t.push({path:`${d}.dataBar`,message:"数据条应包含 0–1 有序比例与 #RRGGBB 颜色"}),z(r.richParagraphs,d,t),Array.isArray(r.children)&&r.children.forEach((c,m)=>{B(c,`${i}.grid.cells.${o}.${f}.children.${m}`,t,s)})})})}}function T(e,i,t,s){e!==void 0&&!i.includes(e)&&s.push({path:t,message:"未知富文本属性值"})}function O(e,i,t,s,n=0){for(const a of i){const o=e[a];o!==void 0&&(typeof o!="number"||!Number.isFinite(o)||o<n)&&s.push({path:`${t}.${a}`,message:"富文本数值应为范围内有限数字"})}}function le(e,i,t){if(e!==void 0){if(!p(e)){t.push({path:i,message:"富文本样式应为对象"});return}for(const s of["fontFamily","color","backgroundColor","lineColor","borderColor"])e[s]!==void 0&&typeof e[s]!="string"&&t.push({path:`${i}.${s}`,message:"富文本样式应为字符串"});for(const s of["bold","italic","underline","borderTop","borderRight","borderBottom","borderLeft"])e[s]!==void 0&&typeof e[s]!="boolean"&&t.push({path:`${i}.${s}`,message:"富文本样式应为布尔值"});O(e,["fontSize","fontSizePx","lineWidthPt","lineHeight","opacity"],i,t),O(e,["letterSpacing","rotateDeg"],i,t,-1/0),typeof e.opacity=="number"&&e.opacity>1&&t.push({path:`${i}.opacity`,message:"透明度不能大于1"}),T(e.align,["left","center","right","justify"],`${i}.align`,t),T(e.verticalAlign,["top","middle","bottom"],`${i}.verticalAlign`,t)}}function ye(e,i,t){if(!p(e)){t.push({path:i,message:"富文本片段应为对象"});return}T(e.kind,["text","field"],`${i}.kind`,t);for(const s of["text","field"])e[s]!==void 0&&typeof e[s]!="string"&&t.push({path:`${i}.${s}`,message:"富文本内容应为字符串"});le(e.style,`${i}.style`,t)}function z(e,i,t){if(e!==void 0){if(!Array.isArray(e)){t.push({path:`${i}.richParagraphs`,message:"richParagraphs 应为数组"});return}e.forEach((s,n)=>{const a=`${i}.richParagraphs.${n}`;if(!p(s)||!Array.isArray(s.segments)){t.push({path:a,message:"段落缺少 segments 数组"});return}T(s.align,["left","center","right","justify"],`${a}.align`,t),O(s,["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"],a,t),s.segments.forEach((o,r)=>ye(o,`${a}.segments.${r}`,t))})}}function D(e,i,t,s=[]){const n=k.componentTreeIssue([e],i);if(n){t.push(n);return}B(e,i,t,s)}function B(e,i,t,s=[]){if(!p(e)){t.push({path:i,message:"组件应为对象"});return}const n=e.kind;typeof n!="string"?t.push({path:`${i}.kind`,message:"组件缺少 kind 字符串"}):he.has(n)||s.push({path:`${i}.kind`,message:`未知组件类型 ${R(n)},将以兜底方式渲染`});for(const a of["leftMm","topMm","widthMm","heightMm"])me(e,a,i,t);typeof e.leftMm=="number"&&e.leftMm<-100&&t.push({path:`${i}.leftMm`,message:"几何数值异常(leftMm<-100)"});for(const a of["widthMm","heightMm"])typeof e[a]=="number"&&e[a]<0&&t.push({path:`${i}.${a}`,message:"组件尺寸不能为负数"});ge(e.table,i,t),be(e.code,n,i,t),$e(e,i,t),e.pageAnchor!==void 0&&!["header","footer"].includes(e.pageAnchor)&&t.push({path:`${i}.pageAnchor`,message:"页面锚点应为 header 或 footer"}),e.lineDirection!==void 0&&!["down","up"].includes(e.lineDirection)&&t.push({path:`${i}.lineDirection`,message:"线段方向应为 down 或 up"}),pe(e.grid,i,t,s),z(e.richParagraphs,i,t)}function $e(e,i,t){if(e.chartBinding!==void 0)try{if(P.validateReportChartBinding(e.chartBinding),e.kind!=="chart"||["binding","imageData","grid","pageAnchor"].some(s=>e[s]!==void 0))throw new Error("绑定图表不能设置图片、网格、记录绑定或页眉页脚");if(typeof e.widthMm!="number"||e.widthMm<45||typeof e.heightMm!="number"||e.heightMm<35)throw new Error("绑定图表至少需要 45×35mm")}catch(s){t.push({path:`${i}.chartBinding`,message:s instanceof Error?s.message:String(s)})}}function be(e,i,t,s){if(e!==void 0)for(const n of de.codeOptionIssues(e,i))s.push({path:`${t}.code${n.path?`.${n.path}`:""}`,message:n.message})}function q(e,i,t){if(!p(e))return;e.binding!==void 0&&t.push({path:`${i}.binding`,message:"渲染计划不允许未解析字段绑定"}),e.chartBinding!==void 0&&t.push({path:`${i}.chartBinding`,message:"渲染计划不允许未解析图表绑定"});const s=e.grid;!p(s)||!Array.isArray(s.cells)||s.cells.forEach((n,a)=>{Array.isArray(n)&&n.forEach((o,r)=>{!p(o)||!Array.isArray(o.children)||o.children.forEach((f,d)=>q(f,`${i}.grid.cells.${a}.${r}.children.${d}`,t))})})}function X(e,i,t,s=[]){if(!p(e)){t.push({path:i,message:"页应为对象"});return}const n=e.pageWidthMm,a=e.pageHeightMm;(typeof n!="number"||!Number.isFinite(n)||n<=0)&&t.push({path:`${i}.pageWidthMm`,message:`页宽非法: ${R(n)}`}),(typeof a!="number"||!(a>0&&a<5e3))&&t.push({path:`${i}.pageHeightMm`,message:`页高非法: ${R(a)}`}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&t.push({path:`${i}.layout`,message:"布局应为 page 或 wide"});const o=e.components;if(!Array.isArray(o))t.push({path:`${i}.components`,message:"components 应为数组"});else if(Array.isArray(o)){const r=k.componentTreeIssue(o,`${i}.components`);if(r){t.push(r);return}o.forEach((f,d)=>{B(f,`${i}.components.${d}`,t,s),q(f,`${i}.components.${d}`,t)})}}function Y(e){const i=[],t=[],s=p(e)?e.pages:void 0;if(p(e)&&e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean"&&i.push({path:"$.requiresRecalculation",message:"重算能力要求应为布尔值"}),!Array.isArray(s))i.push({path:"$.pages",message:e==null?"渲染计划为空":"渲染计划缺少 pages 数组"});else{const n=k.renderTreeIssue(s);if(n)return{ok:!1,errors:[...i,n],warnings:t};s.forEach((o,r)=>X(o,`$.pages.${r}`,i,t)),s.length>2e3&&t.push({path:"$.pages",message:`页数异常大(${s.length} 页),渲染与打印耗时可能显著增加`});const a=s.reduce((o,r)=>o+(p(r)&&Array.isArray(r.components)?r.components.length:0),0);a>5e4&&t.push({path:"$.pages",message:`组件总数异常大(${a} 个),可能触发浏览器性能限制`})}return{ok:i.length===0,errors:i,warnings:t}}function Ae(e){const i=Y(e);if(!i.ok){const t=i.errors.slice(0,3).map(s=>`${s.path}: ${s.message}`).join("; ");throw new Error(`渲染计划校验失败(${i.errors.length} 处): ${t}`)}return e.pages}function Q(e){return e.kind==="list"?e.id:e.nid}function Z(e){return e.kind==="list"?!1:e.pageAnchor!==void 0||e.kind==="text"&&typeof e.text=="string"&&/\{(?:page|totalPages)\}/.test(e.text)}function we(e,i){if(e.filter(s=>s.kind==="list"&&s.cardinality!=="record").length&&e.length!==1)throw new Error("纵向重复区域必须独占流式分段,不能与静态或单记录区域并排");for(const s of e){const n=s.kind==="list"?s.topMm+(s.rowHeightMm??0):s.topMm+s.heightMm;if(s.topMm<i.topMm-.001||n>i.topMm+i.heightMm+.001)throw new Error("流式分段应完整包含其组件的原始纵向范围")}}function Me(e,i){if(!i)return e.map(s=>({components:[s]}));const t=new Map(e.filter(s=>!Z(s)).map(s=>[Q(s),s]));return i.bands.map(s=>({band:s,components:s.componentIds.map(n=>{const a=t.get(n);if(!a)throw new Error(`流式区域引用不存在的组件:${n}`);return a})}))}function ee(e,i){if(!i||!Array.isArray(i.bands)||!i.bands.length||i.bands.length>1e4)throw new Error("流式排版应包含 1–10000 个区域");const t=new Map,s=new Set;for(const n of e){if(Z(n))continue;const a=Q(n);if(!a||t.has(a))throw new Error("流式排版组件应具有唯一标识");t.set(a,n)}if(Ee(i,t,s),s.size!==t.size)throw new Error("流式排版必须显式包含每个非锚点组件")}function Ee(e,i,t){let s=-1/0;for(const n of e.bands){if(!Number.isFinite(n.topMm)||!Number.isFinite(n.heightMm)||n.topMm<0||n.heightMm<=0||n.topMm<s-.001)throw new Error("流式区域应按原始位置排序,尺寸有效且不重叠");if(!Array.isArray(n.componentIds)||!n.componentIds.length)throw new Error("流式区域不能没有组件");const a=[];for(const o of n.componentIds){const r=i.get(o);if(!r||t.has(o))throw new Error(`流式区域组件缺失、重复或包含页锚点:${o}`);t.add(o),a.push(r)}we(a,n),s=n.topMm+n.heightMm}}const ke=new Set(["__proto__","prototype","constructor"]);function $(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function S(e){return typeof e=="string"&&!!e.trim()&&!ke.has(e)}function x(e,i,t,s){for(const n of Object.keys(e))i.includes(n)||s.push({path:`${t}.${n}`,message:"存在未知配置字段"})}function Se(e,i,t){if(e!==void 0){if(!$(e)||!["number","percent","date"].includes(String(e.kind))){t.push({path:i,message:"绑定格式应为 number、percent 或 date"});return}x(e,e.kind==="date"?["kind","pattern"]:e.kind==="number"?["kind","digits","thousands"]:["kind","digits"],i,t),e.digits!==void 0&&(!Number.isInteger(e.digits)||Number(e.digits)<0||Number(e.digits)>100)&&t.push({path:`${i}.digits`,message:"精度应为 0..100 整数"}),e.thousands!==void 0&&typeof e.thousands!="boolean"&&t.push({path:`${i}.thousands`,message:"千分位开关应为布尔值"}),e.pattern!==void 0&&typeof e.pattern!="string"&&t.push({path:`${i}.pattern`,message:"日期格式应为字符串"})}}function ve(e,i,t){const s=e.binding;if(s===void 0)return;const n=`${i}.binding`;if(!$(s)){t.push({path:n,message:"字段绑定应为对象"});return}(!["text","image","barcode","qrcode"].includes(String(e.kind))||e.grid!==void 0)&&t.push({path:n,message:"绑定仅支持独立文本、图片、条码与二维码组件"}),x(s,["field","format","prefix","suffix","emptyText"],n,t),S(s.field)||t.push({path:`${n}.field`,message:"绑定字段应为安全的非空字段名(按字面读取自有字段)"});for(const a of["prefix","suffix","emptyText"])s[a]!==void 0&&typeof s[a]!="string"&&t.push({path:`${n}.${a}`,message:"应为字符串"});Se(s.format,`${n}.format`,t),e.kind==="image"&&["format","prefix","suffix"].some(a=>s[a]!==void 0)&&t.push({path:n,message:"图片绑定直接读取 PNG/JPEG data URL,不支持文本格式或前后缀"})}function Ne(e,i){if(!$(e)){i.push({path:"$.repeat",message:"逐记录配置应为对象"});return}x(e,["dataset","rowKey","copies"],"$.repeat",i),S(e.dataset)||i.push({path:"$.repeat.dataset",message:"数据集应为安全的非空名称"}),e.rowKey!==void 0&&!S(e.rowKey)&&i.push({path:"$.repeat.rowKey",message:"业务主键应为安全的非空字段名"});const t=e.copies;t!==void 0&&($(t)?(x(t,["field"],"$.repeat.copies",i),S(t.field)||i.push({path:"$.repeat.copies.field",message:"复制数字段应为安全的非空字段名"})):(!Number.isSafeInteger(t)||Number(t)<1||Number(t)>1e3)&&i.push({path:"$.repeat.copies",message:"每条记录复制数应为 1..1000 整数"}))}function te(e,i,t,s){if(!$(e))return;ve(e,i,s),e.binding!==void 0&&!t&&s.push({path:`${i}.binding`,message:"字段绑定需要模板 repeat 数据集;普通报表请使用列表字段"}),t&&e.kind==="list"&&s.push({path:i,message:"逐记录标签使用固定组件;动态列表请使用普通报表模板"}),e.chartBinding!==void 0&&(t||i.includes(".children."))&&s.push({path:`${i}.chartBinding`,message:"数据图表应放在普通报表的页面或流式分区,不放在逐记录标签或嵌套单元格内"});const n=e.grid;$(n)&&Array.isArray(n.cells)&&n.cells.forEach((a,o)=>{Array.isArray(a)&&a.forEach((r,f)=>{$(r)&&Array.isArray(r.children)&&r.children.forEach((d,c)=>te(d,`${i}.grid.cells.${o}.${f}.children.${c}`,t,s))})})}function ie(e,i){const t=e.repeat!==void 0;t&&Ne(e.repeat,i),Array.isArray(e.pages)&&e.pages.forEach((s,n)=>{if(!$(s))return;const a=`$.pages.${n}`;t&&(s.layout==="wide"||s.flow!==void 0)&&i.push({path:a,message:"逐记录标签仅支持固定尺寸页面,不支持宽表或流式分区"}),Array.isArray(s.components)&&s.components.forEach((o,r)=>{const f=`${a}.components.${r}`;if(te(o,f,t,i),!t||!$(o))return;const{leftMm:d,topMm:c,widthMm:m,heightMm:l}=o;[d,c,m,l,s.widthMm,s.heightMm].every(y=>typeof y=="number"&&Number.isFinite(y))&&(Number(d)<0||Number(c)<0||Number(d)+Number(m)>Number(s.widthMm)+.001||Number(c)+Number(l)>Number(s.heightMm)+.001)&&i.push({path:f,message:"标签组件超出纸张边界,请调整位置或尺寸"})})})}function Re(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function _(e,i,t){if(e!==void 0)try{P.compileReportPredicate(e)}catch(s){t.push({path:i,message:s instanceof Error?s.message:String(s)})}}function se(e,i,t){if(e===void 0)return;if(!Array.isArray(e)||e.length>2048){t.push({path:i,message:"聚合应为数组且最多 2048 项"});return}const s=new Set;e.forEach((n,a)=>{const o=`${i}.${a}`;if(!Re(n)){t.push({path:o,message:"聚合应为对象"});return}const r=n.field;typeof r!="string"||!r.trim()||s.has(r)?t.push({path:`${o}.field`,message:"聚合输出字段应非空且唯一"}):s.add(r),n.numeric!==void 0&&n.numeric!=="number"&&n.numeric!=="decimal"&&t.push({path:`${o}.numeric`,message:"数值模式应为 number 或 decimal"}),n.digits!==void 0&&(!Number.isInteger(n.digits)||Number(n.digits)<0||Number(n.digits)>100)&&t.push({path:`${o}.digits`,message:"小数位应为 0–100 的整数"});try{P.createAggregateAccumulator({...n,field:n.valueField??r})}catch(f){t.push({path:o,message:f instanceof Error?f.message:String(f)})}})}function Te(e,i,t){if(e===void 0)return;const s=P.validateComputedFields(e);for(const n of s.errors)t.push({path:i,message:n})}function xe(e,i,t){if(e!==void 0)try{fe.validateMatrixOptions(e)}catch(s){t.push({path:i,message:s instanceof Error?s.message:String(s)})}}function Ce(e,i,t){if(e.tree===void 0)return;const s=`${i}.tree`;try{w.validateTreeOptions(e.tree);const n=e.tree;if(e.matrix||e.detail||e.groupBy||Array.isArray(e.groups)&&e.groups.length||e.rowVisibleWhen)throw new Error("树形布局不能同时配置普通分组、矩阵、主从或行可见条件");if(e.rowKey!==void 0&&e.rowKey!==n.idField)throw new Error("树形 rowKey 应与 idField 一致");if(!Array.isArray(e.columns)||!e.columns.some(a=>a&&a.field===n.labelField&&!a.hidden))throw new Error("树形布局需要可见的标签列");Array.isArray(e.computed)&&w.validateTreeComputed(n,e.computed)}catch(n){t.push({path:s,message:n instanceof Error?n.message:String(n)})}}const Pe=new Set(["__proto__","prototype","constructor"]),Fe=new Set(["text","number","boolean","date","decimal"]);function v(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function I(e){return typeof e=="string"&&!!e.trim()&&e.length<=4096&&!Pe.has(e)}function Oe(e,i,t){if(!Array.isArray(e)||!e.length||e.length>2048){t.push({path:i,message:"绑定契约应包含 1–2048 个字段"});return}const s=new Set;e.forEach((n,a)=>{const o=`${i}.${a}`;if(!v(n)||!I(n.field)||s.has(n.field)){t.push({path:o,message:"字段名应安全、非空且唯一"});return}s.add(n.field);for(const r of["label","semanticKey","unit"])n[r]!==void 0&&(typeof n[r]!="string"||String(n[r]).length>4096)&&t.push({path:`${o}.${r}`,message:"应为不超过 4096 位的字符串"});n.type!==void 0&&!Fe.has(String(n.type))&&t.push({path:`${o}.type`,message:"未知绑定字段类型"})})}function L(e,i,t){if(e===void 0)return;if(!v(e)||!v(e.datasets)){t.push({path:i,message:"模板数据契约应声明 datasets"});return}e.source!==void 0&&!I(e.source)&&t.push({path:`${i}.source`,message:"来源应为安全的非空业务标识"});const s=Object.entries(e.datasets);(!s.length||s.length>256)&&t.push({path:`${i}.datasets`,message:"应声明 1–256 个数据集"});for(const[n,a]of s){const o=`${i}.datasets.${n}`;!I(n)||!v(a)?t.push({path:o,message:"数据集应使用安全名称和字段契约"}):Oe(a.fields,`${o}.fields`,t)}}function H(e,i){return new Map(e.datasets[i]?.fields.map(t=>[t.field,t])??[])}function _e(e,i,t,s){const n=e.label||e.field;for(const[a,o,r]of[["semanticKey","semantic","业务含义"],["type","type","类型"],["unit","unit","单位"]])e[a]!==i[a]&&(e[a]!==void 0||i[a]!==void 0)&&s.push({...t,code:o,message:`字段“${n}”的${r}不兼容(${e[a]??"未声明"} → ${i[a]??"未声明"}),请重新绑定`})}function Ie(e,i){const t=[],s=[];if(L(i,"$.target",s),L(e.dataContract,"$.template.dataContract",s),s.length)return{ok:!1,issues:s.map(o=>({...o,code:"contract"}))};const n=e.dataContract;if(!n)return{ok:!1,issues:[{code:"contract",path:"$.template.dataContract",message:"模板未声明数据来源,请核对业务字段并重新绑定"}]};n.source!==i.source&&t.push({code:"source",path:"$.template.dataContract.source",message:`模板来源与当前报表不一致(${n.source??"未声明"} → ${i.source??"未声明"}),请从当前报表创建或重新绑定模板`});const a=new Set;for(const o of w.collectTemplateDatasetBindings(e)){const r=H(n,o.dataset),f=H(i,o.dataset);if(!r.size||!f.size){t.push({code:"dataset",dataset:o.dataset,path:o.path,message:`数据集“${o.dataset}”缺少来源或目标字段契约`});continue}for(const d of o.fields){if(o.generated.has(d.field)||d.summary&&o.summaries.has(d.field))continue;const c=`${o.dataset}\0${d.field}`;if(a.has(c))continue;a.add(c);const m=r.get(d.field),l=f.get(d.field),y={...d,dataset:o.dataset};!m||!l?t.push({...y,code:"field",message:`数据集“${o.dataset}”的字段“${d.field}”未声明,请重新绑定`}):_e(m,l,y,t)}}return{ok:t.length===0,issues:t}}const V="1.0";class M extends Error{constructor(i){super(`模板校验失败:${i.slice(0,3).map(t=>`${t.path}: ${t.message}`).join("; ")}`),this.errors=i,this.name="ReportTemplateError"}}const Le=new Set(["__proto__","prototype","constructor"]),De=new Set(["schemaVersion","id","name","revision","description","template"]),Be=new Set(["left","center","right","justify"]),N=2e5,Ve=64;function u(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function je(e,i,t){const s=Object.getPrototypeOf(e),n=Array.isArray(e);if(n?s!==Array.prototype:s!==Object.prototype&&s!==null)return t.push({path:i,message:"模板对象必须使用普通 JSON 对象原型"}),!1;if(n){const a=Object.keys(e);if(a.length!==e.length||a.some(o=>!/^(0|[1-9]\d*)$/.test(o)||Number(o)>=e.length))return t.push({path:i,message:"模板数组不能包含空位或额外属性"}),!1}return Object.getOwnPropertySymbols(e).length>0?(t.push({path:i,message:"模板不能包含 Symbol 键"}),!1):!0}function Ke(e,i,t,s){return Le.has(e)?(s.push({path:t,message:"模板不能包含可能污染原型的键"}),!1):i.get||i.set||!i.enumerable?(s.push({path:t,message:"模板不能包含访问器或不可枚举字段"}),!1):!0}function He(e){return e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)}function j(e,i){const t=new Set;let s=0,n=0,a=!1;const o=(r,f,d)=>{if(!a){if(++s>N){s===N+1&&i.push({path:f,message:"模板超过 JSON 节点安全上限"});return}if(d>Ve){i.push({path:f,message:"模板嵌套层级过深"});return}if(typeof r=="string"){n+=r.length,n>w.MAX_TEMPLATE_JSON_CHARACTERS&&(a=!0,i.push({path:f,message:"模板文本超过 1000 万字符的安全上限"}));return}if(!He(r)){if(!r||typeof r!="object"){i.push({path:f,message:"模板只允许 JSON 值,不允许函数、undefined 或非有限数字"});return}if(t.has(r)){i.push({path:f,message:"模板不能包含循环引用"});return}if(je(r,f,i)){t.add(r);for(const[c,m]of Object.entries(Object.getOwnPropertyDescriptors(r))){if(Array.isArray(r)&&c==="length")continue;const l=`${f}.${c}`;if(Ke(c,m,l,i)&&o(m.value,l,d+1),s>N||a)break}t.delete(r)}}}};o(e,"$",0)}function h(e,i,t,s,n=!1){const a=e[i];a===void 0&&!n||(typeof a!="string"||n&&!a.trim())&&s.push({path:`${t}.${i}`,message:n?"应为非空字符串":"应为字符串"})}function g(e,i,t,s,n=0,a=!1){const o=e[i];o===void 0&&!a||(typeof o!="number"||!Number.isFinite(o)||o<n)&&s.push({path:`${t}.${i}`,message:`应为大于等于 ${n} 的有限数字`})}function A(e,i,t,s){e[i]!==void 0&&typeof e[i]!="boolean"&&s.push({path:`${t}.${i}`,message:"应为布尔值"})}function E(e,i,t,s=!1){e!==void 0&&!Be.has(e)&&!(s&&e==="auto")&&t.push({path:i,message:`未知对齐方式${s?"(支持 auto)":""}`})}function b(e,i,t){if(e!==void 0){if(!u(e)){t.push({path:i,message:"样式应为对象"});return}E(e.align,`${i}.align`,t),e.verticalAlign!==void 0&&!["top","middle","bottom"].includes(e.verticalAlign)&&t.push({path:`${i}.verticalAlign`,message:"未知垂直对齐方式"});for(const s of["fontSize","fontSizePx","lineWidthPt","lineHeight"])g(e,s,i,t);for(const s of["letterSpacing","rotateDeg"])g(e,s,i,t,-1/0);g(e,"opacity",i,t),typeof e.opacity=="number"&&e.opacity>1&&t.push({path:`${i}.opacity`,message:"透明度不能大于 1"});for(const s of["bold","italic","underline","borderTop","borderRight","borderBottom","borderLeft"])A(e,s,i,t);for(const s of["fontFamily","color","backgroundColor","lineColor","borderColor"])h(e,s,i,t)}}function Je(e,i,t){if(e===void 0)return;if(!Array.isArray(e)){t.push({path:i,message:"参数定义应为数组"});return}const s=new Set,n=t.length;e.forEach((a,o)=>{const r=`${i}.${o}`;if(!u(a)){t.push({path:r,message:"参数定义应为对象"});return}h(a,"field",r,t,!0),typeof a.field=="string"&&(s.has(a.field)&&t.push({path:`${r}.field`,message:"参数名重复"}),s.add(a.field)),a.type!==void 0&&!["text","number","date","month","year","dateRange","select","multiSelect","cascader","numberRange"].includes(a.type)&&t.push({path:`${r}.type`,message:"未知参数类型"});for(const f of["label","defaultValue","placeholder"])h(a,f,r,t);A(a,"required",r,t);for(const f of["minLength","maxLength"]){const d=a[f];d!==void 0&&(typeof d!="number"||!Number.isSafeInteger(d)||d<0)&&t.push({path:`${r}.${f}`,message:"长度边界应为非负整数"})}We(a,r,t),a.options!==void 0&&(Array.isArray(a.options)?a.options.forEach((f,d)=>{const c=`${r}.options.${d}`;if(!u(f))t.push({path:c,message:"选项应为对象"});else for(const m of["label","value"])typeof f[m]!="string"&&t.push({path:`${c}.${m}`,message:"选项标签与值应为字符串(允许空白选项)"})}):t.push({path:`${r}.options`,message:"选项应为数组"}))}),t.length===n&&t.push(...W.validateReportParamDefinitions(e).map(a=>({path:a.path.replace("$.paramDefs",i),message:a.message})))}function We(e,i,t){for(const a of["min","max"]){const o=e[a];if(o===void 0)continue;W.isReportTemporalBound(e.type,o)||["number","numberRange"].includes(e.type)&&typeof o=="number"&&Number.isFinite(o)||t.push({path:`${i}.${a}`,message:"数字使用有限数字边界,日期/月/年使用对应规范字符串边界"})}const s=typeof e.min=="number"&&typeof e.max=="number"&&e.min>e.max,n=typeof e.min=="string"&&typeof e.max=="string"&&e.min>e.max;(s||n)&&t.push({path:i,message:"最小边界不能大于最大边界"}),typeof e.minLength=="number"&&typeof e.maxLength=="number"&&e.minLength>e.maxLength&&t.push({path:i,message:"最小长度不能大于最大长度"})}function ne(e,i,t){if(!Array.isArray(e)||e.length===0){t.push({path:i,message:"列表至少需要一列"});return}e.every(s=>u(s)&&s.hidden===!0)&&t.push({path:i,message:"列表至少需要一列可见列"}),e.forEach((s,n)=>{const a=`${i}.${n}`;if(!u(s)){t.push({path:a,message:"列应为对象"});return}if(G(s,a,t),s.visual!==void 0&&!w.validColumnVisual(s.visual)&&t.push({path:`${a}.visual`,message:"列可视化配置无效,请检查类型、数值范围和颜色"}),A(s,"hidden",a,t),_(s.visibleWhen,`${a}.visibleWhen`,t),typeof s.header!="string"&&t.push({path:`${a}.header`,message:"表头应为字符串(允许空白表头)"}),h(s,"field",a,t,!0),g(s,"widthMm",a,t,Number.MIN_VALUE,!0),b(s.style,`${a}.style`,t),b(s.headerStyle,`${a}.headerStyle`,t),E(s.align,`${a}.align`,t,!0),E(s.headerAlign,`${a}.headerAlign`,t),s.semanticRole!==void 0&&!["identifier","dimension","measure","date","text"].includes(s.semanticRole)&&t.push({path:`${a}.semanticRole`,message:"未知列语义"}),s.format!==void 0)if(!u(s.format)||!["number","percent","date"].includes(s.format.kind))t.push({path:`${a}.format`,message:"未知列格式"});else{const o=s.format.digits;o!==void 0&&(typeof o!="number"||!Number.isInteger(o)||o<0||o>100)&&t.push({path:`${a}.format.digits`,message:"小数位应为 0–100 的整数"}),A(s.format,"thousands",`${a}.format`,t),h(s.format,"pattern",`${a}.format`,t)}s.rules!==void 0&&(Array.isArray(s.rules)?s.rules.forEach((o,r)=>{const f=`${a}.rules.${r}`;if(!u(o)||!u(o.when)){t.push({path:f,message:"条件格式缺少 when 对象"});return}_(o.when,`${f}.when`,t),b(o.style,`${f}.style`,t)}):t.push({path:`${a}.rules`,message:"条件格式应为数组"}))})}function ae(e,i,t){if(e!==void 0){if(!u(e)){t.push({path:i,message:"分组应为对象"});return}h(e,"field",i,t,!0);for(const s of["headerTemplate","subtotalLabel"])h(e,s,i,t);for(const s of["headerStyle","subtotalStyle"])b(e[s],`${i}.${s}`,t);A(e,"keepWithNext",i,t),A(e,"repeatHeader",i,t),se(e.aggregates,`${i}.aggregates`,t),e.subtotal!==void 0&&(!Array.isArray(e.subtotal)||e.subtotal.some(s=>typeof s!="string"))&&t.push({path:`${i}.subtotal`,message:"小计字段应为字符串数组"})}}function Ge(e,i,t){if(!(e===void 0||typeof e=="boolean")){if(!u(e)){t.push({path:i,message:"合计应为布尔值或对象"});return}h(e,"label",i,t),se(e.aggregates,`${i}.aggregates`,t),b(e.style,`${i}.style`,t),e.fields!==void 0&&(!Array.isArray(e.fields)||e.fields.some(s=>typeof s!="string"))&&t.push({path:`${i}.fields`,message:"合计字段应为字符串数组"})}}function Ue(e,i,t,s){const n={kind:"rect",leftMm:0,topMm:0,widthMm:1,heightMm:1,grid:e};if(D(n,t,s,[]),K(n,t,s),!u(e)||!Array.isArray(e.cells))return;const a=e.cells,o=Array.isArray(i)?i.length:0;if(a.length*o>N){s.push({path:t,message:"表头逻辑网格超过 20 万格安全上限"});return}e.cells.length||s.push({path:`${t}.cells`,message:"表头至少需要一行"}),Array.isArray(e.colWidthsMm)&&e.colWidthsMm.length!==o&&s.push({path:`${t}.colWidthsMm`,message:"表头列宽数量应与列表列数一致"}),Array.isArray(e.rowHeightsMm)&&e.rowHeightsMm.length!==e.cells.length&&s.push({path:`${t}.rowHeightsMm`,message:"表头行高数量应与行数一致"}),ze(a,o,t,s)}function ze(e,i,t,s){const n=new Set;e.forEach((a,o)=>{if(!Array.isArray(a))return;let r=0;a.forEach((f,d)=>{for(;n.has(`${o}:${r}`);)r++;const c=u(f)&&typeof f.colSpan=="number"?f.colSpan:1,m=u(f)&&typeof f.rowSpan=="number"?f.rowSpan:1;(r+c>i||o+m>e.length)&&s.push({path:`${t}.cells.${o}.${d}`,message:"表头合并区域超出表头边界"});for(let l=o;l<Math.min(e.length,o+m);l++)for(let y=r;y<Math.min(i,r+c);y++)n.has(`${l}:${y}`)&&s.push({path:`${t}.cells.${o}.${d}`,message:"表头合并区域重叠"}),n.add(`${l}:${y}`);r+=c})})}function qe(e,i,t){if(Ce(e,i,t),Te(e.computed,`${i}.computed`,t),xe(e.matrix,`${i}.matrix`,t),e.matrix&&(e.detail||e.groupBy||Array.isArray(e.groups)&&e.groups.length||e.grandTotal)&&t.push({path:`${i}.matrix`,message:"矩阵请使用自身 totals 汇总,不能同时配置普通分组、总计或主从明细"}),_(e.rowVisibleWhen,`${i}.rowVisibleWhen`,t),e.groups!==void 0&&(!Array.isArray(e.groups)||e.groups.length>16?t.push({path:`${i}.groups`,message:"分组应为数组,最多 16 级"}):e.groups.forEach((a,o)=>ae(a,`${i}.groups.${o}`,t))),e.detail===void 0)return;const s=e.detail,n=`${i}.detail`;if(!u(s)){t.push({path:n,message:"主从关联应为对象"});return}for(const a of["dataset","parentKey","foreignKey"])h(s,a,n,t,!0);for(const a of["rowKey","revisionField","sourceTokenField"])h(s,a,n,t,s[a]!==void 0);h(s,"label",n,t),A(s,"header",n,t),g(s,"rowHeightMm",n,t,Number.MIN_VALUE),ne(s.columns,`${n}.columns`,t),s.unmatched!==void 0&&s.unmatched!=="error"&&s.unmatched!=="ignore"&&t.push({path:`${n}.unmatched`,message:"未关联明细策略应为 error 或 ignore"})}function Xe(e,i,t){for(const s of["leftMm","topMm"])g(e,s,i,t,-1/0,!0);g(e,"widthMm",i,t,Number.MIN_VALUE,!0),h(e,"dataset",i,t,!0),h(e,"title",i,t);for(const s of["rowKey","revisionField","sourceTokenField"])h(e,s,i,t,e[s]!==void 0);e.headerGrid!==void 0&&Ue(e.headerGrid,e.columns,`${i}.headerGrid`,t),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&t.push({path:`${i}.layout`,message:"布局应为 page 或 wide"}),ne(e.columns,`${i}.columns`,t);for(const s of["fontSizePt","rowHeightMm"])g(e,s,i,t,Number.MIN_VALUE);g(e,"paddingMm",i,t);for(const s of["header","headerBold","headerEveryPage","border"])A(e,s,i,t);e.cardinality!==void 0&&e.cardinality!=="record"&&t.push({path:`${i}.cardinality`,message:"单记录区域类型应为 record"}),h(e,"headerBackgroundColor",i,t),E(e.align,`${i}.align`,t,!0),E(e.headerAlign,`${i}.headerAlign`,t),b(e.headerStyle,`${i}.headerStyle`,t),qe(e,i,t),ae(e.groupBy,`${i}.groupBy`,t),Ge(e.grandTotal,`${i}.grandTotal`,t)}function J(e,i,t){Array.isArray(e.richParagraphs)&&e.richParagraphs.forEach((s,n)=>{if(!u(s))return;const a=`${i}.richParagraphs.${n}`;E(s.align,`${a}.align`,t);for(const o of["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"])g(s,o,a,t);Array.isArray(s.segments)&&s.segments.forEach((o,r)=>{const f=`${a}.segments.${r}`;if(!u(o)){t.push({path:f,message:"富文本片段应为对象"});return}o.kind!==void 0&&o.kind!=="text"&&o.kind!=="field"&&t.push({path:`${f}.kind`,message:"未知富文本片段类型"});for(const d of["text","field"])h(o,d,f,t);b(o.style,`${f}.style`,t)})})}function K(e,i,t){b(e.style,`${i}.style`,t);for(const n of["text","rawText","imageData","fallbackText","nid","rkey"])h(e,n,i,t);if(e.lines!==void 0&&(!Array.isArray(e.lines)||e.lines.some(n=>typeof n!="string"))&&t.push({path:`${i}.lines`,message:"文本行应为字符串数组"}),J(e,i,t),!u(e.grid))return;const s=e.grid;g(s,"gapMm",`${i}.grid`,t),g(s,"paddingMm",`${i}.grid`,t);for(const n of["colWidthsMm","rowHeightsMm"]){const a=s[n];a!==void 0&&(!Array.isArray(a)||a.some(o=>typeof o!="number"||!Number.isFinite(o)||o<0))&&t.push({path:`${i}.grid.${n}`,message:"网格尺寸应为有限非负数字数组"})}Array.isArray(s.cells)&&s.cells.forEach((n,a)=>{Array.isArray(n)&&n.forEach((o,r)=>{const f=`${i}.grid.cells.${a}.${r}`;if(o!==null){if(!u(o)){t.push({path:f,message:"网格单元格应为对象或 null"});return}for(const d of["text","rawText","numberFormat"])h(o,d,f,t);for(const d of["colSpan","rowSpan"]){const c=o[d];c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<=0)&&t.push({path:`${f}.${d}`,message:"跨度应为正整数"})}o.value!==void 0&&o.value!==null&&!["string","number","boolean"].includes(typeof o.value)&&t.push({path:`${f}.value`,message:"Excel 原始值应为字符串、数字、布尔值或 null"}),b(o.style,`${f}.style`,t),J(o,f,t),o.children!==void 0&&(Array.isArray(o.children)?o.children.forEach((d,c)=>{u(d)&&K(d,`${f}.children.${c}`,t)}):t.push({path:`${f}.children`,message:"嵌套组件应为数组"}))}})})}function Ye(e,i,t){if(!(e.flow===void 0||!Array.isArray(e.components)))try{ee(e.components,e.flow)}catch(s){t.push({path:`${i}.flow`,message:s instanceof Error?s.message:String(s)})}}function oe(e){const i=[],t=[];return j(e,i),i.length?{ok:!1,errors:i,warnings:t}:(u(e)?(e.schemaVersion!==void 0&&e.schemaVersion!==k.RENDER_PLAN_SCHEMA_VERSION&&i.push({path:"$.schemaVersion",message:"不支持的模板 schemaVersion"}),Je(e.params,"$.params",i),L(e.dataContract,"$.dataContract",i),ie(e,i),!Array.isArray(e.pages)||e.pages.length===0?i.push({path:"$.pages",message:"模板至少需要一页"}):e.pages.forEach((s,n)=>{const a=`$.pages.${n}`;if(!u(s)){i.push({path:a,message:"页应为对象"});return}g(s,"widthMm",a,i,Number.MIN_VALUE,!0),g(s,"heightMm",a,i,Number.MIN_VALUE,!0),s.layout!==void 0&&s.layout!=="page"&&s.layout!=="wide"&&i.push({path:`${a}.layout`,message:"布局应为 page 或 wide"}),typeof s.heightMm=="number"&&s.heightMm>=5e3&&i.push({path:`${a}.heightMm`,message:"页高应小于 5000mm"});for(const o of["marginTopMm","marginBottomMm","marginLeftMm","marginRightMm"])g(s,o,a,i);typeof s.widthMm=="number"&&Number(s.marginLeftMm??0)+Number(s.marginRightMm??0)>=s.widthMm&&i.push({path:a,message:"横向页边距占满页面"}),typeof s.heightMm=="number"&&Number(s.marginTopMm??0)+Number(s.marginBottomMm??0)>=s.heightMm&&i.push({path:a,message:"纵向页边距占满页面"}),Array.isArray(s.components)?s.components.forEach((o,r)=>{const f=`${a}.components.${r}`;u(o)&&o.kind==="list"?Xe(o,f,i):(D(o,f,i,t),u(o)&&K(o,f,i))}):i.push({path:`${a}.components`,message:"组件应为数组"}),Ye(s,a,i)})):i.push({path:"$",message:"模板应为对象"}),{ok:i.length===0,errors:i,warnings:t})}function re(e){const i=[],t=[];if(j(e,i),i.length)return{ok:!1,errors:i,warnings:t};if(!u(e))i.push({path:"$",message:"模板文档应为对象"});else{for(const n of Object.keys(e))De.has(n)||i.push({path:`$.${n}`,message:"模板文档存在未知字段;只保存模板与描述,不保存取数或业务数据"});e.schemaVersion!==V&&i.push({path:"$.schemaVersion",message:"不支持的模板文档版本"});for(const n of["id","name"])h(e,n,"$",i,!0);for(const n of["revision","description"])h(e,n,"$",i);const s=oe(e.template);i.push(...s.errors.map(n=>({...n,path:`$.template${n.path.slice(1)}`}))),t.push(...s.warnings.map(n=>({...n,path:`$.template${n.path.slice(1)}`})))}return{ok:i.length===0,errors:i,warnings:t}}function F(e){const i=re(e);if(!i.ok)throw new M(i.errors)}function Qe(e){const i=[];if(j(e,i),i.length)throw new M(i);const t={...e,schemaVersion:e.schemaVersion??V};return F(t),C(t)}function Ze(e){let i=e;if(typeof e=="string"){if(e.length>w.MAX_TEMPLATE_JSON_CHARACTERS)throw new M([{path:"$",message:"模板 JSON 超过 1000 万字符的导出/导入上限"}]);try{i=JSON.parse(e)}catch{throw new M([{path:"$",message:"模板 JSON 语法无效"}])}}return F(i),C(i)}function et(e){F(e);try{return w.stringifyValidatedTemplate(e)}catch(i){throw i instanceof RangeError?new M([{path:"$",message:i.message}]):i}}function C(e){return JSON.parse(JSON.stringify(e))}function tt(e=[]){const i=new Map,t={get:s=>{const n=i.get(s);return n?C(n):void 0},list:()=>Array.from(i.values(),({template:s,...n})=>({...n})),register:(s,n={})=>{if(F(s),i.has(s.id)&&!n.replace)throw new M([{path:"$.id",message:`模板 ID ${s.id} 已注册;更新需显式 replace:true`}]);i.set(s.id,C(s))},remove:s=>i.delete(s)};for(const s of e)t.register(s);return t}exports.REPORT_TEMPLATE_DOCUMENT_VERSION=V;exports.ReportTemplateError=M;exports.assertRenderPlan=Ae;exports.createTemplateRegistry=tt;exports.defineReportTemplate=Qe;exports.inspectReportTemplateCompatibility=Ie;exports.parseReportTemplate=Ze;exports.reportFlowGroups=Me;exports.serializeReportTemplate=et;exports.validateComponent=D;exports.validatePage=X;exports.validateRenderPlan=Y;exports.validateReportPageFlow=ee;exports.validateReportTemplate=oe;exports.validateReportTemplateDocument=re;exports.validateTemplateRepeat=ie;
|