@agile-team/mach-report 2.19.1 → 2.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +22 -3
  2. package/dist/ExcelBindingWizard-B2xXBOJu.cjs +1 -0
  3. package/dist/{ExcelBindingWizard-xJIYmnZ_.js → ExcelBindingWizard-CixTPQAL.js} +351 -351
  4. package/dist/ParamEditor-DhHlNxai.cjs +1 -0
  5. package/dist/{ParamEditor-D1wWemaf.js → ParamEditor-gKhvEsnr.js} +10 -10
  6. package/dist/{ReportBatchPanel-BkJFqeEW.cjs → ReportBatchPanel-BUdUfTdm.cjs} +1 -1
  7. package/dist/{ReportBatchPanel-B88R-fME.js → ReportBatchPanel-D-lyWKyf.js} +2 -2
  8. package/dist/ReportLabelStudio-BcjQt73a.cjs +1 -0
  9. package/dist/ReportLabelStudio-N2w6DdaZ.js +764 -0
  10. package/dist/ReportParamPanel-CVpK8mFc.cjs +1 -0
  11. package/dist/{ReportParamPanel-mQkeN70Q.js → ReportParamPanel-peB-KEmm.js} +10 -2
  12. package/dist/{ReportPreview-DBbctg6C.js → ReportPreview-BBJNlu2U.js} +2093 -1978
  13. package/dist/ReportPreview-nf4Dk1Jc.cjs +6 -0
  14. package/dist/{ReportTemplateLibrary-BOh2MgjQ.cjs → ReportTemplateLibrary-Cs9WKneQ.cjs} +1 -1
  15. package/dist/{ReportTemplateLibrary-BGELmgd3.js → ReportTemplateLibrary-WZl-AK-2.js} +1 -1
  16. package/dist/{RuleEditor-CoLqgehG.js → RuleEditor-DGpmjCko.js} +178 -174
  17. package/dist/RuleEditor-Dtcq-7LO.cjs +1 -0
  18. package/dist/{TemplateOutlinePanel-DiG8tRRe.cjs → TemplateOutlinePanel-CkCh506f.cjs} +1 -1
  19. package/dist/{TemplateOutlinePanel-DU95loB-.js → TemplateOutlinePanel-cxp95OT9.js} +1 -1
  20. package/dist/{TemplateReusePanel-DE1KSD6c.js → TemplateReusePanel-BZ8VTtrO.js} +2 -2
  21. package/dist/{TemplateReusePanel-G-Y299wc.cjs → TemplateReusePanel-CwttuSta.cjs} +1 -1
  22. package/dist/{TemplateReviewPanel-KQx9ts0D.cjs → TemplateReviewPanel-C2YjiaEC.cjs} +1 -1
  23. package/dist/{TemplateReviewPanel-vqFJ_Y9o.js → TemplateReviewPanel-C9cTvsRs.js} +1 -1
  24. package/dist/artifact-integrity.json +92 -94
  25. package/dist/{assets-2eC3mOcV.js → assets-CxHunY_9.js} +2 -2
  26. package/dist/{assets-B0Hxn4l6.cjs → assets-vbjAGgk8.cjs} +1 -1
  27. package/dist/{auto-BlchZ1b8.js → auto-BkdGiNtr.js} +4 -4
  28. package/dist/{auto-B0EZFIK1.cjs → auto-Tq7ReIC1.cjs} +1 -1
  29. package/dist/{component-tree-CvW4lzpv.js → component-tree-1_QCiQJX.js} +1 -1
  30. package/dist/component-tree-BjZIp6w9.cjs +1 -0
  31. package/dist/{data-bar-PtjXhMgN.js → data-bar-8baGYEZ9.js} +1 -1
  32. package/dist/{data-bar-Ce38juRZ.cjs → data-bar-YltqGTaC.cjs} +1 -1
  33. package/dist/designer-CDqok4S5.cjs +2 -0
  34. package/dist/designer-CIDHt5xz.js +6869 -0
  35. package/dist/designer.cjs +1 -1
  36. package/dist/designer.d.cts +166 -7
  37. package/dist/designer.d.ts +166 -7
  38. package/dist/designer.js +1 -1
  39. package/dist/{encoding-B--eZpp1.cjs → encoding-B79hW4zq.cjs} +1 -1
  40. package/dist/{encoding-mctOLocI.js → encoding-BSeUwrN7.js} +2 -2
  41. package/dist/{font-loader-DBBJ5KE9.cjs → font-loader-BB372_XN.cjs} +1 -1
  42. package/dist/{font-loader-DW8tIaNp.js → font-loader-Di0lQKFf.js} +1 -1
  43. package/dist/grid-geometry-D3SJgWFv.js +136 -0
  44. package/dist/grid-geometry-D8ReblRV.cjs +1 -0
  45. package/dist/index.cjs +6 -6
  46. package/dist/index.js +194 -195
  47. package/dist/json-snapshot-I5VI84Vp.cjs +2 -0
  48. package/dist/{json-snapshot-By4ZVVUt.js → json-snapshot-Kgn459Oj.js} +895 -879
  49. package/dist/{pdf-DqyxJ96U.cjs → pdf-CARdBcuw.cjs} +45 -45
  50. package/dist/{pdf-CKROKygt.js → pdf-DmlnL5eB.js} +13 -14
  51. package/dist/pdf.cjs +1 -1
  52. package/dist/pdf.js +2 -2
  53. package/dist/{plugin-CPyHs4UC.cjs → plugin-BaRUGORD.cjs} +1 -1
  54. package/dist/{plugin-DsXJRR6Q.js → plugin-D4kAxfLG.js} +1 -1
  55. package/dist/{prefill-D7EswyTI.cjs → prefill-Bpyn58AZ.cjs} +1 -1
  56. package/dist/{prefill-B8H9qwE4.js → prefill-CJSazcVY.js} +2 -2
  57. package/dist/{prepared-CGVphji3.cjs → prepared-BiSz_9vN.cjs} +1 -1
  58. package/dist/{prepared-BE-4jfX5.js → prepared-BwjwEzFz.js} +1 -1
  59. package/dist/{protocol-Cr81vFSQ.js → protocol-Bs9-ohHN.js} +3 -3
  60. package/dist/{protocol-ByRVzzQG.cjs → protocol-C8VWF9An.cjs} +1 -1
  61. package/dist/record-bindings-Ct1HkPrc.cjs +1 -0
  62. package/dist/{record-bindings-DEJtmo3p.js → record-bindings-VZGS-Qd8.js} +1 -1
  63. package/dist/{region-binding-workflow-CBg0l_tj.js → region-binding-workflow-Cy4GIOUo.js} +2 -2
  64. package/dist/{region-binding-workflow-D05tOYn3.cjs → region-binding-workflow-JNowHd0A.cjs} +1 -1
  65. package/dist/report-encoding-worker.cjs +1 -1
  66. package/dist/report-encoding-worker.js +1 -1
  67. package/dist/rich-text-layout-K48VHUoW.cjs +3 -0
  68. package/dist/{rich-text-layout-Ct5WrY1g.js → rich-text-layout-wxBhnAS7.js} +1 -1
  69. package/dist/{runtime-CEMvybO7.js → runtime-BDf5x1i1.js} +5 -5
  70. package/dist/runtime-DsJt1PIf.cjs +1 -0
  71. package/dist/sbom.cdx.json +1 -1
  72. package/dist/server-node.cjs +4 -4
  73. package/dist/server-node.js +1272 -1274
  74. package/dist/server.cjs +1 -1
  75. package/dist/server.js +8 -8
  76. package/dist/style.css +1 -1
  77. package/dist/{template-catalog-CmbWOJqy.js → template-catalog-DFwIS9aN.js} +3 -3
  78. package/dist/{template-catalog-Utu4GP09.cjs → template-catalog-D_2jdnkL.cjs} +1 -1
  79. package/dist/template-fragments-DZVUBhuB.cjs +1 -0
  80. package/dist/{template-fragments-DWgo9tlZ.js → template-fragments-Dng-AlHk.js} +11 -11
  81. package/dist/{template-registry-BIhIHOab.js → template-registry-DhBqoD7W.js} +120 -118
  82. package/dist/template-registry-DpLUSLwF.cjs +1 -0
  83. package/dist/{column-visual-BpgQVWwT.js → template-serialization-Cc3h-miv.js} +74 -65
  84. package/dist/{column-visual-CtYxnBCP.cjs → template-serialization-D1R5oAqh.cjs} +1 -1
  85. package/dist/{textwrap-BEIg2w8y.js → textwrap-CkGjRFT3.js} +1 -1
  86. package/dist/textwrap-OTOUMr4f.cjs +4 -0
  87. package/dist/vue/async.d.cts +8 -0
  88. package/dist/vue/async.d.ts +8 -0
  89. package/dist/vue/index.d.cts +10 -2
  90. package/dist/vue/index.d.ts +10 -2
  91. package/dist/vue-async.cjs +1 -1
  92. package/dist/vue-async.js +3 -3
  93. package/dist/vue.cjs +1 -1
  94. package/dist/vue.js +6 -6
  95. package/dist/{workbook-session-B94EwVa_.cjs → workbook-session-NYv01LHe.cjs} +1 -1
  96. package/dist/{workbook-session-BoScoOg-.js → workbook-session-oinxX3qo.js} +2 -2
  97. package/dist/worker.cjs +1 -1
  98. package/dist/worker.js +4 -4
  99. package/dist/xlsx.cjs +4 -4
  100. package/dist/xlsx.js +204 -205
  101. package/package.json +1 -1
  102. package/dist/ExcelBindingWizard-UHSApSG9.cjs +0 -1
  103. package/dist/ParamEditor-BZb-okUd.cjs +0 -1
  104. package/dist/ReportLabelStudio-B4WZ2XNN.js +0 -239
  105. package/dist/ReportLabelStudio-BN-fYNCr.cjs +0 -1
  106. package/dist/ReportParamPanel-sOANVRz-.cjs +0 -1
  107. package/dist/ReportPreview-CuoHl15N.cjs +0 -6
  108. package/dist/RuleEditor-XaLcCdTb.cjs +0 -1
  109. package/dist/component-tree-6TV7W6Yj.cjs +0 -1
  110. package/dist/designer-CyKXBhQg.cjs +0 -2
  111. package/dist/designer-fVvpYg8H.js +0 -5824
  112. package/dist/grid-geometry-BNptEcMm.js +0 -65
  113. package/dist/grid-geometry-CZ_cYB6O.cjs +0 -1
  114. package/dist/json-snapshot-jiXff4lc.cjs +0 -2
  115. package/dist/record-bindings-ehjnCDHt.cjs +0 -1
  116. package/dist/rich-text-layout-ALlMoYOG.cjs +0 -3
  117. package/dist/runtime-CDA6d263.cjs +0 -1
  118. package/dist/style-67OqfNed.js +0 -73
  119. package/dist/style-C22Pbv3T.cjs +0 -1
  120. package/dist/template-fragments-C_zSHJAa.cjs +0 -1
  121. package/dist/template-registry-DzWswQI5.cjs +0 -1
  122. package/dist/textwrap-BI-yJ6Wt.cjs +0 -4
@@ -1,5 +1,5 @@
1
- "use strict";var Vi=Object.create;var en=Object.defineProperty;var Hi=Object.getOwnPropertyDescriptor;var Ui=Object.getOwnPropertyNames;var Gi=Object.getPrototypeOf,Yi=Object.prototype.hasOwnProperty;var qi=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ui(t))!Yi.call(e,o)&&o!==r&&en(e,o,{get:()=>t[o],enumerable:!(n=Hi(t,o))||n.enumerable});return e};var Ye=(e,t,r)=>(r=e!=null?Vi(Gi(e)):{},qi(t||!e||!e.__esModule?en(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const de=require("./progress-DJBd9Rb9.cjs"),Ne=require("node:worker_threads"),he=require("node:crypto"),A=require("node:fs"),D=require("node:path");var Vt=typeof document<"u"?document.currentScript:null;const kt=1.35,Ar=10.5,Wn='"Microsoft YaHei", sans-serif',Xi="1.0.0-mach",Ae=Xi,Jn=/[\u3000-\u9fff\uff00-\uffef]/,pe=new Uint8Array(128);{for(const e of"iljtf.,:;'`|!()[]")pe[e.charCodeAt(0)]=1;for(const e of"mwMW@")pe[e.charCodeAt(0)]=2;for(let e=48;e<=57;e++)pe[e]=3;for(let e=65;e<=90;e++)pe[e]=4;pe[32]=5}const Zi=[.54,.26,.95,.59,.67,.3];function Qi(e){const t=e.charCodeAt(0);return t<128?Zi[pe[t]]:Jn.test(e)?1:/[A-Z]/.test(e)?.67:.54}const kr={measureMm(e,t){const{fontSizePt:r,bold:n=!1,letterSpacingPt:o=0}=t,i=25.4/72;let s=0;for(const a of e)s+=Qi(a);return n&&(s*=1.04),(s*r+o*Math.max(0,Array.from(e).length-1))*i}};function es(e,t,r){const n=[];let o="";const i=()=>{o&&(n.push({text:o,widthMm:r.measureMm(o,t),cjk:!1}),o="")};for(const s of e){if(s===`
1
+ "use strict";var Gi=Object.create;var en=Object.defineProperty;var Yi=Object.getOwnPropertyDescriptor;var qi=Object.getOwnPropertyNames;var Xi=Object.getPrototypeOf,Zi=Object.prototype.hasOwnProperty;var Qi=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of qi(t))!Zi.call(e,o)&&o!==r&&en(e,o,{get:()=>t[o],enumerable:!(n=Yi(t,o))||n.enumerable});return e};var Ye=(e,t,r)=>(r=e!=null?Gi(Xi(e)):{},Qi(t||!e||!e.__esModule?en(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const me=require("./progress-DJBd9Rb9.cjs"),Ne=require("node:worker_threads"),ge=require("node:crypto"),A=require("node:fs"),D=require("node:path");var Jt=typeof document<"u"?document.currentScript:null;const Nt=1.35,Mr=10.5,Wn='"Microsoft YaHei", sans-serif',es="1.0.0-mach",ze=es,Jn=/[\u3000-\u9fff\uff00-\uffef]/,ye=new Uint8Array(128);{for(const e of"iljtf.,:;'`|!()[]")ye[e.charCodeAt(0)]=1;for(const e of"mwMW@")ye[e.charCodeAt(0)]=2;for(let e=48;e<=57;e++)ye[e]=3;for(let e=65;e<=90;e++)ye[e]=4;ye[32]=5}const ts=[.54,.26,.95,.59,.67,.3];function rs(e){const t=e.charCodeAt(0);return t<128?ts[ye[t]]:Jn.test(e)?1:/[A-Z]/.test(e)?.67:.54}const $r={measureMm(e,t){const{fontSizePt:r,bold:n=!1,letterSpacingPt:o=0}=t,i=25.4/72;let s=0;for(const a of e)s+=rs(a);return n&&(s*=1.04),(s*r+o*Math.max(0,Array.from(e).length-1))*i}};function ns(e,t,r){const n=[];let o="";const i=()=>{o&&(n.push({text:o,widthMm:r.measureMm(o,t),cjk:!1}),o="")};for(const s of e){if(s===`
2
2
  `){i(),n.push({text:`
3
- `,widthMm:0,cjk:!1,br:!0});continue}if(s===" "){i(),n.push({text:s,widthMm:r.measureMm(s,t),cjk:!1,space:!0});continue}if(Jn.test(s)){i(),n.push({text:s,widthMm:r.measureMm(s,t),cjk:!0});continue}o+=s}return i(),n}function Ve(e,t,r,n=kr){if(!e)return[""];e=e.replace(/\r\n?/g,`
4
- `);const o=[];let i="",s=0;const a=(r.letterSpacingPt??0)*25.4/72,c=()=>{o.push(i),i="",s=0};for(const u of es(e,r,n)){if(u.br){c();continue}const f=i.length>0?a:0;if(s+f+u.widthMm<=t){i+=u.text,s+=f+u.widthMm;continue}if(u.space){c();continue}if(u.cjk){i.length>0&&c(),i=u.text,s=u.widthMm;continue}if(i.length>0&&c(),u.widthMm<=t){i=u.text,s=u.widthMm;continue}for(const d of u.text)n.measureMm(i+d,r)>t&&i.length>0&&c(),i+=d,s=n.measureMm(i,r)}return c(),o}const ts=4096,tn=128*1024;function rs(e){const t=new Map;let r=0;return{measureMm(n,o){const i=JSON.stringify([n,o.fontSizePt,o.fontFamily,o.bold,o.italic,o.letterSpacingPt]),s=t.get(i);if(s!==void 0)return t.delete(i),t.set(i,s),s;const a=e.measureMm(n,o);if(Number.isFinite(a)&&i.length<=tn){for(;t.size>=ts||r+i.length>tn;){const c=t.keys().next().value;r-=c.length,t.delete(c)}t.set(i,a),r+=i.length}return a}}}const st=1e3;function me(e){if(!Number.isSafeInteger(e)||e<0||e>st*2)throw new Error("十进制精度超出预算");return 10n**BigInt(e)}function Nt(e){if(e.coefficient.toString().length>st*2||e.scale>st*2)throw new Error("十进制结果超出精度预算");return e}function V(e){if(typeof e!="string"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("十进制参数必须是有限数字或十进制文本");const t=String(e);if(t.length>st)throw new Error("十进制文本超出精度预算");const r=/^([+-]?)(\d+)(?:\.(\d*))?(?:[eE]([+-]?\d{1,4}))?$/.exec(t);if(!r)throw new Error("无效十进制文本");const n=r[3]??"",o=Number(r[4]??0),i=n.length-o,s=BigInt(`${r[1]==="-"?"-":""}${r[2]}${n}`);return Nt(i<0?{coefficient:s*me(-i),scale:0}:{coefficient:s,scale:i})}function zn(e,t){const r=Math.max(e.scale,t.scale);return[e.coefficient*me(r-e.scale),t.coefficient*me(r-t.scale),r]}function at(e,t){const[r,n]=zn(e,t);return r<n?-1:r>n?1:0}function ct(e,t){const[r,n,o]=zn(e,t);return Nt({coefficient:r+n,scale:o})}function Nr(e,t){return Nt({coefficient:e.coefficient*t.coefficient,scale:e.scale+t.scale})}function Vn(e,t){const r=e/t,n=e%t,o=i=>i<0n?-i:i;return o(n)*2n<o(t)?r:r+(e<0n==t<0n?1n:-1n)}function He(e){if(!Number.isInteger(e)||e<0||e>100)throw new Error("十进制小数位应为 0–100 的整数")}function rr(e,t,r=20){if(He(r),t.coefficient===0n)throw new Error("不能除以零");const n=t.scale-e.scale+r,o=e.coefficient*me(Math.max(0,n)),i=t.coefficient*me(Math.max(0,-n));return Nt({coefficient:Vn(o,i),scale:r})}function Pt(e,t){let r=e.coefficient,n=e.scale;t!==void 0&&(He(t),r=t>=n?r*me(t-n):Vn(r,me(n-t)),n=t);const o=r<0n,i=(o?-r:r).toString().padStart(n+1,"0");let s=n?i.slice(-n):"";return t===void 0&&(s=s.replace(/0+$/,"")),`${o?"-":""}${n?i.slice(0,-n):i}${s?`.${s}`:""}`}function rn(e,t,r=!1,n=!1){let o=V(e);n&&(o=Nr(o,{coefficient:100n,scale:0}));const[i,s]=Pt(o,t).split(".");return`${r?i.replace(/\B(?=(\d{3})+(?!\d))/g,","):i}${s===void 0?"":`.${s}`}${n?"%":""}`}const Hn=new Set(["__proto__","prototype","constructor"]);function Un(e){if(!e||typeof e!="object"||Array.isArray(e)||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw new Error("条件应为普通声明式对象");for(const[t,r]of Object.entries(Object.getOwnPropertyDescriptors(e)))if(Hn.has(t)||!Object.prototype.hasOwnProperty.call(r,"value"))throw new Error("条件不允许访问器或不安全属性")}function nn(e){if(typeof e!="string"||!e.trim()||e.length>512||Hn.has(e))throw new Error("条件字段应为安全的非空字段名")}function Ht(e){if(e!==null&&typeof e!="boolean"&&typeof e!="string"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("条件常量应为有限 JSON 标量");if(typeof e=="string"&&e.length>16384)throw new Error("条件文本超出预算")}function nr(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(e))throw new Error("日期条件使用 YYYY-MM-DD 日历日");const[t,r,n]=e.split("-").map(Number),o=new Date(0);if(o.setUTCFullYear(t,r-1,n),o.setUTCHours(0,0,0,0),o.getUTCFullYear()!==t||o.getUTCMonth()!==r-1||o.getUTCDate()!==n)throw new Error("无效日历日");return e}function on(e){return["string","boolean"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e)}function sn(e){return e==null||e===""}function ns(e){const t=e.values?.[0]??(e.right&&"value"in e.right?e.right.value:e.value);return e.valueType??e.numeric??(typeof t=="number"?"decimal":typeof t=="boolean"?"boolean":"text")}function Qe(e,t,r){if(sn(e)||sn(t))return;const n=ns(r);try{if(n==="decimal")return at(V(e),V(t));if(n==="number")return!["number","string"].includes(typeof e)||!["number","string"].includes(typeof t)?void 0:at(V(e),V(t));if(n==="date"&&(e=nr(e),t=nr(t)),n==="boolean"&&(typeof e!="boolean"||typeof t!="boolean")||n==="text"&&(!on(e)||!on(t)))return;const o=String(e),i=String(t);return o<i?-1:o>i?1:0}catch{return}}function os(e){if(nn(e.field),![">",">=","<","<=","==","!=","between","contains","isNull","isNotNull"].includes(e.op))throw new Error("未知条件运算符");if(e.numeric!==void 0&&!["number","decimal"].includes(e.numeric))throw new Error("未知条件数值模式");if(e.valueType!==void 0&&!["number","decimal","text","date","boolean"].includes(e.valueType))throw new Error("未知条件值类型");if(!(e.op==="isNull"||e.op==="isNotNull"))if(e.op==="between"){if(!Array.isArray(e.values)||e.values.length!==2||Object.keys(e.values).length!==2)throw new Error("范围条件需要两个明确边界");e.values.forEach(Ht);const t=Qe(e.values[0],e.values[1],e);if(t===void 0||t>0)throw new Error("范围边界无效或顺序颠倒")}else if(e.right!==void 0){if(Un(e.right),Object.keys(e.right).length!==1)throw new Error("条件 right 只能指定一个 field 或 value");if("field"in e.right?nn(e.right.field):Ht(e.right.value),e.value!==void 0)throw new Error("条件不能同时指定 value 和 right")}else Ht(e.value)}function Ut(e,t){if(t===void 0)return!1;switch(e){case">":return t>0;case">=":return t>=0;case"<":return t<0;case"<=":return t<=0;case"==":return t===0;case"!=":return t!==0;default:return!1}}function is(e){os(e),e={...e,right:e.right?{...e.right}:void 0,values:e.values?[e.values[0],e.values[1]]:void 0};const t=(r,n)=>Object.prototype.hasOwnProperty.call(r,n)?r[n]:void 0;return r=>{const n=t(r,e.field);if(e.op==="isNull")return n==null;if(e.op==="isNotNull")return n!=null;if(e.op==="between")return Ut(">=",Qe(n,e.values[0],e))&&Ut("<=",Qe(n,e.values[1],e));const o=e.right?"field"in e.right?t(r,e.right.field):e.right.value:e.value;return e.op==="contains"?typeof n=="string"&&typeof o=="string"&&n.includes(o):Ut(e.op,Qe(n,o,e))}}function Y(e,t={nodes:0},r=0){if(++t.nodes>256||r>16)throw new Error("条件超出深度或节点预算");if(Un(e),["all","any","not","field"].filter(o=>Object.prototype.hasOwnProperty.call(e,o)).length!==1)throw new Error("条件只能指定一种组合或比较");if("not"in e){const o=Y(e.not,t,r+1);return i=>!o(i)}if("all"in e||"any"in e){const o="all"in e?e.all:e.any;if(!Array.isArray(o)||o.length<1||o.length>256||Object.keys(o).length!==o.length)throw new Error("组合条件需要有界、无空位的非空数组");const i=o.map(s=>Y(s,t,r+1));return"all"in e?s=>i.every(a=>a(s)):s=>i.some(a=>a(s))}return is(e)}function ss(e){Y(e);const t=new Set;function r(n){"all"in n?n.all.forEach(r):"any"in n?n.any.forEach(r):"not"in n?r(n.not):(t.add(n.field),n.right&&"field"in n.right&&t.add(n.right.field))}return r(e),[...t]}function Gn(e){if(!e||e.kind==="date")return;const t=e.digits;if(!(t!==void 0&&(!Number.isInteger(t)||t<0||t>100))){if(e.kind==="percent"){const r=t??2;return`0${r?`.${"0".repeat(r)}`:""}%`}return t===void 0?e.thousands?"#,##0.###############":void 0:`${e.thousands?"#,##0":"0"}${t?`.${"0".repeat(t)}`:""}`}}function as(e){const t=/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$/.exec(e.trim());if(t){const n=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return Number.isNaN(n.getTime())?null:n}const r=new Date(e);return Number.isNaN(r.getTime())?null:r}function or(e,t){return e.toLocaleString("en-US",{minimumFractionDigits:t,maximumFractionDigits:t})}function cs(e,t){const r=n=>String(n).padStart(2,"0");return t.replace(/YYYY/g,String(e.getFullYear())).replace(/MM/g,r(e.getMonth()+1)).replace(/DD/g,r(e.getDate())).replace(/hh/g,r(e.getHours())).replace(/mm/g,r(e.getMinutes())).replace(/ss/g,r(e.getSeconds()))}function us(e,t,r){return r!=null?t?or(e,r):e.toFixed(r):t?or(e):String(e)}function an(e){const t=typeof e=="number"?e:Number(String(e).replace(/,/g,""));return Number.isFinite(t)?t:null}function Pr(e,t){if(e==null||e===""||!t)return String(e??"");switch(t.kind){case"number":{if(typeof e=="string")try{return rn(e,t.digits,t.thousands===!0)}catch{return e}const r=an(e);return r==null?String(e):us(r,t.thousands===!0,t.digits)}case"percent":{if(typeof e=="string")try{return rn(e,t.digits??2,!0,!0)}catch{return e}const r=an(e);return r==null?String(e):`${or(r*100,t.digits??2)}%`}case"date":{const r=t.pattern??"YYYY-MM-DD",n=e instanceof Date?e:as(String(e));return n?cs(n,r):String(e)}default:return String(e)}}const fs=[{name:"add",minArgs:2,maxArgs:256,input:"numeric",output:"numeric",example:"add(quantity, adjustment)"},{name:"subtract",minArgs:2,maxArgs:2,input:"numeric",output:"numeric",example:"subtract(input, output)"},{name:"multiply",minArgs:2,maxArgs:256,input:"numeric",output:"numeric",example:"multiply(quantity, price)"},{name:"divide",minArgs:2,maxArgs:2,input:"numeric",output:"numeric",example:"divide(amount, quantity)"},{name:"coalesce",minArgs:2,maxArgs:256,input:"scalar",output:"scalar",example:"coalesce(actual, planned)"},{name:"if",minArgs:2,maxArgs:2,input:"condition + branches",output:"scalar",example:"if(quantity > 0, divide(amount, quantity), null)"},{name:"round",minArgs:1,maxArgs:2,input:"numeric, digits?",output:"numeric",example:"round(amount, 2)"},{name:"abs",minArgs:1,maxArgs:1,input:"numeric",output:"numeric",example:"abs(difference)"},{name:"concat",minArgs:2,maxArgs:256,input:"text",output:"text",example:"concat(plant, '-' , heat)"},{name:"trim",minArgs:1,maxArgs:1,input:"text",output:"text",example:"trim(heat)"},{name:"upper",minArgs:1,maxArgs:1,input:"text",output:"text",example:"upper(grade)"},{name:"lower",minArgs:1,maxArgs:1,input:"text",output:"text",example:"lower(code)"},{name:"dateYear",minArgs:1,maxArgs:1,input:"YYYY-MM-DD",output:"number",example:"dateYear(reportDate)"},{name:"dateMonth",minArgs:1,maxArgs:1,input:"YYYY-MM-DD",output:"number",example:"dateMonth(reportDate)"},{name:"dateDay",minArgs:1,maxArgs:1,input:"YYYY-MM-DD",output:"number",example:"dateDay(reportDate)"}],ls=Object.freeze(fs.map(e=>Object.freeze(e)));function ds(e,t,r,n,o){if(t.some(a=>a==null)){if(o==="error")throw new Error("函数参数包含空值");return null}if(e==="round"||e==="abs")return ms(e,t,r,n);if(e.startsWith("date")){const a=nr(t[0]);return Number(a.slice(e==="dateYear"?0:e==="dateMonth"?5:8,e==="dateYear"?4:e==="dateMonth"?7:10))}if(t.some(a=>typeof a!="string"))throw new Error("文本函数只接受文本,不隐式转换数字或空值");if(t.reduce((a,c)=>a+c.length,0)>1e6)throw new Error("计算文本超出长度预算");const i=t[0],s=e==="concat"?t.join(""):e==="trim"?i.trim():e==="upper"?i.toUpperCase():i.toLowerCase();if(s.length>1e6)throw new Error("计算文本超出长度预算");return s}function ms(e,t,r,n){const o=t[0];if(r!=="decimal"&&(typeof o!="number"||!Number.isFinite(o)))throw new Error("普通数值函数需要有限数字");const i=V(o);e==="abs"&&(i.coefficient=i.coefficient<0n?-i.coefficient:i.coefficient);const s=e==="round"?t.length===2?t[1]:n??0:n;if(s!==void 0){if(typeof s!="number")throw new Error("小数位必须为数字");He(s)}const a=Pt(i,s),c=Number(a);if(r!=="decimal"&&!Number.isFinite(c))throw new Error("计算结果不是有限数字");return r==="decimal"?a:c}const hs=["sum","count","avg","min","max","weightedAvg"];function cn(e){if(typeof e!="number"||!Number.isFinite(e))throw new Error("聚合度量必须是有限数字,不能隐式转换;小数文本请显式选择 decimal");return e}function ut(e,t){return t&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function gs(e){let t=0,r=0,n=0,o=0,i=1/0,s=-1/0;const a=c=>{const u=c-n,f=r+u;n=f-r-u,r=f};return{add(c){const u=ut(c,e.field);if(e.op==="count"){(!e.field||u!=null)&&t++;return}if(u==null)return;const f=cn(u),d=e.op==="weightedAvg"?ut(c,e.weightField):1;if(d==null)return;const l=cn(d);if(e.op==="weightedAvg"&&l<0)throw new Error("加权平均的权重不能为负数");["sum","avg","weightedAvg"].includes(e.op)&&a(f*l),o+=l,i=Math.min(i,f),s=Math.max(s,f),t++},value(){if(e.op==="count")return t;if(!t)return null;const c=e.op==="min"?i:e.op==="max"?s:e.op==="avg"?r/t:e.op==="weightedAvg"?o===0?null:r/o:r;if(c!==null&&!Number.isFinite(c))throw new Error("聚合计算溢出");return c}}}function ps(e){let t=0,r=V("0"),n=V("0"),o,i;return{add(s){const a=ut(s,e.field);if(e.op==="count"){(!e.field||a!=null)&&t++;return}if(a==null)return;const c=e.op==="weightedAvg"?ut(s,e.weightField):"1";if(c==null)return;const u=V(a),f=V(c);if(e.op==="weightedAvg"&&f.coefficient<0n)throw new Error("加权平均的权重不能为负数");["sum","avg","weightedAvg"].includes(e.op)&&(r=ct(r,Nr(u,f))),e.op==="weightedAvg"&&(n=ct(n,f)),(!o||at(u,o)<0)&&(o=u),(!i||at(u,i)>0)&&(i=u),t++},value(){if(e.op==="count")return t;if(!t||e.op==="weightedAvg"&&n.coefficient===0n)return null;let s=e.op==="min"?o:e.op==="max"?i:r;return e.op==="avg"&&(s=rr(r,V(t),e.digits)),e.op==="weightedAvg"&&(s=rr(r,n,e.digits)),Pt(s,e.digits)}}}function oe(e){if(e.digits!==void 0&&He(e.digits),e.numeric!==void 0&&e.numeric!=="number"&&e.numeric!=="decimal")throw new Error("未知聚合数值模式");if(!hs.includes(e.op))throw new Error("未知聚合操作");if(e.op!=="count"&&!e.field)throw new Error("聚合需要度量字段");if(e.op==="weightedAvg"&&!e.weightField)throw new Error("加权平均需要权重字段");return e.numeric==="decimal"?ps(e):gs(e)}function Be(e,t){const r=oe(t);for(const n of e)r.add(n);return r.value()}const ys=new Set(["__proto__","prototype","constructor"]);function K(e){if(typeof e!="string"||!e.trim()||ys.has(e))throw new Error("计算字段应为安全的非空字段名")}function Fr(e){return e===null||["string","boolean"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e)}function ws(e){if(e.some(t=>typeof t!="number"||!Number.isFinite(t)))throw new Error("算术参数必须是有限数字;空值和小数文本不会隐式转换");return e}function bs(e,t){const r=ws(t);let n;if(e==="add")n=r.reduce((o,i)=>o+i,0);else if(e==="multiply")n=r.reduce((o,i)=>o*i,1);else if(e==="subtract")n=r[0]-r[1];else{if(r[1]===0)throw new Error("不能除以零");n=r[0]/r[1]}if(!Number.isFinite(n))throw new Error("计算结果不是有限数字");return n}function xs(e,t,r){const n=t.map(V);let o;return e==="add"?o=n.reduce(ct):e==="multiply"?o=n.reduce(Nr):e==="subtract"?o=ct(n[0],{...n[1],coefficient:-n[1].coefficient}):o=rr(n[0],n[1],r),Pt(o,r)}function vs(e,t,r){return r.nulls!=="error"&&t.some(n=>n==null)||e==="divide"&&r.divisionByZero==="null"&&(r.numeric==="decimal"?V(t[1]).coefficient===0n:t[1]===0)?null:r.numeric==="decimal"?xs(e,t,r.digits):bs(e,t)}function Ms(e,t){e.field!==void 0&&K(e.field),e.weightField!==void 0&&K(e.weightField);const r={op:e.aggregate,field:e.field,weightField:e.weightField,numeric:t.numeric,digits:t.digits};Be([],r);const n=new WeakMap;return o=>{let i=n.get(o.rows);if(!i){try{i={value:Be(o.rows,r)}}catch(s){i={error:s instanceof Error?s:new Error(String(s))}}n.set(o.rows,i)}if(i.error)throw i.error;return i.value}}function $s(e,t){for(const r of e){const n=r(t);if(n!=null)return n}return null}function Or(e,t={},r={nodes:0},n=0){if(++r.nodes>256||n>16)throw new Error("计算表达式超出深度或节点预算");if(!e||typeof e!="object"||Array.isArray(e))throw new Error("计算表达式应为声明式对象");if("aggregate"in e)return Ms(e,t);if("field"in e){K(e.field);const o=e.field;return({row:i})=>Object.prototype.hasOwnProperty.call(i,o)?i[o]:void 0}if("value"in e){if(!Fr(e.value))throw new Error("常量应为有限 JSON 标量");return()=>e.value}return Ss(e,t,r,n)}function Ss(e,t,r,n){const o=ls.find(a=>a.name===e.op);if(!o||!Array.isArray(e.args))throw new Error("未知计算操作");if(e.args.length>256||Object.keys(e.args).length!==e.args.length)throw new Error("计算参数超出预算或包含空位");if(e.args.length<o.minArgs||e.args.length>o.maxArgs)throw new Error("运算参数数量不正确");const i=e.op==="if"?Y(e.condition,r,n+1):void 0;if(e.op!=="if"&&e.condition!==void 0)throw new Error("仅 IF 运算接受 condition");const s=e.args.map(a=>Or(a,t,r,n+1));return i?a=>s[i(a.row)?0:1](a):["add","subtract","multiply","divide","coalesce"].includes(e.op)?e.op==="coalesce"?a=>$s(s,a):a=>vs(e.op,s.map(c=>c(a)),t):a=>ds(e.op,s.map(c=>c(a)),t.numeric,t.digits,t.nulls)}function Es(e){Or(e);const t=new Set,r=n=>{"field"in n&&n.field&&t.add(n.field),"aggregate"in n&&n.weightField&&t.add(n.weightField),"args"in n&&(n.args.forEach(r),n.condition&&ss(n.condition).forEach(o=>t.add(o)))};return r(e),[...t]}const As=16,ir=1024*1024,un=5e5,ft=new WeakMap,fe=Symbol("uncacheable-computation-definition");function et(e,t,r=0){if(++t.nodes>1e4||r>32)throw fe;if(e==null)return[String(e)];if(typeof e=="number")return["number",Object.is(e,-0)?"-0":String(e)];if(typeof e=="boolean")return["boolean",e];if(typeof e=="string"){if(t.units+=e.length,t.units>ir)throw fe;return["string",e]}if(typeof e!="object")throw fe;if(Array.isArray(e)){if(Object.getPrototypeOf(e)!==Array.prototype||Object.keys(e).length!==e.length)throw fe;return["array",Array.from({length:e.length},(n,o)=>et(fn(e,String(o)),t,r+1))]}if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw fe;return["object",Object.keys(e).map(n=>[et(n,t,r+1),et(fn(e,n),t,r+1)])]}function fn(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||r.get||r.set)throw fe;return r.value}function ks(e){try{return JSON.stringify(et(e,{nodes:0,units:0}))}catch(t){if(t!==fe)throw t;return}}function Ns(e){ft.set(e,{programs:new Map,units:0,slots:0})}function Ps(e,t){const r=ft.get(e);if(!r)return;const n={programs:new Map,units:r.units,slots:r.slots};for(const[o,i]of r.programs){const s=new WeakMap;t.forEach((a,c)=>{const u=i.rows.get(e[c]);u&&s.set(a,u)}),n.programs.set(o,{...i,rows:s})}ft.set(t,n)}function Fs(e,t,r){const n=ft.get(e);if(!n||t.some(u=>typeof u.expression=="string"))return;const o=ks(t);if(o===void 0||o.length>ir)return;const i=n.programs.get(o);if(i)return i;const s=r(),a=e.length*s.reduce((u,f)=>u+f.dependencies.length+1,0),c={fields:s,rows:new WeakMap,slots:a,cacheRows:a<=un};if(!c.cacheRows)return c;for(;n.programs.size>=As||n.units+o.length>ir||n.slots+a>un;){const u=n.programs.keys().next().value;n.slots-=n.programs.get(u).slots,n.units-=u.length,n.programs.delete(u)}return n.programs.set(o,c),n.units+=o.length,n.slots+=a,c}function Os(e,t,r,n){if((r.definition.scope??"row")!=="row")return;const o=e.program?.rows.get(t)?.get(r.definition.field);return o?.dependencies.every((i,s)=>Object.is(n[r.dependencies[s]],i))?o:void 0}function Is(e,t,r,n,o){const i=e.program;if(!i?.cacheRows||(r.definition.scope??"row")!=="row")return;let s=e.writes.get(t);s||(s=new Map(i.rows.get(t)),e.writes.set(t,s),i.rows.set(t,s)),s.set(r.definition.field,{dependencies:r.dependencies.map(a=>n[a]),value:n[r.definition.field],...o?{issue:{field:o.field,message:o.message}}:{}})}function Rs(e){if(K(e.field),e.scope!==void 0&&!["row","group","dataset"].includes(e.scope))throw new Error("未知计算范围");if(e.numeric!==void 0&&e.numeric!=="number"&&e.numeric!=="decimal")throw new Error("未知数值模式");if(e.digits!==void 0&&He(e.digits),e.nulls!==void 0&&e.nulls!=="propagate"&&e.nulls!=="error")throw new Error("未知空值规则");if(e.divisionByZero!==void 0&&e.divisionByZero!=="null"&&e.divisionByZero!=="error")throw new Error("未知除零规则");if(e.scope==="group"&&(!Array.isArray(e.groupBy)||!e.groupBy.length))throw new Error("分组计算需要 groupBy 字段");Cs(e)}function Cs(e){if(e.groupBy!==void 0){if(!Array.isArray(e.groupBy)||e.groupBy.length>16)throw new Error("计算分组最多 16 级");e.groupBy.forEach(K)}if(e.dependsOn!==void 0){if(!Array.isArray(e.dependsOn)||e.dependsOn.length>2048)throw new Error("计算依赖超出预算");e.dependsOn.forEach(K)}}function Ir(e){return[...new Set([...typeof e.expression=="string"?e.dependsOn??[]:Es(e.expression),...e.groupBy??[]])]}function Yn(e){if(!Array.isArray(e)||e.length>2048)throw new Error("计算字段应为数组且最多2048项");const t=new Map;for(const s of e){if(Rs(s),t.has(s.field))throw new Error(`计算字段重复:${s.field}`);t.set(s.field,s)}const r=new Set,n=new Set,o=[];function i(s){if(!n.has(s.field)){if(r.has(s.field))throw new Error(`计算字段存在循环依赖:${[...r,s.field].join(" → ")}`);r.add(s.field);for(const a of Ir(s)){const c=t.get(a);c&&i(c)}r.delete(s.field),n.add(s.field),o.push(s)}}return e.forEach(i),o}function Ts(e){try{const t=Yn(e);return{valid:!0,errors:[],order:t.map(r=>r.field),fields:e.map(r=>({field:r.field,dependencies:Ir(r),scope:r.scope??"row"}))}}catch(t){return{valid:!1,errors:[t instanceof Error?t.message:String(t)],fields:[],order:[]}}}function ln(e){return Yn(e.fields).map(t=>{const r=Ir(t);if(typeof t.expression!="string")return{definition:t,dependencies:r,read:Or(t.expression,t)};if(!e.formula)throw new Error("字符串公式需要显式配置 formula adapter");const n=t.expression;return{definition:t,dependencies:r,read:o=>e.formula.evaluate(n,o)}})}function js(e,t){return JSON.stringify(t.map(r=>{const n=Object.prototype.hasOwnProperty.call(e,r)?e[r]:null;if(n!=null&&!Fr(n))throw new Error("分组字段应为有限 JSON 标量");return[typeof n,n??null]}))}function Ds(e,t){if(t.scope==="dataset")return()=>e;if(t.scope!=="group"){const o=new WeakMap;return i=>{let s=o.get(i);return s||(s=[i],o.set(i,s)),s}}const r=new Map,n=new WeakMap;for(const o of e){const i=js(o,t.groupBy);n.set(o,i);const s=r.get(i);s?s.push(o):r.set(i,[o])}return o=>r.get(n.get(o))}function Ls(e,t){const r=t.maxRows??1e5,n=t.maxCells??2e6;if(!Array.isArray(e)||!Number.isSafeInteger(r)||r<1||e.length>r)throw new Error("计算数据行数超出预算或输入不是数组");if(!Array.isArray(t.fields)||t.fields.length>2048)throw new Error("计算字段应为数组且最多2048项");if(!Number.isSafeInteger(n)||n<1||e.length*t.fields.length>n)throw new Error("计算单元格超出 maxCells 预算")}function dn(e){if(e?.aborted){const t=new Error("数据计算已取消");throw t.name="AbortError",t}}function Bs(e,t,r,n,o,i){try{const s=e.read({row:t,rowIndex:r,rows:n});if(s!==void 0&&!Fr(s))throw new Error("计算结果应为有限 JSON 标量,异步公式请先在数据源中求值");t[e.definition.field]=s??null}catch(s){const a=s instanceof Error?s.message:String(s);if(o.onError!=="null")throw Object.assign(new Error(`第 ${r+1} 行 ${e.definition.field}:${a}`),{cause:s});t[e.definition.field]=null,i.push({rowIndex:r,field:e.definition.field,message:a})}}function _s(e,t,r,n,o,i,s,a){const c=Os(e,t,r,n);if(c&&(!c.issue||s.onError==="null")){n[r.definition.field]=c.value,c.issue&&a.push({...c.issue,rowIndex:o});return}const u=a.length;Bs(r,n,o,i,s,a),Is(e,t,r,n,a.length>u?a[a.length-1]:void 0)}function Ft(e,t){Ls(e,t),dn(t.signal);const r=Fs(e,t.fields,()=>ln(t)),n={program:r,writes:new WeakMap},o=r?.fields??ln(t),i=[],s=e.map((a,c)=>{if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`第 ${c+1} 行应为对象`);return{...a}});for(const a of o){const c=Ds(s,a.definition);s.forEach((u,f)=>{dn(t.signal),_s(n,e[f],a,u,f,c(u),t,i)})}return{rows:s,issues:i}}function Pe(e,t,r){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype||e.length>t)throw new TypeError(`${r}应为有界普通数组`);if(Reflect.ownKeys(e).length!==e.length+1)throw new TypeError(`${r}不支持自定义数组方法或迭代器`);const n=[];for(let o=0;o<e.length;o++){const i=Object.getOwnPropertyDescriptor(e,String(o));if(!i||!Object.prototype.hasOwnProperty.call(i,"value"))throw new TypeError(`${r}不支持空洞或访问器`);n.push(i.value)}return n}const Me=["#2563eb","#0d9488","#d97706","#7c3aed","#dc2626","#0284c7"];function Ks(e){if(!["bar","line","stackedBar","percentBar"].includes(e.type))throw new Error("未知图表类型");if(!Array.isArray(e.categories)||!Array.isArray(e.series)||!e.categories.length||e.categories.length>200||!e.series.length||e.series.length>12)throw new Error("图表支持 1–200 个分类、1–12 个系列;大数据应先聚合");const t=Pe(e.categories,200,"图表分类"),r=Pe(e.series,12,"图表系列").map(n=>({...n,values:Pe(n?.values,200,"图表数值")}));for(const n of t)if(typeof n!="string")throw new Error("图表分类应为字符串");Ws(e);for(const n of r)Js(n,t.length);return{...e,categories:t,series:r}}function Ws(e){for(const t of["leftMm","topMm","widthMm","heightMm"])if(!Number.isFinite(e[t])||e[t]<0)throw new Error(`${t} 应为有限非负数`);if(e.widthMm<45||e.heightMm<35)throw new Error("图表至少需要 45×35mm");if(!Number.isFinite(e.leftMm+e.widthMm)||!Number.isFinite(e.topMm+e.heightMm))throw new Error("图表几何范围溢出")}function Js(e,t){if(!e||typeof e.name!="string"||!Array.isArray(e.values)||e.values.length!==t)throw new Error("图表系列应提供名称及逐分类的有限数字或 null");for(const r of e.values)if(r!==null&&!Number.isFinite(r))throw new Error("图表系列应提供名称及逐分类的有限数字或 null");if(e.color!==void 0&&!/^#[\da-f]{6}$/i.test(e.color))throw new Error("图表颜色应为 #RRGGBB")}function sr(e,t,r,n,o,i=.8){return{kind:"line",leftMm:Math.min(e,r),topMm:Math.min(t,n),widthMm:Math.abs(r-e),heightMm:Math.abs(n-t),lineDirection:n<t?"up":"down",style:{lineColor:o,lineWidthPt:i}}}function ye(e,t,r,n,o="center"){return{kind:"text",text:e,leftMm:t,topMm:r,widthMm:n,heightMm:5,style:{fontSize:8,color:"#475569",align:o,verticalAlign:"middle"}}}function lt(e){return Number(e.toPrecision(5)).toString()}function zs(e){let t=0,r=0;const n=qn(e)?Vs(e):void 0;if(n)t=n.min,r=n.max;else for(const d of e.series)for(const l of d.values)l!==null&&(t=Math.min(t,l),r=Math.max(r,l));t===r&&(r=t+1);const o=e.leftMm+13,i=e.topMm+8,s=e.widthMm-17,a=e.heightMm-23,c=Math.max(Math.abs(t),Math.abs(r),1),u=t/c,f=r/c-u;return{left:o,top:i,width:s,height:a,min:t,max:r,y:d=>i+a*(1-(d/c-u)/f)}}function qn(e){return e.type==="stackedBar"||e.type==="percentBar"}function Vs(e){let t=0,r=e.type==="percentBar"?100:0;for(let n=0;n<e.categories.length;n++){let o=0,i=0;for(const s of e.series){const a=s.values[n]??0;a<0?i+=a:o+=a}if(!Number.isFinite(o)||!Number.isFinite(i))throw new Error("图表堆叠合计溢出,请先明确缩放单位");t=Math.min(t,i),r=Math.max(r,o)}return{min:t,max:r}}function Hs(e){if(e.type!=="percentBar")return e;const t=e.categories.map((r,n)=>{let o=0;for(const i of e.series){const s=i.values[n];if(s!==null&&s<0)throw new Error("占比图需要非负度量,负数口径应由业务明确处理");o=Math.max(o,s??0)}return{scale:o,total:o?e.series.reduce((i,s)=>i+(s.values[n]??0)/o,0):0}});return{...e,series:e.series.map(r=>({...r,values:r.values.map((n,o)=>{if(n===null)return null;const{scale:i,total:s}=t[o];return i&&s?n/i/s*100:0})}))}}function Us(e,t){const r=[],n=t.width/e.categories.length;return e.categories.forEach((o,i)=>{let s=0,a=0;e.series.forEach((c,u)=>{const f=c.values[i];if(f==null)return;const d=f<0?a:s,l=d+f;f<0?a=l:s=l;const m=Math.min(t.y(d),t.y(l)),h=Math.abs(t.y(l)-t.y(d)),p=c.color??Me[u%Me.length],w=t.left+n*(i+.15),y=n*.7;r.push({kind:"rect",leftMm:w,topMm:m,widthMm:y,heightMm:h,style:{backgroundColor:p,borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}}),e.showValues&&h>=5&&r.push({...ye(e.type==="percentBar"?`${lt(f)}%`:lt(f),w,m+h/2-2.5,y),style:{fontSize:7,color:"#ffffff",align:"center"}})})}),r}function Gs(e,t){const r=[];e.title&&r.push({...ye(e.title,e.leftMm,e.topMm,e.widthMm),style:{fontSize:10,bold:!0,align:"left"}});for(let i=0;i<=4;i++){const s=i/4,a=t.min*(1-s)+t.max*s,c=t.y(a);r.push(sr(t.left,c,t.left+t.width,c,"#e2e8f0",.4),ye(`${lt(a)}${e.type==="percentBar"?"%":""}`,e.leftMm,c-2.5,11,"right"))}r.push(sr(t.left,t.top,t.left,t.top+t.height,"#94a3b8"));const n=Math.max(1,Math.ceil(e.categories.length/Math.max(1,Math.floor(t.width/14))));e.categories.forEach((i,s)=>{s%n===0&&r.push(ye(i,t.left+(s+.5)*t.width/e.categories.length-7,t.top+t.height+1,14))});const o=t.width/e.series.length;return e.series.forEach((i,s)=>{r.push({...ye(i.name,t.left+s*o,e.topMm+e.heightMm-5,o),style:{fontSize:8,color:i.color??Me[s%Me.length],align:"center"}})}),r}function Ys(e,t,r,n){const o=[],i=r.color??Me[n%Me.length],s=t.width/e.categories.length,a=s*.75/e.series.length;let c;return r.values.forEach((u,f)=>{if(u===null){c=void 0;return}const d=t.left+(f+.5)*s,l=t.y(u);e.type==="bar"?o.push({kind:"rect",leftMm:t.left+f*s+s*.125+n*a,topMm:Math.min(l,t.y(0)),widthMm:a,heightMm:Math.abs(t.y(0)-l),style:{backgroundColor:i,borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}}):(c&&o.push(sr(c.x,c.y,d,l,i,1.2)),o.push({kind:"ellipse",leftMm:d-.7,topMm:l-.7,widthMm:1.4,heightMm:1.4,style:{backgroundColor:i,borderColor:i}}),c={x:d,y:l}),e.showValues&&o.push({...ye(lt(u),d-s/2,Math.max(t.top,l-5),s),style:{fontSize:7,color:i,align:"center"}})}),o}function qs(e,t){let r=0,n=!1;for(const o of t.values){if(o===null){n=!1;continue}r+=1+ +!!e.showValues,e.type==="line"&&n&&r++,n=!0}return r}function Xs(e){const t=e.categories.length,r=Math.max(1,Math.ceil(t/Math.max(1,Math.floor((e.widthMm-17)/14)))),n=11+ +!!e.title+Math.ceil(t/r)+e.series.length;return e.series.reduce((o,i)=>o+qs(e,i),n)}function Zs(e){e=Hs(Ks(e));const t=zs(e);return[...Gs(e,t),...qn(e)?Us(e,t):e.series.flatMap((r,n)=>Ys(e,t,r,n))]}function dt(e,t,r){if(e===void 0)return t;if(!Number.isSafeInteger(e)||Number(e)<1||Number(e)>r)throw new RangeError("图表预算超出允许范围");return Number(e)}function Xn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("图表绑定应为对象");if(K(e.dataset),K(e.categoryField),!["bar","line","stackedBar","percentBar"].includes(e.type))throw new TypeError("图表类型无效");if(e.sort!==void 0&&!["asc","desc"].includes(e.sort))throw new TypeError("图表排序无效");if(e.title!==void 0&&(typeof e.title!="string"||e.title.length>512))throw new TypeError("图表标题过长");if(e.showValues!==void 0&&typeof e.showValues!="boolean")throw new TypeError("图表数值标签应为布尔值");if(!Array.isArray(e.measures)||!e.measures.length||e.measures.length>12)throw new RangeError("图表支持 1–12 个度量");for(const t of Pe(e.measures,12,"图表度量"))Qs(t);dt(e.maxRows,1e5,1e5),dt(e.maxCategories,200,200)}function Qs(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("图表度量应为对象");if(e.field!==void 0&&K(e.field),e.weightField!==void 0&&K(e.weightField),e.label!==void 0&&(typeof e.label!="string"||e.label.length>256))throw new TypeError("图表系列名称过长");if(e.color!==void 0&&!/^#[\da-f]{6}$/i.test(e.color))throw new TypeError("图表颜色应为 #RRGGBB");oe(e)}function ea(e){if(e==null)return{key:"null",label:"—"};if(typeof e!="string"&&typeof e!="boolean"&&!(typeof e=="number"&&Number.isFinite(e)))throw new TypeError("图表分类应为文本、布尔或有限数字");const t=String(e);if(t.length>512)throw new RangeError("图表分类名称过长");return{key:JSON.stringify([typeof e,e]),label:t}}function ta(e){if(e===null)return null;const t=Number(e);if(!Number.isFinite(t))throw new RangeError("聚合结果超出图表有限数值范围");return t}function ra(e,t,r){if(r?.aborted){const a=new Error("图表数据处理已取消");throw a.name="AbortError",a}Xn(t);const n=Pe(t.measures,12,"图表度量");if(!Array.isArray(e)||e.length>dt(t.maxRows,1e5,1e5))throw new RangeError("图表数据超出行数预算");const o=new Map,i=dt(t.maxCategories,200,200);for(let a=0;a<e.length;a++){if(r?.aborted){const d=new Error("图表数据处理已取消");throw d.name="AbortError",d}const c=e[a];if(!c||typeof c!="object"||Array.isArray(c))throw new TypeError("图表数据行应为对象");const u=ea(Object.prototype.hasOwnProperty.call(c,t.categoryField)?c[t.categoryField]:null);let f=o.get(u.key);if(!f){if(o.size>=i)throw new RangeError("图表分类超出预算,请明确筛选或聚合数据");f={label:u.label,accumulators:n.map(oe)},o.set(u.key,f)}f.accumulators.forEach(d=>d.add(c))}const s=[...o.values()];return t.sort&&s.sort((a,c)=>(t.sort==="desc"?-1:1)*(a.label<c.label?-1:a.label>c.label?1:0)),{categories:s.map(a=>a.label),series:n.map((a,c)=>({name:a.label??`${a.field??"记录"} · ${a.op}`,values:s.map(u=>ta(u.accumulators[c].value())),...a.color?{color:a.color}:{}}))}}class $e extends Error{constructor(t,r){super(`报表页数超出上限 ${t}(至少 ${r} 页)`),this.limit=t,this.actual=r,this.code="page-limit",this.name="PaginatePageLimitError"}}class _e extends Error{constructor(t,r){super(`报表单元格数量超出上限 ${t}(至少 ${r} 格)`),this.limit=t,this.actual=r,this.code="cell-limit",this.name="PaginateCellLimitError"}}class Ke extends Error{constructor(t,r){super(`报表图表图元数量预计超出上限 ${t}(本次估算 ${r})`),this.limit=t,this.estimated=r,this.code="chart-component-limit",this.name="PaginateChartComponentLimitError"}}const Rr=5e4;function Ot(e=Rr){if(!Number.isSafeInteger(e)||e<1||e>1e6)throw new RangeError("maxChartComponents 应为 1..1000000 的安全整数")}function na(e,t,r){const n=e.chartBinding;if(e.kind!=="chart"||e.grid||e.imageData||e.binding||e.pageAnchor)throw new TypeError("绑定图表不能同时设置图片、网格、记录绑定或页眉页脚");const o=Object.prototype.hasOwnProperty.call(t,n.dataset)?t[n.dataset]:void 0;if(!Array.isArray(o))throw new TypeError(`图表数据集 ${n.dataset} 未提供`);return{...ra(o,n,r),type:n.type,leftMm:e.leftMm,topMm:e.topMm,widthMm:e.widthMm,heightMm:e.heightMm,title:n.title,showValues:n.showValues}}function oa(e,t,r=Rr){Ot(r);let n=0;return Object.assign(i=>{if(!i.chartBinding)return[i];const s=na(i,e,t),a=n+(s.categories.length?Xs(s):1);if(!Number.isSafeInteger(a))throw new RangeError("图表图元估算应为有限安全整数");if(a>r)throw new Ke(r,a);const c=s.categories.length?Zs(s):[{kind:"text",leftMm:i.leftMm,topMm:i.topMm,widthMm:i.widthMm,heightMm:i.heightMm,text:"—",style:{align:"center",verticalAlign:"middle",color:"#94a3b8",fontSize:10}}];return n+=c.length,c},{used:()=>n})}function Fe(e,t){return JSON.stringify([e.slice(0,t.length),t.map(r=>[r===null?"null":typeof r,r])])}function Zn(e,t){return t.map(r=>{const n=Object.prototype.hasOwnProperty.call(e,r)?e[r]:null;if(n==null)return null;if(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))return n;throw new Error("矩阵维度必须是有限 JSON 标量")})}function ia(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("矩阵层级应为对象");for(const n of[e.emptyLabel,e.subtotalLabel,e.totalLabel])if(n!==void 0&&typeof n!="string")throw new Error("矩阵层级标签应为字符串");mn(e.row,t.length),mn(e.column,r.length)}function mn(e,t){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("矩阵轴配置应为对象");if(e.labels!==void 0&&(!Array.isArray(e.labels)||e.labels.length!==t||e.labels.some(r=>typeof r!="string")))throw new Error("矩阵维度标签必须与维度字段一一对应");if(e.sort!==void 0&&(!Array.isArray(e.sort)||e.sort.length>t||e.sort.some(r=>!["source","asc","desc"].includes(r))))throw new Error("矩阵维度排序应为 source、asc 或 desc");if(e.subtotals!==void 0&&(!Array.isArray(e.subtotals)||new Set(e.subtotals).size!==e.subtotals.length||e.subtotals.some(r=>!Number.isInteger(r)||r<1||r>=t)))throw new Error("矩阵小计深度应唯一且位于 1 至末级之前")}}function hn(e,t,r){return{fields:e,options:t??{},hierarchy:r,root:{values:[],children:new Map},leaves:0,expanded:0}}function gn(e,t){const r=Zn(t,e.fields);let n=e.root;for(let o=1;o<=r.length;o++){const i=r.slice(0,o),s=Fe(e.fields,i);let a=n.children.get(s);a||(a={values:i,children:new Map},n.children.set(s,a),o===r.length?(e.leaves++,e.expanded++):e.options.subtotals?.includes(o)&&e.expanded++),n=a}}function sa(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;if(typeof e=="number"&&typeof t=="number")return e-t;const r=`${typeof e}:${e}`,n=`${typeof t}:${t}`;return r<n?-1:1}function aa(e,t){const r=[...e.children.values()];return t&&t!=="source"&&r.sort((n,o)=>sa(n.values[n.values.length-1],o.values[o.values.length-1])*(t==="desc"?-1:1)),r}function Gt(e,t,r){return{key:Fe(e.fields,t),kind:r,depth:t.length,fields:e.fields.slice(0,t.length),values:t,labels:t.map(n=>n===null?e.hierarchy.emptyLabel??"(空)":String(n))}}function pn(e,t){const r=[];function n(o){for(const i of aa(o,e.options.sort?.[o.values.length]))i.children.size?(n(i),e.options.subtotals?.includes(i.values.length)&&r.push(Gt(e,i.values,"subtotal"))):r.push(Gt(e,i.values,"member"))}return n(e.root),t&&e.leaves&&r.push(Gt(e,[],"total")),r}function yn(e,t,r){const n=Zn(t,e.fields),o=[Fe(e.fields,n),...(e.options.subtotals??[]).map(i=>Fe(e.fields,n.slice(0,i)))];return r&&o.push(Fe(e.fields,[])),o}function ca(e,t,r){if(!(e.kind!=="member"&&t>e.depth))return e.kind==="total"?{key:"total",text:r.totalLabel??"合计",rowSpan:0}:e.kind==="subtotal"&&t===e.depth?{key:e.key,text:r.subtotalLabel??"小计",rowSpan:0}:{key:JSON.stringify(e.values.slice(0,t+1).map(n=>[typeof n,n])),text:e.labels[t],rowSpan:1}}function ua(e,t){const r=e.columnFields.length+1,n=e.rowFields.length,o=Array.from({length:r},()=>Array(n+t.length).fill(null));for(let i=0;i<e.columnFields.length;i++){let s;t.forEach((a,c)=>{const u=ca(a,i,e.hierarchy);if(!u){s=void 0;return}if(s?.key===u.key){s.cell.colSpan=(s.cell.colSpan??1)+1;return}const f={text:u.text,rowSpan:u.rowSpan||e.columnFields.length-i,editable:!1,derived:!0};o[i][n+c]=f,s={key:u.key,cell:f}})}return e.rowFields.forEach((i,s)=>{o[0][s]={text:e.hierarchy.row?.labels?.[s]??i,rowSpan:r,editable:!1,derived:!0}}),t.forEach((i,s)=>{const a=e.measures[i.measure];o[r-1][n+s]={text:a.label??`${a.field} (${a.op})`,editable:!1,derived:!0}}),{cells:o.map(i=>i.filter(s=>s!==null)),colWidthsMm:[...e.rowFields.map(()=>e.rowWidthMm??40),...t.map(()=>e.columnWidthMm??28)]}}function wn(e,t,r,n){const o=+(!!t.totals&&e>0),i=r.expanded+o,s=(n.expanded+o)*t.measures.length+t.rowFields.length;if(i>(t.maxRows??1e3)||n.expanded+o>(t.maxColumns??200))throw new Error("矩阵层级展开数量超出预算(包含小计/总计)");if(i*s>(t.maxCells??2e6))throw new Error("矩阵输出超出 maxCells 预算");return{rowCount:i,columnCount:s,cells:i*s}}function Qn(e,t){if(!Array.isArray(e)||e.length>(t.maxInputRows??1e5))throw new Error("矩阵输入超出预算");const r=hn(t.rowFields,t.hierarchy.row,t.hierarchy),n=hn(t.columnFields,t.hierarchy.column,t.hierarchy);if(e.length*(1+(r.options.subtotals?.length??0)+ +!!t.totals)*(1+(n.options.subtotals?.length??0)+ +!!t.totals)*t.measures.length>(t.maxAggregateUpdates??1e7))throw new Error("矩阵聚合更新超出 maxAggregateUpdates 预算");let i=wn(0,t,r,n);for(const s of e){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("矩阵数据行应为对象");gn(r,s),gn(n,s),i=wn(e.length,t,r,n)}return{row:r,column:n,shape:i}}function fa(e,t){return Qn(e,t).shape}function la(e,t,r){const n=new Map;for(const o of e){const i=yn(r.row,o,!!t.totals),s=yn(r.column,o,!!t.totals);for(const a of i){let c=n.get(a);c||(c=new Map,n.set(a,c));for(const u of s){let f=c.get(u);f||(f=t.measures.map(d=>oe({...d,field:d.valueField??d.field})),c.set(u,f)),f.forEach(d=>d.add(o))}}}return n}function da(e,t){return e.flatMap((r,n)=>t.measures.map((o,i)=>({...r,field:r.kind==="total"?`total_${i}`:`c${n}_${i}`,measure:i,measureField:o.field,valueField:o.valueField??o.field,operation:o.op})))}function ma(e,t){return e.kind==="total"?t.hierarchy.totalLabel??"合计":[...e.labels,...e.kind==="subtotal"?[t.hierarchy.subtotalLabel??"小计"]:[]].join(" / ")}function ha(e,t){return[...t.rowFields.map((r,n)=>({field:`r${n}`,header:t.hierarchy.row?.labels?.[n]??r,semanticRole:"dimension"})),...e.map(r=>{const n=t.measures[r.measure];return{field:r.field,header:`${ma(r,t)} · ${n.label??`${n.field} (${n.op})`}`,semanticRole:"measure",...n.digits===void 0?{}:{format:{kind:"number",digits:n.digits}}}})]}function ga(e,t,r,n){return e.map(o=>{const i={};r.rowFields.forEach((s,a)=>{i[`r${a}`]=o.kind==="total"?a===0?r.hierarchy.totalLabel??"合计":null:o.labels[a]??(a===o.depth?r.hierarchy.subtotalLabel??"小计":null)});for(const s of t)i[s.field]=n.get(o.key)?.get(s.key)?.[s.measure]?.value()??(r.measures[s.measure].op==="count"?0:null);return i})}function pa(e,t){const r=Qn(e,t),n=pn(r.row,!!t.totals),o=da(pn(r.column,!!t.totals),t),i=la(e,t,r);return{columns:ha(o,t),rows:ga(n,o,t,i),headerGrid:ua(t,o),metadata:{rowFields:[...t.rowFields],rowLabels:[...t.hierarchy.row?.labels??t.rowFields],columnFields:[...t.columnFields],columnLabels:[...t.hierarchy.column?.labels??t.columnFields],rows:n,columns:o}}}function ya(e,t){const r=()=>t.measures.map(c=>oe(c)),n=new Map,o=new Map,i=new Map,s=t.totals?r():void 0,a=(c,u)=>c?.forEach(f=>f.add(u));for(const c of e){const u=t.row(c),f=t.column(c);o.has(f.key)||o.set(f.key,f.label);let d=n.get(u.key);d||(d={label:u.label,cells:new Map,...t.totals?{totals:r()}:{}},n.set(u.key,d)),t.check(n.size,o.size);let l=d.cells.get(f.key);if(l||(l=r(),d.cells.set(f.key,l)),a(l,c),!t.totals)continue;let m=i.get(f.key);m||(m=r(),i.set(f.key,m)),a(d.totals,c),a(m,c),a(s,c)}return{groups:n,columns:o,columnTotals:i,totals:s}}function mt(e,t){const r=t.map(n=>Object.prototype.hasOwnProperty.call(e,n)?e[n]:null);if(r.some(n=>n!=null&&typeof n!="string"&&typeof n!="boolean"&&!(typeof n=="number"&&Number.isFinite(n))))throw new Error("矩阵维度必须是有限 JSON 标量");return{key:JSON.stringify(r.map(n=>[typeof n,n??null])),label:r.map(n=>n==null?"":String(n)).join(" / ")}}function wa(e){for(const t of["maxRows","maxColumns","maxInputRows","maxCells","maxAggregateUpdates"])if(e[t]!==void 0&&(!Number.isSafeInteger(e[t])||e[t]<1))throw new Error("矩阵预算应为正安全整数");for(const t of["columnWidthMm","rowWidthMm"])if(e[t]!==void 0&&(!Number.isFinite(e[t])||e[t]<=0))throw new Error("矩阵列宽应为正数")}function Cr(e){if(!e||!Array.isArray(e.rowFields)||!Array.isArray(e.columnFields)||!Array.isArray(e.measures))throw new Error("矩阵需要行维度、列维度和度量数组");for(const r of[e.rowFields,e.columnFields])if(r.some(n=>typeof n!="string"||!n.trim())||new Set(r).size!==r.length)throw new Error("矩阵维度字段应非空且唯一");if(wa(e),!e.rowFields.length||!e.columnFields.length||e.rowFields.length>16||e.columnFields.length>16)throw new Error("矩阵需要 1–16 个行/列维度");if(!e.measures.length||e.measures.length>32)throw new Error("矩阵需要 1–32 个度量");if(e.measures.map(r=>{if(!r||typeof r!="object")throw new Error("矩阵度量应为对象");if(oe({...r,field:r.valueField??r.field}),r.label!==void 0&&typeof r.label!="string")throw new Error("矩阵度量标签应为字符串");return r.field}).some(r=>typeof r!="string"||!r.trim()))throw new Error("矩阵度量字段应非空");e.hierarchy!==void 0&&ia(e.hierarchy,e.rowFields,e.columnFields)}function eo(e,t){if(Cr(t),t.hierarchy)return fa(e,t);if(!Array.isArray(e)||e.length>(t.maxInputRows??1e5))throw new Error("矩阵输入超出预算");const r=new Set,n=new Set;for(const s of e){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("矩阵数据行应为对象");if(r.add(mt(s,t.rowFields).key),n.add(mt(s,t.columnFields).key),r.size>(t.maxRows??1e3)||n.size>(t.maxColumns??200))throw new Error("矩阵维度数量超出预算");if((r.size+ +!!t.totals)*((n.size+ +!!t.totals)*t.measures.length+1)>(t.maxCells??2e6))throw new Error("矩阵输出超出 maxCells 预算")}const o=r.size+ +(!!t.totals&&e.length>0),i=(n.size+ +!!t.totals)*t.measures.length+1;return{rowCount:o,columnCount:i,cells:o*i}}function ba(e,t){if(t?.hierarchy)return Cr(t),pa(e,t);eo(e,t);const r=ya(e,{row:s=>mt(s,t.rowFields),column:s=>mt(s,t.columnFields),measures:t.measures.map(s=>({...s,field:s.valueField??s.field})),totals:t.totals,check:()=>{}}),n=[...r.groups.values()].map(s=>({rowLabel:s.label})),o=[{field:"rowLabel",header:t.rowHeader??t.rowFields.join(" / "),semanticRole:"dimension"}],i={rowLabel:"合计"};return t.measures.forEach((s,a)=>{const c=[...r.columns.entries()].map(([u,f],d)=>({key:u,label:f,field:`c${d}_${a}`}));t.totals&&c.push({key:"",label:"合计",field:`total_${a}`});for(const u of c){const f=u.field===`total_${a}`;o.push({field:u.field,header:`${u.label} · ${s.label??`${s.field} (${s.op})`}`,semanticRole:"measure",...s.digits===void 0?{}:{format:{kind:"number",digits:s.digits}}});let d=0;for(const l of r.groups.values())n[d++][u.field]=(f?l.totals?.[a]:l.cells.get(u.key)?.[a])?.value()??(s.op==="count"?0:null);i[u.field]=(f?r.totals?.[a]:r.columnTotals.get(u.key)?.[a])?.value()??(s.op==="count"?0:null)}}),t.totals&&e.length&&n.push(i),{rows:n,columns:o}}const xa=96;function va(e,t=xa){return e*t/72}function It(e,t=96,r=Ar){if(e?.fontSizePx!=null)return{fontSizePt:e.fontSizePx*72/t,fontSizePx:e.fontSizePx};const n=e?.fontSize??r;return{fontSizePt:n,fontSizePx:va(n,t)}}function Ma(e){return e?.lineHeight??kt}function Q(e,t){const r={...e,...t};return t?.fontSize!=null&&t.fontSizePx==null&&delete r.fontSizePx,t?.fontSizePx!=null&&t.fontSize==null&&delete r.fontSize,r}function $a(e,t){const r=e.length;if(r===0)return[];const n=e.reduce((a,c)=>a+c,0),o=n>0&&t>0?t/n:1,i=[];let s=0;for(let a=0;a<r;a++){const c=Math.max(0,e[a]*o);i.push({pos:s,size:c}),s+=c}return i}function bn(e,t,r){return e?.length?$a(e,t):Array.from({length:r},(n,o)=>({pos:t*o/r,size:t/r}))}function to(e,t,r){const n=e.cells??[],o=Math.max(n.length,1),i=e.colWidthsMm?.length??Math.max(1,...n.map(g=>Array.isArray(g)?g.length:0)),s=bn(e.colWidthsMm,t,i),a=g=>g<=0?0:g>=i?s[s.length-1].pos+s[s.length-1].size:s[g].pos,c=bn(e.rowHeightsMm,r,o),u=g=>g<=0?0:g>=o?c[c.length-1].pos+c[c.length-1].size:c[g].pos,f=new Set,d=(g,x)=>`${g}:${x}`,l=[],m=new Set,h=new Set,p=(g,x)=>`v${g}:${x}`,w=(g,x)=>`h${g}:${x}`;n.forEach((g,x)=>{if(!Array.isArray(g))return;let b=0;for(const $ of g){for(;b<i&&f.has(d(x,b));)b++;if(b>=i)break;const T=Math.max(1,Math.min($?.colSpan??1,i-b)),j=Math.max(1,$?.rowSpan??1),v=Math.min(o,x+j),M=Math.min(i,b+T);for(let N=x;N<v;N++)for(let I=b;I<M;I++)f.add(d(N,I));for(let N=b+1;N<M;N++)for(let I=x;I<v;I++)m.add(p(N,I));for(let N=x+1;N<v;N++)for(let I=b;I<M;I++)h.add(w(N,I));const S=a(b),R=u(x);l.push({ri:x,ci:b,cell:$??{},xMm:S,yMm:R,widthMm:a(M)-S,heightMm:u(v)-R}),b=M}});const y=[];for(let g=1;g<i;g++){let x=-1;for(let b=0;b<=o;b++){const $=b<o&&!m.has(p(g,b));$&&x<0&&(x=b),!$&&x>=0&&(y.push({kind:"v",pos:a(g),from:u(x),to:u(b)}),x=-1)}}for(let g=1;g<o;g++){let x=-1;for(let b=0;b<=i;b++){const $=b<i&&!h.has(w(g,b));$&&x<0&&(x=b),!$&&x>=0&&(y.push({kind:"h",pos:u(g),from:a(x),to:a(b)}),x=-1)}}return{columns:s,rows:c,cells:l,edges:y}}function Sa(e,t,r,n=e.paddingMm??1){return t.field!==e.tree.labelField?0:Math.min(r.depth*(e.tree.indentMm??3),Math.max(0,t.widthMm-n*2-4))}function Ea(e,t,r,n){const o=n.tree;(o.input==="nested"||[o.idField,o.parentField].includes(t.field))&&(e.editable=!1),r.hasChildren&&o.parentValues==="leaf-aggregate"&&o.aggregates?.some(i=>i.field===t.field)&&(e.derived=!0,e.editable=!1)}function ro(e,t,r){return r==="identifier"||r==="dimension"||r==="date"?"center":r==="measure"?"right":r==="text"?"left":t?.kind==="number"||t?.kind==="percent"?"right":t?.kind==="date"||e instanceof Date||typeof e=="boolean"?"center":typeof e=="number"&&Number.isFinite(e)?"right":"left"}function Tr(e){if(e==null)return"";if(typeof e=="string"||typeof e=="number")return String(e);if(typeof e=="boolean")return e?"是":"否";if(e instanceof Date)return e.toISOString().slice(0,10);try{return JSON.stringify(e)}catch{return String(e)}}function no(e,t){let r=Q({fontSize:e.fontSizePt??Ar,bold:e.headerBold??!0,align:"center",verticalAlign:"middle",backgroundColor:e.headerBackgroundColor},t.style);return e.headerAlign!==void 0&&(r.align=e.headerAlign),r=Q(r,e.headerStyle),t.headerAlign!==void 0&&(r.align=t.headerAlign),Q(r,t.headerStyle)}function Aa(e,t){return{member:"body",subtotal:"subtotal",total:"grand-total"}[e?.rows.get(t)?.kind??"member"]}function ka(e){const t=e.matrix;if(!t.hierarchy)return t;const r=new Map(e.columns.map(o=>[o.field,o.header])),n={sum:"求和",count:"计数",avg:"平均",min:"最小",max:"最大",weightedAvg:"加权平均"};return{...t,hierarchy:{...t.hierarchy,row:{...t.hierarchy.row,labels:t.hierarchy.row?.labels??t.rowFields.map(o=>r.get(o)??o)},column:{...t.hierarchy.column,labels:t.hierarchy.column?.labels??t.columnFields.map(o=>r.get(o)??o)}},measures:t.measures.map(o=>{const i=r.get(o.field)??r.get(o.valueField??o.field);return o.label===void 0&&i?{...o,label:`${i}(${n[o.op]})`}:o})}}function Na(e,t){if(!e.matrix)return{list:e,rows:t};if(e.detail||e.groupBy||e.groups?.length||e.grandTotal)throw new Error("矩阵不能同时配置普通分组、总计或主从明细");const r=ba(t,ka(e)),n=r.columns.map(a=>({...a,widthMm:a.semanticRole==="dimension"?e.matrix.rowWidthMm??40:e.matrix.columnWidthMm??28,editable:!1,align:a.semanticRole==="dimension"?"center":"right"})),o={...e,columns:n,headerGrid:r.headerGrid,rowKey:void 0,revisionField:void 0,sourceTokenField:void 0};e.layout==="wide"&&(o.widthMm=n.reduce((a,c)=>a+c.widthMm,0));const i=r.metadata,s=i?{rows:new WeakMap(r.rows.map((a,c)=>[a,i.rows[c]])),header:{columns:i.columns,rowFields:i.rowFields,rowLabels:i.rowLabels,columnFields:i.columnFields,columnLabels:i.columnLabels}}:void 0;return{list:o,rows:r.rows,...s?{matrix:s}:{}}}function Pa(e,t){if(!e.matrix?.hierarchy||!e.headerGrid)return e.headerGrid;const r=e.paddingMm??1,n=e.headerGrid.cells.map(()=>e.rowHeightMm??0),o=e.columns.map(c=>c.widthMm),i=to({...e.headerGrid,colWidthsMm:o},o.reduce((c,u)=>c+u,0),n.length),s=new WeakMap;for(const{cell:c,ci:u,ri:f,widthMm:d}of i.cells){const l={...no(e,e.columns[u]),...c.style},m=It(l).fontSizePt,p=(Ve(c.text??"",Math.max(1,d-r*2),{fontSizePt:m,fontFamily:l.fontFamily,bold:l.bold,italic:l.italic,letterSpacingPt:l.letterSpacing},t).length*m*(l.lineHeight??kt)*25.4/72+r*2)/(c.rowSpan??1);for(let w=f;w<f+(c.rowSpan??1);w++)n[w]=Math.max(n[w]??0,p);s.set(c,l)}const a=e.headerGrid.cells.map(c=>c.map(u=>u?{...u,style:s.get(u)}:null));return{...e.headerGrid,cells:a,rowHeightsMm:n}}class oo extends Error{constructor(t){super(`树节点超出行数预算 ${t}`),this.limit=t,this.code="tree-row-limit",this.name="TreeRowLimitError"}}function Yt(e,t,r,n){const o=e??t;if(!Number.isInteger(o)||o<1||o>r)throw new Error(`${n}应为 1–${r} 的整数`);return o}function jr(e){return{rows:Yt(e.maxRows,1e5,1e6,"树行数预算"),depth:Yt(e.maxDepth,64,256,"树深度预算"),visits:Yt(e.maxAggregationVisits,1e6,1e7,"树聚合访问预算")}}function io(e){return typeof e=="string"&&!!e.trim()}function we(e){return io(e)&&!["__proto__","prototype","constructor"].includes(e)}function so(e){if(io(e)||typeof e=="number"&&Number.isFinite(e))return e;throw new Error("树节点业务键应为非空字符串或有限数字")}function ao(e){return JSON.stringify([typeof e,e])}function co(e){return[e.idField,...e.input==="flat"?[e.parentField??""]:[e.childrenField??"children"]]}function Dr(e,t){const r=co(e);if(t?.some(n=>n.scope&&n.scope!=="row"||r.includes(n.field)))throw new Error("树形布局仅支持不覆盖结构键的当前行计算")}function Se(e){if(!e?.aborted)return;const t=new Error("树报表处理已取消");throw t.name="AbortError",t}function Fa(e){const t=e.aggregates??[];if(!Array.isArray(t)||t.length>32)throw new Error("树聚合最多 32 项");if(e.parentValues!=="leaf-aggregate"&&t.length)throw new Error("树聚合需显式选择 leaf-aggregate 父级取值策略");if(e.parentValues==="leaf-aggregate"&&!t.length)throw new Error("叶子聚合策略至少需要一个聚合字段");const r=new Set;for(const n of t){if(!n||!we(n.field)||r.has(n.field))throw new Error("树聚合输出字段应安全、非空且唯一");for(const o of[n.valueField,n.weightField])if(o!==void 0&&!we(o))throw new Error("树聚合来源字段应安全且非空");if([...co(e),e.labelField].includes(n.field))throw new Error("树聚合不能覆盖结构键或标签字段");r.add(n.field),oe({...n,field:n.valueField??n.field})}}function Oa(e){if(!we(e.idField)||!we(e.labelField))throw new Error("树需要安全的业务键和标签字段");if(e.input==="flat"&&(!we(e.parentField)||e.parentField===e.idField))throw new Error("扁平树需要独立的父键字段");if(e.childrenField!==void 0&&!we(e.childrenField))throw new Error("子节点字段应安全且非空");if(e.input==="nested"&&[e.idField,e.labelField].includes(e.childrenField??"children"))throw new Error("子节点字段不能覆盖业务键或标签字段")}function uo(e){if(!e||typeof e!="object"||!["flat","nested"].includes(e.input))throw new Error("树输入应为 flat 或 nested");if(Oa(e),e.orphan!==void 0&&!["error","root"].includes(e.orphan))throw new Error("树孤儿策略应为 error 或 root");if(e.parentValues!==void 0&&!["source","leaf-aggregate"].includes(e.parentValues))throw new Error("未知树父级取值策略");if(e.indentMm!==void 0&&(!Number.isFinite(e.indentMm)||e.indentMm<0||e.indentMm>20))throw new Error("树每级缩进应为 0–20 mm");jr(e),Fa(e)}function fo(e,t,r,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("树节点应为对象");if(r.size>=n.rows)throw new oo(n.rows);const o=so(e[t.idField]),i=ao(o);if(r.has(i))throw new Error(`树节点业务键重复:${String(o)}`);const s={original:e,row:e,key:o,depth:0,children:[]};return r.set(i,s),s}function Ia(e,t,r,n,o){for(const s of e)Se(o),fo(s,t,r,n);const i=[];for(const s of r.values()){Se(o);const a=s.row[t.parentField];if(a==null){i.push(s);continue}const c=r.get(ao(so(a)));if(!c){if(t.orphan!=="root")throw new Error(`树节点 ${String(s.key)} 的父节点不存在`);i.push(s);continue}if(c===s)throw new Error("树节点不能以自身为父节点");s.parent=c,c.children.push(s)}return i}function Ra(e,t,r,n,o){const i=[],s=[{rows:e,next:0}];for(;s.length;){Se(o);const a=s[s.length-1];if(a.next>=a.rows.length){s.pop();continue}const c=fo(a.rows[a.next++],t,r,n);if(c.parent=a.parent,c.depth=s.length-1,s.length>n.depth)throw new Error(`树节点超出深度预算 ${n.depth}`);(a.parent?.children??i).push(c);const u=c.row[t.childrenField??"children"];if(u!=null){if(!Array.isArray(u))throw new Error("嵌套树 children 字段应为数组");u.length&&s.push({rows:u,next:0,parent:c})}}return i}function Ca(e,t,r,n){const o=[],i=[{nodes:e,next:0}];for(;i.length;){Se(n);const s=i[i.length-1];if(s.next>=s.nodes.length){i.pop();continue}if(i.length>r.depth)throw new Error(`树节点超出深度预算 ${r.depth}`);const a=s.nodes[s.next++];a.depth=i.length-1,o.push(a),a.children.length&&i.push({nodes:a.children,next:0})}if(o.length!==t)throw new Error("树父子关系存在循环");return o}function Ta(e,t,r,n){if(t.parentValues!=="leaf-aggregate")return;const o=t.aggregates,i=new Map;for(const a of e)a.children.length&&i.set(a,o.map(c=>oe({...c,field:c.valueField??c.field})));let s=0;for(const a of e)if(!a.children.length)for(let c=a.parent;c;c=c.parent){if(Se(n),s+=o.length,s>r.visits)throw new Error(`树聚合超出访问预算 ${r.visits}`);for(const u of i.get(c))u.add(a.row)}for(const[a,c]of i)a.row={...a.row},o.forEach((u,f)=>{a.row[u.field]=c[f].value()})}function lo(e,t,r){if(uo(t),Se(r),!Array.isArray(e))throw new Error("树数据应为节点数组");const n=jr(t),o=new Map,i=t.input==="flat"?Ia(e,t,o,n,r):Ra(e,t,o,n,r);return Ca(i,o.size,n,r)}function mo(e,t,r){return lo(e,t,r).map(n=>n.original)}function ho(e,t,r={}){const n=lo(e,t,r.signal);if(Dr(t,r.computed?.fields),r.computed?.fields.length){const o=Ft(n.map(i=>i.row),{...r.computed,signal:r.signal}).rows;n.forEach((i,s)=>{i.row=o[s]})}return Ta(n,t,jr(t),r.signal),{rows:n.map(o=>o.row),entries:n.map(o=>({row:o.row,original:o.original,key:o.key,depth:o.depth,hasChildren:!!o.children.length})),leaves:n.filter(o=>!o.children.length).map(o=>o.row)}}function ja(e,t,r){const n=new Set,o=e.cells.map((i,s)=>{const a=[];let c=0;for(const u of i){for(;n.has(`${s}:${c}`);)c++;const f=u?.colSpan??1,d=u?.rowSpan??1;let l=0;for(let m=c;m<c+f;m++){t.has(m)&&l++;for(let h=s+1;h<s+d;h++)n.add(`${h}:${m}`)}l&&a.push(u?{...u,colSpan:l}:null),c+=f}return a});return{...e,cells:o,colWidthsMm:r}}function Da(e){if(!e.columns.some(n=>n.hidden))return e;const t=new Set,r=e.columns.filter((n,o)=>n.hidden?!1:(t.add(o),!0));if(!r.length)throw new Error("列表至少需要一列可见列");return{...e,columns:r,...e.headerGrid?{headerGrid:ja(e.headerGrid,t,r.map(n=>n.widthMm))}:{}}}function Lr(e){return e.kind==="list"?e.id:e.nid}function La(e){return e.kind==="list"?!1:e.pageAnchor!==void 0||e.kind==="text"&&typeof e.text=="string"&&/\{(?:page|totalPages)\}/.test(e.text)}function Ba(e,t){const r=e.filter(o=>t.componentIds.includes(Lr(o)??""));if(r.filter(o=>o.kind==="list"&&o.cardinality!=="record").length&&r.length!==1)throw new Error("纵向重复区域必须独占流式分段,不能与静态或单记录区域并排");for(const o of r){const i=o.kind==="list"?o.topMm+(o.rowHeightMm??0):o.topMm+o.heightMm;if(o.topMm<t.topMm-.001||i>t.topMm+t.heightMm+.001)throw new Error("流式分段应完整包含其组件的原始纵向范围")}}function _a(e,t){if(!t)return e.map(n=>({components:[n]}));const r=new Map(e.map(n=>[Lr(n),n]));return t.bands.map(n=>({band:n,components:n.componentIds.map(o=>{const i=r.get(o);if(!i)throw new Error(`流式区域引用不存在的组件:${o}`);return i})}))}function go(e,t){if(!t||!Array.isArray(t.bands)||!t.bands.length||t.bands.length>1e4)throw new Error("流式排版应包含 1–10000 个区域");const r=new Set,n=new Set;for(const o of e){if(La(o))continue;const i=Lr(o);if(!i||r.has(i))throw new Error("流式排版组件应具有唯一标识");r.add(i)}if(Ka(e,t,r,n),n.size!==r.size)throw new Error("流式排版必须显式包含每个非锚点组件")}function Ka(e,t,r,n){let o=-1/0;for(const i of t.bands){if(!Number.isFinite(i.topMm)||!Number.isFinite(i.heightMm)||i.topMm<0||i.heightMm<=0||i.topMm<o-.001)throw new Error("流式区域应按原始位置排序,尺寸有效且不重叠");if(!Array.isArray(i.componentIds)||!i.componentIds.length)throw new Error("流式区域不能没有组件");for(const s of i.componentIds){if(!r.has(s)||n.has(s))throw new Error(`流式区域组件缺失、重复或包含页锚点:${s}`);n.add(s)}Ba(e,i),o=i.topMm+i.heightMm}}function*Wa(e){const{page:t}=e;go(t.components,t.flow);let r=0,n=0;for(const o of _a(t.components,t.flow)){e.active();const i=o.band,s=o.components.some(f=>f.kind==="list"&&f.cardinality!=="record"),a=s?0:o.components.reduce((f,d)=>Math.max(f,d.topMm-i.topMm+(d.kind==="list"?e.height(d):d.heightMm)),i.heightMm);let c=Math.max(e.top(),n+i.topMm-r);if(!s&&a>e.bottom()-e.top()+.001)throw new Error(`静态区域 ${i.componentIds.join(",")} 高度超出单页可用范围`);!s&&c+a>e.bottom()+.001&&(e.nextPage(),yield*e.takePages(),e.active(),c=e.top());let u=c+a;for(const f of o.components){const d=c+f.topMm-i.topMm;f.kind==="list"?(yield*e.list(f,d,l=>{u=s?l:Math.max(u,l)}),e.active()):e.append({...f,topMm:d})}n=u,r=i.topMm+i.heightMm}}function Ja(e){return!!(e.computed?.length||e.groups?.length||e.groupBy||e.grandTotal||e.rowVisibleWhen||e.matrix||e.tree||e.detail||e.columns.some(t=>t.rules?.length||t.visibleWhen||t.visual))}function Rt(e){return e.pages.some(t=>t.components.some(r=>r.kind==="list"?Ja(r):!!r.chartBinding))}const za=new Set(["__proto__","prototype","constructor"]);function te(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tt(e){return typeof e=="string"&&!!e.trim()&&!za.has(e)}function ht(e,t,r,n){for(const o of Object.keys(e))t.includes(o)||n.push({path:`${r}.${o}`,message:"存在未知配置字段"})}function Va(e,t,r){if(e!==void 0){if(!te(e)||!["number","percent","date"].includes(String(e.kind))){r.push({path:t,message:"绑定格式应为 number、percent 或 date"});return}ht(e,e.kind==="date"?["kind","pattern"]:e.kind==="number"?["kind","digits","thousands"]:["kind","digits"],t,r),e.digits!==void 0&&(!Number.isInteger(e.digits)||Number(e.digits)<0||Number(e.digits)>100)&&r.push({path:`${t}.digits`,message:"精度应为 0..100 整数"}),e.thousands!==void 0&&typeof e.thousands!="boolean"&&r.push({path:`${t}.thousands`,message:"千分位开关应为布尔值"}),e.pattern!==void 0&&typeof e.pattern!="string"&&r.push({path:`${t}.pattern`,message:"日期格式应为字符串"})}}function Ha(e,t,r){const n=e.binding;if(n===void 0)return;const o=`${t}.binding`;if(!te(n)){r.push({path:o,message:"字段绑定应为对象"});return}(!["text","image","barcode","qrcode"].includes(String(e.kind))||e.grid!==void 0)&&r.push({path:o,message:"绑定仅支持独立文本、图片、条码与二维码组件"}),ht(n,["field","format","prefix","suffix","emptyText"],o,r),tt(n.field)||r.push({path:`${o}.field`,message:"绑定字段应为安全的非空字段名(按字面读取自有字段)"});for(const i of["prefix","suffix","emptyText"])n[i]!==void 0&&typeof n[i]!="string"&&r.push({path:`${o}.${i}`,message:"应为字符串"});Va(n.format,`${o}.format`,r),e.kind==="image"&&["format","prefix","suffix"].some(i=>n[i]!==void 0)&&r.push({path:o,message:"图片绑定直接读取 PNG/JPEG data URL,不支持文本格式或前后缀"})}function Ua(e,t){if(!te(e)){t.push({path:"$.repeat",message:"逐记录配置应为对象"});return}ht(e,["dataset","rowKey","copies"],"$.repeat",t),tt(e.dataset)||t.push({path:"$.repeat.dataset",message:"数据集应为安全的非空名称"}),e.rowKey!==void 0&&!tt(e.rowKey)&&t.push({path:"$.repeat.rowKey",message:"业务主键应为安全的非空字段名"});const r=e.copies;r!==void 0&&(te(r)?(ht(r,["field"],"$.repeat.copies",t),tt(r.field)||t.push({path:"$.repeat.copies.field",message:"复制数字段应为安全的非空字段名"})):(!Number.isSafeInteger(r)||Number(r)<1||Number(r)>1e3)&&t.push({path:"$.repeat.copies",message:"每条记录复制数应为 1..1000 整数"}))}function po(e,t,r,n){if(!te(e))return;Ha(e,t,n),e.binding!==void 0&&!r&&n.push({path:`${t}.binding`,message:"字段绑定需要模板 repeat 数据集;普通报表请使用列表字段"}),r&&e.kind==="list"&&n.push({path:t,message:"逐记录标签使用固定组件;动态列表请使用普通报表模板"}),e.chartBinding!==void 0&&(r||t.includes(".children."))&&n.push({path:`${t}.chartBinding`,message:"数据图表应放在普通报表的页面或流式分区,不放在逐记录标签或嵌套单元格内"});const o=e.grid;te(o)&&Array.isArray(o.cells)&&o.cells.forEach((i,s)=>{Array.isArray(i)&&i.forEach((a,c)=>{te(a)&&Array.isArray(a.children)&&a.children.forEach((u,f)=>po(u,`${t}.grid.cells.${s}.${c}.children.${f}`,r,n))})})}function yo(e,t){const r=e.repeat!==void 0;r&&Ua(e.repeat,t),Array.isArray(e.pages)&&e.pages.forEach((n,o)=>{if(!te(n))return;const i=`$.pages.${o}`;r&&(n.layout==="wide"||n.flow!==void 0)&&t.push({path:i,message:"逐记录标签仅支持固定尺寸页面,不支持宽表或流式分区"}),Array.isArray(n.components)&&n.components.forEach((s,a)=>{const c=`${i}.components.${a}`;if(po(s,c,r,t),!r||!te(s))return;const{leftMm:u,topMm:f,widthMm:d,heightMm:l}=s;[u,f,d,l,n.widthMm,n.heightMm].every(m=>typeof m=="number"&&Number.isFinite(m))&&(Number(u)<0||Number(f)<0||Number(u)+Number(d)>Number(n.widthMm)+.001||Number(f)+Number(l)>Number(n.heightMm)+.001)&&t.push({path:c,message:"标签组件超出纸张边界,请调整位置或尺寸"})})})}const Ga=512,xn=256*1024;function Ya(){const e=new Map;let t=0,r;return(n,o,i,s)=>{s!==r&&(e.clear(),t=0,r=s);const a=JSON.stringify([n,o,i.fontSizePt,i.fontFamily,i.bold,i.italic,i.letterSpacingPt]),c=e.get(a);if(c)return e.delete(a),e.set(a,c),c.lines.slice();const u=Ve(n,o,i,s),f=a.length+u.reduce((d,l)=>d+l.length,0);if(f<=xn){for(;e.size>=Ga||t+f>xn;){const d=e.keys().next().value;t-=e.get(d).units,e.delete(d)}e.set(a,{lines:u.slice(),units:f}),t+=f}return u}}function qa(e){return typeof e=="string"&&/^data:image\/(png|jpe?g);base64,[A-Za-z0-9+/\r\n]+=*$/.test(e)}class H extends Error{constructor(t,r,n,o){super(`${t}: ${r}`),this.path=t,this.rowIndex=n,this.field=o,this.code="report-binding",this.name="ReportBindingError"}}function Br(e,t,r={}){const n=r.rowIndex??0,i=`$.datasets.${r.dataset??"label"}[${n}].${t}`,s=Object.getOwnPropertyDescriptor(e,t);if(!s||s.get||s.set)throw new H(i,"字段必须是记录的自有数据字段,不能缺失、使用访问器或从原型继承",n,t);const a=s.value;if(a==null||typeof a=="string"||typeof a=="boolean"||typeof a=="number"&&Number.isFinite(a))return a;throw new H(i,"绑定值应为字符串、有限数字、布尔值或空值",n,t)}function Xa(e,t,r={}){const n=Br(t,e.field,r);return n==null||n===""?e.emptyText??"":`${e.prefix??""}${Pr(n,e.format)}${e.suffix??""}`}const Za=1e4,vn=25e4;function _r(e){if(e?.aborted)throw e.reason??new DOMException("标签生成已取消","AbortError")}function wo(e,t,r){const n=typeof e.copies=="object"?Br(t,e.copies.field,r):e.copies??1;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>1e3)throw new H(`$.datasets.${r.dataset}[${r.rowIndex}]`,"每条记录复制数必须是 1..1000 的数值型整数",r.rowIndex,typeof e.copies=="object"?e.copies.field:void 0);return n}function bo(e,t,r){if(e.rowKey===void 0)return;const n=Br(t,e.rowKey,r);if(typeof n=="string"&&n.trim()||typeof n=="number"&&Number.isFinite(n))return n;throw new H(`$.datasets.${r.dataset}[${r.rowIndex}].${e.rowKey}`,"业务主键必须是非空字符串或有限数字",r.rowIndex,e.rowKey)}function Qa(e){const t=r=>1+(r.grid?.cells.reduce((n,o)=>n+1+o.length+o.reduce((i,s)=>i+(s?.children?.reduce((a,c)=>a+t(c),0)??0),0),0)??0);return e.pages.reduce((r,n)=>r+n.components.reduce((o,i)=>o+t(i),0),0)}function ec(e,t,r){const n=e.repeat,o=Object.prototype.hasOwnProperty.call(t,n.dataset)?t[n.dataset]:void 0;if(!Array.isArray(o))throw new H(`$.datasets.${n.dataset}`,"逐记录标签数据集缺失,应提供对象数组(允许空数组)");const i=new Set,s=r.maxPages??Za,a=Qa(e);let c=0,u=0;for(const[f,d]of o.entries()){if(_r(r.signal),!d||typeof d!="object"||Array.isArray(d))throw new H(`$.datasets.${n.dataset}[${f}]`,"标签记录应为对象",f);const l={rowIndex:f,dataset:n.dataset},m=bo(n,d,l);if(m!==void 0){const p=JSON.stringify([typeof m,m]);if(i.has(p))throw new H(`$.datasets.${n.dataset}[${f}].${n.rowKey}`,"业务主键重复;请先确认记录来源,避免重复打印标签",f,n.rowKey);i.add(p)}const h=wo(n,d,l);if(c+=h*e.pages.length,u+=h*a,c>s)throw new $e(s,c);if(u>vn)throw new H("$.repeat",`标签组件总量(含网格行、槽位及嵌套组件)超过安全预算 ${vn},请分批生成`,f)}return o}function tc(e,t,r){if(!e.binding)return e;const{binding:n,...o}=e,i=Xa(n,t.row,t);if(e.kind==="image"){if(!i)return;if(!qa(i))throw new H(`${r}.binding`,"图片字段只接受 PNG/JPEG base64 data URL;业务 URL 应由宿主安全加载后转换",t.rowIndex,n.field);return{...o,imageData:i}}return e.kind==="barcode"||e.kind==="qrcode"?(delete o.imageData,{...o,code:{...o.code,value:i},fallbackText:i}):(delete o.lines,delete o.richParagraphs,{...o,text:i})}function rc(e,t,r){if(e.kind!=="text"||e.grid||e.richParagraphs?.length)return e;const n=e.style??{},o=It(n).fontSizePt,i=e.text??e.lines?.join(`
5
- `)??"";if(i.length>16384)throw new H(r,"标签文本超过 16384 字符预算,请缩小字段内容",t.rowIndex);const s=t.wrapText(i,e.widthMm,{fontSizePt:o,bold:n.bold,italic:n.italic,fontFamily:n.fontFamily,letterSpacingPt:n.letterSpacing},t.options.measurer??kr),a=s.length*o*Ma(n)*25.4/72;if(a>e.heightMm+.05)throw new H(r,`标签文字需要约 ${a.toFixed(2)}mm 高,超出 ${e.heightMm}mm;请增大文本区域、减少内容或调整字号`,t.rowIndex,e.binding?.field);return{...e,lines:s}}function xo(e,t,r){_r(t.options.signal);const n=tc(e,t,r);if(!n)return;let o=n.grid;return o&&(o={...o,cells:o.cells.map((i,s)=>i.map((a,c)=>a?.children?.length?{...a,children:a.children.flatMap((u,f)=>{const d=xo(u,t,`${r}.grid.cells.${s}.${c}.children.${f}`);return d?[d]:[]})}:a))}),rc(o===n.grid?n:{...n,grid:o},t,r)}function nc(e,t,r,n,o,i){return{...e,components:e.components.flatMap((s,a)=>{const c=xo(s,r,`$.pages.${t}.components.${a}`);return c?[{...c,meta:{...c.meta,labelSource:{pageIndex:t,componentIndex:a}}}]:[]}),meta:{...e.meta,record:{dataset:r.dataset,rowIndex:r.rowIndex,...i===void 0?{}:{rowKey:i},copyIndex:n,copyCount:o,templatePageIndex:t}}}}function*oc(e,t,r){const n=[];if(yo(e,n),n.length)throw new H(n[0].path,n[0].message);if(!e.repeat){for(const[a,c]of e.pages.entries())yield{page:c,pageIndex:a};return}const o=e.repeat,i=ec(e,t,r),s=Ya();for(const[a,c]of i.entries()){const u={row:c,rowIndex:a,dataset:o.dataset,options:r,wrapText:s},f=wo(o,c,u),d=bo(o,c,u);for(let l=0;l<f;l++)for(const[m,h]of e.pages.entries())_r(r.signal),yield{page:nc(h,m,u,l,f,d),pageIndex:m}}}const ic=/^#[0-9a-f]{6}$/i;function vo(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return t.kind!=="colorScale"&&t.kind!=="dataBar"||t.field!==void 0&&(typeof t.field!="string"||!t.field.trim())||t.numeric!==void 0&&!["number","decimal"].includes(t.numeric)||[t.min,t.max].some(r=>r!==void 0&&(typeof r!="number"||!Number.isFinite(r)))||t.min!==void 0&&t.max!==void 0&&t.min>t.max?!1:Object.entries(t).every(([r,n])=>!["color","negativeColor","lowColor","highColor"].includes(r)||typeof n=="string"&&ic.test(n))}function Mo(e,t){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(t!=="decimal"||typeof e!="string"||e.length>1024||!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e))return;const r=Number(e);return Number.isFinite(r)?r:void 0}function sc(e,t,r){let n="#";for(const o of[1,3,5]){const i=parseInt(e.slice(o,o+2),16),s=parseInt(t.slice(o,o+2),16);n+=Math.round(i+(s-i)*r).toString(16).padStart(2,"0")}return n}function qt(e,t,r){if(t===r)return e<t?0:e>r?1:.5;if(e<=t)return 0;if(e>=r)return 1;const n=r-t;return Number.isFinite(n)?(e-t)/n:(e/2-t/2)/(r/2-t/2)}function ac(e,t,r,n){const o=new WeakMap;return{apply(i,s){const a=Mo(s[t],e.numeric);if(a===void 0)return;if(e.kind==="dataBar"){const l=Math.min(r,0),m=Math.max(n,0),h=qt(0,l,m),p=l===m?h:qt(a,l,m);i.dataBar={start:Math.min(h,p),end:Math.max(h,p),color:a<0?e.negativeColor??"#f3bcc3":e.color??"#bad8fa"};return}const c=sc(e.lowColor??"#f0f7ff",e.highColor??"#8bbcf1",qt(a,r,n)),u=i.style??{},f=o.get(u)??new Map;o.set(u,f);let d=f.get(c);d||(d={...u,backgroundColor:c},f.set(c,d)),i.style=d}}}function cc(e,t,r){return e.map(n=>{Mn(r);const o=n.visual;if(!o)return;if(!vo(o))throw new TypeError("Invalid column visual rule");const i=o.field??n.field;let s=1/0,a=-1/0,c=0;if(o.min===void 0||o.max===void 0)for(const d of t){(c++&1023)===0&&Mn(r);const l=Mo(d[i],o.numeric);l!==void 0&&(s=Math.min(s,l),a=Math.max(a,l))}let u=o.min??s,f=o.max??a;if(!(!Number.isFinite(u)||!Number.isFinite(f)))return u>f&&(o.min!==void 0?f=u:u=f),ac(o,i,u,f)})}function Mn(e){if(e?.aborted)throw e.reason??new DOMException("Aborted","AbortError")}function uc(e){return{widthMm:e.widthMm,heightMm:e.heightMm,marginTopMm:e.marginTopMm??0,marginBottomMm:e.marginBottomMm??0,marginLeftMm:e.marginLeftMm??0,marginRightMm:e.marginRightMm??0,components:[]}}function gt(e,t){const r=t.heightMm-(e.layout==="wide"?t.marginBottomMm:e.marginBottomMm??t.marginBottomMm);return e.components.reduce((n,o)=>o.kind!=="list"&&o.pageAnchor==="footer"?Math.min(n,o.topMm):n,r)}function We(e){return e.components.reduce((t,r)=>r.kind!=="list"&&r.pageAnchor==="header"?Math.max(t,r.topMm+r.heightMm):t,0)}function $o(e,t){let r=e.textMetrics.get(t);if(!r){const n=It(t).fontSizePt;r={measureOptions:{fontSizePt:n,fontFamily:t.fontFamily??Wn,italic:t.italic,bold:t.bold,letterSpacingPt:t.letterSpacing},lineMm:n*(t.lineHeight??kt)*25.4/72},e.textMetrics.set(t,r)}return r}function fc(e){if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function Kr(e,t,r=[],n){const o=e.fontSizePt??Ar,i=e.paddingMm??1,s=e.columns.map(y=>y.align??y.style?.align??e.align??"left"),a=e.columns.map((y,g)=>({...Q({fontSize:o,verticalAlign:"middle"},y.style),align:s[g]==="auto"?"left":s[g]})),c=a.map((y,g)=>s[g]==="auto"?{left:y,center:{...y,align:"center"},right:{...y,align:"right"}}:void 0),u=e.columns.map((y,g)=>y.rules?.map(x=>{const b=c[g];if(b)return{left:Q(b.left,x.style),center:Q(b.center,x.style),right:Q(b.right,x.style)};const $=Q(a[g],x.style);return{left:$,center:$,right:$}})),f=e.columns.map(y=>no(e,y)),d=e.columns.map(y=>y.header);let l=e.rowHeightMm??0;for(let y=0;y<d.length;y++){const g=f[y],x=It(g).fontSizePt,b=Ve(d[y],e.columns[y].widthMm-i*2,{fontSizePt:x,fontFamily:g.fontFamily??Wn,italic:g.italic,bold:g.bold,letterSpacingPt:g.letterSpacing},t),$=x*(g.lineHeight??kt)*25.4/72;l=Math.max(l,Math.max(b.length,1)*$+i*2)}const m=d.map((y,g)=>({text:y,style:f[g]})),h=e.border===!1?{borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}:{borderBottom:!0,borderLeft:!0,borderRight:!0,borderTop:!0},p=e.columns.map(y=>y.widthMm),w=lc(Pa(e,t),p,{cells:[m],colWidthsMm:p,rowHeightsMm:[l],paddingMm:i});return{fontSizePt:o,paddingMm:i,visuals:cc(e.columns,r,n),visibility:e.columns.map(y=>y.visibleWhen?Y(y.visibleWhen):void 0),ruleReaders:e.columns.map(y=>y.rules?.map(g=>Y(g.when))),cellStyles:a,autoStyles:c,ruleStyles:u,textMetrics:new WeakMap,numberFormats:e.columns.map(y=>Gn(y.format)),derivedFields:new Set(e.computed?.map(y=>y.field)),borderStyle:h,headerHeightMm:w.rowHeightsMm.reduce((y,g)=>y+g,0),headerGrid:w,colWidthsMm:p,columns:e.columns}}function lc(e,t,r){if(!e)return r;if(!e.cells.length)throw new Error("自定义列表表头至少需要一行");const n=e.rowHeightsMm??e.cells.map(()=>r.rowHeightsMm[0]);if(n.length!==e.cells.length||n.some(o=>!Number.isFinite(o)||o<=0))throw new Error("自定义列表表头行高无效");return{...e,colWidthsMm:t,rowHeightsMm:n}}function dc(e,t,r){const n=t.format?.kind==="number"||t.format?.kind==="percent";t.valueType!==void 0?e.valueType=t.valueType:n&&(e.valueType="number"),t.editable!==void 0&&(e.editable=t.editable),(typeof e.value=="number"||e.value==null)&&r!==void 0&&(e.numberFormat=r)}function Je(e,t,r){const n=e.columns,o=e.tree?.rows.get(t);let i=e.rowHeightFloorMm;const s=new Array(n.length);for(let a=0;a<n.length;a++){const c=n[a],u=e.visibility[a]?.(t)!==!1,f=u?t[c.field]:null,d=e.autoStyles[a]?ro(f,c.format,c.semanticRole):"left";let l=e.autoStyles[a]?.[d]??e.cellStyles[a];if(c.rules){for(let x=0;x<c.rules.length;x++)if(e.ruleReaders[a][x](t)){l=e.ruleStyles[a][x][d];break}}const m=c.format?Pr(f,c.format):Tr(f),h=mc(e,c,o);l=hc(e,c,l,o);const p=$o(e,l),w=Ve(m,Math.max(1,c.widthMm-e.paddingMm*2-h),p.measureOptions,r);i=Math.max(i,w.length*p.lineMm+e.paddingMm*2);const y=fc(f),g={text:m,style:l};f!=null&&e.visuals[a]?.apply(g,t),y!==void 0&&(g.value=y),dc(g,c,e.numberFormats[a]),gc(g,c,e,o,h),e.derivedFields.has(c.field)&&(g.derived=!0,g.editable=!1),u||(g.editable=!1),s[a]=g}return{grid:{cells:[s],colWidthsMm:e.colWidthsMm,rowHeightsMm:[i],paddingMm:e.paddingMm},heightMm:i,...e.matrix?{meta:{matrix:{row:e.matrix.rows.get(t)}}}:{}}}function mc(e,t,r){return!r||t.field!==e.tree.list.tree.labelField?0:Sa(e.tree.list,t,r,e.paddingMm)}function hc(e,t,r,n){return!n||t.field!==e.tree.list.tree.labelField||r.align==="left"?r:{...r,align:"left"}}function gc(e,t,r,n,o=0){n&&(o&&(e.indentMm=o),Ea(e,t,n,r.tree.list))}function So(e){if(e!=null&&typeof e!="string"&&typeof e!="boolean"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("分组字段应为有限 JSON 标量");return JSON.stringify([typeof e,e??null])}function*Eo(e,t,r=0){const n=t[r];if(!n){for(const i of e)yield{kind:"row",row:i};return}const o=new Map;for(const i of e){const s=So(i[n.field]),a=o.get(s);a?a.push(i):o.set(s,[i])}for(const i of o.values())yield{kind:"groupHeader",label:(n.headerTemplate??"{value}").replace(/\{value\}/g,Tr(i[0][n.field])),firstRow:i[0],group:n,depth:r,rows:i},yield*Eo(i,t,r+1),(n.subtotal?.length||n.aggregates?.length)&&(yield{kind:"subtotal",label:n.subtotalLabel??"小计",rows:i,group:n,depth:r}),yield{kind:"groupEnd",depth:r}}function Ao(e,t,r,n=[]){const o=[...r.filter(i=>!n.some(s=>s.field===i)).map(i=>({field:i,op:"sum"})),...n];return new Map(o.map(i=>{const s=e.find(c=>c.field===i.field)?.format??{kind:"number",thousands:!0},a=Be(t,{...i,field:i.valueField??i.field});return[i.field,{text:Pr(a,s),...a===null?{}:{value:a},...typeof a=="number"?{numberFormat:Gn(s)}:{}}]}))}function ko(e,t){const r=e.findIndex(n=>t.includes(n.field));return r<0?1:r}function Oe(e,t,r,n,o,i){const s=[],a=Math.max(0,Math.min(i,e.columns.length)),c=Q({fontSize:e.fontSizePt},o);a&&s.push({text:r,colSpan:a,style:{bold:!0,...c}});for(let l=a;l<e.columns.length;l++){const m=e.columns[l],h=n.get(m.field),p=e.autoStyles[l]?.[ro(h?.value,m.format)]??e.cellStyles[l];s.push({...h,text:h?.text??"",style:Q(p,o)})}const u={text:r,colSpan:e.columns.length,style:{bold:!0,...c}},f=a?[s]:[[u],s],d=f.map(l=>pc(e,l,t));return{grid:{cells:f,colWidthsMm:e.colWidthsMm,rowHeightsMm:d,paddingMm:e.paddingMm},heightMm:d.reduce((l,m)=>l+m,0)}}function pc(e,t,r){let n=e.rowHeightFloorMm,o=0;for(const i of t){let s=0;const a=o+(i.colSpan??1);for(;o<a;o++)s+=e.colWidthsMm[o]??0;const c=$o(e,i.style),u=Ve(i.text??"",s-e.paddingMm*2,c.measureOptions,r);n=Math.max(n,u.length*c.lineMm+e.paddingMm*2)}return n}function yc(e,t,r){const{templatePage:n,current:o,warnings:i,nextId:s,pushCurrent:a}=r,c=()=>gt(n,o),u=Math.max(o.marginTopMm,We(n)),f=n.layout==="wide"?We(n):u,d={id:r.tableId,columnKeys:e.columns.map(v=>v.field),...e.layout===void 0?{}:{layout:e.layout},...e.title===void 0?{}:{title:e.title}},l=new Map,m=new Map,h={kind:"rect",leftMm:e.leftMm,topMm:0,widthMm:e.widthMm,heightMm:t.headerHeightMm,grid:t.headerGrid,nid:s("listh"),table:{...d,role:"header",rowIndex:-1},style:t.borderStyle,...e.meta||t.matrix?{meta:{...e.meta,...t.matrix?{matrix:t.matrix.header}:{}}}:{}},p=v=>o.components.push({...h,topMm:v});if(r.flow&&e.header!==!1&&t.headerHeightMm>c()-u+.001)throw new Error(`流式列表 ${e.id??e.dataset} 的表头高度超出单页可用范围`);let w=Math.max(r.startTop??e.topMm,u);e.header!==!1&&(p(w),w+=t.headerHeightMm+r.mmPerRow);function y(){const v=Math.max(r.flow||n.layout==="wide"?0:e.topMm,f);return(e.header!==!1&&e.headerEveryPage!==!1?v+t.headerHeightMm:f)+[...m.values()].reduce((S,R)=>S+R.heightMm,0)}function g(){const v=n.layout==="wide"?0:o.marginBottomMm;return Math.min(n.heightMm-v,gt(n,o))-y()}function x(v){if(w+v<=c())return;a(),o.components=[],o.heightMm=n.heightMm,n.layout==="wide"&&(o.marginTopMm=0,o.marginBottomMm=0);const M=Math.max(r.flow||n.layout==="wide"?0:e.topMm,f);e.header!==!1&&e.headerEveryPage!==!1?(p(M),w=M+t.headerHeightMm):w=f;for(const S of m.values())$(S,"listgr","group-header")}function b(v,M,S,R){const N=g();if(r.flow&&v.heightMm>N+.001)throw new Error(`流式列表 ${e.id??e.dataset} 的单行高度超出单页可用范围`);v.heightMm>N&&i.push(`列表 ${e.id??e.dataset} 行高 ${v.heightMm.toFixed(2)}mm 超出单页可用高度 ${N.toFixed(2)}mm,预览与打印可能截断内容`),x(v.heightMm),$(v,M,S,R)}function $(v,M,S,R){const N=v.table?.id??d.id,I=S==="header"?-1:l.get(N)??0;S!=="header"&&l.set(N,I+v.grid.cells.length),o.components.push({kind:"rect",leftMm:e.leftMm,topMm:w,widthMm:e.widthMm,heightMm:v.heightMm,grid:v.grid,nid:s(M),table:{...d,...v.table,role:S,rowIndex:I,...R?{source:R}:{}},style:t.borderStyle,...e.meta||v.meta?{meta:{...e.meta,...v.meta}}:{}}),w+=v.heightMm}function T(v){v<=g()&&x(v)}return{keepTogether:T,placeGridRow:b,setGroupHeader:(v,M)=>{M?m.set(v,M):m.delete(v)},bottom:()=>w}}function wc(e,t){if(!e.rowKey)return;const r=t[e.rowKey];if((typeof r!="string"||!r.trim())&&!(typeof r=="number"&&Number.isFinite(r)))throw new Error(`数据集 ${e.dataset} 的 ${e.rowKey} 应为稳定的字符串或有限数字主键`);const n=e.revisionField?t[e.revisionField]:void 0,o=e.sourceTokenField?t[e.sourceTokenField]:void 0;if(n!==void 0&&typeof n!="string"&&!(typeof n=="number"&&Number.isFinite(n)))throw new Error("业务修订号应为字符串或有限数字");if(o!==void 0&&typeof o!="string")throw new Error("来源令牌应为字符串");return{datasetId:e.dataset,rowKey:r,...n===void 0?{}:{revision:n},...o===void 0?{}:{sourceToken:o}}}function Ct(e,t){const r=new Map;if(!e.rowKey)return r;const n=new Set;for(const o of t){const i=wc(e,o),s=JSON.stringify(i.rowKey);if(n.has(s))throw new Error(`数据集 ${e.dataset} 的业务主键重复:${String(i.rowKey)}`);n.add(s),r.set(o,i)}return r}function bc(e,t,r,n,o){if(!e.grandTotal)return;const i=typeof e.grandTotal=="object"?e.grandTotal:void 0,s=Tt(e)[0],a=i?.fields??s?.subtotal??[],c=i?.aggregates??s?.aggregates??[];if(a.length===0&&c.length===0){n.warnings.push(`列表 ${e.id??""} 配置了 grandTotal 但未提供合计字段(groupBy.subtotal 或 grandTotal.fields)`);return}const u=Oe(r,n.measurer,i?.label??"合计",Ao(e.columns,t,a,c),i?.style??{},ko(e.columns,[...a,...c.map(f=>f.field)]));o.placeGridRow(u,"listgt","grand-total")}function ze(e){if(e?.aborted){const t=new Error("报表排版已取消");throw t.name="AbortError",t}}function Tt(e){const t=e.groups??(e.groupBy?[e.groupBy]:[]);if(t.length>16)throw new Error("列表最多支持 16 级分组");return t}function Wr(e){const t=Da(e),r=t.columns.reduce((o,i)=>o+i.widthMm,0),n=r>t.widthMm?t.widthMm/r:1;return n===1?t:{...t,columns:t.columns.map(o=>({...o,widthMm:o.widthMm*n}))}}function xc(e,t,r){const n=e.detail;if(!n)return;const o=new Set;for(const u of t){const f=ar(u[n.parentKey]);if(o.has(f))throw new Error("主从明细的主表关联键重复");o.add(f)}const i=r.datasets[n.dataset]??[],s=new Map,a=[];for(const u of i){const f=u[n.foreignKey];if(!No(f)&&n.unmatched==="ignore")continue;const d=ar(f);if(!o.has(d)){if(n.unmatched!=="ignore")throw new Error(`明细数据集 ${n.dataset} 存在未关联的业务键`);continue}const l=s.get(d);l?l.push(u):s.set(d,[u]),a.push(u)}const c=Wr({...e,id:`${e.id??e.dataset}:detail`,dataset:n.dataset,rowKey:n.rowKey,revisionField:n.revisionField,sourceTokenField:n.sourceTokenField,computed:void 0,columns:n.columns,headerGrid:void 0,rowHeightMm:n.rowHeightMm??e.rowHeightMm,detail:void 0});return{list:c,inter:{...Kr(c,r.measurer,a,r.signal),rowHeightFloorMm:c.rowHeightMm??0},rows:s,sources:Ct(c,a)}}function No(e){return typeof e=="string"&&!!e.trim()||typeof e=="number"&&Number.isFinite(e)}function ar(e){if(!No(e))throw new Error("主从关联键必须是非空字符串或有限数字");return So(e)}function*vc(e,t,r,n,o){if(!r)return;const i=r.rows.get(ar(t[e.detail.parentKey]))??[];if(!i.length)return;const s={id:`${n.tableId}:detail`,columnKeys:r.list.columns.map(a=>a.field),title:e.detail.label};e.detail.label&&o.placeGridRow({...Oe(r.inter,n.measurer,e.detail.label,new Map,{},r.list.columns.length),table:s},"listdl","group-header"),e.detail.header!==!1&&o.placeGridRow({grid:r.inter.headerGrid,heightMm:r.inter.headerHeightMm,table:s},"listdh","header"),yield*n.takePages();for(const a of i)ze(n.signal),o.placeGridRow({...Je(r.inter,a,n.measurer),table:s},"listdr","body",r.sources.get(a)),yield*n.takePages()}function Po(e){if(e.matrix||e.detail||e.groups?.length||e.groupBy||e.rowVisibleWhen)throw new Error("树形布局不能同时配置普通分组、矩阵、主从或行可见条件");if(e.rowKey&&e.rowKey!==e.tree.idField)throw new Error("树形布局的 rowKey 应与 idField 一致");if(!e.columns.some(t=>t.field===e.tree.labelField&&!t.hidden))throw new Error("树形布局需要可见的标签列");Dr(e.tree,e.computed)}function Mc(e,t,r){Po(e);const n=ho(t,e.tree,{signal:r.signal,computed:e.computed?.length?{fields:e.computed,formula:r.formula}:void 0}),o={...e,rowKey:e.tree.idField},i=Ct(o,n.entries.map(c=>c.original)),s=new Map,a=new WeakMap;for(const c of n.entries)s.set(c.row,i.get(c.original)),a.set(c.row,c);return{list:o,rows:n.rows,sources:s,treeRows:a,totalRows:n.leaves}}function $c(e,t){if(e.cardinality==="record"){if(t.length>1)throw new Error(`单记录区域 ${e.id??e.dataset} 仅允许 0 或 1 行数据`);if(e.tree||e.matrix||e.detail||e.groups?.length||e.groupBy||e.grandTotal||e.rowVisibleWhen)throw new Error("单记录区域不能配置树、矩阵、主从、分组、总计或行过滤");if(!t.length)return{list:{...e,columns:e.columns.map(r=>({...r,editable:!1}))},rows:[{}],sources:new Map}}}function Fo(e,t,r){const n=r.prepared.get(e);if(n)return n;const o=$c(e,t);if(o)return r.prepared.set(e,o),o;if(e.tree){const c=Mc(e,t,r);return r.prepared.set(e,c),c}let i=e.computed?.length?Ft(t,{fields:e.computed,signal:r.signal,formula:r.formula}).rows:t;const s=i===t?void 0:new Map(i.map((c,u)=>[c,t[u]]));e.rowVisibleWhen&&(i=i.filter(Y(e.rowVisibleWhen)));const a=Na(e,i);if(!e.matrix){const c=Ct(e,s?i.map(u=>s.get(u)):i);a.sources=s?new Map(i.map(u=>[u,c.get(s.get(u))])):c}return r.prepared.set(e,a),a}function Sc(e,t,r,n){if(!n.flow)return;const{current:o,templatePage:i}=n,s=Math.max(o.marginTopMm,We(i)),a=Math.max(n.startTop??e.topMm,s),c=(e.header===!1?0:t.headerHeightMm)+(r[0]?Je(t,r[0],n.measurer).heightMm:0);a+c<=gt(i,o)+.001||a<=s+.001||(n.pushCurrent(),o.components=[],o.heightMm=i.heightMm,i.layout==="wide"&&(o.marginTopMm=0,o.marginBottomMm=0),n.startTop=Math.max(o.marginTopMm,We(i)))}function*Ec(e,t,r){const n=Fo(e,t,r),o=n.rows;e=n.list,e.layout==="wide"&&(r.current.widthMm=Math.max(r.current.widthMm,e.leftMm+e.widthMm+r.current.marginRightMm));const i=n.sources??Ct(e,o),s=Wr(e),a=Tt(s),c={...Kr(s,r.measurer,o,r.signal),rowHeightFloorMm:s.rowHeightMm??0,matrix:n.matrix,...n.treeRows?{tree:{list:s,rows:n.treeRows}}:{}};Sc(s,c,o,r);const u=yc(s,c,r),f=xc(s,o,r);let d;for(const l of Eo(o,a)){if(ze(r.signal),l.kind==="row")u.placeGridRow(d??Je(c,l.row,r.measurer),"listr",Aa(n.matrix,l.row),i.get(l.row)),d=void 0,yield*r.takePages(),yield*vc(s,l.row,f,r,u);else if(l.kind==="groupHeader"){const m=Oe(c,r.measurer,l.label,new Map,l.group.headerStyle??{},s.columns.length);d??=Je(c,l.firstRow,r.measurer);const h=a.slice(l.depth+1).reduce((p,w)=>p+Oe(c,r.measurer,(w.headerTemplate??"{value}").replace(/\{value\}/g,Tr(l.firstRow[w.field])),new Map,w.headerStyle??{},s.columns.length).heightMm,0);l.group.keepWithNext!==!1&&u.keepTogether(m.heightMm+h+d.heightMm),u.placeGridRow(m,"listg","group-header"),l.group.repeatHeader&&u.setGroupHeader(l.depth,m)}else if(l.kind==="subtotal"){const m=l.group.subtotal??[],h=l.group.aggregates??[],p=Oe(c,r.measurer,l.label,Ao(s.columns,l.rows,m,h),l.group.subtotalStyle??{},ko(s.columns,[...m,...h.map(w=>w.field)]));u.placeGridRow(p,"listst","subtotal")}else u.setGroupHeader(l.depth);yield*r.takePages()}bc(s,n.totalRows??o,c,r,u),r.finished?.(u.bottom()),yield*r.takePages()}function jt(e){return e.kind!=="list"&&(e.pageAnchor!==void 0||e.kind==="text"&&typeof e.text=="string"&&(e.text.includes("{page}")||e.text.includes("{totalPages}")))}function Dt(e,t){return{...e,...e.text===void 0?{}:{text:t(e.text)},...e.lines?{lines:e.lines.map(t)}:{},...e.richParagraphs?{richParagraphs:e.richParagraphs.map(r=>({...r,segments:r.segments.map(n=>({...n,...n.text===void 0?{}:{text:t(n.text)}}))}))}:{},...e.grid?{grid:{...e.grid,cells:e.grid.cells.map(r=>r.map(n=>n?{...n,...n.text===void 0?{}:{text:t(n.text)},...n.children?{children:n.children.map(o=>Dt(o,t))}:{}}:null))}}:{}}}function Ac(e){let t=!1;for(const r of e.pages)for(const n of r.components)jt(n)&&Dt(n,o=>(o.includes("{totalPages}")&&(t=!0),o));return t}function kc(e,t,r,n,o,i){const s={pageWidthMm:t.widthMm,pageHeightMm:t.heightMm,...e.layout===void 0?{}:{layout:e.layout},marginTopMm:t.marginTopMm,marginBottomMm:t.marginBottomMm,marginLeftMm:t.marginLeftMm,marginRightMm:t.marginRightMm,components:t.components,...e.meta?{meta:e.meta}:{}},a=c=>{const u=c.replace(/\{page\}/g,String(n));return i===void 0?u:u.replace(/\{totalPages\}/g,String(i))};for(const c of r)s.components.push(Dt(c,a));if(e.layout==="wide"){const c=s.components.reduce((u,f)=>Math.max(u,f.topMm+f.heightMm),0);s.marginBottomMm=o?e.marginBottomMm??0:0,s.pageHeightMm=Math.max(1,c+s.marginBottomMm)}return s}function Jr(e){return e.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+Oo(s),0)??0):0),0),0)}function Oo(e){return e.grid?Jr(e.grid):0}function Io(e){for(const t of["maxPages","maxCells","knownTotalPages"])if(e[t]!==void 0&&(!Number.isSafeInteger(e[t])||e[t]<1))throw new RangeError(`${t} 应为正安全整数`);Ot(e.maxChartComponents)}function Nc(e,t){const r=Fo(e,t.datasets[e.dataset]??[],t),n=Wr(r.list),o={...Kr(n,t.measurer,r.rows,t.signal),rowHeightFloorMm:n.rowHeightMm??0};return(n.header===!1?0:o.headerHeightMm)+r.rows.reduce((i,s)=>i+Je(o,s,t.measurer).heightMm,0)}function*Pc(e){const{templatePage:t,current:r}=e,n=new Map(t.components.map((i,s)=>[i,s])),o=(i,s,a)=>{const c=e.datasets[i.dataset];return Array.isArray(c)||e.warnings.push(`数据集 ${i.dataset} 未提供数据,列表 ${i.id??""} 输出为空`),Ec(i,Array.isArray(c)?c:[],{...e,tableId:`${e.tableId}:${n.get(i)}`,startTop:s,finished:a,flow:!!t.flow})};if(t.flow){yield*Wa({page:t,active:()=>ze(e.signal),top:()=>Math.max(r.marginTopMm,We(t)),bottom:()=>gt(t,r),append:i=>{r.components.push(...e.resolveChart(i))},nextPage:()=>{e.pushCurrent(),r.components=[],r.heightMm=t.heightMm,t.layout==="wide"&&(r.marginTopMm=0,r.marginBottomMm=0)},takePages:e.takePages,height:i=>Nc(i,e),list:o});return}for(const i of t.components)jt(i)||(i.kind==="list"?yield*o(i):r.components.push(...e.resolveChart(i)))}function*cr(e,t,r,n,o,i=new WeakMap,s){let a=0,c=0,u=0;const f=rs(r.measurer??kr),d=oa(t,r.signal,r.maxChartComponents),l=m=>`${m}_${(++a).toString(36)}`;for(const{pageIndex:m,page:h}of oc(e,t,r)){ze(r.signal);const p=uc(h),w=h.components.filter(jt);let y=[];const g=(b=!1)=>{if(ze(r.signal),r.maxPages!==void 0&&c>=r.maxPages)throw new $e(r.maxPages,c+1);if(r.maxCells!==void 0&&(u+=[...p.components,...w].reduce(($,T)=>$+Oo(T),0),u>r.maxCells))throw new _e(r.maxCells,u);y.push(kc(h,p,w,++c,b,o))},x=()=>{const b=y;return y=[],b};yield*Pc({templatePage:h,current:p,warnings:n,nextId:l,pushCurrent:g,takePages:x,datasets:t,resolveChart:d,signal:r.signal,formula:r.formula,prepared:i,measurer:f,mmPerRow:r.mmPerRow??0,tableId:`table:${m}`}),g(!0),yield*x()}s&&(s.chartComponents=d.used())}function*Fc(e,t,r,n){Io(r);const o=Ac(e),i=new WeakMap;let s=r.knownTotalPages;if(o&&s===void 0){s=0;for(const u of cr(e,t,r,[],void 0,i))s++}const a=[];let c=0;for(const u of cr(e,t,r,a,s,i,n)){for(;c<a.length;c++)r.onWarning?.(a[c]);yield u}}function Oc(e,t,r={}){const n=typeof r=="number"?{mmPerRow:r}:r;Io(n);const o=[],i={chartComponents:0},s=[...cr(e,t,n,o,n.knownTotalPages,void 0,i)];for(const a of s)a.components=a.components.map(c=>jt(c)?Dt(c,u=>u.replace(/\{totalPages\}/g,String(s.length))):c);return o.forEach(a=>n.onWarning?.(a)),{plan:{schemaVersion:Ae,...Rt(e)?{requiresRecalculation:!0}:{},pages:s},warnings:o,...i}}function Ic(e){const t=e.columns.find(i=>!i.hidden)?.field;if(!t)return{groups:0,total:0};const r=Tt(e),n=(i=[],s=[])=>i.includes(t)||s.some(a=>a.field===t),o=typeof e.grandTotal=="object"?e.grandTotal:void 0;return{groups:r.filter(i=>n(i.subtotal,i.aggregates)).length,total:Number(n(o?.fields??r[0]?.subtotal,o?.aggregates??r[0]?.aggregates))}}function Rc(e,t,r){Po(e);const n=mo(t[e.dataset]??[],e.tree,r),o=e.columns.filter(s=>!s.hidden).length,i=e.header===!1?0:e.headerGrid?Jr(e.headerGrid):o;return n.length*o+i+ +!!e.grandTotal*2*o}function Cc(e,t,r={}){if(e.tree)return Rc(e,t,r.signal);if(e.matrix){let c=t[e.dataset]??[];e.computed?.length&&(c=Ft(c,{fields:e.computed,...r}).rows),e.rowVisibleWhen&&(c=c.filter(Y(e.rowVisibleWhen)));const u=eo(c,e.matrix);return u.cells+(e.header===!1?0:u.columnCount*(e.matrix.hierarchy?e.matrix.columnFields.length+1:1))}const n=t[e.dataset]?.length??0,o=e.columns.filter(c=>!c.hidden).length,i=Tt(e).length,s=Ic(e);let a=(n*(1+2*i+s.groups)+ +!!e.grandTotal*(1+s.total))*o;if(a+=e.header===!1?0:e.headerGrid?Jr(e.headerGrid):o,e.cardinality==="record"&&n===0&&(a+=o),e.detail){const c=t[e.detail.dataset]?.length??0,u=e.detail.columns.filter(f=>!f.hidden).length;a+=(c+n*(+(e.detail.header!==!1)+ +!!e.detail.label))*u}if(!Number.isSafeInteger(a))throw new RangeError("报表单元格估算超出安全整数预算");return a}function Tc(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const{start:t,end:r,color:n}=e;return typeof t=="number"&&typeof r=="number"&&Number.isFinite(t)&&Number.isFinite(r)&&t>=0&&r<=1&&t<=r&&typeof n=="string"&&/^#[0-9a-f]{6}$/i.test(n)}function rt(e){return!!e&&typeof e=="object"}function Ro(e,t,r,n,o){if(++o.nodes>1e6)return{path:t,message:"组件树超过100万个结构节点预算"};if(rt(e)){if(r>64)return{path:t,message:"组件嵌套超过64层预算"};if(n.has(e))return{path:t,message:"组件树包含循环引用"};if(!(!rt(e.grid)||!Array.isArray(e.grid.cells))){n.add(e);try{for(const[i,s]of e.grid.cells.entries())if(Array.isArray(s))for(const[a,c]of s.entries()){if(++o.nodes>1e6)return{path:t,message:"组件树超过100万个结构节点预算"};if(!(!rt(c)||!Array.isArray(c.children)))for(const[u,f]of c.children.entries()){const d=Ro(f,`${t}.grid.cells.${i}.${a}.children.${u}`,r+1,n,o);if(d)return d}}}finally{n.delete(e)}}}}function zr(e,t="$.components",r={nodes:0}){for(const[n,o]of e.entries()){const i=Ro(o,`${t}.${n}`,0,new Set,r);if(i)return i}}function Co(e){const t={nodes:0};for(const[r,n]of e.entries()){if(!rt(n)||!Array.isArray(n.components))continue;const o=zr(n.components,`$.pages.${r}.components`,t);if(o)return o}}function jc(e){const t=Co(e.pages);if(t)throw new TypeError(`${t.path}: ${t.message}`)}function Dc(e,t,r){e!==void 0&&(typeof e!="string"||!e.trim()||e.length>4096)&&r.push({path:t,message:"来源范围应为不超过 4096 字符的非空字符串"})}function To(e,t,r){e.editable!==void 0&&typeof e.editable!="boolean"&&r.push({path:`${t}.editable`,message:"编辑控制应为布尔值"}),e.valueType!==void 0&&!["text","number","boolean"].includes(e.valueType)&&r.push({path:`${t}.valueType`,message:"编辑类型应为 text、number 或 boolean"})}function Lc(e,t,r){To(e,t,r),e.indentMm!==void 0&&(typeof e.indentMm!="number"||!Number.isFinite(e.indentMm)||e.indentMm<0)&&r.push({path:`${t}.indentMm`,message:"单元格缩进应为有限非负数"}),e.derived!==void 0&&typeof e.derived!="boolean"&&r.push({path:`${t}.derived`,message:"派生结果标记应为布尔值"}),jo(e.source,`${t}.source`,r,!0),e.formula!==void 0&&typeof e.formula!="string"&&r.push({path:`${t}.formula`,message:"单元格公式应为字符串"})}function jo(e,t,r,n=!1){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e)){r.push({path:t,message:"业务来源应为对象"});return}const o=e;Dc(o.sourceScope,`${t}.sourceScope`,r);for(const i of["datasetId",...n?["field"]:[]])(typeof o[i]!="string"||!o[i].trim())&&r.push({path:`${t}.${i}`,message:"业务标识应为非空字符串"});for(const i of["rowKey","revision"]){const s=o[i];s===void 0&&!(n&&i==="rowKey")||typeof s!="string"&&!(typeof s=="number"&&Number.isFinite(s))&&r.push({path:`${t}.${i}`,message:"业务键及修订号应为字符串或有限数字"})}o.sourceToken!==void 0&&typeof o.sourceToken!="string"&&r.push({path:`${t}.sourceToken`,message:"来源令牌应为字符串"})}function Bc(e){const t=[];return e.value!==void 0&&typeof e.value!="string"&&t.push({path:"value",message:"Symbol value must be a string."}),e.symbology!==void 0&&!["code128","code39","ean13","ean8"].includes(e.symbology)&&t.push({path:"symbology",message:"Unsupported barcode symbology."}),e.errorCorrection!==void 0&&!["L","M","Q","H"].includes(e.errorCorrection)&&t.push({path:"errorCorrection",message:"Unsupported QR error correction."}),e.showText!==void 0&&typeof e.showText!="boolean"&&t.push({path:"showText",message:"showText must be a boolean."}),t}function _c(e,t){const r=[];return t!=="barcode"&&t!=="qrcode"&&r.push({path:"",message:"code is only supported by barcode and qrcode components."}),t==="qrcode"&&e.symbology!==void 0&&r.push({path:"symbology",message:"QR components do not use a linear symbology."}),t==="qrcode"&&e.showText===!0&&r.push({path:"showText",message:"Use a separate text component below a QR code."}),t==="barcode"&&e.errorCorrection!==void 0&&r.push({path:"errorCorrection",message:"Linear barcodes do not use QR error correction."}),r}function Kc(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return[{path:"",message:"code must be an object."}];const r=e,n=[...Bc(r),..._c(r,t)];for(const s of Object.keys(r))["value","symbology","errorCorrection","quietZoneModules","showText"].includes(s)||n.push({path:s,message:"Unknown symbol option."});const o=r.symbology==="ean13"||r.symbology==="ean8",i=t==="qrcode"?4:o?11:10;return r.quietZoneModules!==void 0&&(!Number.isSafeInteger(r.quietZoneModules)||Number(r.quietZoneModules)<i||Number(r.quietZoneModules)>64)&&n.push({path:"quietZoneModules",message:`Quiet zone must contain ${i}–64 whole modules.`}),n}const Wc=new Set(["text","image","barcode","qrcode","chart","line","rect","ellipse"]);function z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pt(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 Jc(e,t,r,n){const o=e[t];(typeof o!="number"||!Number.isFinite(o))&&n.push({path:`${r}.${t}`,message:`应为有限数字,实际 ${pt(o)}`})}function zc(e,t,r){if(e!==void 0){const n=`${t}.table`;if(!z(e))r.push({path:n,message:"逻辑表来源应为对象"});else{jo(e.source,`${n}.source`,r),(typeof e.id!="string"||!e.id.trim())&&r.push({path:`${n}.id`,message:"逻辑表 ID 应为非空字符串"});const o=e.role;["header","body","group-header","subtotal","grand-total"].includes(o)||r.push({path:`${n}.role`,message:"未知逻辑表行角色"});const i=e.rowIndex;(typeof i!="number"||!Number.isInteger(i)||(o==="header"?i!==-1:i<0))&&r.push({path:`${n}.rowIndex`,message:"表头索引应为 -1,内容行索引应为非负整数"}),(!Array.isArray(e.columnKeys)||e.columnKeys.some(s=>typeof s!="string"))&&r.push({path:`${n}.columnKeys`,message:"逻辑列字段应为字符串数组"}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&r.push({path:`${n}.layout`,message:"布局应为 page 或 wide"}),e.title!==void 0&&typeof e.title!="string"&&r.push({path:`${n}.title`,message:"逻辑表名称应为字符串"})}}}function Vc(e,t,r,n){if(e!==void 0)if(!z(e)||!Array.isArray(e.cells))r.push({path:`${t}.grid.cells`,message:"grid.cells 应为二维数组"});else{const o=e.paddingMm;o!==void 0&&(typeof o!="number"||!Number.isFinite(o)||o<0)&&r.push({path:`${t}.grid.paddingMm`,message:"单元格内距应为有限非负数"}),e.cells.forEach((i,s)=>{if(!Array.isArray(i)){r.push({path:`${t}.grid.cells.${s}`,message:"行应为数组"});return}i.forEach((a,c)=>{if(a==null)return;const u=`${t}.grid.cells.${s}.${c}`;if(!z(a)){r.push({path:u,message:"网格单元格应为对象或 null"});return}Lc(a,u,r),a.dataBar!==void 0&&!Tc(a.dataBar)&&r.push({path:`${u}.dataBar`,message:"数据条应包含 0–1 有序比例与 #RRGGBB 颜色"}),Do(a.richParagraphs,u,r),Array.isArray(a.children)&&a.children.forEach((f,d)=>{Vr(f,`${t}.grid.cells.${s}.${c}.children.${d}`,r,n)})})})}}function yt(e,t,r,n){e!==void 0&&!t.includes(e)&&n.push({path:r,message:"未知富文本属性值"})}function ur(e,t,r,n,o=0){for(const i of t){const s=e[i];s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||s<o)&&n.push({path:`${r}.${i}`,message:"富文本数值应为范围内有限数字"})}}function Hc(e,t,r){if(e!==void 0){if(!z(e)){r.push({path:t,message:"富文本样式应为对象"});return}for(const n of["fontFamily","color","backgroundColor","lineColor","borderColor"])e[n]!==void 0&&typeof e[n]!="string"&&r.push({path:`${t}.${n}`,message:"富文本样式应为字符串"});for(const n of["bold","italic","underline","borderTop","borderRight","borderBottom","borderLeft"])e[n]!==void 0&&typeof e[n]!="boolean"&&r.push({path:`${t}.${n}`,message:"富文本样式应为布尔值"});ur(e,["fontSize","fontSizePx","lineWidthPt","lineHeight","opacity"],t,r),ur(e,["letterSpacing","rotateDeg"],t,r,-1/0),typeof e.opacity=="number"&&e.opacity>1&&r.push({path:`${t}.opacity`,message:"透明度不能大于1"}),yt(e.align,["left","center","right","justify"],`${t}.align`,r),yt(e.verticalAlign,["top","middle","bottom"],`${t}.verticalAlign`,r)}}function Uc(e,t,r){if(!z(e)){r.push({path:t,message:"富文本片段应为对象"});return}yt(e.kind,["text","field"],`${t}.kind`,r);for(const n of["text","field"])e[n]!==void 0&&typeof e[n]!="string"&&r.push({path:`${t}.${n}`,message:"富文本内容应为字符串"});Hc(e.style,`${t}.style`,r)}function Do(e,t,r){if(e!==void 0){if(!Array.isArray(e)){r.push({path:`${t}.richParagraphs`,message:"richParagraphs 应为数组"});return}e.forEach((n,o)=>{const i=`${t}.richParagraphs.${o}`;if(!z(n)||!Array.isArray(n.segments)){r.push({path:i,message:"段落缺少 segments 数组"});return}yt(n.align,["left","center","right","justify"],`${i}.align`,r),ur(n,["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"],i,r),n.segments.forEach((s,a)=>Uc(s,`${i}.segments.${a}`,r))})}}function Lo(e,t,r,n=[]){const o=zr([e],t);if(o){r.push(o);return}Vr(e,t,r,n)}function Vr(e,t,r,n=[]){if(!z(e)){r.push({path:t,message:"组件应为对象"});return}const o=e.kind;typeof o!="string"?r.push({path:`${t}.kind`,message:"组件缺少 kind 字符串"}):Wc.has(o)||n.push({path:`${t}.kind`,message:`未知组件类型 ${pt(o)},将以兜底方式渲染`});for(const i of["leftMm","topMm","widthMm","heightMm"])Jc(e,i,t,r);typeof e.leftMm=="number"&&e.leftMm<-100&&r.push({path:`${t}.leftMm`,message:"几何数值异常(leftMm<-100)"});for(const i of["widthMm","heightMm"])typeof e[i]=="number"&&e[i]<0&&r.push({path:`${t}.${i}`,message:"组件尺寸不能为负数"});zc(e.table,t,r),Yc(e.code,o,t,r),Gc(e,t,r),e.pageAnchor!==void 0&&!["header","footer"].includes(e.pageAnchor)&&r.push({path:`${t}.pageAnchor`,message:"页面锚点应为 header 或 footer"}),e.lineDirection!==void 0&&!["down","up"].includes(e.lineDirection)&&r.push({path:`${t}.lineDirection`,message:"线段方向应为 down 或 up"}),Vc(e.grid,t,r,n),Do(e.richParagraphs,t,r)}function Gc(e,t,r){if(e.chartBinding!==void 0)try{if(Xn(e.chartBinding),e.kind!=="chart"||["binding","imageData","grid","pageAnchor"].some(n=>e[n]!==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(n){r.push({path:`${t}.chartBinding`,message:n instanceof Error?n.message:String(n)})}}function Yc(e,t,r,n){if(e!==void 0)for(const o of Kc(e,t))n.push({path:`${r}.code${o.path?`.${o.path}`:""}`,message:o.message})}function Bo(e,t,r){if(!z(e))return;e.binding!==void 0&&r.push({path:`${t}.binding`,message:"渲染计划不允许未解析字段绑定"}),e.chartBinding!==void 0&&r.push({path:`${t}.chartBinding`,message:"渲染计划不允许未解析图表绑定"});const n=e.grid;!z(n)||!Array.isArray(n.cells)||n.cells.forEach((o,i)=>{Array.isArray(o)&&o.forEach((s,a)=>{!z(s)||!Array.isArray(s.children)||s.children.forEach((c,u)=>Bo(c,`${t}.grid.cells.${i}.${a}.children.${u}`,r))})})}function qc(e,t,r,n=[]){if(!z(e)){r.push({path:t,message:"页应为对象"});return}const o=e.pageWidthMm,i=e.pageHeightMm;(typeof o!="number"||!Number.isFinite(o)||o<=0)&&r.push({path:`${t}.pageWidthMm`,message:`页宽非法: ${pt(o)}`}),(typeof i!="number"||!(i>0&&i<5e3))&&r.push({path:`${t}.pageHeightMm`,message:`页高非法: ${pt(i)}`}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&r.push({path:`${t}.layout`,message:"布局应为 page 或 wide"});const s=e.components;if(!Array.isArray(s))r.push({path:`${t}.components`,message:"components 应为数组"});else if(Array.isArray(s)){const a=zr(s,`${t}.components`);if(a){r.push(a);return}s.forEach((c,u)=>{Vr(c,`${t}.components.${u}`,r,n),Bo(c,`${t}.components.${u}`,r)})}}function Ue(e){const t=[],r=[],n=z(e)?e.pages:void 0;if(z(e)&&e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean"&&t.push({path:"$.requiresRecalculation",message:"重算能力要求应为布尔值"}),!Array.isArray(n))t.push({path:"$.pages",message:e==null?"渲染计划为空":"渲染计划缺少 pages 数组"});else{const o=Co(n);if(o)return{ok:!1,errors:[...t,o],warnings:r};n.forEach((s,a)=>qc(s,`$.pages.${a}`,t,r)),n.length>2e3&&r.push({path:"$.pages",message:`页数异常大(${n.length} 页),渲染与打印耗时可能显著增加`});const i=n.reduce((s,a)=>s+(z(a)&&Array.isArray(a.components)?a.components.length:0),0);i>5e4&&r.push({path:"$.pages",message:`组件总数异常大(${i} 个),可能触发浏览器性能限制`})}return{ok:t.length===0,errors:t,warnings:r}}function wt(e,t){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype)return;const r=Object.getOwnPropertyDescriptor(e,"length")?.value;if(typeof r!="number"||!Number.isSafeInteger(r)||r<0||r>t||Reflect.ownKeys(e).length!==r+1)return;const o=[];for(let i=0;i<r;i++){const s=Object.getOwnPropertyDescriptor(e,String(i));if(!s||!Object.prototype.hasOwnProperty.call(s,"value"))return;o.push(s.value)}return o}const Hr=100,_o=16,fr=104857;function Ko(e,t,r){if(typeof e=="string"){if(e.length>fr)return;try{e=JSON.parse(e)}catch{return}}const n=wt(e,t);if(!n)return;const o=[];let i=2;for(const s of n){if(typeof s!="string"||!s.trim()||s.length>1024||r&&o.includes(s)||(i+=JSON.stringify(s).length+(o.length?1:0),i>fr))return;o.push(s)}return o}function Xc(e){return Ko(e,Hr,!0)}function Zc(e){return Ko(e,_o,!1)}function Qc(e){if(typeof e=="string"){if(e.length>2048)return;try{e=JSON.parse(e)}catch{return}}const t=wt(e,2);if(!t||t.length!==2)return;const r=t[0],n=t[1];return typeof r=="number"&&typeof n=="number"&&Number.isFinite(r)&&Number.isFinite(n)&&r<=n?[r,n]:void 0}function U(e){return["multiSelect","cascader","numberRange"].includes(e.type??"")}function Lt(e,t){return e.type==="numberRange"?Qc(t):e.type==="cascader"?Zc(t):Xc(t)}function eu(e,t,r=!1){const n=wt(e,1e3);if(!n)return!1;const o=[{items:n,depth:1}],i=new Set;let s=0;for(let a=0;a<o.length;a++){const{items:c,depth:u}=o[a];if(u>_o)return!1;const f=new Set;for(const d of c){const l=tu(d,r);if(++s>1e3||!l||i.has(d)||f.has(l.value))return!1;if(i.add(d),f.add(l.value),l.children!==void 0){const m=wt(l.children,1e3);if(!t||!m)return!1;m.length&&o.push({items:m,depth:u+1})}}}return!0}function Wo(e){return e.map(t=>({value:t.value,label:t.label,...t.children?{children:Wo(t.children)}:{}}))}function tu(e,t){if(!e||typeof e!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(e)))return;const r=Object.getOwnPropertyDescriptors(e);if(Object.values(r).some(i=>!Object.prototype.hasOwnProperty.call(i,"value")))return;const n=r.value?.value,o=r.label?.value;if(!(typeof n!="string"||!t&&!n.trim()||n.length>1024||typeof o!="string"||o.length>1024))return{value:n,label:o,...r.children?{children:r.children.value}:{}}}function ru(e,t){let r=e;for(const[n,o]of t.entries()){const i=r.find(s=>s.value===o);if(!i)return!1;if(r=i.children??[],n===t.length-1)return r.length===0}return!1}function nu(e,t){const r=Lt(e,t);if(!r)return[["type",e.type==="numberRange"?"请填写完整数字范围,最小值不能大于最大值":e.type==="cascader"?"请选择完整的末级路径":"请选择有效选项,不能重复或超出数量限制"]];if(e.type==="numberRange")return ou(e,r);const n=r,o=[];return e.type==="cascader"&&e.options&&!ru(e.options,n)&&o.push(["option","应为允许选项中的完整叶节点路径"]),e.type==="multiSelect"&&(e.options&&n.some(i=>!e.options.some(s=>s.value===i))&&o.push(["option","不在允许的选项中"]),e.minItems!==void 0&&n.length<e.minItems&&o.push(["minItems",`至少选择 ${e.minItems} 项`]),e.maxItems!==void 0&&n.length>e.maxItems&&o.push(["maxItems",`最多选择 ${e.maxItems} 项`])),o}function ou(e,t){const r=[];return typeof e.min=="number"&&t[0]<e.min&&r.push(["minimum",`不能小于 ${e.min}`]),typeof e.max=="number"&&t[1]>e.max&&r.push(["maximum",`不能大于 ${e.max}`]),r}function iu(e){const t=[];for(const r of["minItems","maxItems"])e[r]!==void 0&&(e.type!=="multiSelect"||!Number.isSafeInteger(e[r])||e[r]<0||e[r]>Hr)&&t.push(`${r} 应为多选参数的 0–100 整数边界`);return e.minItems!==void 0&&e.maxItems!==void 0&&e.minItems>e.maxItems&&t.push("最少项目数不能大于最多项目数"),t}function su(e){if(e.type==="numberRange"){const r={type:"number",...typeof e.min=="number"?{minimum:e.min}:{},...typeof e.max=="number"?{maximum:e.max}:{}};return{type:"array",minItems:2,maxItems:2,prefixItems:[r,{...r}],items:!1,"x-report-number-range":{ordered:!0},"x-report-wire-encoding":"json"}}const t={"x-report-wire-encoding":"json","x-report-wire-max-code-units":fr,type:"array",minItems:Math.max(e.required?1:0,e.minItems??0),maxItems:e.type==="cascader"?16:e.maxItems??Hr,items:{type:"string",minLength:1,maxLength:1024,pattern:"\\S","x-report-max-code-units":1024}};return e.type==="multiSelect"?(t.uniqueItems=!0,e.options&&(t.items={...t.items,enum:e.options.map(r=>r.value)})):t["x-report-cascader"]={leafOnly:!0,...e.options?{options:Wo(e.options)}:{}},t}function au(e){const t=[];return e.optionsSource!==void 0&&((!["select","multiSelect","cascader"].includes(e.type??"")||typeof e.optionsSource!="string"||!/^[\w][\w.:-]{0,127}$/.test(e.optionsSource))&&t.push("远程选项来源应为选择参数的有效来源键(最多 128 字符)"),e.options!==void 0&&t.push("远程选项来源与静态选项不能同时配置")),e.dependsOn!==void 0&&(!e.optionsSource||!Array.isArray(e.dependsOn)||e.dependsOn.length>32||e.dependsOn.some(r=>typeof r!="string"||!r)||new Set(e.dependsOn).size!==e.dependsOn.length)&&t.push("联动依赖应为远程选项的最多 32 个唯一参数名"),t}function cu(e){const t=new Map(e.map((o,i)=>[o.field,{def:o,index:i,degree:0,children:[]}])),r=[];for(const o of t.values())for(const i of o.def.dependsOn??[]){const s=t.get(i);if(!s){r.push({index:o.index,message:`联动依赖参数 ${i} 未声明`});continue}o.degree++,s.children.push(o.def.field)}const n=[...t.values()].filter(o=>o.degree===0);for(let o=0;o<n.length;o++)for(const i of n[o].children){const s=t.get(i);--s.degree===0&&n.push(s)}for(const o of t.values())o.degree>0&&r.push({index:o.index,message:"联动依赖不能形成循环"});return r}function bt(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e)||e.startsWith("0000-"))return!1;const t=new Date(`${e}T00:00:00.000Z`);return Number.isFinite(t.getTime())&&t.toISOString().slice(0,10)===e}function Ur(e){return e.length===4&&/^\d{4}$/.test(e)&&e!=="0000"}function Jo(e){return e.length===7&&/^\d{4}-(?:0[1-9]|1[0-2])$/.test(e)&&Ur(e.slice(0,4))}function zo(e){const[t,r,n]=e.split("/");if(!(n!==void 0||!t||!r||!bt(t)||!bt(r)||t>r))return{start:t,end:r}}function Vo(e,t){return typeof t!="string"?!1:e==="month"?Jo(t):e==="year"?Ur(t):(e==="date"||e==="dateRange")&&bt(t)}function uu(e,t){if(e==="date"&&!bt(t))return"应为有效的 YYYY-MM-DD 日期";if(e==="month"&&!Jo(t))return"应为有效的 YYYY-MM 月份";if(e==="year"&&!Ur(t))return"应为 0001 至 9999 的四位年份";if(e==="dateRange"&&!zo(t))return"应为完整且有序的 YYYY-MM-DD/YYYY-MM-DD 日期范围"}class Bt extends Error{constructor(t){super(t.map(r=>`${r.field}: ${r.message}`).join("; ")),this.issues=t,this.code="params",this.name="ReportParamValidationError"}}function Ho(e){return/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e)&&Number.isFinite(Number(e))}function Uo(e,t){if(U(e))return nu(e,t);if(e.type==="number"&&!Ho(t))return[["type","应为有限数字"]];const r=uu(e.type,t);if(r)return[["type",r]];const n=[];e.type==="select"&&e.options&&!e.options.some(i=>i.value===t)&&n.push(["option","不在允许的选项中"]);const o=Array.from(t).length;return e.minLength!==void 0&&o<e.minLength&&n.push(["minLength",`至少 ${e.minLength} 个字符`]),e.maxLength!==void 0&&o>e.maxLength&&n.push(["maxLength",`最多 ${e.maxLength} 个字符`]),n.push(...fu(e,t)),n}function fu(e,t){const r=e.type==="dateRange"?zo(t):void 0,n=r?.start??(e.type==="number"?Number(t):t),o=r?.end??n,i=[];return e.min!==void 0&&n<e.min&&i.push(["minimum",`不能小于 ${e.min}`]),e.max!==void 0&&o>e.max&&i.push(["maximum",`不能大于 ${e.max}`]),i}function lu(e){const t=[];for(const o of["min","max"]){const i=e[o];if(i===void 0)continue;Vo(e.type,i)||["number","numberRange"].includes(e.type??"")&&typeof i=="number"&&Number.isFinite(i)||t.push(`${o} 应为数字的有限边界或日期/月/年的规范字符串边界`)}const r=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;return(r||n)&&t.push("最小边界不能大于最大边界"),[...t,...du(e),...iu(e)]}function du(e){const t=[];U(e)&&(e.minLength!==void 0||e.maxLength!==void 0)&&t.push("复合参数使用项目数或数值边界,而不是文本长度约束"),e.type==="number"&&(e.minLength!==void 0||e.maxLength!==void 0)&&t.push("number 参数使用 min/max 而不是文本长度约束");for(const r of["minLength","maxLength"]){const n=e[r];n!==void 0&&(!Number.isSafeInteger(n)||n<0)&&t.push(`${r} 应为非负整数`)}return typeof e.minLength=="number"&&typeof e.maxLength=="number"&&e.minLength>e.maxLength&&t.push("最小长度不能大于最大长度"),t}function _t(e){if(!Array.isArray(e))return[{code:"definition",field:"",path:"$.paramDefs",message:"参数定义应为数组"}];const t=new Set,r=e.flatMap((n,o)=>{const i=n&&typeof n.field=="string"?n.field:"";return hu(n,t).map(a=>({code:"definition",field:i,path:`$.paramDefs.${o}`,message:a}))});return r.length?r:cu(e).map(({index:n,message:o})=>({code:"definition",field:e[n].field,path:`$.paramDefs.${n}`,message:o}))}function mu(e){const t=[];return e.type!==void 0&&!["text","number","date","month","year","dateRange","select","multiSelect","cascader","numberRange"].includes(e.type)&&t.push("未知参数类型"),e.label!==void 0&&typeof e.label!="string"&&t.push("参数标签应为字符串"),e.placeholder!==void 0&&typeof e.placeholder!="string"&&t.push("提示文字应为字符串"),e.required!==void 0&&typeof e.required!="boolean"&&t.push("required 应为布尔值"),e.defaultValue!==void 0&&typeof e.defaultValue!="string"&&t.push("默认值应为字符串"),e.options!==void 0&&!eu(e.options,e.type==="cascader",!U(e))&&t.push("选项应为包含字符串 label/value 的数组"),[...t,...au(e)]}function hu(e,t){if(!e||typeof e!="object"||Array.isArray(e))return["参数定义项应为对象"];const r=mu(e);return typeof e.field!="string"||!e.field.trim()||t.has(e.field)?r.push("参数名应为非空且不重复的字符串"):t.add(e.field),r.length||(r.push(...lu(e)),r.length)||e.defaultValue!==void 0&&(e.required&&(!e.defaultValue.trim()||U(e)&&Lt(e,e.defaultValue)?.length===0)?r.push("必填参数的默认值不能为空"):e.defaultValue.trim()&&r.push(...Uo(e,e.defaultValue).map(([,n])=>`默认值${n}`))),r}function gu(e,t,r){for(const[n,o]of Object.entries(e))(typeof o=="string"||typeof o=="number"&&Number.isFinite(o))&&(Object.defineProperty(t,n,{value:String(o),writable:!0,enumerable:!0,configurable:!0}),Object.defineProperty(r,n,{value:o,writable:!0,enumerable:!0,configurable:!0}))}function xt(e){return e==null||typeof e=="string"&&!e.trim()}function lr(e,t={}){const r=Object.create(null),n=Object.create(null),o=_t(e);if((!t||typeof t!="object"||Array.isArray(t))&&o.push({code:"type",field:"",path:"$.params",message:"参数应为对象"}),o.length)return{ok:!1,values:r,typedValues:n,issues:o};gu(t,r,n);for(const i of e){const s=Object.prototype.hasOwnProperty.call(t,i.field)&&t[i.field]!==void 0?t[i.field]:i.defaultValue;pu(i,s,{values:r,typedValues:n,issues:o})}return o.push(...yu(e,r)),{ok:o.length===0,values:r,typedValues:n,issues:o}}function pu(e,t,r){const{values:n,typedValues:o,issues:i}=r,s=(f,d)=>i.push({code:f,path:`$.params.${e.field}`,field:e.field,message:d}),a=U(e)&&!xt(t)?Lt(e,t):void 0;if(xt(t)||a?.length===0){e.required&&s("required","此参数为必填项"),(typeof t=="string"||a)&&(n[e.field]=a?"":String(t)),delete o[e.field];return}if(!a&&typeof t!="string"&&!(typeof t=="number"&&Number.isFinite(t))){s("type","参数应为字符串、有限数字或当前控件的规范数组");return}const c=a?JSON.stringify(a):String(t);n[e.field]=c;const u=Uo(e,c);u.forEach(([f,d])=>s(f,d)),u.length&&U(e)?delete o[e.field]:o[e.field]=a??(e.type==="number"&&Ho(c)?Number(c):c)}function yu(e,t){return e.flatMap(r=>!xt(t[r.field])&&r.dependsOn?.some(n=>xt(t[n]))?[{code:"dependency",path:`$.params.${r.field}`,field:r.field,message:"请先填写联动依赖的上级参数"}]:[])}function $n(e,t={}){const r=lr(e,t);if(!r.ok)throw new Bt(r.issues);return r.values}function wu(e){const t={},r="(?![\\s\\S])";return e.type==="date"&&(t.format="date"),e.type==="month"&&(t.pattern=`^(?!0000)[0-9]{4}-(0[1-9]|1[0-2])${r}`),e.type==="year"&&(t.pattern=`^(?!0000)[0-9]{4}${r}`),e.type==="dateRange"&&(t.pattern=`^[0-9]{4}-[0-9]{2}-[0-9]{2}/[0-9]{4}-[0-9]{2}-[0-9]{2}${r}`),e.type==="dateRange"&&(t["x-report-date-range"]={separator:"/",ordered:!0,calendarDates:!0}),t}function bu(e){const t={type:e.type==="number"?"number":"string",title:e.label??e.field,...wu(e)};return U(e)&&Object.assign(t,su(e)),e.required&&!U(e)&&e.type!=="number"&&!t.pattern&&(t.pattern="\\S"),e.type==="select"&&e.options&&(t.enum=e.options.map(r=>r.value)),Object.assign(t,vu(e)),Object.assign(t,xu(e)),t}function xu(e){const t={};return e.defaultValue!==void 0&&(!(e.type==="number"||U(e))||e.defaultValue.trim())&&(t.default=U(e)?Lt(e,e.defaultValue):e.type==="number"?Number(e.defaultValue):e.defaultValue),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),!U(e)&&typeof e.min=="number"&&(t.minimum=e.min),!U(e)&&typeof e.max=="number"&&(t.maximum=e.max),typeof e.min=="string"&&(t["x-report-minimum"]=e.min),typeof e.max=="string"&&(t["x-report-maximum"]=e.max),t}function vu(e){return{...e.optionsSource?{"x-report-options-source":e.optionsSource}:{},...e.dependsOn?.length?{"x-report-depends-on":[...e.dependsOn]}:{}}}function Mu(e){const t=_t(e);if(t.length)throw new Bt(t);return{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:Object.fromEntries(e.map(r=>[r.field,bu(r)])),required:e.filter(r=>r.required).map(r=>r.field),additionalProperties:!0}}function vt(e,t){const r=new Set;return t.flatMap(n=>{const o=Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0,i=o?.params??(typeof o?.template=="function"?[]:o?.template.params)??[],s=_t(i);if(s.length)throw new Bt(s);return i.filter(a=>r.has(a.field)?!1:(r.add(a.field),!0))})}function $u(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function dr(e,t,r){if(e!==void 0)try{Y(e)}catch(n){r.push({path:t,message:n instanceof Error?n.message:String(n)})}}function Go(e,t,r){if(e===void 0)return;if(!Array.isArray(e)||e.length>2048){r.push({path:t,message:"聚合应为数组且最多 2048 项"});return}const n=new Set;e.forEach((o,i)=>{const s=`${t}.${i}`;if(!$u(o)){r.push({path:s,message:"聚合应为对象"});return}const a=o.field;typeof a!="string"||!a.trim()||n.has(a)?r.push({path:`${s}.field`,message:"聚合输出字段应非空且唯一"}):n.add(a),o.numeric!==void 0&&o.numeric!=="number"&&o.numeric!=="decimal"&&r.push({path:`${s}.numeric`,message:"数值模式应为 number 或 decimal"}),o.digits!==void 0&&(!Number.isInteger(o.digits)||Number(o.digits)<0||Number(o.digits)>100)&&r.push({path:`${s}.digits`,message:"小数位应为 0–100 的整数"});try{oe({...o,field:o.valueField??a})}catch(c){r.push({path:s,message:c instanceof Error?c.message:String(c)})}})}function Su(e,t,r){if(e===void 0)return;const n=Ts(e);for(const o of n.errors)r.push({path:t,message:o})}function Eu(e,t,r){if(e!==void 0)try{Cr(e)}catch(n){r.push({path:t,message:n instanceof Error?n.message:String(n)})}}function Au(e,t,r){if(e.tree===void 0)return;const n=`${t}.tree`;try{uo(e.tree);const o=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!==o.idField)throw new Error("树形 rowKey 应与 idField 一致");if(!Array.isArray(e.columns)||!e.columns.some(i=>i&&i.field===o.labelField&&!i.hidden))throw new Error("树形布局需要可见的标签列");Array.isArray(e.computed)&&Dr(o,e.computed)}catch(o){r.push({path:n,message:o instanceof Error?o.message:String(o)})}}class ku extends Error{constructor(t){super(`模板校验失败:${t.slice(0,3).map(r=>`${r.path}: ${r.message}`).join("; ")}`),this.errors=t,this.name="ReportTemplateError"}}const Nu=new Set(["__proto__","prototype","constructor"]),Pu=new Set(["left","center","right","justify"]),nt=2e5,Fu=64,Ou=1e7;function C(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Iu(e,t,r){const n=Object.getPrototypeOf(e),o=Array.isArray(e);if(o?n!==Array.prototype:n!==Object.prototype&&n!==null)return r.push({path:t,message:"模板对象必须使用普通 JSON 对象原型"}),!1;if(o){const i=Object.keys(e);if(i.length!==e.length||i.some(s=>!/^(0|[1-9]\d*)$/.test(s)||Number(s)>=e.length))return r.push({path:t,message:"模板数组不能包含空位或额外属性"}),!1}return Object.getOwnPropertySymbols(e).length>0?(r.push({path:t,message:"模板不能包含 Symbol 键"}),!1):!0}function Ru(e,t,r,n){return Nu.has(e)?(n.push({path:r,message:"模板不能包含可能污染原型的键"}),!1):t.get||t.set||!t.enumerable?(n.push({path:r,message:"模板不能包含访问器或不可枚举字段"}),!1):!0}function Cu(e){return e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)}function Tu(e,t){const r=new Set;let n=0,o=0,i=!1;const s=(a,c,u)=>{if(!i){if(++n>nt){n===nt+1&&t.push({path:c,message:"模板超过 JSON 节点安全上限"});return}if(u>Fu){t.push({path:c,message:"模板嵌套层级过深"});return}if(typeof a=="string"){o+=a.length,o>Ou&&(i=!0,t.push({path:c,message:"模板文本超过 1000 万字符的安全上限"}));return}if(!Cu(a)){if(!a||typeof a!="object"){t.push({path:c,message:"模板只允许 JSON 值,不允许函数、undefined 或非有限数字"});return}if(r.has(a)){t.push({path:c,message:"模板不能包含循环引用"});return}if(Iu(a,c,t)){r.add(a);for(const[f,d]of Object.entries(Object.getOwnPropertyDescriptors(a))){if(Array.isArray(a)&&f==="length")continue;const l=`${c}.${f}`;if(Ru(f,d,l,t)&&s(d.value,l,u+1),n>nt||i)break}r.delete(a)}}}};s(e,"$",0)}function _(e,t,r,n,o=!1){const i=e[t];i===void 0&&!o||(typeof i!="string"||o&&!i.trim())&&n.push({path:`${r}.${t}`,message:o?"应为非空字符串":"应为字符串"})}function W(e,t,r,n,o=0,i=!1){const s=e[t];s===void 0&&!i||(typeof s!="number"||!Number.isFinite(s)||s<o)&&n.push({path:`${r}.${t}`,message:`应为大于等于 ${o} 的有限数字`})}function se(e,t,r,n){e[t]!==void 0&&typeof e[t]!="boolean"&&n.push({path:`${r}.${t}`,message:"应为布尔值"})}function Ee(e,t,r,n=!1){e!==void 0&&!Pu.has(e)&&!(n&&e==="auto")&&r.push({path:t,message:`未知对齐方式${n?"(支持 auto)":""}`})}function re(e,t,r){if(e!==void 0){if(!C(e)){r.push({path:t,message:"样式应为对象"});return}Ee(e.align,`${t}.align`,r),e.verticalAlign!==void 0&&!["top","middle","bottom"].includes(e.verticalAlign)&&r.push({path:`${t}.verticalAlign`,message:"未知垂直对齐方式"});for(const n of["fontSize","fontSizePx","lineWidthPt","lineHeight"])W(e,n,t,r);for(const n of["letterSpacing","rotateDeg"])W(e,n,t,r,-1/0);W(e,"opacity",t,r),typeof e.opacity=="number"&&e.opacity>1&&r.push({path:`${t}.opacity`,message:"透明度不能大于 1"});for(const n of["bold","italic","underline","borderTop","borderRight","borderBottom","borderLeft"])se(e,n,t,r);for(const n of["fontFamily","color","backgroundColor","lineColor","borderColor"])_(e,n,t,r)}}function ju(e,t,r){if(e===void 0)return;if(!Array.isArray(e)){r.push({path:t,message:"参数定义应为数组"});return}const n=new Set,o=r.length;e.forEach((i,s)=>{const a=`${t}.${s}`;if(!C(i)){r.push({path:a,message:"参数定义应为对象"});return}_(i,"field",a,r,!0),typeof i.field=="string"&&(n.has(i.field)&&r.push({path:`${a}.field`,message:"参数名重复"}),n.add(i.field)),i.type!==void 0&&!["text","number","date","month","year","dateRange","select","multiSelect","cascader","numberRange"].includes(i.type)&&r.push({path:`${a}.type`,message:"未知参数类型"});for(const c of["label","defaultValue","placeholder"])_(i,c,a,r);se(i,"required",a,r);for(const c of["minLength","maxLength"]){const u=i[c];u!==void 0&&(typeof u!="number"||!Number.isSafeInteger(u)||u<0)&&r.push({path:`${a}.${c}`,message:"长度边界应为非负整数"})}Du(i,a,r),i.options!==void 0&&(Array.isArray(i.options)?i.options.forEach((c,u)=>{const f=`${a}.options.${u}`;if(!C(c))r.push({path:f,message:"选项应为对象"});else for(const d of["label","value"])typeof c[d]!="string"&&r.push({path:`${f}.${d}`,message:"选项标签与值应为字符串(允许空白选项)"})}):r.push({path:`${a}.options`,message:"选项应为数组"}))}),r.length===o&&r.push(..._t(e).map(i=>({path:i.path.replace("$.paramDefs",t),message:i.message})))}function Du(e,t,r){for(const i of["min","max"]){const s=e[i];if(s===void 0)continue;Vo(e.type,s)||["number","numberRange"].includes(e.type)&&typeof s=="number"&&Number.isFinite(s)||r.push({path:`${t}.${i}`,message:"数字使用有限数字边界,日期/月/年使用对应规范字符串边界"})}const n=typeof e.min=="number"&&typeof e.max=="number"&&e.min>e.max,o=typeof e.min=="string"&&typeof e.max=="string"&&e.min>e.max;(n||o)&&r.push({path:t,message:"最小边界不能大于最大边界"}),typeof e.minLength=="number"&&typeof e.maxLength=="number"&&e.minLength>e.maxLength&&r.push({path:t,message:"最小长度不能大于最大长度"})}function Yo(e,t,r){if(!Array.isArray(e)||e.length===0){r.push({path:t,message:"列表至少需要一列"});return}e.every(n=>C(n)&&n.hidden===!0)&&r.push({path:t,message:"列表至少需要一列可见列"}),e.forEach((n,o)=>{const i=`${t}.${o}`;if(!C(n)){r.push({path:i,message:"列应为对象"});return}if(To(n,i,r),n.visual!==void 0&&!vo(n.visual)&&r.push({path:`${i}.visual`,message:"列可视化配置无效,请检查类型、数值范围和颜色"}),se(n,"hidden",i,r),dr(n.visibleWhen,`${i}.visibleWhen`,r),typeof n.header!="string"&&r.push({path:`${i}.header`,message:"表头应为字符串(允许空白表头)"}),_(n,"field",i,r,!0),W(n,"widthMm",i,r,Number.MIN_VALUE,!0),re(n.style,`${i}.style`,r),re(n.headerStyle,`${i}.headerStyle`,r),Ee(n.align,`${i}.align`,r,!0),Ee(n.headerAlign,`${i}.headerAlign`,r),n.semanticRole!==void 0&&!["identifier","dimension","measure","date","text"].includes(n.semanticRole)&&r.push({path:`${i}.semanticRole`,message:"未知列语义"}),n.format!==void 0)if(!C(n.format)||!["number","percent","date"].includes(n.format.kind))r.push({path:`${i}.format`,message:"未知列格式"});else{const s=n.format.digits;s!==void 0&&(typeof s!="number"||!Number.isInteger(s)||s<0||s>100)&&r.push({path:`${i}.format.digits`,message:"小数位应为 0–100 的整数"}),se(n.format,"thousands",`${i}.format`,r),_(n.format,"pattern",`${i}.format`,r)}n.rules!==void 0&&(Array.isArray(n.rules)?n.rules.forEach((s,a)=>{const c=`${i}.rules.${a}`;if(!C(s)||!C(s.when)){r.push({path:c,message:"条件格式缺少 when 对象"});return}dr(s.when,`${c}.when`,r),re(s.style,`${c}.style`,r)}):r.push({path:`${i}.rules`,message:"条件格式应为数组"}))})}function qo(e,t,r){if(e!==void 0){if(!C(e)){r.push({path:t,message:"分组应为对象"});return}_(e,"field",t,r,!0);for(const n of["headerTemplate","subtotalLabel"])_(e,n,t,r);for(const n of["headerStyle","subtotalStyle"])re(e[n],`${t}.${n}`,r);se(e,"keepWithNext",t,r),se(e,"repeatHeader",t,r),Go(e.aggregates,`${t}.aggregates`,r),e.subtotal!==void 0&&(!Array.isArray(e.subtotal)||e.subtotal.some(n=>typeof n!="string"))&&r.push({path:`${t}.subtotal`,message:"小计字段应为字符串数组"})}}function Lu(e,t,r){if(!(e===void 0||typeof e=="boolean")){if(!C(e)){r.push({path:t,message:"合计应为布尔值或对象"});return}_(e,"label",t,r),Go(e.aggregates,`${t}.aggregates`,r),re(e.style,`${t}.style`,r),e.fields!==void 0&&(!Array.isArray(e.fields)||e.fields.some(n=>typeof n!="string"))&&r.push({path:`${t}.fields`,message:"合计字段应为字符串数组"})}}function Bu(e,t,r,n){const o={kind:"rect",leftMm:0,topMm:0,widthMm:1,heightMm:1,grid:e};if(Lo(o,r,n,[]),Gr(o,r,n),!C(e)||!Array.isArray(e.cells))return;const i=e.cells,s=Array.isArray(t)?t.length:0;if(i.length*s>nt){n.push({path:r,message:"表头逻辑网格超过 20 万格安全上限"});return}e.cells.length||n.push({path:`${r}.cells`,message:"表头至少需要一行"}),Array.isArray(e.colWidthsMm)&&e.colWidthsMm.length!==s&&n.push({path:`${r}.colWidthsMm`,message:"表头列宽数量应与列表列数一致"}),Array.isArray(e.rowHeightsMm)&&e.rowHeightsMm.length!==e.cells.length&&n.push({path:`${r}.rowHeightsMm`,message:"表头行高数量应与行数一致"}),_u(i,s,r,n)}function _u(e,t,r,n){const o=new Set;e.forEach((i,s)=>{if(!Array.isArray(i))return;let a=0;i.forEach((c,u)=>{for(;o.has(`${s}:${a}`);)a++;const f=C(c)&&typeof c.colSpan=="number"?c.colSpan:1,d=C(c)&&typeof c.rowSpan=="number"?c.rowSpan:1;(a+f>t||s+d>e.length)&&n.push({path:`${r}.cells.${s}.${u}`,message:"表头合并区域超出表头边界"});for(let l=s;l<Math.min(e.length,s+d);l++)for(let m=a;m<Math.min(t,a+f);m++)o.has(`${l}:${m}`)&&n.push({path:`${r}.cells.${s}.${u}`,message:"表头合并区域重叠"}),o.add(`${l}:${m}`);a+=f})})}function Ku(e,t,r){if(Au(e,t,r),Su(e.computed,`${t}.computed`,r),Eu(e.matrix,`${t}.matrix`,r),e.matrix&&(e.detail||e.groupBy||Array.isArray(e.groups)&&e.groups.length||e.grandTotal)&&r.push({path:`${t}.matrix`,message:"矩阵请使用自身 totals 汇总,不能同时配置普通分组、总计或主从明细"}),dr(e.rowVisibleWhen,`${t}.rowVisibleWhen`,r),e.groups!==void 0&&(!Array.isArray(e.groups)||e.groups.length>16?r.push({path:`${t}.groups`,message:"分组应为数组,最多 16 级"}):e.groups.forEach((i,s)=>qo(i,`${t}.groups.${s}`,r))),e.detail===void 0)return;const n=e.detail,o=`${t}.detail`;if(!C(n)){r.push({path:o,message:"主从关联应为对象"});return}for(const i of["dataset","parentKey","foreignKey"])_(n,i,o,r,!0);for(const i of["rowKey","revisionField","sourceTokenField"])_(n,i,o,r,n[i]!==void 0);_(n,"label",o,r),se(n,"header",o,r),W(n,"rowHeightMm",o,r,Number.MIN_VALUE),Yo(n.columns,`${o}.columns`,r),n.unmatched!==void 0&&n.unmatched!=="error"&&n.unmatched!=="ignore"&&r.push({path:`${o}.unmatched`,message:"未关联明细策略应为 error 或 ignore"})}function Wu(e,t,r){for(const n of["leftMm","topMm"])W(e,n,t,r,-1/0,!0);W(e,"widthMm",t,r,Number.MIN_VALUE,!0),_(e,"dataset",t,r,!0),_(e,"title",t,r);for(const n of["rowKey","revisionField","sourceTokenField"])_(e,n,t,r,e[n]!==void 0);e.headerGrid!==void 0&&Bu(e.headerGrid,e.columns,`${t}.headerGrid`,r),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&r.push({path:`${t}.layout`,message:"布局应为 page 或 wide"}),Yo(e.columns,`${t}.columns`,r);for(const n of["fontSizePt","rowHeightMm"])W(e,n,t,r,Number.MIN_VALUE);W(e,"paddingMm",t,r);for(const n of["header","headerBold","headerEveryPage","border"])se(e,n,t,r);e.cardinality!==void 0&&e.cardinality!=="record"&&r.push({path:`${t}.cardinality`,message:"单记录区域类型应为 record"}),_(e,"headerBackgroundColor",t,r),Ee(e.align,`${t}.align`,r,!0),Ee(e.headerAlign,`${t}.headerAlign`,r),re(e.headerStyle,`${t}.headerStyle`,r),Ku(e,t,r),qo(e.groupBy,`${t}.groupBy`,r),Lu(e.grandTotal,`${t}.grandTotal`,r)}function Sn(e,t,r){Array.isArray(e.richParagraphs)&&e.richParagraphs.forEach((n,o)=>{if(!C(n))return;const i=`${t}.richParagraphs.${o}`;Ee(n.align,`${i}.align`,r);for(const s of["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"])W(n,s,i,r);Array.isArray(n.segments)&&n.segments.forEach((s,a)=>{const c=`${i}.segments.${a}`;if(!C(s)){r.push({path:c,message:"富文本片段应为对象"});return}s.kind!==void 0&&s.kind!=="text"&&s.kind!=="field"&&r.push({path:`${c}.kind`,message:"未知富文本片段类型"});for(const u of["text","field"])_(s,u,c,r);re(s.style,`${c}.style`,r)})})}function Gr(e,t,r){re(e.style,`${t}.style`,r);for(const o of["text","rawText","imageData","fallbackText","nid","rkey"])_(e,o,t,r);if(e.lines!==void 0&&(!Array.isArray(e.lines)||e.lines.some(o=>typeof o!="string"))&&r.push({path:`${t}.lines`,message:"文本行应为字符串数组"}),Sn(e,t,r),!C(e.grid))return;const n=e.grid;W(n,"gapMm",`${t}.grid`,r),W(n,"paddingMm",`${t}.grid`,r);for(const o of["colWidthsMm","rowHeightsMm"]){const i=n[o];i!==void 0&&(!Array.isArray(i)||i.some(s=>typeof s!="number"||!Number.isFinite(s)||s<0))&&r.push({path:`${t}.grid.${o}`,message:"网格尺寸应为有限非负数字数组"})}Array.isArray(n.cells)&&n.cells.forEach((o,i)=>{Array.isArray(o)&&o.forEach((s,a)=>{const c=`${t}.grid.cells.${i}.${a}`;if(s!==null){if(!C(s)){r.push({path:c,message:"网格单元格应为对象或 null"});return}for(const u of["text","rawText","numberFormat"])_(s,u,c,r);for(const u of["colSpan","rowSpan"]){const f=s[u];f!==void 0&&(typeof f!="number"||!Number.isInteger(f)||f<=0)&&r.push({path:`${c}.${u}`,message:"跨度应为正整数"})}s.value!==void 0&&s.value!==null&&!["string","number","boolean"].includes(typeof s.value)&&r.push({path:`${c}.value`,message:"Excel 原始值应为字符串、数字、布尔值或 null"}),re(s.style,`${c}.style`,r),Sn(s,c,r),s.children!==void 0&&(Array.isArray(s.children)?s.children.forEach((u,f)=>{C(u)&&Gr(u,`${c}.children.${f}`,r)}):r.push({path:`${c}.children`,message:"嵌套组件应为数组"}))}})})}function Ju(e,t,r){if(!(e.flow===void 0||!Array.isArray(e.components)))try{go(e.components,e.flow)}catch(n){r.push({path:`${t}.flow`,message:n instanceof Error?n.message:String(n)})}}function zu(e){const t=[],r=[];return Tu(e,t),t.length?{ok:!1,errors:t,warnings:r}:(C(e)?(e.schemaVersion!==void 0&&e.schemaVersion!==Ae&&t.push({path:"$.schemaVersion",message:"不支持的模板 schemaVersion"}),ju(e.params,"$.params",t),yo(e,t),!Array.isArray(e.pages)||e.pages.length===0?t.push({path:"$.pages",message:"模板至少需要一页"}):e.pages.forEach((n,o)=>{const i=`$.pages.${o}`;if(!C(n)){t.push({path:i,message:"页应为对象"});return}W(n,"widthMm",i,t,Number.MIN_VALUE,!0),W(n,"heightMm",i,t,Number.MIN_VALUE,!0),n.layout!==void 0&&n.layout!=="page"&&n.layout!=="wide"&&t.push({path:`${i}.layout`,message:"布局应为 page 或 wide"}),typeof n.heightMm=="number"&&n.heightMm>=5e3&&t.push({path:`${i}.heightMm`,message:"页高应小于 5000mm"});for(const s of["marginTopMm","marginBottomMm","marginLeftMm","marginRightMm"])W(n,s,i,t);typeof n.widthMm=="number"&&Number(n.marginLeftMm??0)+Number(n.marginRightMm??0)>=n.widthMm&&t.push({path:i,message:"横向页边距占满页面"}),typeof n.heightMm=="number"&&Number(n.marginTopMm??0)+Number(n.marginBottomMm??0)>=n.heightMm&&t.push({path:i,message:"纵向页边距占满页面"}),Array.isArray(n.components)?n.components.forEach((s,a)=>{const c=`${i}.components.${a}`;C(s)&&s.kind==="list"?Wu(s,c,t):(Lo(s,c,t,r),C(s)&&Gr(s,c,t))}):t.push({path:`${i}.components`,message:"组件应为数组"}),Ju(n,i,t)})):t.push({path:"$",message:"模板应为对象"}),{ok:t.length===0,errors:t,warnings:r})}class Vu extends Error{constructor(t){super(t.map(r=>r.message).join(";")),this.issues=t,this.name="ReportValidationError"}}function En(e,t,r){if(!Number.isSafeInteger(e)||e<1||e>r)throw new Error(`校验 ${t} 超出预算`);return e}function Hu(e){if(e.aggregates&&e.scope!=="dataset")throw new Error("仅数据集规则允许汇总");if(e.aggregates&&(!Array.isArray(e.aggregates)||e.aggregates.length>64))throw new Error("校验汇总最多 64 项");const t=new Set;for(const r of e.aggregates??[]){if(K(r.field),t.has(r.field))throw new Error("校验汇总字段重复");t.add(r.field),r.valueField!==void 0&&K(r.valueField),r.weightField!==void 0&&K(r.weightField),Be([],{...r,field:r.valueField??r.field})}}function Xo(e){if(!Array.isArray(e)||e.length>256||Object.keys(e).length!==e.length)throw new Error("校验规则最多 256 条且不允许空位");const t=new Set;return e.map(r=>{if(!r||typeof r!="object")throw new Error("校验规则应为声明式对象");if(K(r.id),t.has(r.id))throw new Error("校验规则 id 重复");if(t.add(r.id),r.field!==void 0&&K(r.field),r.dataset!==void 0&&K(r.dataset),typeof r.message!="string"||!r.message.trim()||r.message.length>2048)throw new Error("校验规则需要有界提示文案");if(r.severity!==void 0&&!["error","warning"].includes(r.severity))throw new Error("未知校验严重程度");if(r.scope!==void 0&&!["row","dataset"].includes(r.scope))throw new Error("未知校验范围");Hu(r);const n={nodes:0},o=Y(r.assert,n),i=r.when?Y(r.when,n):void 0;return{rule:r,assert:o,when:i,checks:n.nodes}})}function An(e){if(e?.aborted){const t=new Error("报表校验已取消");throw t.name="AbortError",t}}function Uu(e,t,r,n){const o=n&&Object.prototype.hasOwnProperty.call(t,n)?t[n]:void 0;if(o!==void 0&&typeof o!="string"&&!(typeof o=="number"&&Number.isFinite(o)))throw new Error("校验定位需要稳定的文本或数值业务键");return{ruleId:e.id,rowIndex:r,...o===void 0?{}:{rowKey:o},field:e.field,severity:e.severity??"error",message:e.message}}function Gu(e,t){const r=t.computed?.length?{fields:t.computed,formula:t.formula,signal:t.signal}:void 0;if(t.tree){const o=ho(e,t.tree,{signal:t.signal,computed:r});if(o.rows.length>1e5)throw new Error("校验展开后数据最多 100000 行");return{rows:o.rows,summaryRows:o.leaves,rowKey:t.tree.idField}}const n=r?Ft(e,r).rows:e;return{rows:n,summaryRows:n,rowKey:t.rowKey}}function Yu(e,t){const r=new Set;e.forEach(n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new Error("校验数据行应为对象");if(!t)return;const o=Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0;if(!(typeof o=="string"&&o.trim())&&!(typeof o=="number"&&Number.isFinite(o)))throw new Error("校验定位需要稳定业务键");if(r.has(o))throw new Error("校验业务键重复");r.add(o)})}function qu(e,t,r){if(!Array.isArray(e)||e.length>1e5)throw new Error("校验数据最多 100000 行");An(t.signal);const n=En(t.maxChecks??2e6,"maxChecks",1e7),o=En(t.maxIssues??1e3,"maxIssues",1e4);t.rowKey!==void 0&&K(t.rowKey);const i=Gu(e,t),{rows:s,summaryRows:a,rowKey:c}=i;Yu(s,c);const u=Xo(t.rules),f=u.reduce((l,m)=>l+(m.rule.scope==="dataset"?m.checks+a.length*(m.rule.aggregates?.length??0):s.length*m.checks),0);if(r.checks+=f,r.checks>n)throw new Error("整批校验超出 maxChecks 预算");const d=[];for(const l of u)(l.rule.scope==="dataset"?[Object.fromEntries((l.rule.aggregates??[]).map(h=>[h.field,Be(a,{...h,field:h.valueField??h.field})]))]:s).forEach((h,p)=>{if(An(t.signal),!h||typeof h!="object"||Array.isArray(h))throw new Error("校验数据行应为对象");if(!(l.when&&!l.when(h)||l.assert(h))){if(d.length>=o)throw new Error("校验问题超出 maxIssues 预算,请缩小范围");d.push(Uu(l.rule,h,l.rule.scope==="dataset"?void 0:p,l.rule.scope==="dataset"?void 0:c))}});return d}function Xu(e,t="allow"){if(!["allow","block"].includes(t))throw new Error("未知校验警告策略");if(!Array.isArray(e)||e.length>1e4||e.some(r=>!r||!["error","warning"].includes(r.severity)||typeof r.ruleId!="string"||!r.ruleId.trim()||typeof r.message!="string"||!r.message.trim()))throw new Error("校验问题结构无效");if(e.some(r=>r.severity==="error"||t==="block"))throw new Vu(e)}function kn(e,t,r){const n=e.get(t);if(n&&JSON.stringify(n)!==JSON.stringify(r))throw new Error("同一数据集的校验计算/业务键存在歧义,请统一绑定");e.set(t,r)}function Zu(e,t,r,n=[]){Xo(t.rules);const o=[],i={checks:0};for(const[a,c]of e.entries()){const u=new Map;for(const f of c.template.pages)for(const d of f.components)d.kind==="list"&&(kn(u,d.dataset,{rowKey:d.tree?.idField??d.rowKey,computed:d.computed,tree:d.tree}),d.detail&&kn(u,d.detail.dataset,{rowKey:d.detail.rowKey}));for(const[f,d]of u){const l=t.rules.filter(m=>!m.dataset||m.dataset===f);if(l.length&&(o.push(...qu(c.datasets[f]??[],{...t,rules:l,...d,formula:n[a],signal:r},i).map(m=>({...m,dataset:f,sourceScope:c.sourceScope}))),o.length>(t.maxIssues??1e3)))throw new Error("整批候选校验问题超出 maxIssues 预算")}}const s=new Set(e.flatMap(a=>a.template.pages.flatMap(c=>c.components.flatMap(u=>u.kind==="list"?[u.dataset,...u.detail?[u.detail.dataset]:[]]:[]))));if(t.rules.some(a=>a.dataset&&!s.has(a.dataset)))throw new Error("校验目标数据集不存在");return o}function Qu(e){return!e||typeof e!="object"?!1:[e.pageIndex,e.componentIndex,e.rowIndex,e.columnIndex].every(t=>Number.isInteger(t)&&t>=0)}function ef(e){return e.value!==void 0?e.value:e.rawText??e.text??null}function tf(e,t){return e.valueType?e.valueType:typeof t=="number"?"number":typeof t=="boolean"?"boolean":t===null&&e.numberFormat&&/[0#?]/.test(e.numberFormat)?"number":"text"}function rf(e,t){if(e.derived)return"derived";if(e.editable===!1)return"cell";if(e.formula!==void 0)return"formula";if(e.children?.length||e.richParagraphs?.length)return"complex";if(t.table&&t.table.role!=="body"&&e.editable!==!0)return"structure"}function nf(e,t){const r=e.table;if(r)return{id:r.id,rowIndex:r.rowIndex+t.rowIndex,role:r.role,columnKey:r.columnKeys[t.columnIndex]}}function of(e,t,r){if(e.derived)return;if(e.source)return{...e.source};const n=t.table?.source,o=t.table?.columnKeys[r.columnIndex];if(!(!n||n.rowKey===void 0||o===void 0))return{...n,rowKey:n.rowKey,field:o}}function sf(e,t,r){const n=ef(r),o=rf(r,e);return{address:{...t},cell:r,component:e,value:n,valueType:tf(r,n),table:nf(e,t),source:of(r,e,t),editable:o===void 0,readOnlyReason:o}}function Zo(e){const t=new Map;return r=>{if(!Qu(r))return null;const n=e.pages[r.pageIndex]?.components[r.componentIndex];if(!n?.grid)return null;let o=t.get(n);if(!o){const s=new Map;o=new Map;for(const a of to(n.grid,n.widthMm,n.heightMm).cells){const c=s.get(a.ri)??0;s.set(a.ri,c+1);const u=n.grid.cells[a.ri]?.[c];u&&o.set(`${a.ri}:${a.ci}`,u)}t.set(n,o)}const i=o.get(`${r.rowIndex}:${r.columnIndex}`);return i?sf(n,r,i):null}}function af(e){const t=[""];let r=!1,n=!1;for(const o of e)o===";"&&!r&&!n?t.push(""):t[t.length-1]+=o,o==='"'&&!n&&(r=!r),n=o==="\\"&&!n;return t}function cf(e,t){const r=af(t),n=e===0&&r.length>2?2:e<0&&r.length>1?1:0;return{pattern:r[n],magnitude:Math.abs(e),negative:e<0&&n===0}}function uf(e){const t=[];return{text:e.replace(/"([^"]*)"|\\(.)/g,(n,o,i)=>(t.push(o??i??""),String.fromCharCode(57344+t.length-1))).replace(/\[(Black|Blue|Cyan|Green|Magenta|Red|White|Yellow|Color\d+)\]/gi,""),literals:t}}function Ie(e,t){return/[0#?@_*%[\]"\\.,/]/.test(e)?null:e.replace(/[\uE000-\uF8FF]/g,r=>t.literals[r.charCodeAt(0)-57344]??"")}function ff(e,t){const r=/^(.*?)(0)(?:\.([0#]+))?E([+-])(0+)(.*?)$/i.exec(t.text);if(!r)return null;const n=Ie(r[1],t),o=Ie(r[6],t),i=r[3]??"";if(n===null||o===null||i.length>100)return null;const[s,a]=e.magnitude.toExponential(i.length).split("e"),c=i.replace(/#/g,"").length,[u,f=""]=s.split("."),d=f.replace(/0+$/,"").padEnd(c,"0"),l=Number(a),m=l<0?"-":r[4]==="+"?"+":"",h=String(Math.abs(l)).padStart(r[5].length,"0");return`${e.negative?"-":""}${n}${u}${d?`.${d}`:""}E${m}${h}${o}`}function lf(e,t){const r=/^(.*?)([#,]*0[0#]*)(?:\.([0#]+))?(%)?(.*?)$/.exec(t.text);if(!r)return Ie(t.text,t);const n=Ie(r[1],t),o=Ie(r[5],t),i=r[2],s=r[3]??"";if(n===null||o===null||s.length>100||!/^(?:0+|#+0+|#,##0+)$/.test(i))return null;const a=e.magnitude*(r[4]?100:1);if(!Number.isFinite(a))return null;const c=a.toLocaleString("en-US",{useGrouping:i.includes(","),minimumIntegerDigits:Math.min(21,i.replace(/[^0]/g,"").length),minimumFractionDigits:s.replace(/#/g,"").length,maximumFractionDigits:s.length});return`${e.negative?"-":""}${n}${c}${r[4]??""}${o}`}function df(e,t,r){if(!t||/^(General|@)$/i.test(t))return String(e);const n=cf(e,t);if(n.pattern==="")return"";const o=uf(n.pattern),i=ff(n,o)??lf(n,o);return i!==null?i:String(e)}function mf(e){return e!==void 0&&e.replace(/"[^"]*"|\\./g,"").includes("%")}class P extends Error{constructor(t){super(`Invalid report cell edit: ${t}`),this.code=t,this.name="ReportCellEditError"}}function hf(e,t){let r=e.trim();const n=t&&r.endsWith("%");if(n&&(r=r.slice(0,-1).trim()),/^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d*)?(?:[eE][+-]?\d+)?$/.test(r)&&(r=r.replace(/,/g,"")),!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(r))throw new P("number");return Number(r)/(n?100:1)}function gf(e,t){if(e===null||typeof e=="string"&&e.trim()==="")return null;if(typeof e!="string"&&typeof e!="number")throw new P("number");const r=typeof e=="number"?e:hf(e,mf(t.cell.numberFormat));if(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r))throw new P("number");return r}function pf(e){if(e===null||typeof e=="string"&&e.trim()==="")return null;if(typeof e=="boolean")return e;const t=String(e).trim().toLowerCase();if(["true","yes","是","1"].includes(t))return!0;if(["false","no","否","0"].includes(t))return!1;throw new P("boolean")}function yf(e,t){return e.valueType==="number"?gf(t,e):e.valueType==="boolean"?pf(t):t===null?null:String(t)}function wf(e,t){const r=t.cell.text,o=[["是","否"],["TRUE","FALSE"],["True","False"],["true","false"],["1","0"]].find(i=>i.includes(r??""));return o?o[e?0:1]:String(e)}function Qo(e,t){return t===null?"":typeof t=="boolean"?wf(t,e):typeof t=="number"?df(t,e.cell.numberFormat):String(t)}function ei(e,t){if(!e.editable)throw new P("readonly");const r=yf(e,t);return{address:{...e.address},table:e.table,source:e.source,previousValue:e.value,previousText:e.cell.text??"",value:r,text:Qo(e,r)}}function bf(e,t){const r=t.source;if(!r)return!1;const n=e.source;return!n||["sourceScope","datasetId","rowKey","field","revision","sourceToken"].some(o=>!Object.is(n[o],r[o]))}function ti(e){const t=[];for(const r of e.template.pages)for(const n of r.components)n.kind==="list"&&(t.push(n.tree?{...n,rowKey:n.tree.idField}:n),n.detail&&t.push({...n.detail,relation:{detail:n.detail,parentRows:e.datasets[n.dataset]??[]}}));return t}function ke(e){return JSON.stringify([e.sourceScope,e.datasetId])}function Nn(e){return JSON.stringify([e.sourceScope,e.datasetId,e.rowKey])}function ri(e){const t=new Map,r=new Set;return e.forEach((n,o)=>{for(const i of ti(n)){if(!i.rowKey)continue;const s=i.relation,a=s?new Set(s.parentRows.map(c=>JSON.stringify(c[s.detail.parentKey]))):void 0;(n.datasets[i.dataset]??[]).forEach((c,u)=>{if(s&&!a.has(JSON.stringify(c[s.detail.foreignKey])))return;const f=c[i.rowKey];if(typeof f!="string"&&typeof f!="number")return;const d=`${o}:${i.dataset}:${u}:${i.rowKey}`;if(r.has(d))return;r.add(d);const l=Nn({sourceScope:n.sourceScope,datasetId:i.dataset,rowKey:f}),m=t.get(l)??[];m.push({partIndex:o,dataset:i.dataset,rowIndex:u,row:c,binding:i}),t.set(l,m)})}}),n=>{const o=t.get(Nn(n));if(!o?.length)throw new P("missing");if(new Set(o.map(i=>`${i.partIndex}:${i.dataset}`)).size!==o.length)throw new P("conflict");return o}}function ni(e,t){const r=e.map(o=>({...o,datasets:{...o.datasets}})),n=new Set;for(const{row:o,field:i,value:s}of t){const a=r[o.partIndex],c=JSON.stringify([o.partIndex,o.dataset]);n.has(c)||(a.datasets[o.dataset]=[...a.datasets[o.dataset]],n.add(c)),a.datasets[o.dataset][o.rowIndex]={...a.datasets[o.dataset][o.rowIndex],[i]:s}}for(const o of n){const[i,s]=JSON.parse(o);Ps(e[i].datasets[s],r[i].datasets[s])}return r}function xf(e,t,r){const n=[],o=new Set;return e.forEach((i,s)=>{for(const a of ti(i))t.has(ke({sourceScope:i.sourceScope,datasetId:a.dataset}))&&(i.datasets[a.dataset]??[]).forEach((c,u)=>{const f={partIndex:s,dataset:a.dataset,rowIndex:u,row:c,binding:a};for(const[d,l]of[[a.revisionField,r.revision],[a.sourceTokenField,r.sourceToken]]){if(!d||l===void 0)continue;const m=`${s}:${a.dataset}:${u}:${d}`;o.has(m)||(o.add(m),n.push({row:f,field:d,value:l}))}})}),n}function vf(e,t,r){if(!r||r.revision===void 0&&r.sourceToken===void 0)return e;const n=new Set(t.edits.flatMap(o=>o.source?[ke(o.source)]:[]));return oi(e,new Map([...n].map(o=>[o,r])))}function oi(e,t){if(!t.size)return e;function r(i){const s=i.datasetId&&t.get(ke({...i,datasetId:i.datasetId}));return!s||(s.revision===void 0||Object.is(s.revision,i.revision))&&(s.sourceToken===void 0||s.sourceToken===i.sourceToken)?i:{...i,...s.revision!==void 0?{revision:s.revision}:{},...s.sourceToken!==void 0?{sourceToken:s.sourceToken}:{}}}function n(i){const s=i.map(a=>{const c=a.table?.source?r(a.table.source):void 0,u=a.table&&c!==a.table.source?{...a.table,source:c}:a.table,f=a.grid?.cells.map(l=>{const m=l.map(h=>{if(!h)return h;const p=h.source?r(h.source):void 0,w=h.children?n(h.children):void 0;return p===h.source&&w===h.children?h:{...h,source:p,children:w}});return m.some((h,p)=>h!==l[p])?m:l}),d=a.grid&&f?.some((l,m)=>l!==a.grid.cells[m])?{...a.grid,cells:f}:a.grid;return u!==a.table||d!==a.grid?{...a,table:u,grid:d}:a});return s.some((a,c)=>a!==i[c])?s:i}const o=e.pages.map(i=>{const s=n(i.components);return s!==i.components?{...i,components:s}:i});return o.some((i,s)=>i!==e.pages[s])?{...e,pages:o}:e}function Mt(e){const t=e.source;if(t)return JSON.stringify([t.sourceScope,t.datasetId,t.rowKey,t.field]);const r=e.table;if(r?.columnKey!==void 0)return JSON.stringify([r.id,r.role,r.rowIndex,r.columnKey]);const n=e.address;return JSON.stringify([n.pageIndex,n.componentIndex,n.rowIndex,n.columnIndex])}function Mf(e){const t=new Map,r=Zo(e);return e.pages.forEach((n,o)=>n.components.forEach((i,s)=>{if(!(!i.grid||i.table?.role!=="body"))for(let a=0;a<i.grid.cells.length;a++)for(let c=0;c<i.table.columnKeys.length;c++){const u=r({pageIndex:o,componentIndex:s,rowIndex:a,columnIndex:c});u?.source&&u.editable&&t.set(Mt(u),u)}})),t}function ii(e,t){if(++e.nodes>1e6||t>128)throw new P("limit")}function $t(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||r.get||r.set)throw new P("conflict");return r.value}function si(e){if(Object.getOwnPropertyDescriptor(e,"toJSON"))throw new P("conflict");const t=Object.getPrototypeOf(e);if(Array.isArray(e)&&(t!==Array.prototype||Object.keys(e).length!==e.length))throw new P("conflict");if(!(e instanceof Date)&&!Array.isArray(e)&&t!==Object.prototype&&t!==null)throw new P("conflict");for(const r of Reflect.ownKeys(e))if(!(Array.isArray(e)&&r==="length")){if(typeof r=="symbol"||!Object.getOwnPropertyDescriptor(e,r)?.enumerable)throw new P("conflict");if(e instanceof Date||Array.isArray(e)&&!/^(0|[1-9]\d*)$/.test(r))throw new P("conflict")}}function ai(e,t,r,n,o){if(ii(n,o),typeof e=="function"||typeof e=="symbol")throw new P("conflict");if(e===null||typeof e!="object")return;if(si(e),r.has(e))throw new P("conflict");r.add(e);const i=Object.keys(e),s=i.map(a=>$t(e,a));t.push({object:e,prototype:Object.getPrototypeOf(e),keys:i,values:s,...e instanceof Date?{date:Date.prototype.getTime.call(e)}:{},...Array.isArray(e)?{length:e.length}:{}});for(const a of s)ai(a,t,r,n,o+1);r.delete(e)}function $f(e){const{object:t,keys:r,values:n}=e;if(si(t),Object.getPrototypeOf(t)!==e.prototype||Object.getOwnPropertyDescriptor(t,"toJSON")||e.date!==void 0&&!Object.is(Date.prototype.getTime.call(t),e.date)||e.length!==void 0&&t.length!==e.length)return!1;const o=Object.keys(t);return o.length===r.length&&r.every((i,s)=>o[s]===i&&Object.is($t(t,i),n[s]))}function Sf(e){const t=[];return ai(e,t,new Set,{nodes:0},0),()=>{try{return t.every($f)}catch{return!1}}}function mr(e,t,r){if(ii(t,r),e===null||typeof e!="object")return e;if(e instanceof Date)return new Date(Date.prototype.getTime.call(e));if(Array.isArray(e)){const n=[];for(let o=0;o<e.length;o++)n[o]=mr($t(e,String(o)),t,r+1);return n}return Object.fromEntries(Object.keys(e).map(n=>[n,mr($t(e,n),t,r+1)]))}function Ef(e){const t=mr(e,{nodes:0},0);for(const r of t)for(const n of Object.values(r.datasets))Ns(n);return t}async function Af(e,t,r={}){const n=[],o={chartComponents:0},i={...r,knownTotalPages:void 0};for(const s of Fc(e,t,i,o))n.push(s),n.length%8===0&&await new Promise(a=>setTimeout(a,0));if(r.signal?.aborted){const s=new Error("报表重算已取消");throw s.name="AbortError",s}return{plan:{schemaVersion:Ae,...Rt(e)?{requiresRecalculation:!0}:{},pages:n},...o}}const Pn=new WeakMap;function qe(e){if(e?.aborted){const t=new Error("报表重算已取消");throw t.name="AbortError",t}}function ci(e,t){return e[t]===void 0?"":e[t]}function kf(e,t){if(t.edits.length>1e4)throw new P("limit");const r=Zo(e),n=new Set,o=[],i=t.edits.map(s=>{const a=r(s.address);if(!a?.source)throw new P("missing");const c=Mt(s);if(n.has(c))throw new P("duplicate");if(n.add(c),bf(a,s)||!Object.is(a.value,s.previousValue)||(a.cell.text??"")!==s.previousText)throw new P("conflict");return o.push(a),ei(a,s.value)});return{batch:{requestId:t.requestId,edits:i},contexts:o}}function Nf(e,t){const r=ri(e);return t.flatMap(n=>{if(!n.source)throw new P("missing");return r(n.source).map(o=>{if(!Object.is(ci(o.row,n.source.field),n.previousValue))throw new P("conflict");if(o.binding.rowKey===n.source.field)throw new P("readonly");return{row:o,field:n.source.field,value:n.value}})})}function Xt(e,t,r){const n={...e,value:t,source:{...e.source,...r?.revision===void 0?{}:{revision:r.revision},...r?.sourceToken===void 0?{}:{sourceToken:r.sourceToken}}};return n.cell={...e.cell,value:n.value,text:Qo(n,n.value)},n}function Pf(e,t,r){if(!r||r.revision===void 0&&r.sourceToken===void 0)return[...e];const n=new Set(t.edits.flatMap(o=>o.source?[ke(o.source)]:[]));return ni(e,xf(e,n,r))}function Ff(e,t,r){const n=new Set(t.edits.map(o=>ke(o.source)));for(const o of n)e.set(o,{...e.get(o),...r.revision!==void 0?{revision:r.revision}:{},...r.sourceToken!==void 0?{sourceToken:r.sourceToken}:{}});return n}function Of(e,t){let r=t.parts;const n=t.rebuild,o=[...t.validationFormulas??[]];let i=Sf(r),s=e,a;const c=new Map,u=new Map;function f(m){if(m!==s)throw new P("conflict");if(a)return a;if(!i?.())throw new P("conflict");return Ef(r)}async function d(m,h,p,w={}){qe(w.signal),h={requestId:h.requestId,edits:h.edits.map(M=>({...M,address:{...M.address},source:M.source?{...M.source}:void 0,table:M.table?{...M.table}:void 0}))},p=p.map(M=>({...M,address:{...M.address},source:M.source?{...M.source}:void 0,table:M.table?{...M.table}:void 0,cell:{...M.cell}})),await new Promise(M=>setTimeout(M,0)),qe(w.signal);const y=f(m),g=ni(y,Nf(y,h.edits)),x=oi(await n(g,w.signal),u);qe(w.signal);let b=!1,$=[],T="allow",j=!1;function v(M){return j=!0,$=Object.freeze(Zu(g,M,w.signal,o).map(S=>Object.freeze({...S}))),j=!1,T=M.warningPolicy??"allow",$}return w.validation&&v(w.validation),{plan:x,get validationIssues(){return $},validate:v,commit(M){if(qe(w.signal),b||s!==m)throw new P("conflict");if(M?.conflicts?.length)throw new P("conflict");if(j)throw new Error("候选规则校验未完成,不能提交");Xu($,T);const S=Pf(g,h,M),R=vf(x,h,M);if(M){const N=Ff(u,h,M);for(const[I,ge]of c)N.has(ke(ge.source))&&c.set(I,Xt(ge,ge.value,M))}return p.forEach((N,I)=>c.set(Mt(N),Xt(N,h.edits[I].value,M))),b=!0,a=S,r=void 0,i=void 0,s=R,Pn.set(s,l),s}}}const l={get plan(){return s},async prepare(m,h,p){const w=kf(m,h);return d(m,w.batch,w.contexts,p)},async prepareHistory(m,h,p,w,y){if(!w.trim()||h.length>1e4)throw new P("limit");const g=f(m),x=ri(g),b=Mf(m),$=new Set,j=h.map(S=>{if(!S.source)throw new P("missing");const R=Mt(S);if($.has(R))throw new P("duplicate");$.add(R);const N=b.get(R)??c.get(R);if(!N?.source)throw new P("missing");const I=x(N.source)[0];return Xt(N,ci(I.row,N.source.field))}).map((S,R)=>({context:S,edit:ei(S,h[R][p])})).filter(({edit:S})=>!Object.is(S.previousValue,S.value)),v={requestId:w,edits:j.map(({edit:S})=>S)},M=j.map(({context:S})=>S);return{batch:v,contexts:M,prepared:await d(m,v,M,y)}}};return Pn.set(e,l),l}let If=0;function ot(){return`report-${Date.now()}-${++If}`}function ve(e,t,r){if(!r?.aborted)try{const n=e?.({...t});n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{})}catch{}}function le(e){const t=e.taskId??ot(),r=(n,o,i)=>{ve(e.onEvent,{taskId:t,...e.correlationId===void 0?{}:{correlationId:e.correlationId},stage:n,status:o,...i===void 0?{}:{reportId:i}},e.signal)};return{taskId:t,progress(n,o,i){ve(e.onEvent,{taskId:t,...e.correlationId===void 0?{}:{correlationId:e.correlationId},stage:n,status:"started",completed:o,total:i},e.signal)},async run(n,o,i){r(n,"started",i);try{const s=await o();return r(n,"completed",i),s}catch(s){throw r(n,"failed",i),s}},runSync(n,o,i){r(n,"started",i);try{const s=o();return r(n,"completed",i),s}catch(s){throw r(n,"failed",i),s}}}}function G(e){throw new Error(`数据契约无效:${e}`)}function hr(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}function Rf(e){for(const t of["description","missingMeaning"])e[t]!==void 0&&!hr(e[t])&&G(`${t} 应为 1–4096 位非空字符串`);e.aggregation!==void 0&&!["sum","avg","min","max","count","none"].includes(e.aggregation)&&G("未知字段聚合语义"),e.aggregation&&!["count","none"].includes(e.aggregation)&&!["number","decimal"].includes(e.type)&&G("数值聚合仅适用于 number/decimal"),e.format!==void 0&&Cf(e),e.calculation!==void 0&&(!e.calculation||!hr(e.calculation.description)||!Array.isArray(e.calculation.dependsOn)||!e.calculation.dependsOn.length||e.calculation.dependsOn.length>256||e.calculation.dependsOn.some(t=>typeof t!="string"||!t.trim())||new Set(e.calculation.dependsOn).size!==e.calculation.dependsOn.length)&&G("计算说明需包含说明及 1–256 个唯一依赖字段")}function Cf(e){const t=e.format;if((!t||!["number","percent","date"].includes(t.kind))&&G("未知字段显示格式"),t.kind==="date"){(e.type!=="date"||t.pattern!==void 0&&(!hr(t.pattern)||t.pattern.length>128))&&G("日期格式仅适用于日期,pattern 最多 128 位");return}["number","decimal"].includes(e.type)||G("数值显示格式仅适用于 number/decimal"),t.digits!==void 0&&(!Number.isSafeInteger(t.digits)||t.digits<0||t.digits>100)&&G("显示小数位应为 0–100 的整数"),t.kind==="number"&&t.thousands!==void 0&&typeof t.thousands!="boolean"&&G("thousands 应为布尔值")}function Tf(e){const t=new Map(e.map(n=>[n.field,n])),r=new Set;for(const n of e){const o=[{field:n.field,exit:!1}],i=new Set;for(;o.length;){const s=o.pop();if(s.exit){i.delete(s.field),r.add(s.field);continue}if(i.has(s.field)&&G("字段计算依赖存在循环"),r.has(s.field))continue;const a=t.get(s.field);a||G(`计算依赖字段未声明:${s.field}`),i.add(s.field),o.push({field:s.field,exit:!0});for(const c of a.calculation?.dependsOn??[])o.push({field:c,exit:!1})}}}const jf=["text","number","boolean","date","decimal"],Df=new Set(["__proto__","prototype","constructor"]);function J(e){throw new Error(`数据契约无效:${e}`)}function ui(e){(!e||!Array.isArray(e.fields)||!e.fields.length||e.fields.length>2048)&&J("fields 应包含 1–2048 个字段");const t=new Set;for(const r of e.fields)(!r||typeof r.field!="string"||!r.field.trim()||Df.has(r.field)||t.has(r.field))&&J("字段名应安全、非空且唯一"),t.add(r.field),jf.includes(r.type)||J(`未知字段类型 ${r.type}`),Kf(r),_f(r),Rf(r),Lf(r);Bf(e,t),Tf(e.fields)}function Lf(e){e.enum!==void 0&&(!Array.isArray(e.enum)||!e.enum.length||e.enum.some(t=>!fi(t,e.type)))&&J("enum 应为匹配字段类型的非空标量数组")}function Bf(e,t){e.rowKey!==void 0&&((typeof e.rowKey!="string"||!e.rowKey.trim()||!t.has(e.rowKey))&&J("rowKey 应为引用已声明字段的非空字符串"),e.fields.find(r=>r.field===e.rowKey)?.type==="boolean"&&J("布尔字段不能作为业务主键"))}function _f(e){for(const t of["label","unit"])e[t]!==void 0&&typeof e[t]!="string"&&J(`${t} 应为字符串`);for(const t of["required","nullable"])e[t]!==void 0&&typeof e[t]!="boolean"&&J(`${t} 应为布尔值`);e.semanticRole!==void 0&&!["identifier","dimension","measure","date","text"].includes(e.semanticRole)&&J("未知字段语义")}function Kf(e){for(const t of["min","max","minLength","maxLength"]){const r=e[t];r!==void 0&&(!Number.isFinite(r)||t.includes("Length")&&(!Number.isInteger(r)||r<0))&&J(`${t} 无效`)}e.min!==void 0&&e.max!==void 0&&e.min>e.max&&J("min 不能超过 max"),e.minLength!==void 0&&e.maxLength!==void 0&&e.minLength>e.maxLength&&J("minLength 不能超过 maxLength"),e.type!=="number"&&(e.min!==void 0||e.max!==void 0)&&J("min/max 仅适用于 number,精确小数文本需业务校验"),["number","boolean"].includes(e.type)&&(e.minLength!==void 0||e.maxLength!==void 0)&&J("长度约束仅适用于文本类型")}function Wf(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return!1;const r=Number(t[1]),n=Number(t[2]),o=Number(t[3]),i=r%4===0&&(r%100!==0||r%400===0);return r>0&&n>=1&&n<=12&&o>=1&&o<=[31,i?29:28,31,30,31,30,31,31,30,31,30,31][n-1]}function fi(e,t){return t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":typeof e!="string"?!1:t==="date"?Wf(e):t==="decimal"?e.length<=1e4&&/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e):!0}function Jf(e,t){if(e==null)return t.required||e===null&&t.nullable===!1?{code:"required",message:"缺少必需字段值"}:void 0;if(!fi(e,t.type))return{code:"type",message:`值应为 ${t.type},不会自动转换原始值`};if(t.enum&&!t.enum.includes(e))return{code:"enum",message:"值不在允许的枚举中"};if(typeof e=="number"&&(t.min!==void 0&&e<t.min||t.max!==void 0&&e>t.max))return{code:"range",message:"数值超出范围"};if(typeof e=="string"&&!zf(e,t))return{code:"range",message:"文本长度超出范围"}}function zf(e,t){if(t.minLength===void 0&&t.maxLength===void 0)return!0;let r=0;for(const n of e)r++;return(t.minLength===void 0||r>=t.minLength)&&(t.maxLength===void 0||r<=t.maxLength)}function Zt(e,t){const r=e??t;if(!Number.isInteger(r)||r<1)throw new Error("数据校验预算应为正整数");return r}function Vf(e,t,r){const n=Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;if((typeof n!="string"||!n.trim())&&!(typeof n=="number"&&Number.isFinite(n)))return"业务主键应为非空字符串或有限数字";const o=JSON.stringify([typeof n,n]);if(r.has(o))return"业务主键重复";r.add(o)}function Hf(e,t,r={}){ui(t);const n=r.path??"$.rows",o=[],i=Zt(r.maxIssues,100);if(!Array.isArray(e))return{ok:!1,issues:[{code:"row",path:n,message:"数据集应为对象数组"}]};if(e.length>Zt(r.maxRows,1e5)||e.length*t.fields.length>Zt(r.maxCells,2e6))return{ok:!1,issues:[{code:"budget",path:n,message:"数据校验超出行数或单元格预算"}]};const s=new Set;for(let a=0;a<e.length&&o.length<i;a++){const c=e[a];if(!c||typeof c!="object"||Array.isArray(c)){o.push({code:"row",path:`${n}[${a}]`,rowIndex:a,message:"行应为对象"});continue}Uf(c,t,a,n,s,o,i)}return{ok:o.length===0,issues:o}}function Uf(e,t,r,n,o,i,s){for(const a of t.fields){if(i.length>=s)return;const c=Jf(Object.prototype.hasOwnProperty.call(e,a.field)?e[a.field]:void 0,a);c&&i.push({...c,rowIndex:r,field:a.field,path:`${n}[${r}].${a.field}`})}if(t.rowKey&&i.length<s){const a=Vf(e,t.rowKey,o);a&&i.push({code:"row-key",path:`${n}[${r}].${t.rowKey}`,message:a,rowIndex:r,field:t.rowKey})}}function Gf(e){return ui(e),{$schema:"https://json-schema.org/draft/2020-12/schema",type:"array",items:{type:"object",properties:Object.fromEntries(e.fields.map(r=>[r.field,Yf(r,r.field===e.rowKey)])),required:e.fields.filter(r=>r.required||r.field===e.rowKey).map(r=>r.field),additionalProperties:!0},...e.rowKey?{"x-report-rowKey":e.rowKey}:{}}}function Yf(e,t){const r=!t&&e.nullable!==!1&&!e.required;return{type:r?[Fn(e.type),"null"]:Fn(e.type),...e.label?{title:e.label}:{},...e.description?{description:e.description}:{},...e.type==="date"?{format:"date"}:{},...e.type==="decimal"?{pattern:"^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$"}:{},...e.enum?{enum:r?[...e.enum,null]:[...e.enum]}:{},...e.min===void 0?{}:{minimum:e.min},...e.max===void 0?{}:{maximum:e.max},...qf(e,t),...t&&e.type==="text"?{pattern:"\\S"}:{},...e.unit?{"x-report-unit":e.unit}:{},...e.semanticRole?{"x-report-semanticRole":e.semanticRole}:{},...e.aggregation?{"x-report-aggregation":e.aggregation}:{},...e.format?{"x-report-format":{...e.format}}:{},...e.missingMeaning?{"x-report-missingMeaning":e.missingMeaning}:{},...e.calculation?{"x-report-calculation":{description:e.calculation.description,dependsOn:[...e.calculation.dependsOn]}}:{}}}function qf(e,t){const r={};return(e.minLength!==void 0||t&&e.type!=="number")&&(r.minLength=Math.max(e.minLength??0,t?1:0)),e.type==="decimal"?r.maxLength=Math.min(e.maxLength??1e4,1e4):e.maxLength!==void 0&&(r.maxLength=e.maxLength),r}function Fn(e){return e==="text"||e==="date"||e==="decimal"?"string":e}function Xf(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e,r=n=>typeof n=="string"&&n.trim().length>0&&n.length<=256;return!r(t.datasetId)||!r(t.field)||t.tableId!==void 0&&!r(t.tableId)||t.reportScope!==void 0&&(typeof t.reportScope!="string"||!t.reportScope.trim()||t.reportScope.length>4096)?!1:t.rowKey===void 0?!0:typeof t.rowKey=="string"?t.rowKey.trim().length>0&&t.rowKey.length<=1024:typeof t.rowKey=="number"&&Number.isFinite(t.rowKey)}function Zf(e){return e==="missing-source"||e==="not-applicable"||e==="not-calculable"}function Yr(e){return e.target!==void 0&&!Xf(e.target)?!1:e.valueState===void 0||Zf(e.valueState)&&e.target!==void 0}function li(e,t,r={}){const n=new Map;for(const i of e.pages)for(const s of i.components){if(s.kind!=="list"||s.tree?.input!=="nested")continue;const a=n.get(s.dataset);if(a&&(a.childrenField??"children")!==(s.tree.childrenField??"children"))throw new Error("同一数据集的嵌套树应使用相同 childrenField");n.set(s.dataset,s.tree)}if(!n.size)return t;const o={...t};for(const[i,s]of n){const a=Math.min(s.maxRows??1e5,r.maxRows??1/0);o[i]=mo(t[i]??[],{...s,maxRows:a},r.signal)}return o}function Qf(e,t,r={}){return Object.values(li(e,t,r)).reduce((n,o)=>n+o.length,0)}function el(e,t,r){const n=Gf(r),o=e?.pages.flatMap(a=>a.components).find(a=>a.kind==="list"&&a.dataset===t&&a.tree?.input==="nested");if(!o||o.kind!=="list"||!o.tree)return n;const i=n.items,s=o.tree.childrenField??"children";return{...n,items:{$ref:"#/$defs/treeNode"},$defs:{treeNode:{...i,properties:{...i.properties,[s]:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/treeNode"}}]}}}}}}function qr(e,t){return JSON.stringify([e,t])}function di(e,t,r){return r===void 0?qr(e,t):JSON.stringify(["shared",r])}function mi(e,t,r){return e.map(n=>{const o=n.table?{...n.table,id:r(n.table.id),...n.table.source?{source:{...n.table.source,sourceScope:t}}:{}}:void 0,i=n.grid?.cells.map(s=>s.map(a=>!a||!a.source&&!a.children?a:{...a,...a.source?{source:{...a.source,sourceScope:t}}:{},...a.children?{children:mi(a.children,t,r)}:{}}));return o||i?{...n,...o?{table:o}:{},...i?{grid:{...n.grid,cells:i}}:{}}:n})}function gr(e){return Ot(e.maxChartComponents),{maxPages:e.maxPages,maxCells:e.maxCells,maxChartComponents:e.maxChartComponents??Rr,usedPages:0,usedCells:0,usedChartComponents:0}}function tl(e,t){if(!e.repeat)return!1;const r=Object.prototype.hasOwnProperty.call(t,e.repeat.dataset)?t[e.repeat.dataset]:void 0;return Array.isArray(r)&&r.length===0}function rl(e){const t=r=>r.grid?.cells.reduce((n,o)=>n+o.reduce((i,s)=>i+(s?1+(s.children?.reduce((a,c)=>a+t(c),0)??0):0),0),0)??0;return e.pages.reduce((r,n)=>r+n.components.reduce((o,i)=>o+t(i),0),0)}function pr(e,t){return e===void 0?void 0:e-t}function Qt(e,t){return e===void 0?t:Math.max(1,Math.min(e,t??e))}function hi(e,t,r,n,o){Ot(e?.maxChartComponents);const i=pr(t.maxPages,t.usedPages),s=t.maxChartComponents-t.usedChartComponents;if(i!==void 0&&i<1&&r.pages.length&&!tl(r,n))throw new $e(0,1);if(s<1&&r.pages.some(a=>a.components.some(c=>c.kind!=="list"&&c.chartBinding)))throw new Ke(s,1);return{...e,signal:o??e?.signal,maxPages:Qt(i,e?.maxPages),maxCells:Qt(pr(t.maxCells,t.usedCells),e?.maxCells),maxChartComponents:Qt(s,e?.maxChartComponents)}}function gi(e,t){const r=rl(t.plan),n=pr(e.maxCells,e.usedCells);if(n!==void 0&&r>n)throw new _e(n,r);e.usedPages+=t.plan.pages.length,e.usedCells+=r,e.usedChartComponents+=t.chartComponents}function pi(e,t){return e instanceof $e&&t.maxPages!==void 0&&(e.limit===t.maxPages-t.usedPages||e.limit===0)?new $e(t.maxPages,t.usedPages+e.actual):e instanceof _e&&t.maxCells!==void 0?new _e(t.maxCells,t.usedCells+e.actual):e instanceof Ke&&e.limit===t.maxChartComponents-t.usedChartComponents?new Ke(t.maxChartComponents,t.usedChartComponents+e.estimated):e}class E extends Error{constructor(t,r,n){super(r),this.name="ReportSourceError",this.code=t,this.cause=n}}function Kt(e){const t=new Error("报表加载已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function X(e){if(e?.aborted)throw Kt(e)}function yr(e,t){return t?new Promise((r,n)=>{const o=()=>t.removeEventListener("abort",i),i=()=>{o(),n(Kt(t))};t.addEventListener("abort",i,{once:!0}),t.aborted&&i(),Promise.resolve(e).then(s=>{o(),r(s)},s=>{o(),n(s)})}):Promise.resolve(e)}function nl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new E("validate",`报表 ${t} 的数据集应为对象`);for(const[r,n]of Object.entries(e))if(!Array.isArray(n)||n.some(o=>!o||typeof o!="object"||Array.isArray(o)))throw new E("validate",`报表 ${t} 的数据集 ${r} 应为对象数组`)}async function ol(e,t,r){const{reportId:n,signal:o}=t;try{const i=await yr(e(t),o);X(o);const s=zu(i);if(!s.ok)throw new E("validate",`报表 ${n} 模板校验失败:${s.errors.slice(0,3).map(a=>`${a.path}: ${a.message}`).join("; ")}`);return r.push(...s.warnings.map(a=>`${n}: ${a.path}: ${a.message}`)),i}catch(i){throw o?.aborted?Kt(o):i instanceof E?i:i instanceof ku?new E("validate",`报表 ${n} 模板校验失败:${i.message}`,i):new E("fetch",`报表 ${n} 模板加载失败:${i instanceof Error?i.message:String(i)}`,i)}}async function il(e,t,r,n){const o=t.signal;let i;try{if(e.load)i=await yr(e.load(t),o);else if(e.provider){const s=await yr(e.provider.query(t),o);X(o),sl(s,r),i=s.datasets,n?.(r,s)}else i=e.datasets??{}}catch(s){throw o?.aborted?Kt(o):s instanceof E?s:new E("fetch",`报表 ${r} 取数失败:${s instanceof Error?s.message:String(s)}`,s)}return X(o),i}function sl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new E("validate",`报表 ${t} Provider 应返回 datasets 结果对象`);for(const r of["revision","sourceToken"])if(e[r]!==void 0&&typeof e[r]!="string")throw new E("validate",`报表 ${t} Provider ${r} 应为字符串`);if(e.diagnostics!==void 0&&(!Array.isArray(e.diagnostics)||e.diagnostics.some(r=>!r||typeof r.code!="string"||typeof r.message!="string"||!["info","warning","error"].includes(r.severity))))throw new E("validate",`报表 ${t} Provider diagnostics 不符合结构化诊断契约`);if(e.diagnostics?.some(r=>!Yr(r)))throw new E("validate",`报表 ${t} Provider 数据说明缺少有效的字段身份或值状态`)}function al(e,t,r,n,o){try{t=li(n,t,{maxRows:e.dataValidation?.maxRows,signal:o})}catch(i){throw new E("validate",`报表 ${r} 树形数据无效:${i instanceof Error?i.message:String(i)}`,i)}for(const[i,s]of Object.entries(e.dataSchema??{})){let a;try{a=Hf(Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0,s,{...e.dataValidation,path:`$.datasets.${i}`})}catch(c){throw new E("config",`报表 ${r} 数据集 ${i} 字段契约配置无效`,c)}if(!a.ok)throw new E("validate",`报表 ${r} 数据集 ${i} 不符合字段契约:${a.issues[0]?.message}`,{issues:a.issues})}}function cl(e,t,r,n,o,i){try{const s=hi(r.pagination,o,e,t,i),a=Oc(e,t,s);return gi(o,a),a}catch(s){const a=pi(s,o);throw new E("validate",`报表 ${n} 排版失败:${a instanceof Error?a.message:String(a)}`,a)}}function yi(e,t,r,n,o){const i=new Map,s=a=>{let c=i.get(a);return c===void 0&&(c=JSON.stringify([r,n,a]),i.set(a,c)),c};for(const a of t.pages)e.push({...a,meta:{...a.meta,reportScope:qr(r,n)},components:mi(a.components,o??di(r,n),s)})}async function ul(e,t,r,n,o){const i=[],s=gr(n);for(const[u,f]of e.entries()){X(o);try{const d=await Af(f.template,f.datasets,hi(t[u]?.pagination,s,f.template,f.datasets,o));gi(s,d),yi(i,d.plan,u,r[u],f.sourceScope)}catch(d){throw pi(d,s)}}const a={schemaVersion:Ae,...e.some(u=>Rt(u.template))?{requiresRecalculation:!0}:{},pages:i},c=Ue(a);if(!c.ok)throw new E("validate",`重算渲染计划校验失败:${c.errors[0]?.message}`);return a}function fl(e,t={}){if(t.maxPages!==void 0&&(!Number.isSafeInteger(t.maxPages)||t.maxPages<1))throw new E("config","maxPages 应为正安全整数");if(t.maxCells!==void 0&&(!Number.isSafeInteger(t.maxCells)||t.maxCells<1))throw new E("config","maxCells 应为正安全整数");try{gr(t)}catch(o){throw new E("config","maxChartComponents 应为 1..1000000 的安全整数",o)}function r(o){const i=Object.prototype.hasOwnProperty.call(e,o)?e[o]:void 0;if(!i)throw new E("config",`未注册报表 ${o}`);if(i.sourceScope!==void 0&&(typeof i.sourceScope!="string"||!i.sourceScope.trim()||i.sourceScope.length>512))throw new E("config","sourceScope 应为不超过 512 字符的非空字符串");return i}return Object.assign(async({reportIds:o,params:i,signal:s,onWarning:a,onQueryResult:c,...u})=>{X(s);const f=le({...u,signal:s}),d=[...o],l={...i};if(d.length===0)throw new E("config","缺少报表 ID");const m=d.map(r),h=f.runSync("validate",()=>m.map(v=>$n(v.params??(typeof v.template=="function"?[]:v.template.params)??[],l))),p=[],w=[],y=gr(t),g=[];for(const[v,M]of m.entries()){X(s);const S=d[v],R={reportId:S,params:h[v],signal:s},N=typeof M.template=="function"?await f.run("query",()=>ol(M.template,R,g),S):M.template;R.params=f.runSync("validate",()=>$n(M.params??N.params??[],R.params),S);const I=await f.run("query",()=>il(M,R,S,(zt,zi)=>c?.(zt,zi,v)),S);f.runSync("validate",()=>{nl(I,S),t.onDatasets?.(S,I,N),al(M,I,S,N,s)},S),X(s);const ge=f.runSync("layout",()=>cl(N,I,M,S,y,s),S),Qr=di(v,S,M.sourceScope);w.push({template:N,datasets:I,sourceScope:Qr}),yi(p,ge.plan,v,S,Qr),g.push(...ge.warnings.map(zt=>`${S}: ${zt}`))}X(s);const x={schemaVersion:Ae,...w.some(v=>Rt(v.template))?{requiresRecalculation:!0}:{},pages:p},b=f.runSync("validate",()=>{const v=Ue(x);if(!v.ok)throw new E("validate",`渲染计划校验失败:${v.errors.slice(0,3).map(M=>`${M.path}: ${M.message}`).join("; ")}`);return v});g.push(...b.warnings.map(v=>`${v.path}: ${v.message}`));const $=m.map(v=>({...v,pagination:{...v.pagination}})),T={maxPages:t.maxPages,maxCells:t.maxCells,maxChartComponents:t.maxChartComponents};try{Of(x,{parts:w,validationFormulas:$.map(v=>v.pagination?.formula),rebuild:(v,M)=>ul(v,$,d,T,M)})}catch{g.push("来源数据无法建立本地重算口径;当前预览仅支持计划内编辑,请使用可序列化模板数据启用规则重算")}const j=a??t.onWarning??(v=>console.warn("[mach-report]",v));for(const v of g)X(s),j(v);return X(s),x},{getParamDefs:o=>vt(e,o)})}const Xr=Object.freeze({maxRows:1e5,maxPages:1e4,maxCells:2e6,maxChartComponents:5e4,maxOutputBytes:1e8,maxPreparedBytes:64e6,maxDurationMs:12e4});class L extends Error{constructor(t,r,n){super(r),this.code=t,this.path=n,this.name="ReportRuntimeError"}}function O(e){if(!e?.aborted)return;if(e.reason instanceof L)throw e.reason;const t=new Error("报表执行已取消");throw t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function B(e,t,r){if(!Number.isFinite(r)||r<0)throw new L("budget",`${t} 的执行统计无效`,`$.budget.${t}`);const n=e[t];if(n!==void 0&&r>n)throw new L("budget",`${t} 超出预算 ${n}(实际 ${r})`,`$.budget.${t}`)}function wi(e){for(const[t,r]of Object.entries(e)){if(r!==void 0&&(!Number.isFinite(r)||r<=0))throw new L("budget",`${t} 应为正有限数字`,`$.budget.${t}`);if(t!=="maxDurationMs"&&r!==void 0&&!Number.isSafeInteger(r))throw new L("budget",`${t} 应为正安全整数`,`$.budget.${t}`);if(t==="maxDurationMs"&&r!==void 0&&r>2147483647)throw new L("budget","maxDurationMs 不能超过 2147483647",`$.budget.${t}`);if(t==="maxChartComponents"&&r!==void 0&&r>1e6)throw new L("budget","maxChartComponents 不能超过 1000000","$.budget.maxChartComponents")}}async function Re(e,t,r){const n=new AbortController,o=()=>n.abort(e?.reason);e?.addEventListener("abort",o,{once:!0}),e?.aborted&&o();const i=Date.now(),s=t===void 0?void 0:setTimeout(()=>n.abort(new L("timeout",`报表执行超过 ${t}ms`)),t);let a;try{O(n.signal);const c=new Promise((f,d)=>{a=()=>{try{O(n.signal)}catch(l){d(l)}},n.signal.addEventListener("abort",a,{once:!0})}),u=await Promise.race([r(n.signal),c]);if(O(n.signal),t!==void 0&&Date.now()-i>t)throw new L("timeout",`报表执行超过 ${t}ms`);return u}finally{s!==void 0&&clearTimeout(s),a&&n.signal.removeEventListener("abort",a),e?.removeEventListener("abort",o)}}function bi(e,t){de.assertOutputActive(t.signal),de.observeOutput(()=>t.onDiagnostic?.(e)),de.assertOutputActive(t.signal)}class ll extends Error{constructor(t){super(`Output contains ${t.length} known fidelity issue(s): ${t[0]?.code}`),this.diagnostics=t,this.code="output-fidelity",this.name="OutputFidelityError"}}class Wt extends Error{constructor(t,r){super(r),this.code=t,this.name="ImageMediaError"}}const er={maxImageBytes:16*1024*1024,maxTotalImageBytes:32*1024*1024,maxImages:1e3,maxImagePixels:16e6,maxTotalImagePixels:64e6,maxImageDimension:16384};function ee(e){throw new Wt("invalid-image-data",e)}function Ce(e){throw new Wt("image-budget-exceeded",e)}function dl(e){const t={...er};for(const r of Object.keys(er)){const n=e[r]??er[r];if(!Number.isSafeInteger(n)||n<=0||n>2147483647)throw new RangeError(`${r} 图片预算须为1至2147483647的整数。`);t[r]=n}return t}function ml(e){if(e.length<33||![137,80,78,71,13,10,26,10].every((r,n)=>e[n]===r))return ee("图片内容与 PNG/JPEG 类型不一致。");const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return t.getUint32(8)!==13||String.fromCharCode(...e.subarray(12,16))!=="IHDR"?ee("PNG must begin with an IHDR header."):[t.getUint32(16),t.getUint32(20)]}const hl=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function gl(e){if(e[0]!==255||e[1]!==216)return ee("图片内容与 PNG/JPEG 类型不一致。");let t=2;for(;t+3<e.length;){if(e[t++]!==255)return ee("JPEG marker is malformed.");for(;e[t]===255;)t++;const r=e[t++];if(r===217||r===218)break;if(r===1||r>=208&&r<=215)continue;const n=e[t]*256+e[t+1];if(n<2||t+n>e.length)return ee("JPEG segment exceeds its data boundary.");if(hl.has(r))return n<8?ee("JPEG frame header is incomplete."):[e[t+5]*256+e[t+6],e[t+3]*256+e[t+4]];t+=n}return ee("JPEG has no supported dimension header.")}function pl(e,t){if(e.length>Math.ceil(t.maxImageBytes/3)*4+64)return Ce("单张图片超过字节预算。");const r=/^data:image\/(png|jpe?g);base64,([A-Za-z0-9+/]+={0,2})$/i.exec(e);if(!r||r[2].length%4)return ee("Image must contain valid PNG/JPEG base64 data.");const n=r[2],o=n.length/4*3-(n.endsWith("==")?2:n.endsWith("=")?1:0);if(o>t.maxImageBytes)return Ce("单张图片超过字节预算。");const i=r[1].toLowerCase()==="png"?"png":"jpeg",s=atob(n),a=new Uint8Array(o);for(let f=0;f<o;f++)a[f]=s.charCodeAt(f);const[c,u]=i==="png"?ml(a):gl(a);return!c||!u?ee("Image dimensions must be positive."):c>t.maxImageDimension||u>t.maxImageDimension||c*u>t.maxImagePixels?Ce("Image exceeds its decoded dimension or pixel budget."):{dataUrl:`data:image/${i};base64,${n}`,bytes:a,extension:i,width:c,height:u}}function yl(e={}){const t=dl(e),r=new Map;let n=0,o=0;return i=>{const s=i.replace(/^data:image\/(png|jpe?g);base64,/i,(u,f)=>`data:image/${f.toLowerCase()==="png"?"png":"jpeg"};base64,`),a=r.get(s);if(a)return a;if(r.size>=t.maxImages)return Ce("唯一图片数量超过预算。");const c=pl(i,t);return n+c.bytes.length>t.maxTotalImageBytes||o+c.width*c.height>t.maxTotalImagePixels?Ce("图片总字节或总像素超过预算。"):(n+=c.bytes.length,o+=c.width*c.height,r.set(s,c),c)}}class Zr extends Error{constructor(t,r){super(t.message),this.name="OutputAssetError",this.diagnostic=t,this.cause=r}}function St(e){if(e.aborted)throw e.reason??new DOMException("The operation was aborted.","AbortError")}function wl(e){const t={maxAssets:1e3,maxImageBytes:33554432,maxTotalImageBytes:134217728,maxDurationMs:3e4,...e.assetBudget};for(const[r,n]of Object.entries(t))if(!Number.isSafeInteger(n)||n<=0||n>2147483647)throw new RangeError(`${r} must be a positive safe integer at most 2147483647.`);return t}function bl(e){const t=/^data:image\/[a-z0-9.+-]+(;base64)?,(.*)$/is.exec(e);if(!t)throw new TypeError("Asset renderers must return an image data URL.");return t[1]?Math.ceil(t[2].length*3/4):new TextEncoder().encode(decodeURIComponent(t[2])).byteLength}function Xe(e,t,r,n,o){const i={code:r,message:n,severity:"warning",format:e.options.format??"dom",pageIndex:t.pageIndex,componentIndex:t.componentIndex,componentPath:t.componentPath,kind:t.component.kind,nid:t.component.nid};if(e.diagnostics.push(i),bi(i,{...e.options,signal:e.signal}),e.options.assetFailure!=="placeholder")throw new Zr(i,o)}async function xl(e,t,r){const n=e.options.assetRegistry?.rendererFor(t)??e.options.assetRenderers?.[t.kind];if(t.imageData||!n)return t.imageData;if(++e.rendered>e.budget.maxAssets)return Xe(e,r,"asset-budget-exceeded","Output exceeded the asset count budget.");let o;try{if(e.active=r,o=await de.waitForOutput(n({...r,signal:e.signal}),e.signal),St(e.signal),o.length>e.budget.maxImageBytes*4+1024)return Xe(e,r,"asset-budget-exceeded","Output exceeded the image payload byte budget.");const i=bl(o);if(i>e.budget.maxImageBytes||e.bytes+i>e.budget.maxTotalImageBytes)return Xe(e,r,"asset-budget-exceeded","Output exceeded the encoded image byte budget.");/^data:image\/(png|jpe?g);base64,/i.test(o)&&e.inspectImage(o),e.bytes+=i}catch(i){if(e.signal.aborted||i instanceof Zr||i instanceof Wt&&i.code==="image-budget-exceeded")throw i;return Xe(e,r,"asset-render-failed",`Asset renderer failed for ${t.kind}; output was not silently omitted.`,i)}return o}function vl(e,t){const r=e.active;if(!r){t.abort(new Error("Asset rendering exceeded maxDurationMs."));return}const n={code:"asset-budget-exceeded",message:"Asset rendering exceeded maxDurationMs.",severity:"warning",format:e.options.format??"dom",pageIndex:r.pageIndex,componentIndex:r.componentIndex,componentPath:r.componentPath,kind:r.component.kind,nid:r.component.nid};e.diagnostics.push(n);try{bi(n,{...e.options,signal:e.signal})}catch(o){t.abort(o);return}t.abort(new Zr(n))}async function Ml(e,t,r,n,o){if(!t?.children?.length)return t;const i=[];for(const[s,a]of t.children.entries())i.push(await xi(e,a,{...r,component:a,componentPath:[...n,s]},o));return i.some((s,a)=>s!==t.children[a])?{...t,children:i}:t}async function xi(e,t,r,n){if(St(e.signal),n.has(t))throw new TypeError("Cyclic grid children cannot be rendered.");let o=e.cache.get(t);o||(o=xl(e,t,r),e.cache.set(t,o));const i=await o;St(e.signal);let s=t.grid;if(s){const a=new Set(n).add(t),c=[];for(const[u,f]of s.cells.entries()){const d=[];for(const[l,m]of f.entries())d.push(await Ml(e,m,r,[...r.componentPath,u,l],a));c.push(d)}c.some((u,f)=>u.some((d,l)=>d!==s.cells[f][l]))&&(s={...s,cells:c})}return i!==t.imageData||s!==t.grid?{...t,imageData:i,grid:s}:t}function $l(e,t,r){const n=new Set,o=i=>{if(de.assertOutputActive(r),!n.has(i)){if(n.add(i),i.imageData&&/^data:image\/(png|jpe?g);base64,/i.test(i.imageData))try{t(i.imageData)}catch(s){if(!(s instanceof Wt)||s.code==="image-budget-exceeded")throw s}for(const s of i.grid?.cells??[])for(const a of s)for(const c of a?.children??[])o(c)}};for(const i of e.pages)for(const s of i.components)o(s)}function Sl(e){if(e.options.fidelity==="strict"&&e.diagnostics.length)throw new ll(e.diagnostics)}async function On(e,t={}){de.assertOutputActive(t.signal),jc(e);const r=wl(t),n=yl(t);if($l(e,n,t.signal),t.signal?.aborted)throw t.signal.reason??new DOMException("The operation was aborted.","AbortError");const o=new AbortController,i=()=>o.abort(t.signal?.reason);if(t.signal?.addEventListener("abort",i,{once:!0}),!t.assetRegistry&&(!t.assetRenderers||!Object.keys(t.assetRenderers).length))return t.signal?.removeEventListener("abort",i),{plan:e,diagnostics:[]};const s={options:t,signal:o.signal,diagnostics:[],rendered:0,bytes:0,budget:r,cache:new WeakMap,inspectImage:n},a=setTimeout(()=>vl(s,o),r.maxDurationMs);try{const c=[];for(const[u,f]of e.pages.entries()){if(u<(t.start??0)||u>(t.end??e.pages.length-1)){c.push(f);continue}const d=[];for(const[l,m]of f.components.entries())d.push(await xi(s,m,{component:m,pageIndex:u,componentIndex:l,componentPath:[]},new Set));c.push(d.some((l,m)=>l!==f.components[m])?{...f,components:d}:f)}return St(s.signal),Sl(s),{plan:c.some((u,f)=>u!==e.pages[f])?{...e,pages:c}:e,diagnostics:s.diagnostics}}finally{clearTimeout(a),t.signal?.removeEventListener("abort",i)}}function Et(e=[]){return e.map(({code:t,message:r,severity:n,pageIndex:o,componentIndex:i})=>({code:t,message:r,severity:n,path:i<0?`$.pages.${o}`:`$.pages.${o}.components.${i}`}))}async function In(e,t,r=Date.now()){const n=e.prepared;if(e.fidelity==="strict"&&n.diagnostics.some(d=>d.code==="asset-render-failed"||d.code==="asset-budget-exceeded"))throw new E("validate","严格输出拒绝已有资产渲染降级,请修复组件后重新准备报表。");const o=e.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;O(e.signal);const i=e.pdf?.customFontFaces??(e.pdf?.customFontBytes?{regular:e.pdf.customFontBytes}:void 0),s=o&&i?o.createFontBytesMeasurer(i):void 0,a=le(e),c=await a.run("encode",async()=>{let d;if(e.format==="pdf"){O(e.signal);const l=await o.renderPlanToPdf(n.plan,{...e.pdf,...s?{measurer:s}:{},fidelity:e.fidelity,signal:e.signal,onProgress:(m,h)=>a.progress("encode",m,h)});d=l.bytes,n.diagnostics.push(...Et(l.diagnostics)),n.diagnostics.push(...l.fidelityWarnings.map(m=>({code:"pdf-fidelity",message:m,severity:"warning"})),...l.pageErrors.map(m=>({code:"pdf-page",message:m,severity:"error"}))),l.unsupportedTextCount&&n.diagnostics.push({code:"pdf-font",message:`${l.unsupportedTextCount} 段文本包含当前字体不支持的字符`,severity:"warning"})}else{const{renderPlanToXlsx:l}=await import("@agile-team/mach-report/xlsx");O(e.signal);const m=await l(n.plan,{...e.xlsx,fidelity:e.fidelity,signal:e.signal,onProgress:(h,p)=>a.progress("encode",h,p)});d=new Uint8Array(m.buffer),n.diagnostics.push(...Et(m.diagnostics)),n.diagnostics.push(...m.warnings.map(h=>({code:"xlsx-fidelity",message:h,severity:"warning"}))),n.diagnostics.push(...(m.notes??[]).map(h=>({code:"xlsx-snapshot",message:h,severity:"info"})))}return O(e.signal),d});B(t,"maxOutputBytes",c.byteLength);const{plan:u,...f}=n;return{...f,bytes:c,format:e.format,contentType:e.format==="pdf"?"application/pdf":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",stats:{...f.stats,durationMs:Date.now()-r,outputBytes:c.byteLength}}}function vi(e,t){const r=t.maxNodes??1e6;if(![t.maxBytes,r].every(f=>Number.isSafeInteger(f)&&f>0))throw t.error("budget","快照预算应为正安全整数");let n=0,o=0;const i=new Set;function s(f){if(o+=f,o>t.maxBytes)throw t.error("budget","快照超过字节预算")}function a(f,d){if(++n>r||d>64)throw t.error("budget","快照节点或深度超过预算");if(n%1024===0&&t.check?.(),typeof f=="string")return s(f.length+2),f;if(f===null||typeof f=="boolean"||typeof f=="number"&&Number.isFinite(f))return s(String(f).length),f;if(!f||typeof f!="object"||i.has(f))throw t.error("input","快照应为无循环的有限 JSON 值");return c(f,d)}function c(f,d){const l=Array.isArray(f),m=Object.getPrototypeOf(f);if(m!==(l?Array.prototype:Object.prototype)&&!(m===null&&!l)||Object.getOwnPropertySymbols(f).length)throw t.error("input","快照应为普通 JSON 对象");const h=Object.getOwnPropertyNames(f).filter(y=>!(l&&y==="length"));if(l&&(h.length!==f.length||h.some((y,g)=>y!==String(g))))throw t.error("input","快照数组应为连续数组");i.add(f),s(2);const p=Object.create(null);let w=0;for(const y of h){const g=Object.getOwnPropertyDescriptor(f,y);if(g.get||g.set||!g.enumerable||["__proto__","constructor","prototype"].includes(y))throw t.error("input","快照不允许访问器或危险键");g.value===void 0&&!l||(s((w++?1:0)+(l?0:y.length+3)),p[y]=a(g.value===void 0?null:g.value,d+1))}return i.delete(f),l?h.map(y=>p[y]):p}t.check?.();const u=JSON.stringify(a(e,0));if(new TextEncoder().encode(u).byteLength>t.maxBytes)throw t.error("budget","快照超过字节预算");return JSON.parse(u)}const El=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Z=(e,t)=>e>>>t|e<<32-t;function Mi(e,t,r){const n=new DataView(e.buffer,e.byteOffset+t,64);for(let o=0;o<16;o++)r[o]=n.getUint32(o*4);for(let o=16;o<64;o++){const i=r[o-15],s=r[o-2],a=Z(i,7)^Z(i,18)^i>>>3,c=Z(s,17)^Z(s,19)^s>>>10;r[o]=r[o-16]+a+r[o-7]+c}}function $i(e,t){let r=e[0],n=e[1],o=e[2],i=e[3],s=e[4],a=e[5],c=e[6],u=e[7];for(let f=0;f<64;f++){const d=Z(s,6)^Z(s,11)^Z(s,25),l=s&a^~s&c,m=u+d+l+El[f]+t[f]>>>0,h=Z(r,2)^Z(r,13)^Z(r,22),p=r&n^r&o^n&o,w=h+p>>>0;u=c,c=a,a=s,s=i+m>>>0,i=o,o=n,n=r,r=m+w>>>0}e[0]=e[0]+r,e[1]=e[1]+n,e[2]=e[2]+o,e[3]=e[3]+i,e[4]=e[4]+s,e[5]=e[5]+a,e[6]=e[6]+c,e[7]=e[7]+u}function Si(e){const t=new Uint8Array(Math.ceil((e.byteLength+9)/64)*64);t.set(e),t[e.byteLength]=128;const r=new DataView(t.buffer);return r.setUint32(t.length-8,Math.floor(e.byteLength/536870912)),r.setUint32(t.length-4,e.byteLength*8>>>0),t}const Ei=()=>new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ai=e=>Array.from(e,t=>t.toString(16).padStart(8,"0")).join("");function Rn(e){const t=Si(e),r=Ei(),n=new Uint32Array(64);for(let o=0;o<t.length;o+=64)Mi(t,o,n),$i(r,n);return Ai(r)}async function Al(e){const t=Si(e),r=Ei(),n=new Uint32Array(64);for(let o=0;o<t.length;o+=64)o>0&&o%262144===0&&await new Promise(i=>setTimeout(i,0)),Mi(t,o,n),$i(r,n);return Ai(r)}function wr(e){return e&&{...e}}function Te(e){if(!e)return;const t=r=>{if(!(r instanceof Uint8Array)&&!(r instanceof ArrayBuffer))throw new E("validate","字体应为 Uint8Array 或 ArrayBuffer");if(r.byteLength>32e6)throw new L("budget","单份字体超过 32 MB","$.pdf");return new Uint8Array(r instanceof Uint8Array?r:new Uint8Array(r))};if(e.customFontFaces){const r=e.customFontFaces;return{customFontName:e.customFontName,customFontFaces:{regular:t(r.regular),...r.bold?{bold:t(r.bold)}:{},...r.italic?{italic:t(r.italic)}:{},...r.boldItalic?{boldItalic:t(r.boldItalic)}:{}}}}return{customFontName:e.customFontName,...e.customFontBytes?{customFontBytes:t(e.customFontBytes)}:{}}}function ki(e){const t=e?.customFontFaces??(e?.customFontBytes?{regular:e.customFontBytes}:void 0);if(!t)return;const r=["regular","bold","italic","boldItalic"].map(n=>{const o=t[n];if(!o)return[n,null];const i=o instanceof Uint8Array?o:new Uint8Array(o);if(i.byteLength>32e6)throw new L("budget","单份字体超过 32 MB","$.pdf");return[n,Rn(i)]});return Rn(new TextEncoder().encode(JSON.stringify(r)))}const br=new WeakMap;function kl(e,t,r){const n=Ni(e,t,r);let o=!0;return{prepared:n,forward(){if(!o)throw new Error("报表快照只能交接一次");return o=!1,br.set(n,t),n}}}function Ni(e,t,r){if(O(r),!Number.isSafeInteger(t)||t<=0)throw new L("budget","快照预算应为正安全整数","$.budget.maxPreparedBytes");const n=br.get(e);if(br.delete(e),n!==void 0&&n<=t)return e;const o=vi(e,{maxBytes:t,maxNodes:t,check:()=>O(r),error:(i,s)=>i==="budget"?new L("budget",s,"$.budget.maxPreparedBytes"):new E("validate",s)});return Fi(o),o}function Pi(e){if(e===void 0)return!0;if(!Array.isArray(e))return!1;const t=new Set;return e.every(r=>!r||typeof r!="object"||Array.isArray(r)||typeof r.reportId!="string"||!r.reportId.trim()||!Number.isSafeInteger(r.reportIndex)||r.reportIndex<0||t.has(r.reportIndex)||typeof r.reportScope!="string"||!r.reportScope.trim()||r.reportScope.length>4096||r.revision!==void 0&&typeof r.revision!="string"||r.sourceToken!==void 0&&typeof r.sourceToken!="string"?!1:(t.add(r.reportIndex),!0))}function Fi(e){if(!Pi(e.sources))throw new E("validate","准备结果来源清单无效");if(!e?.stats||["rows","pages","cells"].some(t=>!Number.isSafeInteger(e.stats[t])||e.stats[t]<0)||!Number.isFinite(e.stats.durationMs)||e.stats.durationMs<0)throw new E("validate","准备结果统计无效");if(!Array.isArray(e.diagnostics)||e.diagnostics.some(t=>!t||typeof t.code!="string"||typeof t.message!="string"||!["info","warning","error"].includes(t.severity)||!Yr(t)))throw new E("validate","准备结果诊断无效");if(!e.revisions||typeof e.revisions!="object"||Array.isArray(e.revisions)||Object.values(e.revisions).some(t=>!t||typeof t!="object"||t.revision!==void 0&&typeof t.revision!="string"||t.sourceToken!==void 0&&typeof t.sourceToken!="string"))throw new E("validate","准备结果修订无效");if(e.layout&&(!["heuristic","provided","font-bytes"].includes(e.layout.textMetrics)||e.layout.fontFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(e.layout.fontFingerprint)))throw new E("validate","准备结果字体度量标识无效")}function Nl(e){if(e.layoutPolicy!==void 0&&!["verify","preserve"].includes(e.layoutPolicy))throw new E("validate","无效的 layoutPolicy");if(e.format!=="pdf")return;if(e.layoutPolicy==="preserve"&&!e.prepared.layout?.fontFingerprint){e.prepared.diagnostics.push({code:"prepared-layout-preserved",severity:"info",message:"显式保持现有分页与几何;未验证排版字体身份,实际 PDF 输出仍遵循 fidelity 校验。"});return}const t=e.prepared.layout?.fontFingerprint,r=ki(e.pdf);if(t===r&&(t!==void 0||e.prepared.layout?.textMetrics==="heuristic"&&!r))return;const n="已准备计划的字体度量无法与本次 PDF 字体确认一致;保持现有分页,未重新查询或排版。请在 prepare 和 exportPrepared 提供相同字体字节。";if(e.fidelity==="strict")throw new E("validate",n);e.prepared.diagnostics.push({code:"prepared-font-metrics",severity:"warning",message:n})}function Cn(e){return{...e,reportIds:[...e.reportIds],...e.params?{params:{...e.params}}:{}}}function Oi(e,t){if(t.length===0)throw new E("config","缺少报表 ID");return t.map(r=>{if(!Object.prototype.hasOwnProperty.call(e,r))throw new E("config",`未注册报表 ${r}`);return e[r]})}function Jt(e){return e.grid?.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+Jt(s),0)??0):0),0),0)??0}function Pl(e,t,r){return e.pages.reduce((n,o)=>n+o.components.reduce((i,s)=>s.kind!=="list"?i+Jt(s):i+Cc(s,t,r),0),0)}function Fl(e,t=Object.keys(e)){return Oi(e,t).map((r,n)=>{const o=t[n],i=vt(e,[o]);return{id:o,params:JSON.parse(JSON.stringify(i)),paramsSchema:Mu(i),datasetsSchema:Object.fromEntries(Object.entries(r.dataSchema??{}).map(([s,a])=>[s,el(typeof r.template=="function"?void 0:r.template,s,a)])),capabilities:{save:!!r.provider?.save,export:!!r.provider?.export,templates:!!r.provider?.templates}}})}function Ii(e,t){Oi(e,t.reportIds);const r=lr(vt(e,t.reportIds),t.params),n=t.reportIds.flatMap(i=>lr(vt(e,[i]),t.params).issues),o=new Map(n.map(i=>[JSON.stringify(i),i]));return{...r,ok:o.size===0,issues:[...o.values()]}}function xr(e,t){const r=Ue(e.plan);if(!r.ok)throw new E("validate",`执行器返回无效计划:${r.errors[0]?.path}`);const n=e.plan.pages.length,o=e.plan.pages.reduce((i,s)=>i+s.components.reduce((a,c)=>a+Jt(c),0),0);return B(t,"maxRows",e.stats.rows),B(t,"maxPages",n),B(t,"maxCells",o),{...e,stats:{...e.stats,pages:n,cells:o}}}function Tn(e,t){const r=Ii(e.reports,t);if(!r.ok)throw new Bt(r.issues)}function Ri(e){const t={...Xr,...e.budget};wi(t);const r=async(o,i)=>{const s=Date.now();let a=0,c=0;const u=[],f={},d=[],l=Object.fromEntries(Object.entries(e.reports).map(([b,$])=>[b,{...$,pagination:{...e.pagination,...$.pagination,...i?{measurer:i}:{}},dataValidation:{...$.dataValidation,maxRows:Math.min(t.maxRows??1e5,$.dataValidation?.maxRows??1/0),maxCells:Math.min(t.maxCells??2e6,$.dataValidation?.maxCells??1/0)}}])),h=await fl(l,{maxPages:t.maxPages,maxCells:t.maxCells,maxChartComponents:t.maxChartComponents,onDatasets:(b,$,T)=>{try{a+=Qf(T,$,{maxRows:t.maxRows,signal:o.signal})}catch(j){throw j instanceof oo?new L("budget",j.message,"$.budget.maxRows"):j}B(t,"maxRows",a),c+=Pl(T,$,l[b]?.pagination),B(t,"maxCells",c)}})({...o,params:o.params??{},onWarning:b=>u.push({code:"layout",message:b,severity:"warning"}),onQueryResult:(b,$,T=0)=>{const j=qr(T,b);Object.defineProperty(f,b,{value:{revision:$.revision,sourceToken:$.sourceToken},enumerable:!0,writable:!0}),d.push({reportId:b,reportIndex:T,reportScope:j,...$.revision===void 0?{}:{revision:$.revision},...$.sourceToken===void 0?{}:{sourceToken:$.sourceToken}}),u.push(...($.diagnostics??[]).map(v=>({...v,...v.target?{target:{...v.target,reportScope:j,...v.target.tableId?{tableId:JSON.stringify([T,b,v.target.tableId])}:{}}}:{}})))}}).catch(b=>{throw b instanceof E&&b.cause instanceof $e?new L("budget",b.cause.message,"$.budget.maxPages"):b instanceof E&&b.cause instanceof _e?new L("budget",b.cause.message,"$.budget.maxCells"):b instanceof E&&b.cause instanceof Ke?new L("budget",b.cause.message,"$.budget.maxChartComponents"):b});O(o.signal);const p=e.assets?await le(o).run("assets",()=>On(h,{...e.assets,signal:o.signal})):{plan:h,diagnostics:[]},w=p.plan;u.push(...Et(p.diagnostics));const y=w.pages.reduce((b,$)=>b+$.components.reduce((T,j)=>T+Jt(j),0),0);B(t,"maxPages",w.pages.length),B(t,"maxCells",y);const g=ki(o.pdf),x=e.pagination?.measurer||Object.values(e.reports).some(b=>b.pagination?.measurer);return{plan:w,diagnostics:u,revisions:f,sources:d,layout:{textMetrics:g?"font-bytes":x?"provided":"heuristic",...g?{fontFingerprint:g}:{}},stats:{rows:a,pages:w.pages.length,cells:y,durationMs:Date.now()-s}}},n=async o=>{const i=Date.now();if(o.format!=="pdf"&&o.format!=="xlsx")throw new E("config","不支持的报表导出格式");const s=o.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;O(o.signal);const a=o.pdf?.customFontFaces??(o.pdf?.customFontBytes?{regular:o.pdf.customFontBytes}:void 0),c=s&&a?s.createFontBytesMeasurer(a):void 0,u=await r(o,c);return O(o.signal),In({...o,prepared:u},t,i)};return{describe:o=>Fl(e.reports,o),validate:o=>Ii(e.reports,o),prepare:o=>Re(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=Cn(o),u={...c,...c.pdf?{pdf:Te(c.pdf)}:{},taskId:c.taskId??ot()},f=a?p=>ve(a,p,i):void 0,d={...u,signal:i,onEvent:f};le(d).runSync("validate",()=>Tn(e,u));let l;const m=u.pdf?.customFontFaces??(u.pdf?.customFontBytes?{regular:u.pdf.customFontBytes}:void 0);if(!e.executor&&m){const p=await import("@agile-team/mach-report/pdf");O(i),l=p.createFontBytesMeasurer(m)}const h=e.executor?await e.executor.prepare(u,i,f):await r(d,l);return xr(h,t)}),exportPrepared:o=>Re(o.signal,t.maxDurationMs,async i=>{const s=Date.now(),{signal:a,onEvent:c,...u}=o,f=xr(Ni(o.prepared,t.maxPreparedBytes??64e6,i),t),d={...u,xlsx:wr(u.xlsx),prepared:f,...u.pdf?{pdf:Te(u.pdf)}:{},taskId:u.taskId??ot()};if(d.format!=="pdf"&&d.format!=="xlsx")throw new E("config","不支持的报表导出格式");const l=c?h=>ve(c,h,i):void 0;if(e.executor){if(!e.executor.exportPrepared)throw new E("config","执行器未实现 exportPrepared;请升级执行器或显式使用本地运行时");const h=await e.executor.exportPrepared(d,i,l);return B(t,"maxRows",h.stats.rows),B(t,"maxPages",h.stats.pages),B(t,"maxCells",h.stats.cells),B(t,"maxOutputBytes",h.bytes.byteLength),{...h,stats:{...h.stats,outputBytes:h.bytes.byteLength}}}const m={...d,signal:i,onEvent:l};if(le(m).runSync("validate",()=>Nl(m)),e.assets){const h=await le(m).run("assets",()=>On(f.plan,{...e.assets,signal:i}));f.plan=h.plan,f.diagnostics.push(...Et(h.diagnostics))}return In(m,t,s)}),export:o=>Re(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=Cn(o),u={...c,xlsx:wr(c.xlsx),...c.pdf?{pdf:Te(c.pdf)}:{},taskId:c.taskId??ot()},f=a?m=>ve(a,m,i):void 0,d={...u,signal:i,onEvent:f};if(le(d).runSync("validate",()=>Tn(e,u)),u.format!=="pdf"&&u.format!=="xlsx")throw new E("config","不支持的报表导出格式");const l=e.executor?await e.executor.export(u,i,f):await n(d);return B(t,"maxRows",l.stats.rows),B(t,"maxPages",l.stats.pages),B(t,"maxCells",l.stats.cells),B(t,"maxOutputBytes",l.bytes.byteLength),{...l,stats:{...l.stats,outputBytes:l.bytes.byteLength}}})}}const Ol={cells:2e4,pages:20,bytes:2e6};function je(e){return e.cells>=e.limits.cells||e.pages>=e.limits.pages||e.bytes>=e.limits.bytes||e.capped}function be(e){return++e.visits>=1e5&&(e.capped=!0),!je(e)}function ie(e){return typeof e=="string"?e.length*2:0}function jn(e,t){for(const r of e??[]){if(!be(t))return;for(const n of r.segments){if(!be(t))return;t.bytes+=ie(n.text)}}}function Ci(e,t,r){if(r>32){t.capped=!0;return}if(be(t)){t.bytes+=ie(e.text)+ie(e.rawText)+ie(e.imageData),jn(e.richParagraphs,t);for(const n of e.lines??[]){if(!be(t))return;t.bytes+=ie(n)}for(const n of e.grid?.cells??[]){if(!be(t))return;for(const o of n){if(!be(t))return;if(o){t.cells++,t.bytes+=ie(o.text)+ie(o.rawText)+ie(o.value),jn(o.richParagraphs,t);for(const i of o.children??[]){if(je(t))return;Ci(i,t,r+1)}}}}}}function Il(e){const t={...Ol,...e.thresholds};for(const r of Object.values(t))if(!Number.isSafeInteger(r)||r<=0)throw new RangeError("导出隔离阈值应为正安全整数");return t}function Rl(e,t){const r=Il(t),n=e.pdf?.customFontFaces?Object.values(e.pdf.customFontFaces):[e.pdf?.customFontBytes],o={pages:e.prepared.plan.pages.length,cells:0,bytes:n.reduce((a,c)=>a+(c?.byteLength??0),0),visits:0,capped:!1,limits:r};for(const a of e.prepared.plan.pages){if(je(o))break;for(const c of a.components){if(je(o))break;Ci(c,o,0)}}let i=je(o)?"worker":"local",s=o.capped?"scan-limit":i==="worker"?"threshold":"small-task";return t.mode==="local"&&(i="local",s="explicit-local"),t.mode==="worker"&&(i="worker",s="explicit-worker"),Object.values(e.xlsx??{}).some(a=>typeof a=="function")&&(i="local",s="nonserializable-options"),{mode:i,reason:s,estimate:{pages:o.pages,cells:o.cells,bytes:o.bytes},hardCancellation:i==="worker"}}const ae="mach-report-worker/1";class vr extends Error{constructor(t){super(t.message),this.name=t.name,this.code=t.code,this.path=t.path,this.issues=t.issues,this.diagnostics=t.diagnostics}}function ce(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Cl(e){return ce(e)?["rows","pages","cells"].every(t=>typeof e[t]=="number"&&Number.isSafeInteger(e[t])&&e[t]>=0)&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0:!1}function Tl(e){return Array.isArray(e)&&e.every(t=>ce(t)&&typeof t.code=="string"&&typeof t.message=="string"&&["info","warning","error"].includes(t.severity)&&Yr(t))}function jl(e){return ce(e)&&Object.values(e).every(t=>ce(t)&&(t.revision===void 0||typeof t.revision=="string")&&(t.sourceToken===void 0||typeof t.sourceToken=="string"))}function Dl(e){return e===void 0?!0:ce(e)&&["heuristic","provided","font-bytes"].includes(e.textMetrics)&&(e.fontFingerprint===void 0||typeof e.fontFingerprint=="string"&&/^[a-f0-9]{64}$/.test(e.fontFingerprint))}function Ll(e,t){if(!ce(e)||!Cl(e.stats)||!Tl(e.diagnostics)||!jl(e.revisions)||!Dl(e.layout)||!Pi(e.sources))return!1;if(t==="prepare")return Ue(e.plan).ok;const r=e.format==="pdf"?"application/pdf":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";return e.bytes instanceof Uint8Array&&(e.format==="pdf"||e.format==="xlsx")&&e.contentType===r}function Ti(e){if(!e||typeof e!="object")return{message:String(e)};const t={};for(const r of["code","path","field","message"]){const n=e[r];typeof n=="string"&&(t[r]=n)}return t}function Bl(e){const t=Ti(e);if(!ce(e))return t;for(const r of["format","severity","kind","nid"])typeof e[r]=="string"&&(t[r]=e[r]);for(const r of["pageIndex","componentIndex"])Number.isSafeInteger(e[r])&&e[r]>=0&&(t[r]=e[r]);return Array.isArray(e.componentPath)&&e.componentPath.every(r=>Number.isSafeInteger(r)&&r>=0)&&(t.componentPath=e.componentPath),t}function ji(e){if(!(e instanceof Error))return{name:"Error",message:String(e)};const t=e;return{name:e.name,message:e.message,...typeof t.code=="string"?{code:t.code}:{},...typeof t.path=="string"?{path:t.path}:{},...Array.isArray(t.issues)?{issues:t.issues.map(Ti)}:{},...Array.isArray(t.diagnostics)?{diagnostics:t.diagnostics.map(Bl)}:{}}}function Di(e){if(!e||typeof e!="object")return!1;const t=e;return t.protocol===ae&&typeof t.id=="string"&&(t.operation==="prepare"||t.operation==="export"||t.operation==="exportPrepared")&&!!t.input&&typeof t.input=="object"}async function Li(e,t,r){try{const n=t.operation==="prepare"?await e.prepare({...t.input,onEvent:r}):t.operation==="exportPrepared"?await e.exportPrepared({...t.input,onEvent:r}):await e.export({...t.input,onEvent:r});return{protocol:ae,id:t.id,result:n}}catch(n){return{protocol:ae,id:t.id,error:ji(n)}}}function Bi(e){const t=e.result;return!t||!("bytes"in t)||!(t.bytes.buffer instanceof ArrayBuffer)?[]:[t.bytes.buffer]}function _l(e,t){if(!ce(e)||typeof e.taskId!="string"||!e.taskId||t.taskId!==void 0&&e.taskId!==t.taskId||e.correlationId!==t.correlationId||e.reportId!==void 0&&(typeof e.reportId!="string"||!("reportIds"in t&&t.reportIds.includes(e.reportId)))||!["query","validate","layout","assets","encode"].includes(e.stage)||!["started","completed","failed"].includes(e.status))return!1;for(const r of["completed","total"])if(e[r]!==void 0&&(typeof e[r]!="number"||!Number.isFinite(e[r])||e[r]<0))return!1;return e.completed===void 0||e.total===void 0||e.completed<=e.total}class Mr extends Error{constructor(t){super("报表 Worker 无法启动"),this.cause=t,this.name="ReportWorkerStartError"}}let Kl=0;function Dn(e){const t=new Error("报表 Worker 任务已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e}),t}function Wl(e,t){if(!e||typeof e!="object")return;const r=e;return r.protocol===ae&&r.id===t?r:void 0}function Jl(e,t={}){const r=t.timeoutMs??12e4;if(!Number.isFinite(r)||r<=0||r>2147483647)throw new RangeError("Worker timeoutMs 应为正有限数字,且不能超过 2147483647");const n=(o,i,s,a)=>s?.aborted?Promise.reject(Dn(s.reason)):new Promise((c,u)=>{let f;try{f=e()}catch(g){u(new Mr(g));return}const d=`mach-report-${Date.now()}-${++Kl}`;let l=!1,m=()=>{},h;const p=(g,x)=>{if(l)return;l=!0,h&&clearTimeout(h);let b;try{m()}catch($){b=$}s?.removeEventListener("abort",w),g??=b,Promise.resolve().then(()=>f.terminate()).then(()=>g===void 0?c(x):u(g),$=>u(g??$))},w=()=>p(Dn(s?.reason)),y=g=>{const x=Wl(g,d);if(!(!x||l)){if("type"in x&&x.type==="event"){const b="event"in x?x.event:void 0;_l(b,i)?ve(a,b,s):p(new Error("报表 Worker 返回无效阶段事件"));return}x.error&&typeof x.error.name=="string"&&typeof x.error.message=="string"?p(new vr(x.error)):Ll(x.result,o)&&(o==="prepare"||"format"in x.result&&"format"in i&&x.result.format===i.format)?p(void 0,x.result):p(new Error("报表 Worker 返回无效响应"))}};try{if(m=f.subscribe(y,g=>p(g??new Error("报表 Worker 执行失败"))),l){m();return}if(s?.addEventListener("abort",w,{once:!0}),h=setTimeout(()=>p(new vr({name:"ReportRuntimeError",code:"timeout",message:`报表 Worker 执行超过 ${r}ms`})),r),s?.aborted)w();else{const{onEvent:g,signal:x,...b}=i,$=zl(b);f.postMessage({protocol:ae,id:d,operation:o,input:b,...t.budget?{budget:t.budget}:{}},$)}}catch(g){p(g)}});return{exportPrepared:(o,i,s)=>n("exportPrepared",o,i,s),prepare:(o,i,s)=>n("prepare",o,i,s),export:(o,i,s)=>n("export",o,i,s)}}function zl(e){return e.pdf?(e.pdf=Te(e.pdf),(e.pdf?.customFontFaces?Object.values(e.pdf.customFontFaces):[e.pdf?.customFontBytes]).filter(r=>r instanceof Uint8Array).map(r=>r.buffer)):[]}function Vl(e){if(e.mode!==void 0&&!["auto","local","worker"].includes(e.mode))throw new TypeError("无效的导出执行模式");if(e.fallback!==void 0&&!["local","error"].includes(e.fallback))throw new TypeError("无效的导出回退策略");wi({...e.budget,maxDurationMs:e.timeoutMs??e.budget?.maxDurationMs??12e4})}function Ln(e,t){de.observeOutput(()=>e.onDecision?.({...t,estimate:{...t.estimate}}))}function Bn(e,t){return{...e,mode:"local",reason:t,hardCancellation:!1}}function Hl(e,t){const r={...Xr,...t.budget},n=kl(e.prepared,r.maxPreparedBytes,e.signal),o=xr(n.prepared,r);n.prepared.stats=o.stats;const i={...e,prepared:n.prepared,pdf:Te(e.pdf),xlsx:wr(e.xlsx)};return{request:i,forward:()=>({...i,prepared:n.forward()})}}function Ul(e,t){Vl(e);const r={...e,thresholds:{...e.thresholds},budget:{...Xr,...e.budget}},n=r.timeoutMs??r.budget.maxDurationMs??12e4,o=Ri({reports:{},budget:{...r.budget,maxDurationMs:n}}),i=new Set;let s=!1;const a=r.mode!=="worker"&&r.fallback!=="error";async function c(u,f){const d=Date.now(),l=()=>{const y=n-(Date.now()-d);if(y<=0)throw new L("timeout",`报表执行超过 ${n}ms`);return y};let m=Rl(u,r);if(m.reason==="nonserializable-options"&&r.mode==="worker")throw new TypeError("Worker 模式不接受函数选项;请使用本地模式或可序列化配置");if(m.mode==="worker"&&!t){if(!a)throw new Mr(new Error("未配置 workerFactory"));m=Bn(m,"worker-unavailable")}const h=Hl(u,r),p=h.request;if(Ln(r,m),O(u.signal),m.mode==="worker")try{const y=t(l());if(!y.exportPrepared)throw new TypeError("隔离执行器缺少 exportPrepared");const{signal:g,onEvent:x,...b}=p,$=await y.exportPrepared(b,g,x);return O(g),B(r.budget,"maxOutputBytes",$.bytes.byteLength),{...$,execution:m}}catch(y){if(!(y instanceof Mr)||!a)throw y;O(u.signal),m=Bn(m,"worker-start-failed"),Ln(r,m)}const w=f?await Re(u.signal,l(),y=>f({...p,signal:y})):await Re(u.signal,l(),y=>o.exportPrepared({...h.forward(),signal:y}));return O(u.signal),B(r.budget,"maxOutputBytes",w.bytes.byteLength),{...w,execution:m}}return{async exportPrepared(u,f){if(s)throw new L("closed","导出执行器已释放");if(O(u.signal),i.size>=2)throw new L("queue-full","同时导出的任务已达 2 个,请等待完成后重试");const d=new AbortController;i.add(d);const l=()=>d.abort(u.signal?.reason);u.signal?.addEventListener("abort",l,{once:!0});try{return await c({...u,signal:d.signal},f)}finally{u.signal?.removeEventListener("abort",l),i.delete(d)}},cancel(){for(const u of i)u.abort()},dispose(){s=!0;for(const u of i)u.abort()}}}async function Gl(e,t){try{if(e.operation!=="exportPrepared")throw new TypeError("内置编码 Worker 仅接受 exportPrepared");return await Li(Ri({reports:{},budget:e.budget}),e,t)}catch(r){return{protocol:ae,id:e.id,error:ji(r)}}}class k extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportJobError"}}function At(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 k("input","任务范围应非空,ID应为1–128位安全标识")}function Yl(e){const t=Array.isArray(e),r=Object.getPrototypeOf(e),n=Object.keys(e);if(r!==(t?Array.prototype:Object.prototype)&&!(r===null&&!t))throw new k("input","任务对象应为普通 JSON 对象");if(Object.getOwnPropertySymbols(e).length)throw new k("input","任务不能包含Symbol");if(Object.getOwnPropertyNames(e).filter(i=>!(t&&i==="length")).length!==n.length)throw new k("input","任务不能包含不可枚举属性");if(t&&(n.length!==e.length||n.some(i=>i!==String(Number(i))||!Number.isSafeInteger(Number(i))||Number(i)<0||Number(i)>=e.length)))throw new k("input","任务数组不能稀疏或包含额外属性");return n.sort()}function ql(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(["__proto__","prototype","constructor"].includes(t)||r.get||r.set)throw new k("input","任务不能包含危险键或访问器");return r.value}function ne(e,t={}){const r=t.maxNodes??2e4,n=t.maxCharacters??1e6;if(!Number.isSafeInteger(r)||r<1||r>2e4||!Number.isSafeInteger(n)||n<1||n>1e6)throw new k("input","任务JSON预算无效");let o=0,i=0;const s=new Set;function a(u,f){if(++o>r||f>32)throw new k("input","任务数据超过节点或深度预算");if(typeof u=="string"){if(i+=u.length,i>n)throw new k("input","任务文本超过预算");return u}if(u===null||typeof u=="boolean"||typeof u=="number"&&Number.isFinite(u))return u;if(!u||typeof u!="object"||s.has(u))throw new k("input","任务只允许无循环的有限 JSON 值");const d=Array.isArray(u),l=Yl(u);s.add(u);const m=Object.create(null);for(const h of l){if(i+=h.length,i>n)throw new k("input","任务文本超过预算");m[h]=a(ql(u,h),f+1)}return s.delete(u),d?Array.from({length:u.length},(h,p)=>m[String(p)]):m}const c=JSON.stringify(a(e,0));if(c.length>n)throw new k("input","任务序列化数据超过字符预算");return c}function tr(e){return JSON.parse(JSON.stringify(e))}function _i(e,t,r,n){if(At(t,r),e.scope!==t||e.id!==r||e.revision!==(n??0)+1||!Number.isSafeInteger(e.revision))throw new k("input","任务身份或修订不匹配");if(![e.createdAt,e.updatedAt,e.attempt].every(o=>Number.isSafeInteger(o)&&o>=0)||!["queued","running","completed","failed","cancelled"].includes(e.status))throw new k("input","任务状态无效");if(e.lease&&(!e.lease.owner||!Number.isSafeInteger(e.lease.expiresAt)))throw new k("input","任务租约无效");if(!e.request||typeof e.request.kind!="string"||!e.request.kind.trim()||e.request.kind.length>128)throw new k("input","任务类型无效");ne(e.request.payload,{maxNodes:19e3,maxCharacters:75e4}),ne(e)}function Xl(e,t){if(e&&(e.createdAt!==t.createdAt||ne(e.request)!==ne(t.request)))throw new k("input","任务创建时间与请求不可变更,请使用新任务ID")}function Zl(e,t){return e.status==="queued"||e.status==="running"&&(e.lease?.expiresAt??0)<=t}function Ql(e={}){const t={maxRecords:e.maxRecords??1e4,maxBytes:e.maxBytes??67108864,maxResultBytes:e.maxResultBytes??262144,controlReserveBytes:e.controlReserveBytes??4096,maxTombstones:e.maxTombstones??1e4,maxTombstoneBytes:e.maxTombstoneBytes??16777216};if(!Object.values(t).every(r=>Number.isSafeInteger(r)&&r>0)||t.controlReserveBytes<4096)throw new k("input","任务容量应为正整数,控制状态预留至少4096字节");return t}function De(e){return new TextEncoder().encode(ne(e)).byteLength}function Ki(e,t){const r={scope:e.scope,id:e.id,revision:1,request:e.request,status:"queued",createdAt:e.createdAt,updatedAt:e.createdAt,attempt:0},n={...e};delete n.result;const o=e.result===void 0?0:De(e.result);if(o>t.maxResultBytes)throw new k("capacity","任务结果超过独立预算,请保存文件引用");return Math.max(De(r)+t.controlReserveBytes,De(n))+o}function Wi(e){return e.status!=="queued"&&e.status!=="running"}function ed(e){const t={...e,tombstoneRetentionMs:e.tombstoneRetentionMs??6048e5,limit:e.limit??100};if(![t.now,t.terminalBefore].every(r=>Number.isSafeInteger(r)&&r>=0)||t.terminalBefore>t.now)throw new k("input","终态清理时间应为不超过当前时间的非负整数");if(![t.tombstoneRetentionMs,t.limit].every(r=>Number.isSafeInteger(r)&&r>0)||!Number.isSafeInteger(t.now+t.tombstoneRetentionMs))throw new k("input","幂等保留期与清理批量应为正整数");return t}async function td(e){const t=new TextEncoder().encode(ne(e)),r=globalThis.crypto?.subtle;if(!r)return Al(t);const n=await r.digest("SHA-256",t);return Array.from(new Uint8Array(n),o=>o.toString(16).padStart(2,"0")).join("")}async function rd(e,t){if(!Wi(e))throw new k("input","只能归档终态任务");return{scope:e.scope,id:e.id,revision:e.revision,status:e.status,createdAt:e.createdAt,updatedAt:e.updatedAt,attempt:e.attempt,requestHash:await td(e.request),expiresAt:t}}function nd(e){if(!e||!["completed","failed","cancelled"].includes(e.status)||!/^[a-f0-9]{64}$/.test(e.requestHash))throw new k("input","任务幂等摘要无效");if(![e.revision,e.createdAt,e.updatedAt,e.attempt,e.expiresAt].every(t=>Number.isSafeInteger(t)&&t>=0)||e.revision<1)throw new k("input","任务幂等摘要时间或修订无效")}function Ge(e){return e?.code}function Le(e,t){return he.createHash("sha256").update(JSON.stringify([e,t])).digest("hex")+".json"}async function $r(e){try{return await A.promises.readFile(e,"utf8")}catch(t){if(Ge(t)==="ENOENT")return;throw t}}async function od(e,t){const r=await $r(e);if(r===void 0)return;let n;try{n=JSON.parse(r)}catch{throw new k("conflict","任务锁尚未完整写入或已损坏,拒绝自动移除")}if(!n||!Number.isSafeInteger(n.pid)||n.pid<1)throw new k("conflict","任务锁身份无效,拒绝自动移除");try{process.kill(n.pid,0)}catch(o){if(Ge(o)==="ESRCH"){await A.promises.unlink(e);return}throw o}throw new k("conflict","任务目录的写入进程仍在运行")}async function id(e,t){if(!t)throw new k("conflict","任务目录已有写入进程;多实例请使用数据库CAS适配器");const r=e+".recovery";let n;try{n=await A.promises.open(r,"wx",384)}catch(o){throw Ge(o)==="EEXIST"?new k("conflict","任务目录恢复正在进行,请稍后重试"):o}try{return await n.writeFile(JSON.stringify({pid:process.pid})),await od(e,!0),await A.promises.open(e,"wx",384)}finally{await n.close(),await A.promises.unlink(r)}}async function sd(e,t){const r=D.join(e,".writer-lock"),n=he.randomUUID();let o;try{o=await A.promises.open(r,"wx",384)}catch(i){if(Ge(i)!=="EEXIST")throw i;o=await id(r,t)}try{await o.writeFile(JSON.stringify({pid:process.pid,token:n})),await o.sync()}catch(i){throw await o.close(),await A.promises.unlink(r).catch(()=>{}),i}return{file:r,token:n,handle:o}}function ad(e,t,r,n){if("tombstone"in r){const o=r.tombstone;if(nd(o),At(o.scope,o.id),Le(o.scope,o.id)!==t)throw new k("input","持久任务摘要身份不匹配");const i=De(o);e.tombstoneBytes+=i,e.tombstones.set(t,{value:o,bytes:i})}else{if(_i(r,r.scope,r.id,r.revision-1),Le(r.scope,r.id)!==t)throw new k("input","持久任务文件身份不匹配");const o=Ki(r,n);e.bytes+=o,e.records.set(t,{record:r,bytes:o})}if(e.bytes>n.maxBytes||e.records.size>n.maxRecords||e.tombstoneBytes>n.maxTombstoneBytes||e.tombstones.size>n.maxTombstones)throw new k("capacity","持久任务及控制状态预留超过目录预算")}async function cd(e,t){const r=await A.promises.readdir(e);for(const i of r.filter(s=>/^\.pending-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(s)))await A.promises.unlink(D.join(e,i));const n=r.filter(i=>/^[a-f0-9]{64}\.json$/.test(i));if(n.length>t.maxRecords+t.maxTombstones)throw new k("capacity","持久任务数量超过目录预算");const o={records:new Map,tombstones:new Map,bytes:0,tombstoneBytes:0};for(const i of n){const s=D.join(e,i);if((await A.promises.stat(s)).size>4e6)throw new k("capacity","持久任务文件超过单文件预算");ad(o,i,JSON.parse(await A.promises.readFile(s,"utf8")),t)}return o}async function ud(e,t,r){const n=D.join(e,`.pending-${he.randomUUID()}`);try{const o=await A.promises.open(n,"wx",384);try{await o.writeFile(r),await o.sync()}finally{await o.close()}await A.promises.rename(n,D.join(e,t));const i=await A.promises.open(e,"r");try{await i.sync()}finally{await i.close()}}finally{await A.promises.unlink(n).catch(o=>{if(Ge(o)!=="ENOENT")throw o})}}async function fd(e){const t=D.resolve(e.directory),r=Ql(e);await A.promises.mkdir(t,{recursive:!0,mode:448});const n=await sd(t,e.recoverDeadOwner??!1);let o;try{o=await cd(t,r)}catch(l){throw await n.handle.close(),await A.promises.unlink(n.file),l}let i=!1,s=Promise.resolve();const a=()=>{if(i)throw new k("closed","持久任务存储已关闭")},c=l=>{a();const m=s.then(async()=>{if(JSON.parse(await A.promises.readFile(n.file,"utf8")).token!==n.token)throw new k("closed","持久任务存储写入锁已失效");return l()});return s=m.then(()=>{},()=>{}),m},u=async(l,m,h)=>{try{await ud(t,l,m)}catch(p){throw await $r(D.join(t,l))===m&&h(),p}h()};return{read:async(l,m)=>{a(),At(l,m),await s;const h=o.records.get(Le(l,m));return h?tr(h.record):void 0},readTombstone:async(l,m)=>{a(),At(l,m),await s;const h=o.tombstones.get(Le(l,m));return h?tr(h.value):void 0},candidates:async(l,m)=>(a(),await s,Array.from(o.records.values(),h=>h.record).filter(h=>Zl(h,l)).sort((h,p)=>h.createdAt-p.createdAt).slice(0,m).map(tr)),compareAndSwap:async(l,m,h,p)=>{const w=JSON.parse(ne(p));return _i(w,l,m,h),c(async()=>{const y=Le(l,m),g=o.records.get(y);if((g?.record.revision??null)!==h||o.tombstones.has(y))return!1;Xl(g?.record,w);const x=Ki(w,r),b=o.bytes-(g?.bytes??0)+x;if(b>r.maxBytes||!g&&o.records.size>=r.maxRecords)throw new k("capacity","持久任务容量已满,请清理终态任务或扩大显式预算");return await u(y,ne(w),()=>{o.records.set(y,{record:w,bytes:x}),o.bytes=b}),!0})},prune:async l=>{const m=ed(l);return c(async()=>{const h={archived:0,expired:0};for(const[p,w]of o.tombstones)w.value.expiresAt>m.now||h.expired>=m.limit||(await A.promises.unlink(D.join(t,p)),o.tombstones.delete(p),o.tombstoneBytes-=w.bytes,h.expired++);for(const[p,w]of o.records){if(!Wi(w.record)||w.record.updatedAt>m.terminalBefore||h.archived+h.expired>=m.limit)continue;const y=await rd(w.record,m.now+m.tombstoneRetentionMs),g=De(y);if(o.tombstones.size>=r.maxTombstones||o.tombstoneBytes+g>r.maxTombstoneBytes)break;await u(p,ne({tombstone:y}),()=>{o.tombstones.set(p,{value:y,bytes:g}),o.tombstoneBytes+=g,o.records.delete(p),o.bytes-=w.bytes}),h.archived++}if(h.expired){const p=await A.promises.open(t,"r");try{await p.sync()}finally{await p.close()}}return h})},close:async()=>{if(i)return;i=!0,await s,await n.handle.close();const l=await $r(n.file);l&&JSON.parse(l).token===n.token&&await A.promises.unlink(n.file)}}}class F extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportDocumentError"}}function ld(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 F("input","文档预算应为正安全整数");return t}function ue(e,t,r){if([e,t,...r===void 0?[]:[r]].some(n=>typeof n!="string"||!n.trim()||n.length>256))throw new F("input","文档 scope、id、version 应为 1–256 位非空字符串");return JSON.stringify([e,t])}function q(e,t,r){return vi(e,{maxBytes:t,maxNodes:t,check:()=>O(r),error:(n,o)=>new F(n==="budget"?"capacity":"input",o)})}function xe(e){return new TextEncoder().encode(JSON.stringify(e)).byteLength}function _n(e){if(!e||e.schemaVersion!==Ae||"pages"in e||e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean")throw new F("input","文档计划头应使用当前版本,且不得携带 pages")}function Ze(e,t){e.bytes=0;for(let r=0;r<8;r++){const n=t+xe(e);if(n===e.bytes)return;e.bytes=n}throw new F("capacity","文档容量统计无效")}function dd(e,t,r=[]){const n=new Map;let o=0,i=Promise.resolve();for(const f of r){const d=ue(f.scope,f.id,f.version);if(_n(f.plan),n.has(d)||!Number.isSafeInteger(f.bytes)||f.bytes<0||!Number.isSafeInteger(f.pageCount)||f.pageCount<0||f.pageCount>t.maxPages||!["building","complete","failed"].includes(f.state)||f.revision!==f.pageCount+(f.state==="building"?0:1))throw new F("input","文档清单无效");n.set(d,q(f,t.maxManifestBytes)),o+=f.bytes}function s(f,d){if(o-(d?.bytes??0)+f.bytes>t.maxBytes||!d&&n.size>=t.maxDocuments)throw new F("capacity","文档存储容量已满,请显式清理旧文档")}if(n.size>t.maxDocuments||o>t.maxBytes)throw new F("capacity","已存文档超过预算");const a=f=>{const d=i.then(f);return i=d.then(()=>{},()=>{}),d},c=(f,d,l,m)=>{const h=n.get(ue(f,d,l));if(!h)throw new F("missing","文档不存在");if(h.version!==l||m!==void 0&&h.revision!==m)throw new F("conflict","文档已变化,请重新读取清单");return h},u=async(f,d,l)=>{const m=q(f,t.maxManifestBytes);return s(m,d),await e.write(m,l),n.set(ue(f.scope,f.id),m),o+=f.bytes-(d?.bytes??0),q(m,t.maxManifestBytes)};return{create:(f,d)=>{const l=q(f,t.maxManifestBytes,d),m=ue(l.scope,l.id,l.version);return _n(l.plan),a(async()=>{if(O(d),n.has(m))throw new F("conflict","文档已存在,不可覆盖");const h={...l,revision:0,state:"building",pageCount:0,bytes:0};return Ze(h,0),u(h)})},append:(f,d,l,m,h,p)=>{const w=q(h,t.maxPageBytes,p),y=Ue({pages:[w]});if(!y.ok)throw new F("input",y.errors[0].message);return a(async()=>{O(p);const g=c(f,d,l,m);if(g.state!=="building")throw new F("conflict","已完成文档不可追加");if(g.pageCount>=t.maxPages)throw new F("capacity","文档页数超过预算");const x={...g,revision:m+1,pageCount:g.pageCount+1};return Ze(x,g.bytes-xe(g)+xe(w)),u(x,g,{index:g.pageCount,value:w})})},complete:(f,d,l,m,h,p)=>{const w=h===void 0?void 0:q(h,t.maxManifestBytes,p);return w&&Fi({...w}),a(async()=>{O(p);const y=c(f,d,l,m);if(y.state!=="building")throw new F("conflict","文档已完成");if(w&&w.stats.pages!==y.pageCount)throw new F("input","准备结果页数与文档页数不一致");const g={...y,revision:m+1,state:"complete",...w?{metadata:w}:{}};return Ze(g,y.bytes-xe(y)),u(g,y)})},fail:(f,d,l,m,h)=>{const p=q(h,4096);if(!p||!["cancelled","generation"].includes(p.code)||typeof p.message!="string"||!p.message.trim()||p.message.length>1024)throw new F("input","文档失败状态无效");return a(async()=>{const w=c(f,d,l,m);if(w.state!=="building")throw new F("conflict","终态文档不可变更");const y={...w,state:"failed",revision:m+1,failure:p};return Ze(y,w.bytes-xe(w)),u(y,w)})},read:async(f,d,l)=>{O(l);const m=ue(f,d);await i,O(l);const h=n.get(m);return h?q(h,t.maxManifestBytes):void 0},readPage:(f,d,l,m,h)=>a(async()=>{O(h);const p=c(f,d,l);if(!Number.isSafeInteger(m)||m<0)throw new F("input","页索引应为非负安全整数");if(m>=p.pageCount)return;const w=await e.readPage(f,d,m);if(O(h),!w)throw new F("missing","已提交的文档页缺失");return q(w,t.maxPageBytes,h)}),remove:(f,d,l,m)=>a(async()=>{O(m);const h=ue(f,d,l),p=n.get(h);return p?(c(f,d,l),await e.remove(p),n.delete(h),o-=p.bytes,!0):!1})}}const Sr=e=>e?.code,it=(e,t)=>he.createHash("sha256").update(ue(e,t)).digest("hex");async function Er(e,t){const r=await A.promises.lstat(e);if(!r.isFile()||r.size>t)throw new F("capacity","文档文件类型或大小无效");return q(JSON.parse(await A.promises.readFile(e,"utf8")),t)}async function Kn(e,t){const r=`${e}.pending-${he.randomUUID()}`;try{await A.promises.writeFile(r,JSON.stringify(t),{flag:"wx",mode:384}),await A.promises.rename(r,e)}finally{await A.promises.unlink(r).catch(n=>{if(Sr(n)!=="ENOENT")throw n})}}async function md(e,t){const r=(await A.promises.readdir(e)).filter(o=>/^[a-f0-9]{64}$/.test(o));if(r.length>t.maxDocuments)throw new F("capacity","文档数量超过目录预算");const n=[];for(const o of r){const i=D.join(e,o);if(!(await A.promises.lstat(i)).isDirectory())throw new F("input","文档目录不允许符号链接");const a=await Er(D.join(i,"manifest.json"),t.maxManifestBytes);if(it(a.scope,a.id)!==o||!Number.isSafeInteger(a.pageCount)||a.pageCount<0||a.pageCount>t.maxPages)throw new F("input","文档清单身份或页数无效");let c=xe(a);for(let u=0;u<a.pageCount;u++){const f=await A.promises.lstat(D.join(i,`${u}.json`));if(!f.isFile()||f.size>t.maxPageBytes)throw new F("capacity","文档页文件类型或大小无效");c+=f.size}if(c!==a.bytes)throw new F("input","文档字节数与已提交页不一致");for(const u of await A.promises.readdir(i)){const f=/^(\d+)\.json$/.exec(u);(f&&Number(f[1])>=a.pageCount||/\.pending-[a-f0-9-]{36}$/.test(u))&&await A.promises.unlink(D.join(i,u))}n.push(a)}return n}async function hd(e){const t=ld(e),r=D.resolve(e.directory);await A.promises.mkdir(r,{recursive:!0,mode:448});const n=D.join(r,".document-writer-lock"),o=he.randomUUID();let i;try{i=await A.promises.open(n,"wx",384)}catch(l){throw Sr(l)==="EEXIST"?new F("conflict","文档目录已被占用;多实例请实现共享存储原子CAS"):l}try{await i.writeFile(JSON.stringify({pid:process.pid,token:o}))}catch(l){throw await i.close(),await A.promises.unlink(n),l}const s=async()=>{try{return(await Er(n,1024)).token===o}catch(l){if(Sr(l)==="ENOENT")return!1;throw l}},a=async()=>{if(!await s())throw new F("closed","文档存储写入锁已失效")};let c=Promise.resolve(),u=!1;const f=l=>{if(u)return Promise.reject(new F("closed","文档存储已关闭"));const m=l();return c=Promise.allSettled([c,m]).then(()=>{}),m};let d;try{const l=await md(r,t);d=dd({write:async(m,h)=>{await a();const p=D.join(r,it(m.scope,m.id));await A.promises.mkdir(p,{recursive:!0,mode:448}),h&&await Kn(D.join(p,`${h.index}.json`),h.value);try{await Kn(D.join(p,"manifest.json"),m)}catch(w){throw h?await A.promises.unlink(D.join(p,`${h.index}.json`)):m.revision===0&&await A.promises.rm(p,{recursive:!0}),w}},readPage:async(m,h,p)=>(await a(),Er(D.join(r,it(m,h),`${p}.json`),t.maxPageBytes)),remove:async m=>{await a(),await A.promises.rm(D.join(r,it(m.scope,m.id)),{recursive:!0})}},t,l)}catch(l){throw await i.close(),await A.promises.unlink(n),l}return{create:(...l)=>f(()=>d.create(...l)),append:(...l)=>f(()=>d.append(...l)),complete:(...l)=>f(()=>d.complete(...l)),fail:(...l)=>f(()=>d.fail(...l)),read:(...l)=>f(()=>d.read(...l)),readPage:(...l)=>f(()=>d.readPage(...l)),remove:(...l)=>f(()=>d.remove(...l)),close:async()=>{u||(u=!0,await c,await i.close(),await s()&&await A.promises.unlink(n))}}}function Ji(e){const t=e.filename??e.workerUrl;if(!t||e.filename&&e.workerUrl)throw new TypeError("请且仅请指定 filename 或 workerUrl");return Jl(()=>{const r=new Ne.Worker(t,e.workerOptions);return{postMessage:(n,o)=>r.postMessage(n,o),terminate:()=>r.terminate(),subscribe:(n,o)=>{const i=s=>o(new Error(`报表 Worker 在响应前退出(code ${s})`));return r.on("message",n),r.on("error",o),r.on("messageerror",o),r.on("exit",i),()=>{r.off("message",n),r.off("error",o),r.off("messageerror",o),r.off("exit",i)}}}},e)}function gd(e){const t=Ne.parentPort;if(!t)throw new Error("serveNodeReportWorker 只能在 worker_threads 中调用");const r=n=>{Di(n)&&Li(e,n,o=>t.postMessage({protocol:ae,id:n.id,type:"event",event:o})).then(o=>t.postMessage(o,Bi(o)))};return t.on("message",r),()=>t.off("message",r)}function pd(e){return he.createHash("sha256").update(e).digest("hex")}function yd(e={}){const t={timeoutMs:e.timeoutMs??e.budget?.maxDurationMs,budget:{...e.budget}};return Ul(e,r=>Ji({filename:typeof __filename=="string"?__filename:new URL(typeof document>"u"?require("url").pathToFileURL(__filename).href:Vt&&Vt.tagName.toUpperCase()==="SCRIPT"&&Vt.src||new URL("server-node.cjs",document.baseURI).href),workerOptions:{workerData:{machReportEncoding:"prepared-v1"}},...t,timeoutMs:r}))}if(Ne.parentPort&&Ne.workerData?.machReportEncoding==="prepared-v1"){const e=Ne.parentPort;e.on("message",t=>{Di(t)&&Gl(t,r=>e.postMessage({protocol:ae,id:t.id,type:"event",event:r})).then(r=>e.postMessage(r,Bi(r)))})}exports.ReportWorkerError=vr;exports.createNodeAutoReportExporter=yd;exports.createNodeReportExecutor=Ji;exports.openFileReportDocumentStore=hd;exports.openFileReportJobStore=fd;exports.reportArtifactSha256=pd;exports.serveNodeReportWorker=gd;
3
+ `,widthMm:0,cjk:!1,br:!0});continue}if(s===" "){i(),n.push({text:s,widthMm:r.measureMm(s,t),cjk:!1,space:!0});continue}if(Jn.test(s)){i(),n.push({text:s,widthMm:r.measureMm(s,t),cjk:!0});continue}o+=s}return i(),n}function Ve(e,t,r,n=$r){if(!e)return[""];e=e.replace(/\r\n?/g,`
4
+ `);const o=[];let i="",s=0;const a=(r.letterSpacingPt??0)*25.4/72,c=()=>{o.push(i),i="",s=0};for(const u of ns(e,r,n)){if(u.br){c();continue}const f=i.length>0?a:0;if(s+f+u.widthMm<=t){i+=u.text,s+=f+u.widthMm;continue}if(u.space){c();continue}if(u.cjk){i.length>0&&c(),i=u.text,s=u.widthMm;continue}if(i.length>0&&c(),u.widthMm<=t){i=u.text,s=u.widthMm;continue}for(const d of u.text)n.measureMm(i+d,r)>t&&i.length>0&&c(),i+=d,s=n.measureMm(i,r)}return c(),o}const os=4096,tn=128*1024;function is(e){const t=new Map;let r=0;return{measureMm(n,o){const i=JSON.stringify([n,o.fontSizePt,o.fontFamily,o.bold,o.italic,o.letterSpacingPt]),s=t.get(i);if(s!==void 0)return t.delete(i),t.set(i,s),s;const a=e.measureMm(n,o);if(Number.isFinite(a)&&i.length<=tn){for(;t.size>=os||r+i.length>tn;){const c=t.keys().next().value;r-=c.length,t.delete(c)}t.set(i,a),r+=i.length}return a}}}const st=1e3;function he(e){if(!Number.isSafeInteger(e)||e<0||e>st*2)throw new Error("十进制精度超出预算");return 10n**BigInt(e)}function Pt(e){if(e.coefficient.toString().length>st*2||e.scale>st*2)throw new Error("十进制结果超出精度预算");return e}function V(e){if(typeof e!="string"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("十进制参数必须是有限数字或十进制文本");const t=String(e);if(t.length>st)throw new Error("十进制文本超出精度预算");const r=/^([+-]?)(\d+)(?:\.(\d*))?(?:[eE]([+-]?\d{1,4}))?$/.exec(t);if(!r)throw new Error("无效十进制文本");const n=r[3]??"",o=Number(r[4]??0),i=n.length-o,s=BigInt(`${r[1]==="-"?"-":""}${r[2]}${n}`);return Pt(i<0?{coefficient:s*he(-i),scale:0}:{coefficient:s,scale:i})}function zn(e,t){const r=Math.max(e.scale,t.scale);return[e.coefficient*he(r-e.scale),t.coefficient*he(r-t.scale),r]}function at(e,t){const[r,n]=zn(e,t);return r<n?-1:r>n?1:0}function ct(e,t){const[r,n,o]=zn(e,t);return Pt({coefficient:r+n,scale:o})}function Sr(e,t){return Pt({coefficient:e.coefficient*t.coefficient,scale:e.scale+t.scale})}function Vn(e,t){const r=e/t,n=e%t,o=i=>i<0n?-i:i;return o(n)*2n<o(t)?r:r+(e<0n==t<0n?1n:-1n)}function He(e){if(!Number.isInteger(e)||e<0||e>100)throw new Error("十进制小数位应为 0–100 的整数")}function er(e,t,r=20){if(He(r),t.coefficient===0n)throw new Error("不能除以零");const n=t.scale-e.scale+r,o=e.coefficient*he(Math.max(0,n)),i=t.coefficient*he(Math.max(0,-n));return Pt({coefficient:Vn(o,i),scale:r})}function Ft(e,t){let r=e.coefficient,n=e.scale;t!==void 0&&(He(t),r=t>=n?r*he(t-n):Vn(r,he(n-t)),n=t);const o=r<0n,i=(o?-r:r).toString().padStart(n+1,"0");let s=n?i.slice(-n):"";return t===void 0&&(s=s.replace(/0+$/,"")),`${o?"-":""}${n?i.slice(0,-n):i}${s?`.${s}`:""}`}function rn(e,t,r=!1,n=!1){let o=V(e);n&&(o=Sr(o,{coefficient:100n,scale:0}));const[i,s]=Ft(o,t).split(".");return`${r?i.replace(/\B(?=(\d{3})+(?!\d))/g,","):i}${s===void 0?"":`.${s}`}${n?"%":""}`}const Hn=new Set(["__proto__","prototype","constructor"]);function Un(e){if(!e||typeof e!="object"||Array.isArray(e)||![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw new Error("条件应为普通声明式对象");for(const[t,r]of Object.entries(Object.getOwnPropertyDescriptors(e)))if(Hn.has(t)||!Object.prototype.hasOwnProperty.call(r,"value"))throw new Error("条件不允许访问器或不安全属性")}function nn(e){if(typeof e!="string"||!e.trim()||e.length>512||Hn.has(e))throw new Error("条件字段应为安全的非空字段名")}function zt(e){if(e!==null&&typeof e!="boolean"&&typeof e!="string"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("条件常量应为有限 JSON 标量");if(typeof e=="string"&&e.length>16384)throw new Error("条件文本超出预算")}function tr(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(e))throw new Error("日期条件使用 YYYY-MM-DD 日历日");const[t,r,n]=e.split("-").map(Number),o=new Date(0);if(o.setUTCFullYear(t,r-1,n),o.setUTCHours(0,0,0,0),o.getUTCFullYear()!==t||o.getUTCMonth()!==r-1||o.getUTCDate()!==n)throw new Error("无效日历日");return e}function on(e){return["string","boolean"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e)}function sn(e){return e==null||e===""}function ss(e){const t=e.values?.[0]??(e.right&&"value"in e.right?e.right.value:e.value);return e.valueType??e.numeric??(typeof t=="number"?"decimal":typeof t=="boolean"?"boolean":"text")}function Qe(e,t,r){if(sn(e)||sn(t))return;const n=ss(r);try{if(n==="decimal")return at(V(e),V(t));if(n==="number")return!["number","string"].includes(typeof e)||!["number","string"].includes(typeof t)?void 0:at(V(e),V(t));if(n==="date"&&(e=tr(e),t=tr(t)),n==="boolean"&&(typeof e!="boolean"||typeof t!="boolean")||n==="text"&&(!on(e)||!on(t)))return;const o=String(e),i=String(t);return o<i?-1:o>i?1:0}catch{return}}function as(e){if(nn(e.field),![">",">=","<","<=","==","!=","between","contains","isNull","isNotNull"].includes(e.op))throw new Error("未知条件运算符");if(e.numeric!==void 0&&!["number","decimal"].includes(e.numeric))throw new Error("未知条件数值模式");if(e.valueType!==void 0&&!["number","decimal","text","date","boolean"].includes(e.valueType))throw new Error("未知条件值类型");if(!(e.op==="isNull"||e.op==="isNotNull"))if(e.op==="between"){if(!Array.isArray(e.values)||e.values.length!==2||Object.keys(e.values).length!==2)throw new Error("范围条件需要两个明确边界");e.values.forEach(zt);const t=Qe(e.values[0],e.values[1],e);if(t===void 0||t>0)throw new Error("范围边界无效或顺序颠倒")}else if(e.right!==void 0){if(Un(e.right),Object.keys(e.right).length!==1)throw new Error("条件 right 只能指定一个 field 或 value");if("field"in e.right?nn(e.right.field):zt(e.right.value),e.value!==void 0)throw new Error("条件不能同时指定 value 和 right")}else zt(e.value)}function Vt(e,t){if(t===void 0)return!1;switch(e){case">":return t>0;case">=":return t>=0;case"<":return t<0;case"<=":return t<=0;case"==":return t===0;case"!=":return t!==0;default:return!1}}function cs(e){as(e),e={...e,right:e.right?{...e.right}:void 0,values:e.values?[e.values[0],e.values[1]]:void 0};const t=(r,n)=>Object.prototype.hasOwnProperty.call(r,n)?r[n]:void 0;return r=>{const n=t(r,e.field);if(e.op==="isNull")return n==null;if(e.op==="isNotNull")return n!=null;if(e.op==="between")return Vt(">=",Qe(n,e.values[0],e))&&Vt("<=",Qe(n,e.values[1],e));const o=e.right?"field"in e.right?t(r,e.right.field):e.right.value:e.value;return e.op==="contains"?typeof n=="string"&&typeof o=="string"&&n.includes(o):Vt(e.op,Qe(n,o,e))}}function q(e,t={nodes:0},r=0){if(++t.nodes>256||r>16)throw new Error("条件超出深度或节点预算");if(Un(e),["all","any","not","field"].filter(o=>Object.prototype.hasOwnProperty.call(e,o)).length!==1)throw new Error("条件只能指定一种组合或比较");if("not"in e){const o=q(e.not,t,r+1);return i=>!o(i)}if("all"in e||"any"in e){const o="all"in e?e.all:e.any;if(!Array.isArray(o)||o.length<1||o.length>256||Object.keys(o).length!==o.length)throw new Error("组合条件需要有界、无空位的非空数组");const i=o.map(s=>q(s,t,r+1));return"all"in e?s=>i.every(a=>a(s)):s=>i.some(a=>a(s))}return cs(e)}function us(e){q(e);const t=new Set;function r(n){"all"in n?n.all.forEach(r):"any"in n?n.any.forEach(r):"not"in n?r(n.not):(t.add(n.field),n.right&&"field"in n.right&&t.add(n.right.field))}return r(e),[...t]}function Gn(e){if(!e||e.kind==="date")return;const t=e.digits;if(!(t!==void 0&&(!Number.isInteger(t)||t<0||t>100))){if(e.kind==="percent"){const r=t??2;return`0${r?`.${"0".repeat(r)}`:""}%`}return t===void 0?e.thousands?"#,##0.###############":void 0:`${e.thousands?"#,##0":"0"}${t?`.${"0".repeat(t)}`:""}`}}function fs(e){const t=/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$/.exec(e.trim());if(t){const n=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return Number.isNaN(n.getTime())?null:n}const r=new Date(e);return Number.isNaN(r.getTime())?null:r}function rr(e,t){return e.toLocaleString("en-US",{minimumFractionDigits:t,maximumFractionDigits:t})}function ls(e,t){const r=n=>String(n).padStart(2,"0");return t.replace(/YYYY/g,String(e.getFullYear())).replace(/MM/g,r(e.getMonth()+1)).replace(/DD/g,r(e.getDate())).replace(/hh/g,r(e.getHours())).replace(/mm/g,r(e.getMinutes())).replace(/ss/g,r(e.getSeconds()))}function ds(e,t,r){return r!=null?t?rr(e,r):e.toFixed(r):t?rr(e):String(e)}function an(e){const t=typeof e=="number"?e:Number(String(e).replace(/,/g,""));return Number.isFinite(t)?t:null}function Er(e,t){if(e==null||e===""||!t)return String(e??"");switch(t.kind){case"number":{if(typeof e=="string")try{return rn(e,t.digits,t.thousands===!0)}catch{return e}const r=an(e);return r==null?String(e):ds(r,t.thousands===!0,t.digits)}case"percent":{if(typeof e=="string")try{return rn(e,t.digits??2,!0,!0)}catch{return e}const r=an(e);return r==null?String(e):`${rr(r*100,t.digits??2)}%`}case"date":{const r=t.pattern??"YYYY-MM-DD",n=e instanceof Date?e:fs(String(e));return n?ls(n,r):String(e)}default:return String(e)}}const ms=[{name:"add",minArgs:2,maxArgs:256,input:"numeric",output:"numeric",example:"add(quantity, adjustment)"},{name:"subtract",minArgs:2,maxArgs:2,input:"numeric",output:"numeric",example:"subtract(input, output)"},{name:"multiply",minArgs:2,maxArgs:256,input:"numeric",output:"numeric",example:"multiply(quantity, price)"},{name:"divide",minArgs:2,maxArgs:2,input:"numeric",output:"numeric",example:"divide(amount, quantity)"},{name:"coalesce",minArgs:2,maxArgs:256,input:"scalar",output:"scalar",example:"coalesce(actual, planned)"},{name:"if",minArgs:2,maxArgs:2,input:"condition + branches",output:"scalar",example:"if(quantity > 0, divide(amount, quantity), null)"},{name:"round",minArgs:1,maxArgs:2,input:"numeric, digits?",output:"numeric",example:"round(amount, 2)"},{name:"abs",minArgs:1,maxArgs:1,input:"numeric",output:"numeric",example:"abs(difference)"},{name:"concat",minArgs:2,maxArgs:256,input:"text",output:"text",example:"concat(plant, '-' , heat)"},{name:"trim",minArgs:1,maxArgs:1,input:"text",output:"text",example:"trim(heat)"},{name:"upper",minArgs:1,maxArgs:1,input:"text",output:"text",example:"upper(grade)"},{name:"lower",minArgs:1,maxArgs:1,input:"text",output:"text",example:"lower(code)"},{name:"dateYear",minArgs:1,maxArgs:1,input:"YYYY-MM-DD",output:"number",example:"dateYear(reportDate)"},{name:"dateMonth",minArgs:1,maxArgs:1,input:"YYYY-MM-DD",output:"number",example:"dateMonth(reportDate)"},{name:"dateDay",minArgs:1,maxArgs:1,input:"YYYY-MM-DD",output:"number",example:"dateDay(reportDate)"}],hs=Object.freeze(ms.map(e=>Object.freeze(e)));function gs(e,t,r,n,o){if(t.some(a=>a==null)){if(o==="error")throw new Error("函数参数包含空值");return null}if(e==="round"||e==="abs")return ps(e,t,r,n);if(e.startsWith("date")){const a=tr(t[0]);return Number(a.slice(e==="dateYear"?0:e==="dateMonth"?5:8,e==="dateYear"?4:e==="dateMonth"?7:10))}if(t.some(a=>typeof a!="string"))throw new Error("文本函数只接受文本,不隐式转换数字或空值");if(t.reduce((a,c)=>a+c.length,0)>1e6)throw new Error("计算文本超出长度预算");const i=t[0],s=e==="concat"?t.join(""):e==="trim"?i.trim():e==="upper"?i.toUpperCase():i.toLowerCase();if(s.length>1e6)throw new Error("计算文本超出长度预算");return s}function ps(e,t,r,n){const o=t[0];if(r!=="decimal"&&(typeof o!="number"||!Number.isFinite(o)))throw new Error("普通数值函数需要有限数字");const i=V(o);e==="abs"&&(i.coefficient=i.coefficient<0n?-i.coefficient:i.coefficient);const s=e==="round"?t.length===2?t[1]:n??0:n;if(s!==void 0){if(typeof s!="number")throw new Error("小数位必须为数字");He(s)}const a=Ft(i,s),c=Number(a);if(r!=="decimal"&&!Number.isFinite(c))throw new Error("计算结果不是有限数字");return r==="decimal"?a:c}const ys=["sum","count","avg","min","max","weightedAvg"];function cn(e){if(typeof e!="number"||!Number.isFinite(e))throw new Error("聚合度量必须是有限数字,不能隐式转换;小数文本请显式选择 decimal");return e}function ut(e,t){return t&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function ws(e){let t=0,r=0,n=0,o=0,i=1/0,s=-1/0;const a=c=>{const u=c-n,f=r+u;n=f-r-u,r=f};return{add(c){const u=ut(c,e.field);if(e.op==="count"){(!e.field||u!=null)&&t++;return}if(u==null)return;const f=cn(u),d=e.op==="weightedAvg"?ut(c,e.weightField):1;if(d==null)return;const l=cn(d);if(e.op==="weightedAvg"&&l<0)throw new Error("加权平均的权重不能为负数");["sum","avg","weightedAvg"].includes(e.op)&&a(f*l),o+=l,i=Math.min(i,f),s=Math.max(s,f),t++},value(){if(e.op==="count")return t;if(!t)return null;const c=e.op==="min"?i:e.op==="max"?s:e.op==="avg"?r/t:e.op==="weightedAvg"?o===0?null:r/o:r;if(c!==null&&!Number.isFinite(c))throw new Error("聚合计算溢出");return c}}}function bs(e){let t=0,r=V("0"),n=V("0"),o,i;return{add(s){const a=ut(s,e.field);if(e.op==="count"){(!e.field||a!=null)&&t++;return}if(a==null)return;const c=e.op==="weightedAvg"?ut(s,e.weightField):"1";if(c==null)return;const u=V(a),f=V(c);if(e.op==="weightedAvg"&&f.coefficient<0n)throw new Error("加权平均的权重不能为负数");["sum","avg","weightedAvg"].includes(e.op)&&(r=ct(r,Sr(u,f))),e.op==="weightedAvg"&&(n=ct(n,f)),(!o||at(u,o)<0)&&(o=u),(!i||at(u,i)>0)&&(i=u),t++},value(){if(e.op==="count")return t;if(!t||e.op==="weightedAvg"&&n.coefficient===0n)return null;let s=e.op==="min"?o:e.op==="max"?i:r;return e.op==="avg"&&(s=er(r,V(t),e.digits)),e.op==="weightedAvg"&&(s=er(r,n,e.digits)),Ft(s,e.digits)}}}function oe(e){if(e.digits!==void 0&&He(e.digits),e.numeric!==void 0&&e.numeric!=="number"&&e.numeric!=="decimal")throw new Error("未知聚合数值模式");if(!ys.includes(e.op))throw new Error("未知聚合操作");if(e.op!=="count"&&!e.field)throw new Error("聚合需要度量字段");if(e.op==="weightedAvg"&&!e.weightField)throw new Error("加权平均需要权重字段");return e.numeric==="decimal"?bs(e):ws(e)}function Be(e,t){const r=oe(t);for(const n of e)r.add(n);return r.value()}const xs=new Set(["__proto__","prototype","constructor"]);function K(e){if(typeof e!="string"||!e.trim()||xs.has(e))throw new Error("计算字段应为安全的非空字段名")}function Ar(e){return e===null||["string","boolean"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e)}function vs(e){if(e.some(t=>typeof t!="number"||!Number.isFinite(t)))throw new Error("算术参数必须是有限数字;空值和小数文本不会隐式转换");return e}function Ms(e,t){const r=vs(t);let n;if(e==="add")n=r.reduce((o,i)=>o+i,0);else if(e==="multiply")n=r.reduce((o,i)=>o*i,1);else if(e==="subtract")n=r[0]-r[1];else{if(r[1]===0)throw new Error("不能除以零");n=r[0]/r[1]}if(!Number.isFinite(n))throw new Error("计算结果不是有限数字");return n}function $s(e,t,r){const n=t.map(V);let o;return e==="add"?o=n.reduce(ct):e==="multiply"?o=n.reduce(Sr):e==="subtract"?o=ct(n[0],{...n[1],coefficient:-n[1].coefficient}):o=er(n[0],n[1],r),Ft(o,r)}function Ss(e,t,r){return r.nulls!=="error"&&t.some(n=>n==null)||e==="divide"&&r.divisionByZero==="null"&&(r.numeric==="decimal"?V(t[1]).coefficient===0n:t[1]===0)?null:r.numeric==="decimal"?$s(e,t,r.digits):Ms(e,t)}function Es(e,t){e.field!==void 0&&K(e.field),e.weightField!==void 0&&K(e.weightField);const r={op:e.aggregate,field:e.field,weightField:e.weightField,numeric:t.numeric,digits:t.digits};Be([],r);const n=new WeakMap;return o=>{let i=n.get(o.rows);if(!i){try{i={value:Be(o.rows,r)}}catch(s){i={error:s instanceof Error?s:new Error(String(s))}}n.set(o.rows,i)}if(i.error)throw i.error;return i.value}}function As(e,t){for(const r of e){const n=r(t);if(n!=null)return n}return null}function kr(e,t={},r={nodes:0},n=0){if(++r.nodes>256||n>16)throw new Error("计算表达式超出深度或节点预算");if(!e||typeof e!="object"||Array.isArray(e))throw new Error("计算表达式应为声明式对象");if("aggregate"in e)return Es(e,t);if("field"in e){K(e.field);const o=e.field;return({row:i})=>Object.prototype.hasOwnProperty.call(i,o)?i[o]:void 0}if("value"in e){if(!Ar(e.value))throw new Error("常量应为有限 JSON 标量");return()=>e.value}return ks(e,t,r,n)}function ks(e,t,r,n){const o=hs.find(a=>a.name===e.op);if(!o||!Array.isArray(e.args))throw new Error("未知计算操作");if(e.args.length>256||Object.keys(e.args).length!==e.args.length)throw new Error("计算参数超出预算或包含空位");if(e.args.length<o.minArgs||e.args.length>o.maxArgs)throw new Error("运算参数数量不正确");const i=e.op==="if"?q(e.condition,r,n+1):void 0;if(e.op!=="if"&&e.condition!==void 0)throw new Error("仅 IF 运算接受 condition");const s=e.args.map(a=>kr(a,t,r,n+1));return i?a=>s[i(a.row)?0:1](a):["add","subtract","multiply","divide","coalesce"].includes(e.op)?e.op==="coalesce"?a=>As(s,a):a=>Ss(e.op,s.map(c=>c(a)),t):a=>gs(e.op,s.map(c=>c(a)),t.numeric,t.digits,t.nulls)}function Ns(e){kr(e);const t=new Set,r=n=>{"field"in n&&n.field&&t.add(n.field),"aggregate"in n&&n.weightField&&t.add(n.weightField),"args"in n&&(n.args.forEach(r),n.condition&&us(n.condition).forEach(o=>t.add(o)))};return r(e),[...t]}const Ps=16,nr=1024*1024,un=5e5,ft=new WeakMap,le=Symbol("uncacheable-computation-definition");function et(e,t,r=0){if(++t.nodes>1e4||r>32)throw le;if(e==null)return[String(e)];if(typeof e=="number")return["number",Object.is(e,-0)?"-0":String(e)];if(typeof e=="boolean")return["boolean",e];if(typeof e=="string"){if(t.units+=e.length,t.units>nr)throw le;return["string",e]}if(typeof e!="object")throw le;if(Array.isArray(e)){if(Object.getPrototypeOf(e)!==Array.prototype||Object.keys(e).length!==e.length)throw le;return["array",Array.from({length:e.length},(n,o)=>et(fn(e,String(o)),t,r+1))]}if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw le;return["object",Object.keys(e).map(n=>[et(n,t,r+1),et(fn(e,n),t,r+1)])]}function fn(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||r.get||r.set)throw le;return r.value}function Fs(e){try{return JSON.stringify(et(e,{nodes:0,units:0}))}catch(t){if(t!==le)throw t;return}}function Os(e){ft.set(e,{programs:new Map,units:0,slots:0})}function Is(e,t){const r=ft.get(e);if(!r)return;const n={programs:new Map,units:r.units,slots:r.slots};for(const[o,i]of r.programs){const s=new WeakMap;t.forEach((a,c)=>{const u=i.rows.get(e[c]);u&&s.set(a,u)}),n.programs.set(o,{...i,rows:s})}ft.set(t,n)}function Rs(e,t,r){const n=ft.get(e);if(!n||t.some(u=>typeof u.expression=="string"))return;const o=Fs(t);if(o===void 0||o.length>nr)return;const i=n.programs.get(o);if(i)return i;const s=r(),a=e.length*s.reduce((u,f)=>u+f.dependencies.length+1,0),c={fields:s,rows:new WeakMap,slots:a,cacheRows:a<=un};if(!c.cacheRows)return c;for(;n.programs.size>=Ps||n.units+o.length>nr||n.slots+a>un;){const u=n.programs.keys().next().value;n.slots-=n.programs.get(u).slots,n.units-=u.length,n.programs.delete(u)}return n.programs.set(o,c),n.units+=o.length,n.slots+=a,c}function Cs(e,t,r,n){if((r.definition.scope??"row")!=="row")return;const o=e.program?.rows.get(t)?.get(r.definition.field);return o?.dependencies.every((i,s)=>Object.is(n[r.dependencies[s]],i))?o:void 0}function Ts(e,t,r,n,o){const i=e.program;if(!i?.cacheRows||(r.definition.scope??"row")!=="row")return;let s=e.writes.get(t);s||(s=new Map(i.rows.get(t)),e.writes.set(t,s),i.rows.set(t,s)),s.set(r.definition.field,{dependencies:r.dependencies.map(a=>n[a]),value:n[r.definition.field],...o?{issue:{field:o.field,message:o.message}}:{}})}function js(e){if(K(e.field),e.scope!==void 0&&!["row","group","dataset"].includes(e.scope))throw new Error("未知计算范围");if(e.numeric!==void 0&&e.numeric!=="number"&&e.numeric!=="decimal")throw new Error("未知数值模式");if(e.digits!==void 0&&He(e.digits),e.nulls!==void 0&&e.nulls!=="propagate"&&e.nulls!=="error")throw new Error("未知空值规则");if(e.divisionByZero!==void 0&&e.divisionByZero!=="null"&&e.divisionByZero!=="error")throw new Error("未知除零规则");if(e.scope==="group"&&(!Array.isArray(e.groupBy)||!e.groupBy.length))throw new Error("分组计算需要 groupBy 字段");Ds(e)}function Ds(e){if(e.groupBy!==void 0){if(!Array.isArray(e.groupBy)||e.groupBy.length>16)throw new Error("计算分组最多 16 级");e.groupBy.forEach(K)}if(e.dependsOn!==void 0){if(!Array.isArray(e.dependsOn)||e.dependsOn.length>2048)throw new Error("计算依赖超出预算");e.dependsOn.forEach(K)}}function Nr(e){return[...new Set([...typeof e.expression=="string"?e.dependsOn??[]:Ns(e.expression),...e.groupBy??[]])]}function Yn(e){if(!Array.isArray(e)||e.length>2048)throw new Error("计算字段应为数组且最多2048项");const t=new Map;for(const s of e){if(js(s),t.has(s.field))throw new Error(`计算字段重复:${s.field}`);t.set(s.field,s)}const r=new Set,n=new Set,o=[];function i(s){if(!n.has(s.field)){if(r.has(s.field))throw new Error(`计算字段存在循环依赖:${[...r,s.field].join(" → ")}`);r.add(s.field);for(const a of Nr(s)){const c=t.get(a);c&&i(c)}r.delete(s.field),n.add(s.field),o.push(s)}}return e.forEach(i),o}function Ls(e){try{const t=Yn(e);return{valid:!0,errors:[],order:t.map(r=>r.field),fields:e.map(r=>({field:r.field,dependencies:Nr(r),scope:r.scope??"row"}))}}catch(t){return{valid:!1,errors:[t instanceof Error?t.message:String(t)],fields:[],order:[]}}}function ln(e){return Yn(e.fields).map(t=>{const r=Nr(t);if(typeof t.expression!="string")return{definition:t,dependencies:r,read:kr(t.expression,t)};if(!e.formula)throw new Error("字符串公式需要显式配置 formula adapter");const n=t.expression;return{definition:t,dependencies:r,read:o=>e.formula.evaluate(n,o)}})}function Bs(e,t){return JSON.stringify(t.map(r=>{const n=Object.prototype.hasOwnProperty.call(e,r)?e[r]:null;if(n!=null&&!Ar(n))throw new Error("分组字段应为有限 JSON 标量");return[typeof n,n??null]}))}function _s(e,t){if(t.scope==="dataset")return()=>e;if(t.scope!=="group"){const o=new WeakMap;return i=>{let s=o.get(i);return s||(s=[i],o.set(i,s)),s}}const r=new Map,n=new WeakMap;for(const o of e){const i=Bs(o,t.groupBy);n.set(o,i);const s=r.get(i);s?s.push(o):r.set(i,[o])}return o=>r.get(n.get(o))}function Ks(e,t){const r=t.maxRows??1e5,n=t.maxCells??2e6;if(!Array.isArray(e)||!Number.isSafeInteger(r)||r<1||e.length>r)throw new Error("计算数据行数超出预算或输入不是数组");if(!Array.isArray(t.fields)||t.fields.length>2048)throw new Error("计算字段应为数组且最多2048项");if(!Number.isSafeInteger(n)||n<1||e.length*t.fields.length>n)throw new Error("计算单元格超出 maxCells 预算")}function dn(e){if(e?.aborted){const t=new Error("数据计算已取消");throw t.name="AbortError",t}}function Ws(e,t,r,n,o,i){try{const s=e.read({row:t,rowIndex:r,rows:n});if(s!==void 0&&!Ar(s))throw new Error("计算结果应为有限 JSON 标量,异步公式请先在数据源中求值");t[e.definition.field]=s??null}catch(s){const a=s instanceof Error?s.message:String(s);if(o.onError!=="null")throw Object.assign(new Error(`第 ${r+1} 行 ${e.definition.field}:${a}`),{cause:s});t[e.definition.field]=null,i.push({rowIndex:r,field:e.definition.field,message:a})}}function Js(e,t,r,n,o,i,s,a){const c=Cs(e,t,r,n);if(c&&(!c.issue||s.onError==="null")){n[r.definition.field]=c.value,c.issue&&a.push({...c.issue,rowIndex:o});return}const u=a.length;Ws(r,n,o,i,s,a),Ts(e,t,r,n,a.length>u?a[a.length-1]:void 0)}function Ot(e,t){Ks(e,t),dn(t.signal);const r=Rs(e,t.fields,()=>ln(t)),n={program:r,writes:new WeakMap},o=r?.fields??ln(t),i=[],s=e.map((a,c)=>{if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`第 ${c+1} 行应为对象`);return{...a}});for(const a of o){const c=_s(s,a.definition);s.forEach((u,f)=>{dn(t.signal),Js(n,e[f],a,u,f,c(u),t,i)})}return{rows:s,issues:i}}function Pe(e,t,r){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype||e.length>t)throw new TypeError(`${r}应为有界普通数组`);if(Reflect.ownKeys(e).length!==e.length+1)throw new TypeError(`${r}不支持自定义数组方法或迭代器`);const n=[];for(let o=0;o<e.length;o++){const i=Object.getOwnPropertyDescriptor(e,String(o));if(!i||!Object.prototype.hasOwnProperty.call(i,"value"))throw new TypeError(`${r}不支持空洞或访问器`);n.push(i.value)}return n}const $e=["#2563eb","#0d9488","#d97706","#7c3aed","#dc2626","#0284c7"];function zs(e){if(!["bar","line","stackedBar","percentBar"].includes(e.type))throw new Error("未知图表类型");if(!Array.isArray(e.categories)||!Array.isArray(e.series)||!e.categories.length||e.categories.length>200||!e.series.length||e.series.length>12)throw new Error("图表支持 1–200 个分类、1–12 个系列;大数据应先聚合");const t=Pe(e.categories,200,"图表分类"),r=Pe(e.series,12,"图表系列").map(n=>({...n,values:Pe(n?.values,200,"图表数值")}));for(const n of t)if(typeof n!="string")throw new Error("图表分类应为字符串");Vs(e);for(const n of r)Hs(n,t.length);return{...e,categories:t,series:r}}function Vs(e){for(const t of["leftMm","topMm","widthMm","heightMm"])if(!Number.isFinite(e[t])||e[t]<0)throw new Error(`${t} 应为有限非负数`);if(e.widthMm<45||e.heightMm<35)throw new Error("图表至少需要 45×35mm");if(!Number.isFinite(e.leftMm+e.widthMm)||!Number.isFinite(e.topMm+e.heightMm))throw new Error("图表几何范围溢出")}function Hs(e,t){if(!e||typeof e.name!="string"||!Array.isArray(e.values)||e.values.length!==t)throw new Error("图表系列应提供名称及逐分类的有限数字或 null");for(const r of e.values)if(r!==null&&!Number.isFinite(r))throw new Error("图表系列应提供名称及逐分类的有限数字或 null");if(e.color!==void 0&&!/^#[\da-f]{6}$/i.test(e.color))throw new Error("图表颜色应为 #RRGGBB")}function or(e,t,r,n,o,i=.8){return{kind:"line",leftMm:Math.min(e,r),topMm:Math.min(t,n),widthMm:Math.abs(r-e),heightMm:Math.abs(n-t),lineDirection:n<t?"up":"down",style:{lineColor:o,lineWidthPt:i}}}function we(e,t,r,n,o="center"){return{kind:"text",text:e,leftMm:t,topMm:r,widthMm:n,heightMm:5,style:{fontSize:8,color:"#475569",align:o,verticalAlign:"middle"}}}function lt(e){return Number(e.toPrecision(5)).toString()}function Us(e){let t=0,r=0;const n=qn(e)?Gs(e):void 0;if(n)t=n.min,r=n.max;else for(const d of e.series)for(const l of d.values)l!==null&&(t=Math.min(t,l),r=Math.max(r,l));t===r&&(r=t+1);const o=e.leftMm+13,i=e.topMm+8,s=e.widthMm-17,a=e.heightMm-23,c=Math.max(Math.abs(t),Math.abs(r),1),u=t/c,f=r/c-u;return{left:o,top:i,width:s,height:a,min:t,max:r,y:d=>i+a*(1-(d/c-u)/f)}}function qn(e){return e.type==="stackedBar"||e.type==="percentBar"}function Gs(e){let t=0,r=e.type==="percentBar"?100:0;for(let n=0;n<e.categories.length;n++){let o=0,i=0;for(const s of e.series){const a=s.values[n]??0;a<0?i+=a:o+=a}if(!Number.isFinite(o)||!Number.isFinite(i))throw new Error("图表堆叠合计溢出,请先明确缩放单位");t=Math.min(t,i),r=Math.max(r,o)}return{min:t,max:r}}function Ys(e){if(e.type!=="percentBar")return e;const t=e.categories.map((r,n)=>{let o=0;for(const i of e.series){const s=i.values[n];if(s!==null&&s<0)throw new Error("占比图需要非负度量,负数口径应由业务明确处理");o=Math.max(o,s??0)}return{scale:o,total:o?e.series.reduce((i,s)=>i+(s.values[n]??0)/o,0):0}});return{...e,series:e.series.map(r=>({...r,values:r.values.map((n,o)=>{if(n===null)return null;const{scale:i,total:s}=t[o];return i&&s?n/i/s*100:0})}))}}function qs(e,t){const r=[],n=t.width/e.categories.length;return e.categories.forEach((o,i)=>{let s=0,a=0;e.series.forEach((c,u)=>{const f=c.values[i];if(f==null)return;const d=f<0?a:s,l=d+f;f<0?a=l:s=l;const m=Math.min(t.y(d),t.y(l)),h=Math.abs(t.y(l)-t.y(d)),p=c.color??$e[u%$e.length],w=t.left+n*(i+.15),y=n*.7;r.push({kind:"rect",leftMm:w,topMm:m,widthMm:y,heightMm:h,style:{backgroundColor:p,borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}}),e.showValues&&h>=5&&r.push({...we(e.type==="percentBar"?`${lt(f)}%`:lt(f),w,m+h/2-2.5,y),style:{fontSize:7,color:"#ffffff",align:"center"}})})}),r}function Xs(e,t){const r=[];e.title&&r.push({...we(e.title,e.leftMm,e.topMm,e.widthMm),style:{fontSize:10,bold:!0,align:"left"}});for(let i=0;i<=4;i++){const s=i/4,a=t.min*(1-s)+t.max*s,c=t.y(a);r.push(or(t.left,c,t.left+t.width,c,"#e2e8f0",.4),we(`${lt(a)}${e.type==="percentBar"?"%":""}`,e.leftMm,c-2.5,11,"right"))}r.push(or(t.left,t.top,t.left,t.top+t.height,"#94a3b8"));const n=Math.max(1,Math.ceil(e.categories.length/Math.max(1,Math.floor(t.width/14))));e.categories.forEach((i,s)=>{s%n===0&&r.push(we(i,t.left+(s+.5)*t.width/e.categories.length-7,t.top+t.height+1,14))});const o=t.width/e.series.length;return e.series.forEach((i,s)=>{r.push({...we(i.name,t.left+s*o,e.topMm+e.heightMm-5,o),style:{fontSize:8,color:i.color??$e[s%$e.length],align:"center"}})}),r}function Zs(e,t,r,n){const o=[],i=r.color??$e[n%$e.length],s=t.width/e.categories.length,a=s*.75/e.series.length;let c;return r.values.forEach((u,f)=>{if(u===null){c=void 0;return}const d=t.left+(f+.5)*s,l=t.y(u);e.type==="bar"?o.push({kind:"rect",leftMm:t.left+f*s+s*.125+n*a,topMm:Math.min(l,t.y(0)),widthMm:a,heightMm:Math.abs(t.y(0)-l),style:{backgroundColor:i,borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}}):(c&&o.push(or(c.x,c.y,d,l,i,1.2)),o.push({kind:"ellipse",leftMm:d-.7,topMm:l-.7,widthMm:1.4,heightMm:1.4,style:{backgroundColor:i,borderColor:i}}),c={x:d,y:l}),e.showValues&&o.push({...we(lt(u),d-s/2,Math.max(t.top,l-5),s),style:{fontSize:7,color:i,align:"center"}})}),o}function Qs(e,t){let r=0,n=!1;for(const o of t.values){if(o===null){n=!1;continue}r+=1+ +!!e.showValues,e.type==="line"&&n&&r++,n=!0}return r}function ea(e){const t=e.categories.length,r=Math.max(1,Math.ceil(t/Math.max(1,Math.floor((e.widthMm-17)/14)))),n=11+ +!!e.title+Math.ceil(t/r)+e.series.length;return e.series.reduce((o,i)=>o+Qs(e,i),n)}function ta(e){e=Ys(zs(e));const t=Us(e);return[...Xs(e,t),...qn(e)?qs(e,t):e.series.flatMap((r,n)=>Zs(e,t,r,n))]}function dt(e,t,r){if(e===void 0)return t;if(!Number.isSafeInteger(e)||Number(e)<1||Number(e)>r)throw new RangeError("图表预算超出允许范围");return Number(e)}function Xn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("图表绑定应为对象");if(K(e.dataset),K(e.categoryField),!["bar","line","stackedBar","percentBar"].includes(e.type))throw new TypeError("图表类型无效");if(e.sort!==void 0&&!["asc","desc"].includes(e.sort))throw new TypeError("图表排序无效");if(e.title!==void 0&&(typeof e.title!="string"||e.title.length>512))throw new TypeError("图表标题过长");if(e.showValues!==void 0&&typeof e.showValues!="boolean")throw new TypeError("图表数值标签应为布尔值");if(!Array.isArray(e.measures)||!e.measures.length||e.measures.length>12)throw new RangeError("图表支持 1–12 个度量");for(const t of Pe(e.measures,12,"图表度量"))ra(t);dt(e.maxRows,1e5,1e5),dt(e.maxCategories,200,200)}function ra(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("图表度量应为对象");if(e.field!==void 0&&K(e.field),e.weightField!==void 0&&K(e.weightField),e.label!==void 0&&(typeof e.label!="string"||e.label.length>256))throw new TypeError("图表系列名称过长");if(e.color!==void 0&&!/^#[\da-f]{6}$/i.test(e.color))throw new TypeError("图表颜色应为 #RRGGBB");oe(e)}function na(e){if(e==null)return{key:"null",label:"—"};if(typeof e!="string"&&typeof e!="boolean"&&!(typeof e=="number"&&Number.isFinite(e)))throw new TypeError("图表分类应为文本、布尔或有限数字");const t=String(e);if(t.length>512)throw new RangeError("图表分类名称过长");return{key:JSON.stringify([typeof e,e]),label:t}}function oa(e){if(e===null)return null;const t=Number(e);if(!Number.isFinite(t))throw new RangeError("聚合结果超出图表有限数值范围");return t}function ia(e,t,r){if(r?.aborted){const a=new Error("图表数据处理已取消");throw a.name="AbortError",a}Xn(t);const n=Pe(t.measures,12,"图表度量");if(!Array.isArray(e)||e.length>dt(t.maxRows,1e5,1e5))throw new RangeError("图表数据超出行数预算");const o=new Map,i=dt(t.maxCategories,200,200);for(let a=0;a<e.length;a++){if(r?.aborted){const d=new Error("图表数据处理已取消");throw d.name="AbortError",d}const c=e[a];if(!c||typeof c!="object"||Array.isArray(c))throw new TypeError("图表数据行应为对象");const u=na(Object.prototype.hasOwnProperty.call(c,t.categoryField)?c[t.categoryField]:null);let f=o.get(u.key);if(!f){if(o.size>=i)throw new RangeError("图表分类超出预算,请明确筛选或聚合数据");f={label:u.label,accumulators:n.map(oe)},o.set(u.key,f)}f.accumulators.forEach(d=>d.add(c))}const s=[...o.values()];return t.sort&&s.sort((a,c)=>(t.sort==="desc"?-1:1)*(a.label<c.label?-1:a.label>c.label?1:0)),{categories:s.map(a=>a.label),series:n.map((a,c)=>({name:a.label??`${a.field??"记录"} · ${a.op}`,values:s.map(u=>oa(u.accumulators[c].value())),...a.color?{color:a.color}:{}}))}}class Se extends Error{constructor(t,r){super(`报表页数超出上限 ${t}(至少 ${r} 页)`),this.limit=t,this.actual=r,this.code="page-limit",this.name="PaginatePageLimitError"}}class _e extends Error{constructor(t,r){super(`报表单元格数量超出上限 ${t}(至少 ${r} 格)`),this.limit=t,this.actual=r,this.code="cell-limit",this.name="PaginateCellLimitError"}}class Ke extends Error{constructor(t,r){super(`报表图表图元数量预计超出上限 ${t}(本次估算 ${r})`),this.limit=t,this.estimated=r,this.code="chart-component-limit",this.name="PaginateChartComponentLimitError"}}const Pr=5e4;function It(e=Pr){if(!Number.isSafeInteger(e)||e<1||e>1e6)throw new RangeError("maxChartComponents 应为 1..1000000 的安全整数")}function sa(e,t,r){const n=e.chartBinding;if(e.kind!=="chart"||e.grid||e.imageData||e.binding||e.pageAnchor)throw new TypeError("绑定图表不能同时设置图片、网格、记录绑定或页眉页脚");const o=Object.prototype.hasOwnProperty.call(t,n.dataset)?t[n.dataset]:void 0;if(!Array.isArray(o))throw new TypeError(`图表数据集 ${n.dataset} 未提供`);return{...ia(o,n,r),type:n.type,leftMm:e.leftMm,topMm:e.topMm,widthMm:e.widthMm,heightMm:e.heightMm,title:n.title,showValues:n.showValues}}function aa(e,t,r=Pr){It(r);let n=0;return Object.assign(i=>{if(!i.chartBinding)return[i];const s=sa(i,e,t),a=n+(s.categories.length?ea(s):1);if(!Number.isSafeInteger(a))throw new RangeError("图表图元估算应为有限安全整数");if(a>r)throw new Ke(r,a);const c=s.categories.length?ta(s):[{kind:"text",leftMm:i.leftMm,topMm:i.topMm,widthMm:i.widthMm,heightMm:i.heightMm,text:"—",style:{align:"center",verticalAlign:"middle",color:"#94a3b8",fontSize:10}}];return n+=c.length,c},{used:()=>n})}function Fe(e,t){return JSON.stringify([e.slice(0,t.length),t.map(r=>[r===null?"null":typeof r,r])])}function Zn(e,t){return t.map(r=>{const n=Object.prototype.hasOwnProperty.call(e,r)?e[r]:null;if(n==null)return null;if(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))return n;throw new Error("矩阵维度必须是有限 JSON 标量")})}function ca(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("矩阵层级应为对象");for(const n of[e.emptyLabel,e.subtotalLabel,e.totalLabel])if(n!==void 0&&typeof n!="string")throw new Error("矩阵层级标签应为字符串");mn(e.row,t.length),mn(e.column,r.length)}function mn(e,t){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("矩阵轴配置应为对象");if(e.labels!==void 0&&(!Array.isArray(e.labels)||e.labels.length!==t||e.labels.some(r=>typeof r!="string")))throw new Error("矩阵维度标签必须与维度字段一一对应");if(e.sort!==void 0&&(!Array.isArray(e.sort)||e.sort.length>t||e.sort.some(r=>!["source","asc","desc"].includes(r))))throw new Error("矩阵维度排序应为 source、asc 或 desc");if(e.subtotals!==void 0&&(!Array.isArray(e.subtotals)||new Set(e.subtotals).size!==e.subtotals.length||e.subtotals.some(r=>!Number.isInteger(r)||r<1||r>=t)))throw new Error("矩阵小计深度应唯一且位于 1 至末级之前")}}function hn(e,t,r){return{fields:e,options:t??{},hierarchy:r,root:{values:[],children:new Map},leaves:0,expanded:0}}function gn(e,t){const r=Zn(t,e.fields);let n=e.root;for(let o=1;o<=r.length;o++){const i=r.slice(0,o),s=Fe(e.fields,i);let a=n.children.get(s);a||(a={values:i,children:new Map},n.children.set(s,a),o===r.length?(e.leaves++,e.expanded++):e.options.subtotals?.includes(o)&&e.expanded++),n=a}}function ua(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;if(typeof e=="number"&&typeof t=="number")return e-t;const r=`${typeof e}:${e}`,n=`${typeof t}:${t}`;return r<n?-1:1}function fa(e,t){const r=[...e.children.values()];return t&&t!=="source"&&r.sort((n,o)=>ua(n.values[n.values.length-1],o.values[o.values.length-1])*(t==="desc"?-1:1)),r}function Ht(e,t,r){return{key:Fe(e.fields,t),kind:r,depth:t.length,fields:e.fields.slice(0,t.length),values:t,labels:t.map(n=>n===null?e.hierarchy.emptyLabel??"(空)":String(n))}}function pn(e,t){const r=[];function n(o){for(const i of fa(o,e.options.sort?.[o.values.length]))i.children.size?(n(i),e.options.subtotals?.includes(i.values.length)&&r.push(Ht(e,i.values,"subtotal"))):r.push(Ht(e,i.values,"member"))}return n(e.root),t&&e.leaves&&r.push(Ht(e,[],"total")),r}function yn(e,t,r){const n=Zn(t,e.fields),o=[Fe(e.fields,n),...(e.options.subtotals??[]).map(i=>Fe(e.fields,n.slice(0,i)))];return r&&o.push(Fe(e.fields,[])),o}function la(e,t,r){if(!(e.kind!=="member"&&t>e.depth))return e.kind==="total"?{key:"total",text:r.totalLabel??"合计",rowSpan:0}:e.kind==="subtotal"&&t===e.depth?{key:e.key,text:r.subtotalLabel??"小计",rowSpan:0}:{key:JSON.stringify(e.values.slice(0,t+1).map(n=>[typeof n,n])),text:e.labels[t],rowSpan:1}}function da(e,t){const r=e.columnFields.length+1,n=e.rowFields.length,o=Array.from({length:r},()=>Array(n+t.length).fill(null));for(let i=0;i<e.columnFields.length;i++){let s;t.forEach((a,c)=>{const u=la(a,i,e.hierarchy);if(!u){s=void 0;return}if(s?.key===u.key){s.cell.colSpan=(s.cell.colSpan??1)+1;return}const f={text:u.text,rowSpan:u.rowSpan||e.columnFields.length-i,editable:!1,derived:!0};o[i][n+c]=f,s={key:u.key,cell:f}})}return e.rowFields.forEach((i,s)=>{o[0][s]={text:e.hierarchy.row?.labels?.[s]??i,rowSpan:r,editable:!1,derived:!0}}),t.forEach((i,s)=>{const a=e.measures[i.measure];o[r-1][n+s]={text:a.label??`${a.field} (${a.op})`,editable:!1,derived:!0}}),{cells:o.map(i=>i.filter(s=>s!==null)),colWidthsMm:[...e.rowFields.map(()=>e.rowWidthMm??40),...t.map(()=>e.columnWidthMm??28)]}}function wn(e,t,r,n){const o=+(!!t.totals&&e>0),i=r.expanded+o,s=(n.expanded+o)*t.measures.length+t.rowFields.length;if(i>(t.maxRows??1e3)||n.expanded+o>(t.maxColumns??200))throw new Error("矩阵层级展开数量超出预算(包含小计/总计)");if(i*s>(t.maxCells??2e6))throw new Error("矩阵输出超出 maxCells 预算");return{rowCount:i,columnCount:s,cells:i*s}}function Qn(e,t){if(!Array.isArray(e)||e.length>(t.maxInputRows??1e5))throw new Error("矩阵输入超出预算");const r=hn(t.rowFields,t.hierarchy.row,t.hierarchy),n=hn(t.columnFields,t.hierarchy.column,t.hierarchy);if(e.length*(1+(r.options.subtotals?.length??0)+ +!!t.totals)*(1+(n.options.subtotals?.length??0)+ +!!t.totals)*t.measures.length>(t.maxAggregateUpdates??1e7))throw new Error("矩阵聚合更新超出 maxAggregateUpdates 预算");let i=wn(0,t,r,n);for(const s of e){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("矩阵数据行应为对象");gn(r,s),gn(n,s),i=wn(e.length,t,r,n)}return{row:r,column:n,shape:i}}function ma(e,t){return Qn(e,t).shape}function ha(e,t,r){const n=new Map;for(const o of e){const i=yn(r.row,o,!!t.totals),s=yn(r.column,o,!!t.totals);for(const a of i){let c=n.get(a);c||(c=new Map,n.set(a,c));for(const u of s){let f=c.get(u);f||(f=t.measures.map(d=>oe({...d,field:d.valueField??d.field})),c.set(u,f)),f.forEach(d=>d.add(o))}}}return n}function ga(e,t){return e.flatMap((r,n)=>t.measures.map((o,i)=>({...r,field:r.kind==="total"?`total_${i}`:`c${n}_${i}`,measure:i,measureField:o.field,valueField:o.valueField??o.field,operation:o.op})))}function pa(e,t){return e.kind==="total"?t.hierarchy.totalLabel??"合计":[...e.labels,...e.kind==="subtotal"?[t.hierarchy.subtotalLabel??"小计"]:[]].join(" / ")}function ya(e,t){return[...t.rowFields.map((r,n)=>({field:`r${n}`,header:t.hierarchy.row?.labels?.[n]??r,semanticRole:"dimension"})),...e.map(r=>{const n=t.measures[r.measure];return{field:r.field,header:`${pa(r,t)} · ${n.label??`${n.field} (${n.op})`}`,semanticRole:"measure",...n.digits===void 0?{}:{format:{kind:"number",digits:n.digits}}}})]}function wa(e,t,r,n){return e.map(o=>{const i={};r.rowFields.forEach((s,a)=>{i[`r${a}`]=o.kind==="total"?a===0?r.hierarchy.totalLabel??"合计":null:o.labels[a]??(a===o.depth?r.hierarchy.subtotalLabel??"小计":null)});for(const s of t)i[s.field]=n.get(o.key)?.get(s.key)?.[s.measure]?.value()??(r.measures[s.measure].op==="count"?0:null);return i})}function ba(e,t){const r=Qn(e,t),n=pn(r.row,!!t.totals),o=ga(pn(r.column,!!t.totals),t),i=ha(e,t,r);return{columns:ya(o,t),rows:wa(n,o,t,i),headerGrid:da(t,o),metadata:{rowFields:[...t.rowFields],rowLabels:[...t.hierarchy.row?.labels??t.rowFields],columnFields:[...t.columnFields],columnLabels:[...t.hierarchy.column?.labels??t.columnFields],rows:n,columns:o}}}function xa(e,t){const r=()=>t.measures.map(c=>oe(c)),n=new Map,o=new Map,i=new Map,s=t.totals?r():void 0,a=(c,u)=>c?.forEach(f=>f.add(u));for(const c of e){const u=t.row(c),f=t.column(c);o.has(f.key)||o.set(f.key,f.label);let d=n.get(u.key);d||(d={label:u.label,cells:new Map,...t.totals?{totals:r()}:{}},n.set(u.key,d)),t.check(n.size,o.size);let l=d.cells.get(f.key);if(l||(l=r(),d.cells.set(f.key,l)),a(l,c),!t.totals)continue;let m=i.get(f.key);m||(m=r(),i.set(f.key,m)),a(d.totals,c),a(m,c),a(s,c)}return{groups:n,columns:o,columnTotals:i,totals:s}}function mt(e,t){const r=t.map(n=>Object.prototype.hasOwnProperty.call(e,n)?e[n]:null);if(r.some(n=>n!=null&&typeof n!="string"&&typeof n!="boolean"&&!(typeof n=="number"&&Number.isFinite(n))))throw new Error("矩阵维度必须是有限 JSON 标量");return{key:JSON.stringify(r.map(n=>[typeof n,n??null])),label:r.map(n=>n==null?"":String(n)).join(" / ")}}function va(e){for(const t of["maxRows","maxColumns","maxInputRows","maxCells","maxAggregateUpdates"])if(e[t]!==void 0&&(!Number.isSafeInteger(e[t])||e[t]<1))throw new Error("矩阵预算应为正安全整数");for(const t of["columnWidthMm","rowWidthMm"])if(e[t]!==void 0&&(!Number.isFinite(e[t])||e[t]<=0))throw new Error("矩阵列宽应为正数")}function Fr(e){if(!e||!Array.isArray(e.rowFields)||!Array.isArray(e.columnFields)||!Array.isArray(e.measures))throw new Error("矩阵需要行维度、列维度和度量数组");for(const r of[e.rowFields,e.columnFields])if(r.some(n=>typeof n!="string"||!n.trim())||new Set(r).size!==r.length)throw new Error("矩阵维度字段应非空且唯一");if(va(e),!e.rowFields.length||!e.columnFields.length||e.rowFields.length>16||e.columnFields.length>16)throw new Error("矩阵需要 1–16 个行/列维度");if(!e.measures.length||e.measures.length>32)throw new Error("矩阵需要 1–32 个度量");if(e.measures.map(r=>{if(!r||typeof r!="object")throw new Error("矩阵度量应为对象");if(oe({...r,field:r.valueField??r.field}),r.label!==void 0&&typeof r.label!="string")throw new Error("矩阵度量标签应为字符串");return r.field}).some(r=>typeof r!="string"||!r.trim()))throw new Error("矩阵度量字段应非空");e.hierarchy!==void 0&&ca(e.hierarchy,e.rowFields,e.columnFields)}function eo(e,t){if(Fr(t),t.hierarchy)return ma(e,t);if(!Array.isArray(e)||e.length>(t.maxInputRows??1e5))throw new Error("矩阵输入超出预算");const r=new Set,n=new Set;for(const s of e){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("矩阵数据行应为对象");if(r.add(mt(s,t.rowFields).key),n.add(mt(s,t.columnFields).key),r.size>(t.maxRows??1e3)||n.size>(t.maxColumns??200))throw new Error("矩阵维度数量超出预算");if((r.size+ +!!t.totals)*((n.size+ +!!t.totals)*t.measures.length+1)>(t.maxCells??2e6))throw new Error("矩阵输出超出 maxCells 预算")}const o=r.size+ +(!!t.totals&&e.length>0),i=(n.size+ +!!t.totals)*t.measures.length+1;return{rowCount:o,columnCount:i,cells:o*i}}function Ma(e,t){if(t?.hierarchy)return Fr(t),ba(e,t);eo(e,t);const r=xa(e,{row:s=>mt(s,t.rowFields),column:s=>mt(s,t.columnFields),measures:t.measures.map(s=>({...s,field:s.valueField??s.field})),totals:t.totals,check:()=>{}}),n=[...r.groups.values()].map(s=>({rowLabel:s.label})),o=[{field:"rowLabel",header:t.rowHeader??t.rowFields.join(" / "),semanticRole:"dimension"}],i={rowLabel:"合计"};return t.measures.forEach((s,a)=>{const c=[...r.columns.entries()].map(([u,f],d)=>({key:u,label:f,field:`c${d}_${a}`}));t.totals&&c.push({key:"",label:"合计",field:`total_${a}`});for(const u of c){const f=u.field===`total_${a}`;o.push({field:u.field,header:`${u.label} · ${s.label??`${s.field} (${s.op})`}`,semanticRole:"measure",...s.digits===void 0?{}:{format:{kind:"number",digits:s.digits}}});let d=0;for(const l of r.groups.values())n[d++][u.field]=(f?l.totals?.[a]:l.cells.get(u.key)?.[a])?.value()??(s.op==="count"?0:null);i[u.field]=(f?r.totals?.[a]:r.columnTotals.get(u.key)?.[a])?.value()??(s.op==="count"?0:null)}}),t.totals&&e.length&&n.push(i),{rows:n,columns:o}}const $a=96;function Sa(e,t=$a){return e*t/72}function Rt(e,t=96,r=Mr){if(e?.fontSizePx!=null)return{fontSizePt:e.fontSizePx*72/t,fontSizePx:e.fontSizePx};const n=e?.fontSize??r;return{fontSizePt:n,fontSizePx:Sa(n,t)}}function Ea(e){return e?.lineHeight??Nt}function Q(e,t){const r={...e,...t};return t?.fontSize!=null&&t.fontSizePx==null&&delete r.fontSizePx,t?.fontSizePx!=null&&t.fontSize==null&&delete r.fontSize,r}function Aa(e,t){const r=e.length;if(r===0)return[];const n=e.reduce((a,c)=>a+c,0),o=n>0&&t>0?t/n:1,i=[];let s=0;for(let a=0;a<r;a++){const c=Math.max(0,e[a]*o);i.push({pos:s,size:c}),s+=c}return i}function bn(e,t,r){return e?.length?Aa(e,t):Array.from({length:r},(n,o)=>({pos:t*o/r,size:t/r}))}function to(e,t,r){const n=e.cells??[],o=Math.max(n.length,1),i=e.colWidthsMm?.length??Math.max(1,...n.map(g=>Array.isArray(g)?g.length:0)),s=bn(e.colWidthsMm,t,i),a=g=>g<=0?0:g>=i?s[s.length-1].pos+s[s.length-1].size:s[g].pos,c=bn(e.rowHeightsMm,r,o),u=g=>g<=0?0:g>=o?c[c.length-1].pos+c[c.length-1].size:c[g].pos,f=new Set,d=(g,x)=>`${g}:${x}`,l=[],m=new Set,h=new Set,p=(g,x)=>`v${g}:${x}`,w=(g,x)=>`h${g}:${x}`;n.forEach((g,x)=>{if(!Array.isArray(g))return;let b=0;for(const $ of g){for(;b<i&&f.has(d(x,b));)b++;if(b>=i)break;const T=Math.max(1,Math.min($?.colSpan??1,i-b)),j=Math.max(1,$?.rowSpan??1),v=Math.min(o,x+j),M=Math.min(i,b+T);for(let N=x;N<v;N++)for(let I=b;I<M;I++)f.add(d(N,I));for(let N=b+1;N<M;N++)for(let I=x;I<v;I++)m.add(p(N,I));for(let N=x+1;N<v;N++)for(let I=b;I<M;I++)h.add(w(N,I));const S=a(b),R=u(x);l.push({ri:x,ci:b,cell:$??{},xMm:S,yMm:R,widthMm:a(M)-S,heightMm:u(v)-R}),b=M}});const y=[];for(let g=1;g<i;g++){let x=-1;for(let b=0;b<=o;b++){const $=b<o&&!m.has(p(g,b));$&&x<0&&(x=b),!$&&x>=0&&(y.push({kind:"v",pos:a(g),from:u(x),to:u(b)}),x=-1)}}for(let g=1;g<o;g++){let x=-1;for(let b=0;b<=i;b++){const $=b<i&&!h.has(w(g,b));$&&x<0&&(x=b),!$&&x>=0&&(y.push({kind:"h",pos:u(g),from:a(x),to:a(b)}),x=-1)}}return{columns:s,rows:c,cells:l,edges:y}}function ka(e,t,r,n=e.paddingMm??1){return t.field!==e.tree.labelField?0:Math.min(r.depth*(e.tree.indentMm??3),Math.max(0,t.widthMm-n*2-4))}function Na(e,t,r,n){const o=n.tree;(o.input==="nested"||[o.idField,o.parentField].includes(t.field))&&(e.editable=!1),r.hasChildren&&o.parentValues==="leaf-aggregate"&&o.aggregates?.some(i=>i.field===t.field)&&(e.derived=!0,e.editable=!1)}function ro(e,t,r){return r==="identifier"||r==="dimension"||r==="date"?"center":r==="measure"?"right":r==="text"?"left":t?.kind==="number"||t?.kind==="percent"?"right":t?.kind==="date"||e instanceof Date||typeof e=="boolean"?"center":typeof e=="number"&&Number.isFinite(e)?"right":"left"}function Or(e){if(e==null)return"";if(typeof e=="string"||typeof e=="number")return String(e);if(typeof e=="boolean")return e?"是":"否";if(e instanceof Date)return e.toISOString().slice(0,10);try{return JSON.stringify(e)}catch{return String(e)}}function no(e,t){let r=Q({fontSize:e.fontSizePt??Mr,bold:e.headerBold??!0,align:"center",verticalAlign:"middle",backgroundColor:e.headerBackgroundColor},t.style);return e.headerAlign!==void 0&&(r.align=e.headerAlign),r=Q(r,e.headerStyle),t.headerAlign!==void 0&&(r.align=t.headerAlign),Q(r,t.headerStyle)}function Pa(e,t){return{member:"body",subtotal:"subtotal",total:"grand-total"}[e?.rows.get(t)?.kind??"member"]}function Fa(e){const t=e.matrix;if(!t.hierarchy)return t;const r=new Map(e.columns.map(o=>[o.field,o.header])),n={sum:"求和",count:"计数",avg:"平均",min:"最小",max:"最大",weightedAvg:"加权平均"};return{...t,hierarchy:{...t.hierarchy,row:{...t.hierarchy.row,labels:t.hierarchy.row?.labels??t.rowFields.map(o=>r.get(o)??o)},column:{...t.hierarchy.column,labels:t.hierarchy.column?.labels??t.columnFields.map(o=>r.get(o)??o)}},measures:t.measures.map(o=>{const i=r.get(o.field)??r.get(o.valueField??o.field);return o.label===void 0&&i?{...o,label:`${i}(${n[o.op]})`}:o})}}function Oa(e,t){if(!e.matrix)return{list:e,rows:t};if(e.detail||e.groupBy||e.groups?.length||e.grandTotal)throw new Error("矩阵不能同时配置普通分组、总计或主从明细");const r=Ma(t,Fa(e)),n=r.columns.map(a=>({...a,widthMm:a.semanticRole==="dimension"?e.matrix.rowWidthMm??40:e.matrix.columnWidthMm??28,editable:!1,align:a.semanticRole==="dimension"?"center":"right"})),o={...e,columns:n,headerGrid:r.headerGrid,rowKey:void 0,revisionField:void 0,sourceTokenField:void 0};e.layout==="wide"&&(o.widthMm=n.reduce((a,c)=>a+c.widthMm,0));const i=r.metadata,s=i?{rows:new WeakMap(r.rows.map((a,c)=>[a,i.rows[c]])),header:{columns:i.columns,rowFields:i.rowFields,rowLabels:i.rowLabels,columnFields:i.columnFields,columnLabels:i.columnLabels}}:void 0;return{list:o,rows:r.rows,...s?{matrix:s}:{}}}function Ia(e,t){if(!e.matrix?.hierarchy||!e.headerGrid)return e.headerGrid;const r=e.paddingMm??1,n=e.headerGrid.cells.map(()=>e.rowHeightMm??0),o=e.columns.map(c=>c.widthMm),i=to({...e.headerGrid,colWidthsMm:o},o.reduce((c,u)=>c+u,0),n.length),s=new WeakMap;for(const{cell:c,ci:u,ri:f,widthMm:d}of i.cells){const l={...no(e,e.columns[u]),...c.style},m=Rt(l).fontSizePt,p=(Ve(c.text??"",Math.max(1,d-r*2),{fontSizePt:m,fontFamily:l.fontFamily,bold:l.bold,italic:l.italic,letterSpacingPt:l.letterSpacing},t).length*m*(l.lineHeight??Nt)*25.4/72+r*2)/(c.rowSpan??1);for(let w=f;w<f+(c.rowSpan??1);w++)n[w]=Math.max(n[w]??0,p);s.set(c,l)}const a=e.headerGrid.cells.map(c=>c.map(u=>u?{...u,style:s.get(u)}:null));return{...e.headerGrid,cells:a,rowHeightsMm:n}}class oo extends Error{constructor(t){super(`树节点超出行数预算 ${t}`),this.limit=t,this.code="tree-row-limit",this.name="TreeRowLimitError"}}function Ut(e,t,r,n){const o=e??t;if(!Number.isInteger(o)||o<1||o>r)throw new Error(`${n}应为 1–${r} 的整数`);return o}function Ir(e){return{rows:Ut(e.maxRows,1e5,1e6,"树行数预算"),depth:Ut(e.maxDepth,64,256,"树深度预算"),visits:Ut(e.maxAggregationVisits,1e6,1e7,"树聚合访问预算")}}function io(e){return typeof e=="string"&&!!e.trim()}function be(e){return io(e)&&!["__proto__","prototype","constructor"].includes(e)}function so(e){if(io(e)||typeof e=="number"&&Number.isFinite(e))return e;throw new Error("树节点业务键应为非空字符串或有限数字")}function ao(e){return JSON.stringify([typeof e,e])}function co(e){return[e.idField,...e.input==="flat"?[e.parentField??""]:[e.childrenField??"children"]]}function Rr(e,t){const r=co(e);if(t?.some(n=>n.scope&&n.scope!=="row"||r.includes(n.field)))throw new Error("树形布局仅支持不覆盖结构键的当前行计算")}function Ee(e){if(!e?.aborted)return;const t=new Error("树报表处理已取消");throw t.name="AbortError",t}function Ra(e){const t=e.aggregates??[];if(!Array.isArray(t)||t.length>32)throw new Error("树聚合最多 32 项");if(e.parentValues!=="leaf-aggregate"&&t.length)throw new Error("树聚合需显式选择 leaf-aggregate 父级取值策略");if(e.parentValues==="leaf-aggregate"&&!t.length)throw new Error("叶子聚合策略至少需要一个聚合字段");const r=new Set;for(const n of t){if(!n||!be(n.field)||r.has(n.field))throw new Error("树聚合输出字段应安全、非空且唯一");for(const o of[n.valueField,n.weightField])if(o!==void 0&&!be(o))throw new Error("树聚合来源字段应安全且非空");if([...co(e),e.labelField].includes(n.field))throw new Error("树聚合不能覆盖结构键或标签字段");r.add(n.field),oe({...n,field:n.valueField??n.field})}}function Ca(e){if(!be(e.idField)||!be(e.labelField))throw new Error("树需要安全的业务键和标签字段");if(e.input==="flat"&&(!be(e.parentField)||e.parentField===e.idField))throw new Error("扁平树需要独立的父键字段");if(e.childrenField!==void 0&&!be(e.childrenField))throw new Error("子节点字段应安全且非空");if(e.input==="nested"&&[e.idField,e.labelField].includes(e.childrenField??"children"))throw new Error("子节点字段不能覆盖业务键或标签字段")}function uo(e){if(!e||typeof e!="object"||!["flat","nested"].includes(e.input))throw new Error("树输入应为 flat 或 nested");if(Ca(e),e.orphan!==void 0&&!["error","root"].includes(e.orphan))throw new Error("树孤儿策略应为 error 或 root");if(e.parentValues!==void 0&&!["source","leaf-aggregate"].includes(e.parentValues))throw new Error("未知树父级取值策略");if(e.indentMm!==void 0&&(!Number.isFinite(e.indentMm)||e.indentMm<0||e.indentMm>20))throw new Error("树每级缩进应为 0–20 mm");Ir(e),Ra(e)}function fo(e,t,r,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("树节点应为对象");if(r.size>=n.rows)throw new oo(n.rows);const o=so(e[t.idField]),i=ao(o);if(r.has(i))throw new Error(`树节点业务键重复:${String(o)}`);const s={original:e,row:e,key:o,depth:0,children:[]};return r.set(i,s),s}function Ta(e,t,r,n,o){for(const s of e)Ee(o),fo(s,t,r,n);const i=[];for(const s of r.values()){Ee(o);const a=s.row[t.parentField];if(a==null){i.push(s);continue}const c=r.get(ao(so(a)));if(!c){if(t.orphan!=="root")throw new Error(`树节点 ${String(s.key)} 的父节点不存在`);i.push(s);continue}if(c===s)throw new Error("树节点不能以自身为父节点");s.parent=c,c.children.push(s)}return i}function ja(e,t,r,n,o){const i=[],s=[{rows:e,next:0}];for(;s.length;){Ee(o);const a=s[s.length-1];if(a.next>=a.rows.length){s.pop();continue}const c=fo(a.rows[a.next++],t,r,n);if(c.parent=a.parent,c.depth=s.length-1,s.length>n.depth)throw new Error(`树节点超出深度预算 ${n.depth}`);(a.parent?.children??i).push(c);const u=c.row[t.childrenField??"children"];if(u!=null){if(!Array.isArray(u))throw new Error("嵌套树 children 字段应为数组");u.length&&s.push({rows:u,next:0,parent:c})}}return i}function Da(e,t,r,n){const o=[],i=[{nodes:e,next:0}];for(;i.length;){Ee(n);const s=i[i.length-1];if(s.next>=s.nodes.length){i.pop();continue}if(i.length>r.depth)throw new Error(`树节点超出深度预算 ${r.depth}`);const a=s.nodes[s.next++];a.depth=i.length-1,o.push(a),a.children.length&&i.push({nodes:a.children,next:0})}if(o.length!==t)throw new Error("树父子关系存在循环");return o}function La(e,t,r,n){if(t.parentValues!=="leaf-aggregate")return;const o=t.aggregates,i=new Map;for(const a of e)a.children.length&&i.set(a,o.map(c=>oe({...c,field:c.valueField??c.field})));let s=0;for(const a of e)if(!a.children.length)for(let c=a.parent;c;c=c.parent){if(Ee(n),s+=o.length,s>r.visits)throw new Error(`树聚合超出访问预算 ${r.visits}`);for(const u of i.get(c))u.add(a.row)}for(const[a,c]of i)a.row={...a.row},o.forEach((u,f)=>{a.row[u.field]=c[f].value()})}function lo(e,t,r){if(uo(t),Ee(r),!Array.isArray(e))throw new Error("树数据应为节点数组");const n=Ir(t),o=new Map,i=t.input==="flat"?Ta(e,t,o,n,r):ja(e,t,o,n,r);return Da(i,o.size,n,r)}function mo(e,t,r){return lo(e,t,r).map(n=>n.original)}function ho(e,t,r={}){const n=lo(e,t,r.signal);if(Rr(t,r.computed?.fields),r.computed?.fields.length){const o=Ot(n.map(i=>i.row),{...r.computed,signal:r.signal}).rows;n.forEach((i,s)=>{i.row=o[s]})}return La(n,t,Ir(t),r.signal),{rows:n.map(o=>o.row),entries:n.map(o=>({row:o.row,original:o.original,key:o.key,depth:o.depth,hasChildren:!!o.children.length})),leaves:n.filter(o=>!o.children.length).map(o=>o.row)}}function Ba(e,t,r){const n=new Set,o=e.cells.map((i,s)=>{const a=[];let c=0;for(const u of i){for(;n.has(`${s}:${c}`);)c++;const f=u?.colSpan??1,d=u?.rowSpan??1;let l=0;for(let m=c;m<c+f;m++){t.has(m)&&l++;for(let h=s+1;h<s+d;h++)n.add(`${h}:${m}`)}l&&a.push(u?{...u,colSpan:l}:null),c+=f}return a});return{...e,cells:o,colWidthsMm:r}}function _a(e){if(!e.columns.some(n=>n.hidden))return e;const t=new Set,r=e.columns.filter((n,o)=>n.hidden?!1:(t.add(o),!0));if(!r.length)throw new Error("列表至少需要一列可见列");return{...e,columns:r,...e.headerGrid?{headerGrid:Ba(e.headerGrid,t,r.map(n=>n.widthMm))}:{}}}function Cr(e){return e.kind==="list"?e.id:e.nid}function Ka(e){return e.kind==="list"?!1:e.pageAnchor!==void 0||e.kind==="text"&&typeof e.text=="string"&&/\{(?:page|totalPages)\}/.test(e.text)}function Wa(e,t){const r=e.filter(o=>t.componentIds.includes(Cr(o)??""));if(r.filter(o=>o.kind==="list"&&o.cardinality!=="record").length&&r.length!==1)throw new Error("纵向重复区域必须独占流式分段,不能与静态或单记录区域并排");for(const o of r){const i=o.kind==="list"?o.topMm+(o.rowHeightMm??0):o.topMm+o.heightMm;if(o.topMm<t.topMm-.001||i>t.topMm+t.heightMm+.001)throw new Error("流式分段应完整包含其组件的原始纵向范围")}}function Ja(e,t){if(!t)return e.map(n=>({components:[n]}));const r=new Map(e.map(n=>[Cr(n),n]));return t.bands.map(n=>({band:n,components:n.componentIds.map(o=>{const i=r.get(o);if(!i)throw new Error(`流式区域引用不存在的组件:${o}`);return i})}))}function go(e,t){if(!t||!Array.isArray(t.bands)||!t.bands.length||t.bands.length>1e4)throw new Error("流式排版应包含 1–10000 个区域");const r=new Set,n=new Set;for(const o of e){if(Ka(o))continue;const i=Cr(o);if(!i||r.has(i))throw new Error("流式排版组件应具有唯一标识");r.add(i)}if(za(e,t,r,n),n.size!==r.size)throw new Error("流式排版必须显式包含每个非锚点组件")}function za(e,t,r,n){let o=-1/0;for(const i of t.bands){if(!Number.isFinite(i.topMm)||!Number.isFinite(i.heightMm)||i.topMm<0||i.heightMm<=0||i.topMm<o-.001)throw new Error("流式区域应按原始位置排序,尺寸有效且不重叠");if(!Array.isArray(i.componentIds)||!i.componentIds.length)throw new Error("流式区域不能没有组件");for(const s of i.componentIds){if(!r.has(s)||n.has(s))throw new Error(`流式区域组件缺失、重复或包含页锚点:${s}`);n.add(s)}Wa(e,i),o=i.topMm+i.heightMm}}function*Va(e){const{page:t}=e;go(t.components,t.flow);let r=0,n=0;for(const o of Ja(t.components,t.flow)){e.active();const i=o.band,s=o.components.some(f=>f.kind==="list"&&f.cardinality!=="record"),a=s?0:o.components.reduce((f,d)=>Math.max(f,d.topMm-i.topMm+(d.kind==="list"?e.height(d):d.heightMm)),i.heightMm);let c=Math.max(e.top(),n+i.topMm-r);if(!s&&a>e.bottom()-e.top()+.001)throw new Error(`静态区域 ${i.componentIds.join(",")} 高度超出单页可用范围`);!s&&c+a>e.bottom()+.001&&(e.nextPage(),yield*e.takePages(),e.active(),c=e.top());let u=c+a;for(const f of o.components){const d=c+f.topMm-i.topMm;f.kind==="list"?(yield*e.list(f,d,l=>{u=s?l:Math.max(u,l)}),e.active()):e.append({...f,topMm:d})}n=u,r=i.topMm+i.heightMm}}function Ha(e){return!!(e.computed?.length||e.groups?.length||e.groupBy||e.grandTotal||e.rowVisibleWhen||e.matrix||e.tree||e.detail||e.columns.some(t=>t.rules?.length||t.visibleWhen||t.visual))}function Tr(e){return e.pages.some(t=>t.components.some(r=>r.kind==="list"?Ha(r):!!r.chartBinding))}const Ua=new Set(["__proto__","prototype","constructor"]);function te(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tt(e){return typeof e=="string"&&!!e.trim()&&!Ua.has(e)}function ht(e,t,r,n){for(const o of Object.keys(e))t.includes(o)||n.push({path:`${r}.${o}`,message:"存在未知配置字段"})}function Ga(e,t,r){if(e!==void 0){if(!te(e)||!["number","percent","date"].includes(String(e.kind))){r.push({path:t,message:"绑定格式应为 number、percent 或 date"});return}ht(e,e.kind==="date"?["kind","pattern"]:e.kind==="number"?["kind","digits","thousands"]:["kind","digits"],t,r),e.digits!==void 0&&(!Number.isInteger(e.digits)||Number(e.digits)<0||Number(e.digits)>100)&&r.push({path:`${t}.digits`,message:"精度应为 0..100 整数"}),e.thousands!==void 0&&typeof e.thousands!="boolean"&&r.push({path:`${t}.thousands`,message:"千分位开关应为布尔值"}),e.pattern!==void 0&&typeof e.pattern!="string"&&r.push({path:`${t}.pattern`,message:"日期格式应为字符串"})}}function Ya(e,t,r){const n=e.binding;if(n===void 0)return;const o=`${t}.binding`;if(!te(n)){r.push({path:o,message:"字段绑定应为对象"});return}(!["text","image","barcode","qrcode"].includes(String(e.kind))||e.grid!==void 0)&&r.push({path:o,message:"绑定仅支持独立文本、图片、条码与二维码组件"}),ht(n,["field","format","prefix","suffix","emptyText"],o,r),tt(n.field)||r.push({path:`${o}.field`,message:"绑定字段应为安全的非空字段名(按字面读取自有字段)"});for(const i of["prefix","suffix","emptyText"])n[i]!==void 0&&typeof n[i]!="string"&&r.push({path:`${o}.${i}`,message:"应为字符串"});Ga(n.format,`${o}.format`,r),e.kind==="image"&&["format","prefix","suffix"].some(i=>n[i]!==void 0)&&r.push({path:o,message:"图片绑定直接读取 PNG/JPEG data URL,不支持文本格式或前后缀"})}function qa(e,t){if(!te(e)){t.push({path:"$.repeat",message:"逐记录配置应为对象"});return}ht(e,["dataset","rowKey","copies"],"$.repeat",t),tt(e.dataset)||t.push({path:"$.repeat.dataset",message:"数据集应为安全的非空名称"}),e.rowKey!==void 0&&!tt(e.rowKey)&&t.push({path:"$.repeat.rowKey",message:"业务主键应为安全的非空字段名"});const r=e.copies;r!==void 0&&(te(r)?(ht(r,["field"],"$.repeat.copies",t),tt(r.field)||t.push({path:"$.repeat.copies.field",message:"复制数字段应为安全的非空字段名"})):(!Number.isSafeInteger(r)||Number(r)<1||Number(r)>1e3)&&t.push({path:"$.repeat.copies",message:"每条记录复制数应为 1..1000 整数"}))}function po(e,t,r,n){if(!te(e))return;Ya(e,t,n),e.binding!==void 0&&!r&&n.push({path:`${t}.binding`,message:"字段绑定需要模板 repeat 数据集;普通报表请使用列表字段"}),r&&e.kind==="list"&&n.push({path:t,message:"逐记录标签使用固定组件;动态列表请使用普通报表模板"}),e.chartBinding!==void 0&&(r||t.includes(".children."))&&n.push({path:`${t}.chartBinding`,message:"数据图表应放在普通报表的页面或流式分区,不放在逐记录标签或嵌套单元格内"});const o=e.grid;te(o)&&Array.isArray(o.cells)&&o.cells.forEach((i,s)=>{Array.isArray(i)&&i.forEach((a,c)=>{te(a)&&Array.isArray(a.children)&&a.children.forEach((u,f)=>po(u,`${t}.grid.cells.${s}.${c}.children.${f}`,r,n))})})}function yo(e,t){const r=e.repeat!==void 0;r&&qa(e.repeat,t),Array.isArray(e.pages)&&e.pages.forEach((n,o)=>{if(!te(n))return;const i=`$.pages.${o}`;r&&(n.layout==="wide"||n.flow!==void 0)&&t.push({path:i,message:"逐记录标签仅支持固定尺寸页面,不支持宽表或流式分区"}),Array.isArray(n.components)&&n.components.forEach((s,a)=>{const c=`${i}.components.${a}`;if(po(s,c,r,t),!r||!te(s))return;const{leftMm:u,topMm:f,widthMm:d,heightMm:l}=s;[u,f,d,l,n.widthMm,n.heightMm].every(m=>typeof m=="number"&&Number.isFinite(m))&&(Number(u)<0||Number(f)<0||Number(u)+Number(d)>Number(n.widthMm)+.001||Number(f)+Number(l)>Number(n.heightMm)+.001)&&t.push({path:c,message:"标签组件超出纸张边界,请调整位置或尺寸"})})})}const Xa=512,xn=256*1024;function Za(){const e=new Map;let t=0,r;return(n,o,i,s)=>{s!==r&&(e.clear(),t=0,r=s);const a=JSON.stringify([n,o,i.fontSizePt,i.fontFamily,i.bold,i.italic,i.letterSpacingPt]),c=e.get(a);if(c)return e.delete(a),e.set(a,c),c.lines.slice();const u=Ve(n,o,i,s),f=a.length+u.reduce((d,l)=>d+l.length,0);if(f<=xn){for(;e.size>=Xa||t+f>xn;){const d=e.keys().next().value;t-=e.get(d).units,e.delete(d)}e.set(a,{lines:u.slice(),units:f}),t+=f}return u}}function Qa(e){return typeof e=="string"&&/^data:image\/(png|jpe?g);base64,[A-Za-z0-9+/\r\n]+=*$/.test(e)}class H extends Error{constructor(t,r,n,o){super(`${t}: ${r}`),this.path=t,this.rowIndex=n,this.field=o,this.code="report-binding",this.name="ReportBindingError"}}function jr(e,t,r={}){const n=r.rowIndex??0,i=`$.datasets.${r.dataset??"label"}[${n}].${t}`,s=Object.getOwnPropertyDescriptor(e,t);if(!s||s.get||s.set)throw new H(i,"字段必须是记录的自有数据字段,不能缺失、使用访问器或从原型继承",n,t);const a=s.value;if(a==null||typeof a=="string"||typeof a=="boolean"||typeof a=="number"&&Number.isFinite(a))return a;throw new H(i,"绑定值应为字符串、有限数字、布尔值或空值",n,t)}function ec(e,t,r={}){const n=jr(t,e.field,r);return n==null||n===""?e.emptyText??"":`${e.prefix??""}${Er(n,e.format)}${e.suffix??""}`}const tc=1e4,vn=25e4;function Dr(e){if(e?.aborted)throw e.reason??new DOMException("标签生成已取消","AbortError")}function wo(e,t,r){const n=typeof e.copies=="object"?jr(t,e.copies.field,r):e.copies??1;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>1e3)throw new H(`$.datasets.${r.dataset}[${r.rowIndex}]`,"每条记录复制数必须是 1..1000 的数值型整数",r.rowIndex,typeof e.copies=="object"?e.copies.field:void 0);return n}function bo(e,t,r){if(e.rowKey===void 0)return;const n=jr(t,e.rowKey,r);if(typeof n=="string"&&n.trim()||typeof n=="number"&&Number.isFinite(n))return n;throw new H(`$.datasets.${r.dataset}[${r.rowIndex}].${e.rowKey}`,"业务主键必须是非空字符串或有限数字",r.rowIndex,e.rowKey)}function rc(e){const t=r=>1+(r.grid?.cells.reduce((n,o)=>n+1+o.length+o.reduce((i,s)=>i+(s?.children?.reduce((a,c)=>a+t(c),0)??0),0),0)??0);return e.pages.reduce((r,n)=>r+n.components.reduce((o,i)=>o+t(i),0),0)}function nc(e,t,r){const n=e.repeat,o=Object.prototype.hasOwnProperty.call(t,n.dataset)?t[n.dataset]:void 0;if(!Array.isArray(o))throw new H(`$.datasets.${n.dataset}`,"逐记录标签数据集缺失,应提供对象数组(允许空数组)");const i=new Set,s=r.maxPages??tc,a=rc(e);let c=0,u=0;for(const[f,d]of o.entries()){if(Dr(r.signal),!d||typeof d!="object"||Array.isArray(d))throw new H(`$.datasets.${n.dataset}[${f}]`,"标签记录应为对象",f);const l={rowIndex:f,dataset:n.dataset},m=bo(n,d,l);if(m!==void 0){const p=JSON.stringify([typeof m,m]);if(i.has(p))throw new H(`$.datasets.${n.dataset}[${f}].${n.rowKey}`,"业务主键重复;请先确认记录来源,避免重复打印标签",f,n.rowKey);i.add(p)}const h=wo(n,d,l);if(c+=h*e.pages.length,u+=h*a,c>s)throw new Se(s,c);if(u>vn)throw new H("$.repeat",`标签组件总量(含网格行、槽位及嵌套组件)超过安全预算 ${vn},请分批生成`,f)}return o}function oc(e,t,r){if(!e.binding)return e;const{binding:n,...o}=e,i=ec(n,t.row,t);if(e.kind==="image"){if(!i)return;if(!Qa(i))throw new H(`${r}.binding`,"图片字段只接受 PNG/JPEG base64 data URL;业务 URL 应由宿主安全加载后转换",t.rowIndex,n.field);return{...o,imageData:i}}return e.kind==="barcode"||e.kind==="qrcode"?(delete o.imageData,{...o,code:{...o.code,value:i},fallbackText:i}):(delete o.lines,delete o.richParagraphs,{...o,text:i})}function ic(e,t,r){if(e.kind!=="text"||e.grid||e.richParagraphs?.length)return e;const n=e.style??{},o=Rt(n).fontSizePt,i=e.text??e.lines?.join(`
5
+ `)??"";if(i.length>16384)throw new H(r,"标签文本超过 16384 字符预算,请缩小字段内容",t.rowIndex);const s=t.wrapText(i,e.widthMm,{fontSizePt:o,bold:n.bold,italic:n.italic,fontFamily:n.fontFamily,letterSpacingPt:n.letterSpacing},t.options.measurer??$r),a=s.length*o*Ea(n)*25.4/72;if(a>e.heightMm+.05)throw new H(r,`标签文字需要约 ${a.toFixed(2)}mm 高,超出 ${e.heightMm}mm;请增大文本区域、减少内容或调整字号`,t.rowIndex,e.binding?.field);return{...e,lines:s}}function xo(e,t,r){Dr(t.options.signal);const n=oc(e,t,r);if(!n)return;let o=n.grid;return o&&(o={...o,cells:o.cells.map((i,s)=>i.map((a,c)=>a?.children?.length?{...a,children:a.children.flatMap((u,f)=>{const d=xo(u,t,`${r}.grid.cells.${s}.${c}.children.${f}`);return d?[d]:[]})}:a))}),ic(o===n.grid?n:{...n,grid:o},t,r)}function sc(e,t,r,n,o,i){return{...e,components:e.components.flatMap((s,a)=>{const c=xo(s,r,`$.pages.${t}.components.${a}`);return c?[{...c,meta:{...c.meta,labelSource:{pageIndex:t,componentIndex:a}}}]:[]}),meta:{...e.meta,record:{dataset:r.dataset,rowIndex:r.rowIndex,...i===void 0?{}:{rowKey:i},copyIndex:n,copyCount:o,templatePageIndex:t}}}}function*ac(e,t,r){const n=[];if(yo(e,n),n.length)throw new H(n[0].path,n[0].message);if(!e.repeat){for(const[a,c]of e.pages.entries())yield{page:c,pageIndex:a};return}const o=e.repeat,i=nc(e,t,r),s=Za();for(const[a,c]of i.entries()){const u={row:c,rowIndex:a,dataset:o.dataset,options:r,wrapText:s},f=wo(o,c,u),d=bo(o,c,u);for(let l=0;l<f;l++)for(const[m,h]of e.pages.entries())Dr(r.signal),yield{page:sc(h,m,u,l,f,d),pageIndex:m}}}const cc=/^#[0-9a-f]{6}$/i;function vo(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return t.kind!=="colorScale"&&t.kind!=="dataBar"||t.field!==void 0&&(typeof t.field!="string"||!t.field.trim())||t.numeric!==void 0&&!["number","decimal"].includes(t.numeric)||[t.min,t.max].some(r=>r!==void 0&&(typeof r!="number"||!Number.isFinite(r)))||t.min!==void 0&&t.max!==void 0&&t.min>t.max?!1:Object.entries(t).every(([r,n])=>!["color","negativeColor","lowColor","highColor"].includes(r)||typeof n=="string"&&cc.test(n))}function Mo(e,t){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(t!=="decimal"||typeof e!="string"||e.length>1024||!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e))return;const r=Number(e);return Number.isFinite(r)?r:void 0}function uc(e,t,r){let n="#";for(const o of[1,3,5]){const i=parseInt(e.slice(o,o+2),16),s=parseInt(t.slice(o,o+2),16);n+=Math.round(i+(s-i)*r).toString(16).padStart(2,"0")}return n}function Gt(e,t,r){if(t===r)return e<t?0:e>r?1:.5;if(e<=t)return 0;if(e>=r)return 1;const n=r-t;return Number.isFinite(n)?(e-t)/n:(e/2-t/2)/(r/2-t/2)}function fc(e,t,r,n){const o=new WeakMap;return{apply(i,s){const a=Mo(s[t],e.numeric);if(a===void 0)return;if(e.kind==="dataBar"){const l=Math.min(r,0),m=Math.max(n,0),h=Gt(0,l,m),p=l===m?h:Gt(a,l,m);i.dataBar={start:Math.min(h,p),end:Math.max(h,p),color:a<0?e.negativeColor??"#f3bcc3":e.color??"#bad8fa"};return}const c=uc(e.lowColor??"#f0f7ff",e.highColor??"#8bbcf1",Gt(a,r,n)),u=i.style??{},f=o.get(u)??new Map;o.set(u,f);let d=f.get(c);d||(d={...u,backgroundColor:c},f.set(c,d)),i.style=d}}}function lc(e,t,r){return e.map(n=>{Mn(r);const o=n.visual;if(!o)return;if(!vo(o))throw new TypeError("Invalid column visual rule");const i=o.field??n.field;let s=1/0,a=-1/0,c=0;if(o.min===void 0||o.max===void 0)for(const d of t){(c++&1023)===0&&Mn(r);const l=Mo(d[i],o.numeric);l!==void 0&&(s=Math.min(s,l),a=Math.max(a,l))}let u=o.min??s,f=o.max??a;if(!(!Number.isFinite(u)||!Number.isFinite(f)))return u>f&&(o.min!==void 0?f=u:u=f),fc(o,i,u,f)})}function Mn(e){if(e?.aborted)throw e.reason??new DOMException("Aborted","AbortError")}function dc(e){return{widthMm:e.widthMm,heightMm:e.heightMm,marginTopMm:e.marginTopMm??0,marginBottomMm:e.marginBottomMm??0,marginLeftMm:e.marginLeftMm??0,marginRightMm:e.marginRightMm??0,components:[]}}function gt(e,t){const r=t.heightMm-(e.layout==="wide"?t.marginBottomMm:e.marginBottomMm??t.marginBottomMm);return e.components.reduce((n,o)=>o.kind!=="list"&&o.pageAnchor==="footer"?Math.min(n,o.topMm):n,r)}function We(e){return e.components.reduce((t,r)=>r.kind!=="list"&&r.pageAnchor==="header"?Math.max(t,r.topMm+r.heightMm):t,0)}function $o(e,t){let r=e.textMetrics.get(t);if(!r){const n=Rt(t).fontSizePt;r={measureOptions:{fontSizePt:n,fontFamily:t.fontFamily??Wn,italic:t.italic,bold:t.bold,letterSpacingPt:t.letterSpacing},lineMm:n*(t.lineHeight??Nt)*25.4/72},e.textMetrics.set(t,r)}return r}function mc(e){if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function Lr(e,t,r=[],n){const o=e.fontSizePt??Mr,i=e.paddingMm??1,s=e.columns.map(y=>y.align??y.style?.align??e.align??"left"),a=e.columns.map((y,g)=>({...Q({fontSize:o,verticalAlign:"middle"},y.style),align:s[g]==="auto"?"left":s[g]})),c=a.map((y,g)=>s[g]==="auto"?{left:y,center:{...y,align:"center"},right:{...y,align:"right"}}:void 0),u=e.columns.map((y,g)=>y.rules?.map(x=>{const b=c[g];if(b)return{left:Q(b.left,x.style),center:Q(b.center,x.style),right:Q(b.right,x.style)};const $=Q(a[g],x.style);return{left:$,center:$,right:$}})),f=e.columns.map(y=>no(e,y)),d=e.columns.map(y=>y.header);let l=e.rowHeightMm??0;for(let y=0;y<d.length;y++){const g=f[y],x=Rt(g).fontSizePt,b=Ve(d[y],e.columns[y].widthMm-i*2,{fontSizePt:x,fontFamily:g.fontFamily??Wn,italic:g.italic,bold:g.bold,letterSpacingPt:g.letterSpacing},t),$=x*(g.lineHeight??Nt)*25.4/72;l=Math.max(l,Math.max(b.length,1)*$+i*2)}const m=d.map((y,g)=>({text:y,style:f[g]})),h=e.border===!1?{borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}:{borderBottom:!0,borderLeft:!0,borderRight:!0,borderTop:!0},p=e.columns.map(y=>y.widthMm),w=hc(Ia(e,t),p,{cells:[m],colWidthsMm:p,rowHeightsMm:[l],paddingMm:i});return{fontSizePt:o,paddingMm:i,visuals:lc(e.columns,r,n),visibility:e.columns.map(y=>y.visibleWhen?q(y.visibleWhen):void 0),ruleReaders:e.columns.map(y=>y.rules?.map(g=>q(g.when))),cellStyles:a,autoStyles:c,ruleStyles:u,textMetrics:new WeakMap,numberFormats:e.columns.map(y=>Gn(y.format)),derivedFields:new Set(e.computed?.map(y=>y.field)),borderStyle:h,headerHeightMm:w.rowHeightsMm.reduce((y,g)=>y+g,0),headerGrid:w,colWidthsMm:p,columns:e.columns}}function hc(e,t,r){if(!e)return r;if(!e.cells.length)throw new Error("自定义列表表头至少需要一行");const n=e.rowHeightsMm??e.cells.map(()=>r.rowHeightsMm[0]);if(n.length!==e.cells.length||n.some(o=>!Number.isFinite(o)||o<=0))throw new Error("自定义列表表头行高无效");return{...e,colWidthsMm:t,rowHeightsMm:n}}function gc(e,t,r){const n=t.format?.kind==="number"||t.format?.kind==="percent";t.valueType!==void 0?e.valueType=t.valueType:n&&(e.valueType="number"),t.editable!==void 0&&(e.editable=t.editable),(typeof e.value=="number"||e.value==null)&&r!==void 0&&(e.numberFormat=r)}function Je(e,t,r){const n=e.columns,o=e.tree?.rows.get(t);let i=e.rowHeightFloorMm;const s=new Array(n.length);for(let a=0;a<n.length;a++){const c=n[a],u=e.visibility[a]?.(t)!==!1,f=u?t[c.field]:null,d=e.autoStyles[a]?ro(f,c.format,c.semanticRole):"left";let l=e.autoStyles[a]?.[d]??e.cellStyles[a];if(c.rules){for(let x=0;x<c.rules.length;x++)if(e.ruleReaders[a][x](t)){l=e.ruleStyles[a][x][d];break}}const m=c.format?Er(f,c.format):Or(f),h=pc(e,c,o);l=yc(e,c,l,o);const p=$o(e,l),w=Ve(m,Math.max(1,c.widthMm-e.paddingMm*2-h),p.measureOptions,r);i=Math.max(i,w.length*p.lineMm+e.paddingMm*2);const y=mc(f),g={text:m,style:l};f!=null&&e.visuals[a]?.apply(g,t),y!==void 0&&(g.value=y),gc(g,c,e.numberFormats[a]),wc(g,c,e,o,h),e.derivedFields.has(c.field)&&(g.derived=!0,g.editable=!1),u||(g.editable=!1),s[a]=g}return{grid:{cells:[s],colWidthsMm:e.colWidthsMm,rowHeightsMm:[i],paddingMm:e.paddingMm},heightMm:i,...e.matrix?{meta:{matrix:{row:e.matrix.rows.get(t)}}}:{}}}function pc(e,t,r){return!r||t.field!==e.tree.list.tree.labelField?0:ka(e.tree.list,t,r,e.paddingMm)}function yc(e,t,r,n){return!n||t.field!==e.tree.list.tree.labelField||r.align==="left"?r:{...r,align:"left"}}function wc(e,t,r,n,o=0){n&&(o&&(e.indentMm=o),Na(e,t,n,r.tree.list))}function So(e){if(e!=null&&typeof e!="string"&&typeof e!="boolean"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("分组字段应为有限 JSON 标量");return JSON.stringify([typeof e,e??null])}function*Eo(e,t,r=0){const n=t[r];if(!n){for(const i of e)yield{kind:"row",row:i};return}const o=new Map;for(const i of e){const s=So(i[n.field]),a=o.get(s);a?a.push(i):o.set(s,[i])}for(const i of o.values())yield{kind:"groupHeader",label:(n.headerTemplate??"{value}").replace(/\{value\}/g,Or(i[0][n.field])),firstRow:i[0],group:n,depth:r,rows:i},yield*Eo(i,t,r+1),(n.subtotal?.length||n.aggregates?.length)&&(yield{kind:"subtotal",label:n.subtotalLabel??"小计",rows:i,group:n,depth:r}),yield{kind:"groupEnd",depth:r}}function Ao(e,t,r,n=[]){const o=[...r.filter(i=>!n.some(s=>s.field===i)).map(i=>({field:i,op:"sum"})),...n];return new Map(o.map(i=>{const s=e.find(c=>c.field===i.field)?.format??{kind:"number",thousands:!0},a=Be(t,{...i,field:i.valueField??i.field});return[i.field,{text:Er(a,s),...a===null?{}:{value:a},...typeof a=="number"?{numberFormat:Gn(s)}:{}}]}))}function ko(e,t){const r=e.findIndex(n=>t.includes(n.field));return r<0?1:r}function Oe(e,t,r,n,o,i){const s=[],a=Math.max(0,Math.min(i,e.columns.length)),c=Q({fontSize:e.fontSizePt},o);a&&s.push({text:r,colSpan:a,style:{bold:!0,...c}});for(let l=a;l<e.columns.length;l++){const m=e.columns[l],h=n.get(m.field),p=e.autoStyles[l]?.[ro(h?.value,m.format)]??e.cellStyles[l];s.push({...h,text:h?.text??"",style:Q(p,o)})}const u={text:r,colSpan:e.columns.length,style:{bold:!0,...c}},f=a?[s]:[[u],s],d=f.map(l=>bc(e,l,t));return{grid:{cells:f,colWidthsMm:e.colWidthsMm,rowHeightsMm:d,paddingMm:e.paddingMm},heightMm:d.reduce((l,m)=>l+m,0)}}function bc(e,t,r){let n=e.rowHeightFloorMm,o=0;for(const i of t){let s=0;const a=o+(i.colSpan??1);for(;o<a;o++)s+=e.colWidthsMm[o]??0;const c=$o(e,i.style),u=Ve(i.text??"",s-e.paddingMm*2,c.measureOptions,r);n=Math.max(n,u.length*c.lineMm+e.paddingMm*2)}return n}function xc(e,t,r){const{templatePage:n,current:o,warnings:i,nextId:s,pushCurrent:a}=r,c=()=>gt(n,o),u=Math.max(o.marginTopMm,We(n)),f=n.layout==="wide"?We(n):u,d={id:r.tableId,columnKeys:e.columns.map(v=>v.field),...e.layout===void 0?{}:{layout:e.layout},...e.title===void 0?{}:{title:e.title}},l=new Map,m=new Map,h={kind:"rect",leftMm:e.leftMm,topMm:0,widthMm:e.widthMm,heightMm:t.headerHeightMm,grid:t.headerGrid,nid:s("listh"),table:{...d,role:"header",rowIndex:-1},style:t.borderStyle,...e.meta||t.matrix?{meta:{...e.meta,...t.matrix?{matrix:t.matrix.header}:{}}}:{}},p=v=>o.components.push({...h,topMm:v});if(r.flow&&e.header!==!1&&t.headerHeightMm>c()-u+.001)throw new Error(`流式列表 ${e.id??e.dataset} 的表头高度超出单页可用范围`);let w=Math.max(r.startTop??e.topMm,u);e.header!==!1&&(p(w),w+=t.headerHeightMm+r.mmPerRow);function y(){const v=Math.max(r.flow||n.layout==="wide"?0:e.topMm,f);return(e.header!==!1&&e.headerEveryPage!==!1?v+t.headerHeightMm:f)+[...m.values()].reduce((S,R)=>S+R.heightMm,0)}function g(){const v=n.layout==="wide"?0:o.marginBottomMm;return Math.min(n.heightMm-v,gt(n,o))-y()}function x(v){if(w+v<=c())return;a(),o.components=[],o.heightMm=n.heightMm,n.layout==="wide"&&(o.marginTopMm=0,o.marginBottomMm=0);const M=Math.max(r.flow||n.layout==="wide"?0:e.topMm,f);e.header!==!1&&e.headerEveryPage!==!1?(p(M),w=M+t.headerHeightMm):w=f;for(const S of m.values())$(S,"listgr","group-header")}function b(v,M,S,R){const N=g();if(r.flow&&v.heightMm>N+.001)throw new Error(`流式列表 ${e.id??e.dataset} 的单行高度超出单页可用范围`);v.heightMm>N&&i.push(`列表 ${e.id??e.dataset} 行高 ${v.heightMm.toFixed(2)}mm 超出单页可用高度 ${N.toFixed(2)}mm,预览与打印可能截断内容`),x(v.heightMm),$(v,M,S,R)}function $(v,M,S,R){const N=v.table?.id??d.id,I=S==="header"?-1:l.get(N)??0;S!=="header"&&l.set(N,I+v.grid.cells.length),o.components.push({kind:"rect",leftMm:e.leftMm,topMm:w,widthMm:e.widthMm,heightMm:v.heightMm,grid:v.grid,nid:s(M),table:{...d,...v.table,role:S,rowIndex:I,...R?{source:R}:{}},style:t.borderStyle,...e.meta||v.meta?{meta:{...e.meta,...v.meta}}:{}}),w+=v.heightMm}function T(v){v<=g()&&x(v)}return{keepTogether:T,placeGridRow:b,setGroupHeader:(v,M)=>{M?m.set(v,M):m.delete(v)},bottom:()=>w}}function vc(e,t){if(!e.rowKey)return;const r=t[e.rowKey];if((typeof r!="string"||!r.trim())&&!(typeof r=="number"&&Number.isFinite(r)))throw new Error(`数据集 ${e.dataset} 的 ${e.rowKey} 应为稳定的字符串或有限数字主键`);const n=e.revisionField?t[e.revisionField]:void 0,o=e.sourceTokenField?t[e.sourceTokenField]:void 0;if(n!==void 0&&typeof n!="string"&&!(typeof n=="number"&&Number.isFinite(n)))throw new Error("业务修订号应为字符串或有限数字");if(o!==void 0&&typeof o!="string")throw new Error("来源令牌应为字符串");return{datasetId:e.dataset,rowKey:r,...n===void 0?{}:{revision:n},...o===void 0?{}:{sourceToken:o}}}function Ct(e,t){const r=new Map;if(!e.rowKey)return r;const n=new Set;for(const o of t){const i=vc(e,o),s=JSON.stringify(i.rowKey);if(n.has(s))throw new Error(`数据集 ${e.dataset} 的业务主键重复:${String(i.rowKey)}`);n.add(s),r.set(o,i)}return r}function Mc(e,t,r,n,o){if(!e.grandTotal)return;const i=typeof e.grandTotal=="object"?e.grandTotal:void 0,s=Tt(e)[0],a=i?.fields??s?.subtotal??[],c=i?.aggregates??s?.aggregates??[];if(a.length===0&&c.length===0){n.warnings.push(`列表 ${e.id??""} 配置了 grandTotal 但未提供合计字段(groupBy.subtotal 或 grandTotal.fields)`);return}const u=Oe(r,n.measurer,i?.label??"合计",Ao(e.columns,t,a,c),i?.style??{},ko(e.columns,[...a,...c.map(f=>f.field)]));o.placeGridRow(u,"listgt","grand-total")}function se(e){if(e?.aborted){const t=new Error("报表排版已取消");throw t.name="AbortError",t}}function Tt(e){const t=e.groups??(e.groupBy?[e.groupBy]:[]);if(t.length>16)throw new Error("列表最多支持 16 级分组");return t}function Br(e){const t=_a(e),r=t.columns.reduce((o,i)=>o+i.widthMm,0),n=r>t.widthMm?t.widthMm/r:1;return n===1?t:{...t,columns:t.columns.map(o=>({...o,widthMm:o.widthMm*n}))}}function $c(e,t,r){const n=e.detail;if(!n)return;const o=new Set;for(const u of t){const f=ir(u[n.parentKey]);if(o.has(f))throw new Error("主从明细的主表关联键重复");o.add(f)}const i=r.datasets[n.dataset]??[],s=new Map,a=[];for(const u of i){const f=u[n.foreignKey];if(!No(f)&&n.unmatched==="ignore")continue;const d=ir(f);if(!o.has(d)){if(n.unmatched!=="ignore")throw new Error(`明细数据集 ${n.dataset} 存在未关联的业务键`);continue}const l=s.get(d);l?l.push(u):s.set(d,[u]),a.push(u)}const c=Br({...e,id:`${e.id??e.dataset}:detail`,dataset:n.dataset,rowKey:n.rowKey,revisionField:n.revisionField,sourceTokenField:n.sourceTokenField,computed:void 0,columns:n.columns,headerGrid:void 0,rowHeightMm:n.rowHeightMm??e.rowHeightMm,detail:void 0});return{list:c,inter:{...Lr(c,r.measurer,a,r.signal),rowHeightFloorMm:c.rowHeightMm??0},rows:s,sources:Ct(c,a)}}function No(e){return typeof e=="string"&&!!e.trim()||typeof e=="number"&&Number.isFinite(e)}function ir(e){if(!No(e))throw new Error("主从关联键必须是非空字符串或有限数字");return So(e)}function*Sc(e,t,r,n,o){if(!r)return;const i=r.rows.get(ir(t[e.detail.parentKey]))??[];if(!i.length)return;const s={id:`${n.tableId}:detail`,columnKeys:r.list.columns.map(a=>a.field),title:e.detail.label};e.detail.label&&o.placeGridRow({...Oe(r.inter,n.measurer,e.detail.label,new Map,{},r.list.columns.length),table:s},"listdl","group-header"),e.detail.header!==!1&&o.placeGridRow({grid:r.inter.headerGrid,heightMm:r.inter.headerHeightMm,table:s},"listdh","header"),yield*n.takePages();for(const a of i)se(n.signal),o.placeGridRow({...Je(r.inter,a,n.measurer),table:s},"listdr","body",r.sources.get(a)),yield*n.takePages()}function Po(e){if(e.matrix||e.detail||e.groups?.length||e.groupBy||e.rowVisibleWhen)throw new Error("树形布局不能同时配置普通分组、矩阵、主从或行可见条件");if(e.rowKey&&e.rowKey!==e.tree.idField)throw new Error("树形布局的 rowKey 应与 idField 一致");if(!e.columns.some(t=>t.field===e.tree.labelField&&!t.hidden))throw new Error("树形布局需要可见的标签列");Rr(e.tree,e.computed)}function Ec(e,t,r){Po(e);const n=ho(t,e.tree,{signal:r.signal,computed:e.computed?.length?{fields:e.computed,formula:r.formula}:void 0}),o={...e,rowKey:e.tree.idField},i=Ct(o,n.entries.map(c=>c.original)),s=new Map,a=new WeakMap;for(const c of n.entries)s.set(c.row,i.get(c.original)),a.set(c.row,c);return{list:o,rows:n.rows,sources:s,treeRows:a,totalRows:n.leaves}}function Ac(e,t){if(e.cardinality==="record"){if(t.length>1)throw new Error(`单记录区域 ${e.id??e.dataset} 仅允许 0 或 1 行数据`);if(e.tree||e.matrix||e.detail||e.groups?.length||e.groupBy||e.grandTotal||e.rowVisibleWhen)throw new Error("单记录区域不能配置树、矩阵、主从、分组、总计或行过滤");if(!t.length)return{list:{...e,columns:e.columns.map(r=>({...r,editable:!1}))},rows:[{}],sources:new Map}}}function Fo(e,t,r){const n=r.prepared.get(e);if(n)return n;const o=Ac(e,t);if(o)return r.prepared.set(e,o),o;if(e.tree){const c=Ec(e,t,r);return r.prepared.set(e,c),c}let i=e.computed?.length?Ot(t,{fields:e.computed,signal:r.signal,formula:r.formula}).rows:t;const s=i===t?void 0:new Map(i.map((c,u)=>[c,t[u]]));e.rowVisibleWhen&&(i=i.filter(q(e.rowVisibleWhen)));const a=Oa(e,i);if(!e.matrix){const c=Ct(e,s?i.map(u=>s.get(u)):i);a.sources=s?new Map(i.map(u=>[u,c.get(s.get(u))])):c}return r.prepared.set(e,a),a}function kc(e,t,r,n){if(!n.flow)return;const{current:o,templatePage:i}=n,s=Math.max(o.marginTopMm,We(i)),a=Math.max(n.startTop??e.topMm,s),c=(e.header===!1?0:t.headerHeightMm)+(r[0]?Je(t,r[0],n.measurer).heightMm:0);a+c<=gt(i,o)+.001||a<=s+.001||(n.pushCurrent(),o.components=[],o.heightMm=i.heightMm,i.layout==="wide"&&(o.marginTopMm=0,o.marginBottomMm=0),n.startTop=Math.max(o.marginTopMm,We(i)))}function*Nc(e,t,r){const n=Fo(e,t,r),o=n.rows;e=n.list,e.layout==="wide"&&(r.current.widthMm=Math.max(r.current.widthMm,e.leftMm+e.widthMm+r.current.marginRightMm));const i=n.sources??Ct(e,o),s=Br(e),a=Tt(s),c={...Lr(s,r.measurer,o,r.signal),rowHeightFloorMm:s.rowHeightMm??0,matrix:n.matrix,...n.treeRows?{tree:{list:s,rows:n.treeRows}}:{}};kc(s,c,o,r);const u=xc(s,c,r),f=$c(s,o,r);let d;for(const l of Eo(o,a)){if(se(r.signal),l.kind==="row")u.placeGridRow(d??Je(c,l.row,r.measurer),"listr",Pa(n.matrix,l.row),i.get(l.row)),d=void 0,yield*r.takePages(),yield*Sc(s,l.row,f,r,u);else if(l.kind==="groupHeader"){const m=Oe(c,r.measurer,l.label,new Map,l.group.headerStyle??{},s.columns.length);d??=Je(c,l.firstRow,r.measurer);const h=a.slice(l.depth+1).reduce((p,w)=>p+Oe(c,r.measurer,(w.headerTemplate??"{value}").replace(/\{value\}/g,Or(l.firstRow[w.field])),new Map,w.headerStyle??{},s.columns.length).heightMm,0);l.group.keepWithNext!==!1&&u.keepTogether(m.heightMm+h+d.heightMm),u.placeGridRow(m,"listg","group-header"),l.group.repeatHeader&&u.setGroupHeader(l.depth,m)}else if(l.kind==="subtotal"){const m=l.group.subtotal??[],h=l.group.aggregates??[],p=Oe(c,r.measurer,l.label,Ao(s.columns,l.rows,m,h),l.group.subtotalStyle??{},ko(s.columns,[...m,...h.map(w=>w.field)]));u.placeGridRow(p,"listst","subtotal")}else u.setGroupHeader(l.depth);yield*r.takePages()}Mc(s,n.totalRows??o,c,r,u),r.finished?.(u.bottom()),yield*r.takePages()}function _r(e){return e.kind!=="list"&&(e.pageAnchor!==void 0||e.kind==="text"&&typeof e.text=="string"&&(e.text.includes("{page}")||e.text.includes("{totalPages}")))}function Kr(e,t){return{...e,...e.text===void 0?{}:{text:t(e.text)},...e.lines?{lines:e.lines.map(t)}:{},...e.richParagraphs?{richParagraphs:e.richParagraphs.map(r=>({...r,segments:r.segments.map(n=>({...n,...n.text===void 0?{}:{text:t(n.text)}}))}))}:{},...e.grid?{grid:{...e.grid,cells:e.grid.cells.map(r=>r.map(n=>n?{...n,...n.text===void 0?{}:{text:t(n.text)},...n.children?{children:n.children.map(o=>Kr(o,t))}:{}}:null))}}:{}}}function Pc(e,t,r,n,o,i){const s={pageWidthMm:t.widthMm,pageHeightMm:t.heightMm,...e.layout===void 0?{}:{layout:e.layout},marginTopMm:t.marginTopMm,marginBottomMm:t.marginBottomMm,marginLeftMm:t.marginLeftMm,marginRightMm:t.marginRightMm,components:t.components,...e.meta?{meta:e.meta}:{}},a=c=>{const u=c.replace(/\{page\}/g,String(n));return i===void 0?u:u.replace(/\{totalPages\}/g,String(i))};for(const c of r)s.components.push(Kr(c,a));if(e.layout==="wide"){const c=s.components.reduce((u,f)=>Math.max(u,f.topMm+f.heightMm),0);s.marginBottomMm=o?e.marginBottomMm??0:0,s.pageHeightMm=Math.max(1,c+s.marginBottomMm)}return s}function Wr(e){return e.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+Oo(s),0)??0):0),0),0)}function Oo(e){return e.grid?Wr(e.grid):0}function Io(e){for(const t of["maxPages","maxCells","knownTotalPages"])if(e[t]!==void 0&&(!Number.isSafeInteger(e[t])||e[t]<1))throw new RangeError(`${t} 应为正安全整数`);It(e.maxChartComponents)}function Fc(e,t){const r=Fo(e,t.datasets[e.dataset]??[],t),n=Br(r.list),o={...Lr(n,t.measurer,r.rows,t.signal),rowHeightFloorMm:n.rowHeightMm??0};return(n.header===!1?0:o.headerHeightMm)+r.rows.reduce((i,s)=>i+Je(o,s,t.measurer).heightMm,0)}function*Oc(e){const{templatePage:t,current:r}=e,n=new Map(t.components.map((i,s)=>[i,s])),o=(i,s,a)=>{const c=e.datasets[i.dataset];return Array.isArray(c)||e.warnings.push(`数据集 ${i.dataset} 未提供数据,列表 ${i.id??""} 输出为空`),Nc(i,Array.isArray(c)?c:[],{...e,tableId:`${e.tableId}:${n.get(i)}`,startTop:s,finished:a,flow:!!t.flow})};if(t.flow){yield*Va({page:t,active:()=>se(e.signal),top:()=>Math.max(r.marginTopMm,We(t)),bottom:()=>gt(t,r),append:i=>{r.components.push(...e.resolveChart(i))},nextPage:()=>{e.pushCurrent(),r.components=[],r.heightMm=t.heightMm,t.layout==="wide"&&(r.marginTopMm=0,r.marginBottomMm=0)},takePages:e.takePages,height:i=>Fc(i,e),list:o});return}for(const i of t.components)_r(i)||(i.kind==="list"?yield*o(i):r.components.push(...e.resolveChart(i)))}function*Ro(e,t,r,n,o,i=new WeakMap,s){let a=0,c=0,u=0;const f=is(r.measurer??$r),d=aa(t,r.signal,r.maxChartComponents),l=m=>`${m}_${(++a).toString(36)}`;for(const{pageIndex:m,page:h}of ac(e,t,r)){se(r.signal);const p=dc(h),w=h.components.filter(_r);let y=[];const g=(b=!1)=>{if(se(r.signal),r.maxPages!==void 0&&c>=r.maxPages)throw new Se(r.maxPages,c+1);if(r.maxCells!==void 0&&(u+=[...p.components,...w].reduce(($,T)=>$+Oo(T),0),u>r.maxCells))throw new _e(r.maxCells,u);y.push(Pc(h,p,w,++c,b,o))},x=()=>{const b=y;return y=[],b};yield*Oc({templatePage:h,current:p,warnings:n,nextId:l,pushCurrent:g,takePages:x,datasets:t,resolveChart:d,signal:r.signal,formula:r.formula,prepared:i,measurer:f,mmPerRow:r.mmPerRow??0,tableId:`table:${m}`}),g(!0),yield*x()}s&&(s.chartComponents=d.used())}function Ic(e,t,r={}){const n=typeof r=="number"?{mmPerRow:r}:r;Io(n);const o=[],i={chartComponents:0},s=[...Ro(e,t,n,o,n.knownTotalPages,void 0,i)];return To(e,n,s,o,i)}async function Co(e,t,r={}){Io(r),se(r.signal);const n=[],o=[],i={chartComponents:0};let s=performance.now(),a=0;for(const c of Ro(e,t,r,n,r.knownTotalPages,void 0,i))o.push(c),(++a>=8||performance.now()-s>=8)&&(await new Promise(u=>setTimeout(u,0)),se(r.signal),s=performance.now(),a=0);return se(r.signal),To(e,r,o,n,i)}function To(e,t,r,n,o){for(const i of r)i.components=i.components.map(s=>_r(s)?Kr(s,a=>a.replace(/\{totalPages\}/g,String(r.length))):s);return n.forEach(i=>t.onWarning?.(i)),{plan:{schemaVersion:ze,...Tr(e)?{requiresRecalculation:!0}:{},pages:r},warnings:n,...o}}function Rc(e){const t=e.columns.find(i=>!i.hidden)?.field;if(!t)return{groups:0,total:0};const r=Tt(e),n=(i=[],s=[])=>i.includes(t)||s.some(a=>a.field===t),o=typeof e.grandTotal=="object"?e.grandTotal:void 0;return{groups:r.filter(i=>n(i.subtotal,i.aggregates)).length,total:Number(n(o?.fields??r[0]?.subtotal,o?.aggregates??r[0]?.aggregates))}}function Cc(e,t,r){Po(e);const n=mo(t[e.dataset]??[],e.tree,r),o=e.columns.filter(s=>!s.hidden).length,i=e.header===!1?0:e.headerGrid?Wr(e.headerGrid):o;return n.length*o+i+ +!!e.grandTotal*2*o}function Tc(e,t,r={}){if(e.tree)return Cc(e,t,r.signal);if(e.matrix){let c=t[e.dataset]??[];e.computed?.length&&(c=Ot(c,{fields:e.computed,...r}).rows),e.rowVisibleWhen&&(c=c.filter(q(e.rowVisibleWhen)));const u=eo(c,e.matrix);return u.cells+(e.header===!1?0:u.columnCount*(e.matrix.hierarchy?e.matrix.columnFields.length+1:1))}const n=t[e.dataset]?.length??0,o=e.columns.filter(c=>!c.hidden).length,i=Tt(e).length,s=Rc(e);let a=(n*(1+2*i+s.groups)+ +!!e.grandTotal*(1+s.total))*o;if(a+=e.header===!1?0:e.headerGrid?Wr(e.headerGrid):o,e.cardinality==="record"&&n===0&&(a+=o),e.detail){const c=t[e.detail.dataset]?.length??0,u=e.detail.columns.filter(f=>!f.hidden).length;a+=(c+n*(+(e.detail.header!==!1)+ +!!e.detail.label))*u}if(!Number.isSafeInteger(a))throw new RangeError("报表单元格估算超出安全整数预算");return a}function jc(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const{start:t,end:r,color:n}=e;return typeof t=="number"&&typeof r=="number"&&Number.isFinite(t)&&Number.isFinite(r)&&t>=0&&r<=1&&t<=r&&typeof n=="string"&&/^#[0-9a-f]{6}$/i.test(n)}function rt(e){return!!e&&typeof e=="object"}function jo(e,t,r,n,o){if(++o.nodes>1e6)return{path:t,message:"组件树超过100万个结构节点预算"};if(rt(e)){if(r>64)return{path:t,message:"组件嵌套超过64层预算"};if(n.has(e))return{path:t,message:"组件树包含循环引用"};if(!(!rt(e.grid)||!Array.isArray(e.grid.cells))){n.add(e);try{for(const[i,s]of e.grid.cells.entries())if(Array.isArray(s))for(const[a,c]of s.entries()){if(++o.nodes>1e6)return{path:t,message:"组件树超过100万个结构节点预算"};if(!(!rt(c)||!Array.isArray(c.children)))for(const[u,f]of c.children.entries()){const d=jo(f,`${t}.grid.cells.${i}.${a}.children.${u}`,r+1,n,o);if(d)return d}}}finally{n.delete(e)}}}}function Jr(e,t="$.components",r={nodes:0}){for(const[n,o]of e.entries()){const i=jo(o,`${t}.${n}`,0,new Set,r);if(i)return i}}function Do(e){const t={nodes:0};for(const[r,n]of e.entries()){if(!rt(n)||!Array.isArray(n.components))continue;const o=Jr(n.components,`$.pages.${r}.components`,t);if(o)return o}}function Dc(e){const t=Do(e.pages);if(t)throw new TypeError(`${t.path}: ${t.message}`)}function Lc(e,t,r){e!==void 0&&(typeof e!="string"||!e.trim()||e.length>4096)&&r.push({path:t,message:"来源范围应为不超过 4096 字符的非空字符串"})}function Lo(e,t,r){e.editable!==void 0&&typeof e.editable!="boolean"&&r.push({path:`${t}.editable`,message:"编辑控制应为布尔值"}),e.valueType!==void 0&&!["text","number","boolean"].includes(e.valueType)&&r.push({path:`${t}.valueType`,message:"编辑类型应为 text、number 或 boolean"})}function Bc(e,t,r){Lo(e,t,r),e.indentMm!==void 0&&(typeof e.indentMm!="number"||!Number.isFinite(e.indentMm)||e.indentMm<0)&&r.push({path:`${t}.indentMm`,message:"单元格缩进应为有限非负数"}),e.derived!==void 0&&typeof e.derived!="boolean"&&r.push({path:`${t}.derived`,message:"派生结果标记应为布尔值"}),Bo(e.source,`${t}.source`,r,!0),e.formula!==void 0&&typeof e.formula!="string"&&r.push({path:`${t}.formula`,message:"单元格公式应为字符串"})}function Bo(e,t,r,n=!1){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e)){r.push({path:t,message:"业务来源应为对象"});return}const o=e;Lc(o.sourceScope,`${t}.sourceScope`,r);for(const i of["datasetId",...n?["field"]:[]])(typeof o[i]!="string"||!o[i].trim())&&r.push({path:`${t}.${i}`,message:"业务标识应为非空字符串"});for(const i of["rowKey","revision"]){const s=o[i];s===void 0&&!(n&&i==="rowKey")||typeof s!="string"&&!(typeof s=="number"&&Number.isFinite(s))&&r.push({path:`${t}.${i}`,message:"业务键及修订号应为字符串或有限数字"})}o.sourceToken!==void 0&&typeof o.sourceToken!="string"&&r.push({path:`${t}.sourceToken`,message:"来源令牌应为字符串"})}function _c(e){const t=[];return e.value!==void 0&&typeof e.value!="string"&&t.push({path:"value",message:"Symbol value must be a string."}),e.symbology!==void 0&&!["code128","code39","ean13","ean8"].includes(e.symbology)&&t.push({path:"symbology",message:"Unsupported barcode symbology."}),e.errorCorrection!==void 0&&!["L","M","Q","H"].includes(e.errorCorrection)&&t.push({path:"errorCorrection",message:"Unsupported QR error correction."}),e.showText!==void 0&&typeof e.showText!="boolean"&&t.push({path:"showText",message:"showText must be a boolean."}),t}function Kc(e,t){const r=[];return t!=="barcode"&&t!=="qrcode"&&r.push({path:"",message:"code is only supported by barcode and qrcode components."}),t==="qrcode"&&e.symbology!==void 0&&r.push({path:"symbology",message:"QR components do not use a linear symbology."}),t==="qrcode"&&e.showText===!0&&r.push({path:"showText",message:"Use a separate text component below a QR code."}),t==="barcode"&&e.errorCorrection!==void 0&&r.push({path:"errorCorrection",message:"Linear barcodes do not use QR error correction."}),r}function Wc(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return[{path:"",message:"code must be an object."}];const r=e,n=[..._c(r),...Kc(r,t)];for(const s of Object.keys(r))["value","symbology","errorCorrection","quietZoneModules","showText"].includes(s)||n.push({path:s,message:"Unknown symbol option."});const o=r.symbology==="ean13"||r.symbology==="ean8",i=t==="qrcode"?4:o?11:10;return r.quietZoneModules!==void 0&&(!Number.isSafeInteger(r.quietZoneModules)||Number(r.quietZoneModules)<i||Number(r.quietZoneModules)>64)&&n.push({path:"quietZoneModules",message:`Quiet zone must contain ${i}–64 whole modules.`}),n}const Jc=new Set(["text","image","barcode","qrcode","chart","line","rect","ellipse"]);function z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pt(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 zc(e,t,r,n){const o=e[t];(typeof o!="number"||!Number.isFinite(o))&&n.push({path:`${r}.${t}`,message:`应为有限数字,实际 ${pt(o)}`})}function Vc(e,t,r){if(e!==void 0){const n=`${t}.table`;if(!z(e))r.push({path:n,message:"逻辑表来源应为对象"});else{Bo(e.source,`${n}.source`,r),(typeof e.id!="string"||!e.id.trim())&&r.push({path:`${n}.id`,message:"逻辑表 ID 应为非空字符串"});const o=e.role;["header","body","group-header","subtotal","grand-total"].includes(o)||r.push({path:`${n}.role`,message:"未知逻辑表行角色"});const i=e.rowIndex;(typeof i!="number"||!Number.isInteger(i)||(o==="header"?i!==-1:i<0))&&r.push({path:`${n}.rowIndex`,message:"表头索引应为 -1,内容行索引应为非负整数"}),(!Array.isArray(e.columnKeys)||e.columnKeys.some(s=>typeof s!="string"))&&r.push({path:`${n}.columnKeys`,message:"逻辑列字段应为字符串数组"}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&r.push({path:`${n}.layout`,message:"布局应为 page 或 wide"}),e.title!==void 0&&typeof e.title!="string"&&r.push({path:`${n}.title`,message:"逻辑表名称应为字符串"})}}}function Hc(e,t,r,n){if(e!==void 0)if(!z(e)||!Array.isArray(e.cells))r.push({path:`${t}.grid.cells`,message:"grid.cells 应为二维数组"});else{const o=e.paddingMm;o!==void 0&&(typeof o!="number"||!Number.isFinite(o)||o<0)&&r.push({path:`${t}.grid.paddingMm`,message:"单元格内距应为有限非负数"}),e.cells.forEach((i,s)=>{if(!Array.isArray(i)){r.push({path:`${t}.grid.cells.${s}`,message:"行应为数组"});return}i.forEach((a,c)=>{if(a==null)return;const u=`${t}.grid.cells.${s}.${c}`;if(!z(a)){r.push({path:u,message:"网格单元格应为对象或 null"});return}Bc(a,u,r),a.dataBar!==void 0&&!jc(a.dataBar)&&r.push({path:`${u}.dataBar`,message:"数据条应包含 0–1 有序比例与 #RRGGBB 颜色"}),_o(a.richParagraphs,u,r),Array.isArray(a.children)&&a.children.forEach((f,d)=>{zr(f,`${t}.grid.cells.${s}.${c}.children.${d}`,r,n)})})})}}function yt(e,t,r,n){e!==void 0&&!t.includes(e)&&n.push({path:r,message:"未知富文本属性值"})}function sr(e,t,r,n,o=0){for(const i of t){const s=e[i];s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||s<o)&&n.push({path:`${r}.${i}`,message:"富文本数值应为范围内有限数字"})}}function Uc(e,t,r){if(e!==void 0){if(!z(e)){r.push({path:t,message:"富文本样式应为对象"});return}for(const n of["fontFamily","color","backgroundColor","lineColor","borderColor"])e[n]!==void 0&&typeof e[n]!="string"&&r.push({path:`${t}.${n}`,message:"富文本样式应为字符串"});for(const n of["bold","italic","underline","borderTop","borderRight","borderBottom","borderLeft"])e[n]!==void 0&&typeof e[n]!="boolean"&&r.push({path:`${t}.${n}`,message:"富文本样式应为布尔值"});sr(e,["fontSize","fontSizePx","lineWidthPt","lineHeight","opacity"],t,r),sr(e,["letterSpacing","rotateDeg"],t,r,-1/0),typeof e.opacity=="number"&&e.opacity>1&&r.push({path:`${t}.opacity`,message:"透明度不能大于1"}),yt(e.align,["left","center","right","justify"],`${t}.align`,r),yt(e.verticalAlign,["top","middle","bottom"],`${t}.verticalAlign`,r)}}function Gc(e,t,r){if(!z(e)){r.push({path:t,message:"富文本片段应为对象"});return}yt(e.kind,["text","field"],`${t}.kind`,r);for(const n of["text","field"])e[n]!==void 0&&typeof e[n]!="string"&&r.push({path:`${t}.${n}`,message:"富文本内容应为字符串"});Uc(e.style,`${t}.style`,r)}function _o(e,t,r){if(e!==void 0){if(!Array.isArray(e)){r.push({path:`${t}.richParagraphs`,message:"richParagraphs 应为数组"});return}e.forEach((n,o)=>{const i=`${t}.richParagraphs.${o}`;if(!z(n)||!Array.isArray(n.segments)){r.push({path:i,message:"段落缺少 segments 数组"});return}yt(n.align,["left","center","right","justify"],`${i}.align`,r),sr(n,["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"],i,r),n.segments.forEach((s,a)=>Gc(s,`${i}.segments.${a}`,r))})}}function Ko(e,t,r,n=[]){const o=Jr([e],t);if(o){r.push(o);return}zr(e,t,r,n)}function zr(e,t,r,n=[]){if(!z(e)){r.push({path:t,message:"组件应为对象"});return}const o=e.kind;typeof o!="string"?r.push({path:`${t}.kind`,message:"组件缺少 kind 字符串"}):Jc.has(o)||n.push({path:`${t}.kind`,message:`未知组件类型 ${pt(o)},将以兜底方式渲染`});for(const i of["leftMm","topMm","widthMm","heightMm"])zc(e,i,t,r);typeof e.leftMm=="number"&&e.leftMm<-100&&r.push({path:`${t}.leftMm`,message:"几何数值异常(leftMm<-100)"});for(const i of["widthMm","heightMm"])typeof e[i]=="number"&&e[i]<0&&r.push({path:`${t}.${i}`,message:"组件尺寸不能为负数"});Vc(e.table,t,r),qc(e.code,o,t,r),Yc(e,t,r),e.pageAnchor!==void 0&&!["header","footer"].includes(e.pageAnchor)&&r.push({path:`${t}.pageAnchor`,message:"页面锚点应为 header 或 footer"}),e.lineDirection!==void 0&&!["down","up"].includes(e.lineDirection)&&r.push({path:`${t}.lineDirection`,message:"线段方向应为 down 或 up"}),Hc(e.grid,t,r,n),_o(e.richParagraphs,t,r)}function Yc(e,t,r){if(e.chartBinding!==void 0)try{if(Xn(e.chartBinding),e.kind!=="chart"||["binding","imageData","grid","pageAnchor"].some(n=>e[n]!==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(n){r.push({path:`${t}.chartBinding`,message:n instanceof Error?n.message:String(n)})}}function qc(e,t,r,n){if(e!==void 0)for(const o of Wc(e,t))n.push({path:`${r}.code${o.path?`.${o.path}`:""}`,message:o.message})}function Wo(e,t,r){if(!z(e))return;e.binding!==void 0&&r.push({path:`${t}.binding`,message:"渲染计划不允许未解析字段绑定"}),e.chartBinding!==void 0&&r.push({path:`${t}.chartBinding`,message:"渲染计划不允许未解析图表绑定"});const n=e.grid;!z(n)||!Array.isArray(n.cells)||n.cells.forEach((o,i)=>{Array.isArray(o)&&o.forEach((s,a)=>{!z(s)||!Array.isArray(s.children)||s.children.forEach((c,u)=>Wo(c,`${t}.grid.cells.${i}.${a}.children.${u}`,r))})})}function Xc(e,t,r,n=[]){if(!z(e)){r.push({path:t,message:"页应为对象"});return}const o=e.pageWidthMm,i=e.pageHeightMm;(typeof o!="number"||!Number.isFinite(o)||o<=0)&&r.push({path:`${t}.pageWidthMm`,message:`页宽非法: ${pt(o)}`}),(typeof i!="number"||!(i>0&&i<5e3))&&r.push({path:`${t}.pageHeightMm`,message:`页高非法: ${pt(i)}`}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&r.push({path:`${t}.layout`,message:"布局应为 page 或 wide"});const s=e.components;if(!Array.isArray(s))r.push({path:`${t}.components`,message:"components 应为数组"});else if(Array.isArray(s)){const a=Jr(s,`${t}.components`);if(a){r.push(a);return}s.forEach((c,u)=>{zr(c,`${t}.components.${u}`,r,n),Wo(c,`${t}.components.${u}`,r)})}}function Ue(e){const t=[],r=[],n=z(e)?e.pages:void 0;if(z(e)&&e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean"&&t.push({path:"$.requiresRecalculation",message:"重算能力要求应为布尔值"}),!Array.isArray(n))t.push({path:"$.pages",message:e==null?"渲染计划为空":"渲染计划缺少 pages 数组"});else{const o=Do(n);if(o)return{ok:!1,errors:[...t,o],warnings:r};n.forEach((s,a)=>Xc(s,`$.pages.${a}`,t,r)),n.length>2e3&&r.push({path:"$.pages",message:`页数异常大(${n.length} 页),渲染与打印耗时可能显著增加`});const i=n.reduce((s,a)=>s+(z(a)&&Array.isArray(a.components)?a.components.length:0),0);i>5e4&&r.push({path:"$.pages",message:`组件总数异常大(${i} 个),可能触发浏览器性能限制`})}return{ok:t.length===0,errors:t,warnings:r}}function wt(e,t){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype)return;const r=Object.getOwnPropertyDescriptor(e,"length")?.value;if(typeof r!="number"||!Number.isSafeInteger(r)||r<0||r>t||Reflect.ownKeys(e).length!==r+1)return;const o=[];for(let i=0;i<r;i++){const s=Object.getOwnPropertyDescriptor(e,String(i));if(!s||!Object.prototype.hasOwnProperty.call(s,"value"))return;o.push(s.value)}return o}const Vr=100,Jo=16,ar=104857;function zo(e,t,r){if(typeof e=="string"){if(e.length>ar)return;try{e=JSON.parse(e)}catch{return}}const n=wt(e,t);if(!n)return;const o=[];let i=2;for(const s of n){if(typeof s!="string"||!s.trim()||s.length>1024||r&&o.includes(s)||(i+=JSON.stringify(s).length+(o.length?1:0),i>ar))return;o.push(s)}return o}function Zc(e){return zo(e,Vr,!0)}function Qc(e){return zo(e,Jo,!1)}function eu(e){if(typeof e=="string"){if(e.length>2048)return;try{e=JSON.parse(e)}catch{return}}const t=wt(e,2);if(!t||t.length!==2)return;const r=t[0],n=t[1];return typeof r=="number"&&typeof n=="number"&&Number.isFinite(r)&&Number.isFinite(n)&&r<=n?[r,n]:void 0}function U(e){return["multiSelect","cascader","numberRange"].includes(e.type??"")}function jt(e,t){return e.type==="numberRange"?eu(t):e.type==="cascader"?Qc(t):Zc(t)}function tu(e,t,r=!1){const n=wt(e,1e3);if(!n)return!1;const o=[{items:n,depth:1}],i=new Set;let s=0;for(let a=0;a<o.length;a++){const{items:c,depth:u}=o[a];if(u>Jo)return!1;const f=new Set;for(const d of c){const l=ru(d,r);if(++s>1e3||!l||i.has(d)||f.has(l.value))return!1;if(i.add(d),f.add(l.value),l.children!==void 0){const m=wt(l.children,1e3);if(!t||!m)return!1;m.length&&o.push({items:m,depth:u+1})}}}return!0}function Vo(e){return e.map(t=>({value:t.value,label:t.label,...t.children?{children:Vo(t.children)}:{}}))}function ru(e,t){if(!e||typeof e!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(e)))return;const r=Object.getOwnPropertyDescriptors(e);if(Object.values(r).some(i=>!Object.prototype.hasOwnProperty.call(i,"value")))return;const n=r.value?.value,o=r.label?.value;if(!(typeof n!="string"||!t&&!n.trim()||n.length>1024||typeof o!="string"||o.length>1024))return{value:n,label:o,...r.children?{children:r.children.value}:{}}}function nu(e,t){let r=e;for(const[n,o]of t.entries()){const i=r.find(s=>s.value===o);if(!i)return!1;if(r=i.children??[],n===t.length-1)return r.length===0}return!1}function ou(e,t){const r=jt(e,t);if(!r)return[["type",e.type==="numberRange"?"请填写完整数字范围,最小值不能大于最大值":e.type==="cascader"?"请选择完整的末级路径":"请选择有效选项,不能重复或超出数量限制"]];if(e.type==="numberRange")return iu(e,r);const n=r,o=[];return e.type==="cascader"&&e.options&&!nu(e.options,n)&&o.push(["option","应为允许选项中的完整叶节点路径"]),e.type==="multiSelect"&&(e.options&&n.some(i=>!e.options.some(s=>s.value===i))&&o.push(["option","不在允许的选项中"]),e.minItems!==void 0&&n.length<e.minItems&&o.push(["minItems",`至少选择 ${e.minItems} 项`]),e.maxItems!==void 0&&n.length>e.maxItems&&o.push(["maxItems",`最多选择 ${e.maxItems} 项`])),o}function iu(e,t){const r=[];return typeof e.min=="number"&&t[0]<e.min&&r.push(["minimum",`不能小于 ${e.min}`]),typeof e.max=="number"&&t[1]>e.max&&r.push(["maximum",`不能大于 ${e.max}`]),r}function su(e){const t=[];for(const r of["minItems","maxItems"])e[r]!==void 0&&(e.type!=="multiSelect"||!Number.isSafeInteger(e[r])||e[r]<0||e[r]>Vr)&&t.push(`${r} 应为多选参数的 0–100 整数边界`);return e.minItems!==void 0&&e.maxItems!==void 0&&e.minItems>e.maxItems&&t.push("最少项目数不能大于最多项目数"),t}function au(e){if(e.type==="numberRange"){const r={type:"number",...typeof e.min=="number"?{minimum:e.min}:{},...typeof e.max=="number"?{maximum:e.max}:{}};return{type:"array",minItems:2,maxItems:2,prefixItems:[r,{...r}],items:!1,"x-report-number-range":{ordered:!0},"x-report-wire-encoding":"json"}}const t={"x-report-wire-encoding":"json","x-report-wire-max-code-units":ar,type:"array",minItems:Math.max(e.required?1:0,e.minItems??0),maxItems:e.type==="cascader"?16:e.maxItems??Vr,items:{type:"string",minLength:1,maxLength:1024,pattern:"\\S","x-report-max-code-units":1024}};return e.type==="multiSelect"?(t.uniqueItems=!0,e.options&&(t.items={...t.items,enum:e.options.map(r=>r.value)})):t["x-report-cascader"]={leafOnly:!0,...e.options?{options:Vo(e.options)}:{}},t}function cu(e){const t=[];return e.optionsSource!==void 0&&((!["select","multiSelect","cascader"].includes(e.type??"")||typeof e.optionsSource!="string"||!/^[\w][\w.:-]{0,127}$/.test(e.optionsSource))&&t.push("远程选项来源应为选择参数的有效来源键(最多 128 字符)"),e.options!==void 0&&t.push("远程选项来源与静态选项不能同时配置")),e.dependsOn!==void 0&&(!e.optionsSource||!Array.isArray(e.dependsOn)||e.dependsOn.length>32||e.dependsOn.some(r=>typeof r!="string"||!r)||new Set(e.dependsOn).size!==e.dependsOn.length)&&t.push("联动依赖应为远程选项的最多 32 个唯一参数名"),t}function uu(e){const t=new Map(e.map((o,i)=>[o.field,{def:o,index:i,degree:0,children:[]}])),r=[];for(const o of t.values())for(const i of o.def.dependsOn??[]){const s=t.get(i);if(!s){r.push({index:o.index,message:`联动依赖参数 ${i} 未声明`});continue}o.degree++,s.children.push(o.def.field)}const n=[...t.values()].filter(o=>o.degree===0);for(let o=0;o<n.length;o++)for(const i of n[o].children){const s=t.get(i);--s.degree===0&&n.push(s)}for(const o of t.values())o.degree>0&&r.push({index:o.index,message:"联动依赖不能形成循环"});return r}function bt(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e)||e.startsWith("0000-"))return!1;const t=new Date(`${e}T00:00:00.000Z`);return Number.isFinite(t.getTime())&&t.toISOString().slice(0,10)===e}function Hr(e){return e.length===4&&/^\d{4}$/.test(e)&&e!=="0000"}function Ho(e){return e.length===7&&/^\d{4}-(?:0[1-9]|1[0-2])$/.test(e)&&Hr(e.slice(0,4))}function Uo(e){const[t,r,n]=e.split("/");if(!(n!==void 0||!t||!r||!bt(t)||!bt(r)||t>r))return{start:t,end:r}}function Go(e,t){return typeof t!="string"?!1:e==="month"?Ho(t):e==="year"?Hr(t):(e==="date"||e==="dateRange")&&bt(t)}function fu(e,t){if(e==="date"&&!bt(t))return"应为有效的 YYYY-MM-DD 日期";if(e==="month"&&!Ho(t))return"应为有效的 YYYY-MM 月份";if(e==="year"&&!Hr(t))return"应为 0001 至 9999 的四位年份";if(e==="dateRange"&&!Uo(t))return"应为完整且有序的 YYYY-MM-DD/YYYY-MM-DD 日期范围"}class Dt extends Error{constructor(t){super(t.map(r=>`${r.field}: ${r.message}`).join("; ")),this.issues=t,this.code="params",this.name="ReportParamValidationError"}}function Yo(e){return/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e)&&Number.isFinite(Number(e))}function qo(e,t){if(U(e))return ou(e,t);if(e.type==="number"&&!Yo(t))return[["type","应为有限数字"]];const r=fu(e.type,t);if(r)return[["type",r]];const n=[];e.type==="select"&&e.options&&!e.options.some(i=>i.value===t)&&n.push(["option","不在允许的选项中"]);const o=Array.from(t).length;return e.minLength!==void 0&&o<e.minLength&&n.push(["minLength",`至少 ${e.minLength} 个字符`]),e.maxLength!==void 0&&o>e.maxLength&&n.push(["maxLength",`最多 ${e.maxLength} 个字符`]),n.push(...lu(e,t)),n}function lu(e,t){const r=e.type==="dateRange"?Uo(t):void 0,n=r?.start??(e.type==="number"?Number(t):t),o=r?.end??n,i=[];return e.min!==void 0&&n<e.min&&i.push(["minimum",`不能小于 ${e.min}`]),e.max!==void 0&&o>e.max&&i.push(["maximum",`不能大于 ${e.max}`]),i}function du(e){const t=[];for(const o of["min","max"]){const i=e[o];if(i===void 0)continue;Go(e.type,i)||["number","numberRange"].includes(e.type??"")&&typeof i=="number"&&Number.isFinite(i)||t.push(`${o} 应为数字的有限边界或日期/月/年的规范字符串边界`)}const r=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;return(r||n)&&t.push("最小边界不能大于最大边界"),[...t,...mu(e),...su(e)]}function mu(e){const t=[];U(e)&&(e.minLength!==void 0||e.maxLength!==void 0)&&t.push("复合参数使用项目数或数值边界,而不是文本长度约束"),e.type==="number"&&(e.minLength!==void 0||e.maxLength!==void 0)&&t.push("number 参数使用 min/max 而不是文本长度约束");for(const r of["minLength","maxLength"]){const n=e[r];n!==void 0&&(!Number.isSafeInteger(n)||n<0)&&t.push(`${r} 应为非负整数`)}return typeof e.minLength=="number"&&typeof e.maxLength=="number"&&e.minLength>e.maxLength&&t.push("最小长度不能大于最大长度"),t}function Lt(e){if(!Array.isArray(e))return[{code:"definition",field:"",path:"$.paramDefs",message:"参数定义应为数组"}];const t=new Set,r=e.flatMap((n,o)=>{const i=n&&typeof n.field=="string"?n.field:"";return gu(n,t).map(a=>({code:"definition",field:i,path:`$.paramDefs.${o}`,message:a}))});return r.length?r:uu(e).map(({index:n,message:o})=>({code:"definition",field:e[n].field,path:`$.paramDefs.${n}`,message:o}))}function hu(e){const t=[];return e.type!==void 0&&!["text","number","date","month","year","dateRange","select","multiSelect","cascader","numberRange"].includes(e.type)&&t.push("未知参数类型"),e.label!==void 0&&typeof e.label!="string"&&t.push("参数标签应为字符串"),e.placeholder!==void 0&&typeof e.placeholder!="string"&&t.push("提示文字应为字符串"),e.required!==void 0&&typeof e.required!="boolean"&&t.push("required 应为布尔值"),e.defaultValue!==void 0&&typeof e.defaultValue!="string"&&t.push("默认值应为字符串"),e.options!==void 0&&!tu(e.options,e.type==="cascader",!U(e))&&t.push("选项应为包含字符串 label/value 的数组"),[...t,...cu(e)]}function gu(e,t){if(!e||typeof e!="object"||Array.isArray(e))return["参数定义项应为对象"];const r=hu(e);return typeof e.field!="string"||!e.field.trim()||t.has(e.field)?r.push("参数名应为非空且不重复的字符串"):t.add(e.field),r.length||(r.push(...du(e)),r.length)||e.defaultValue!==void 0&&(e.required&&(!e.defaultValue.trim()||U(e)&&jt(e,e.defaultValue)?.length===0)?r.push("必填参数的默认值不能为空"):e.defaultValue.trim()&&r.push(...qo(e,e.defaultValue).map(([,n])=>`默认值${n}`))),r}function pu(e,t,r){for(const[n,o]of Object.entries(e))(typeof o=="string"||typeof o=="number"&&Number.isFinite(o))&&(Object.defineProperty(t,n,{value:String(o),writable:!0,enumerable:!0,configurable:!0}),Object.defineProperty(r,n,{value:o,writable:!0,enumerable:!0,configurable:!0}))}function xt(e){return e==null||typeof e=="string"&&!e.trim()}function cr(e,t={}){const r=Object.create(null),n=Object.create(null),o=Lt(e);if((!t||typeof t!="object"||Array.isArray(t))&&o.push({code:"type",field:"",path:"$.params",message:"参数应为对象"}),o.length)return{ok:!1,values:r,typedValues:n,issues:o};pu(t,r,n);for(const i of e){const s=Object.prototype.hasOwnProperty.call(t,i.field)&&t[i.field]!==void 0?t[i.field]:i.defaultValue;yu(i,s,{values:r,typedValues:n,issues:o})}return o.push(...wu(e,r)),{ok:o.length===0,values:r,typedValues:n,issues:o}}function yu(e,t,r){const{values:n,typedValues:o,issues:i}=r,s=(f,d)=>i.push({code:f,path:`$.params.${e.field}`,field:e.field,message:d}),a=U(e)&&!xt(t)?jt(e,t):void 0;if(xt(t)||a?.length===0){e.required&&s("required","此参数为必填项"),(typeof t=="string"||a)&&(n[e.field]=a?"":String(t)),delete o[e.field];return}if(!a&&typeof t!="string"&&!(typeof t=="number"&&Number.isFinite(t))){s("type","参数应为字符串、有限数字或当前控件的规范数组");return}const c=a?JSON.stringify(a):String(t);n[e.field]=c;const u=qo(e,c);u.forEach(([f,d])=>s(f,d)),u.length&&U(e)?delete o[e.field]:o[e.field]=a??(e.type==="number"&&Yo(c)?Number(c):c)}function wu(e,t){return e.flatMap(r=>!xt(t[r.field])&&r.dependsOn?.some(n=>xt(t[n]))?[{code:"dependency",path:`$.params.${r.field}`,field:r.field,message:"请先填写联动依赖的上级参数"}]:[])}function $n(e,t={}){const r=cr(e,t);if(!r.ok)throw new Dt(r.issues);return r.values}function bu(e){const t={},r="(?![\\s\\S])";return e.type==="date"&&(t.format="date"),e.type==="month"&&(t.pattern=`^(?!0000)[0-9]{4}-(0[1-9]|1[0-2])${r}`),e.type==="year"&&(t.pattern=`^(?!0000)[0-9]{4}${r}`),e.type==="dateRange"&&(t.pattern=`^[0-9]{4}-[0-9]{2}-[0-9]{2}/[0-9]{4}-[0-9]{2}-[0-9]{2}${r}`),e.type==="dateRange"&&(t["x-report-date-range"]={separator:"/",ordered:!0,calendarDates:!0}),t}function xu(e){const t={type:e.type==="number"?"number":"string",title:e.label??e.field,...bu(e)};return U(e)&&Object.assign(t,au(e)),e.required&&!U(e)&&e.type!=="number"&&!t.pattern&&(t.pattern="\\S"),e.type==="select"&&e.options&&(t.enum=e.options.map(r=>r.value)),Object.assign(t,Mu(e)),Object.assign(t,vu(e)),t}function vu(e){const t={};return e.defaultValue!==void 0&&(!(e.type==="number"||U(e))||e.defaultValue.trim())&&(t.default=U(e)?jt(e,e.defaultValue):e.type==="number"?Number(e.defaultValue):e.defaultValue),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),!U(e)&&typeof e.min=="number"&&(t.minimum=e.min),!U(e)&&typeof e.max=="number"&&(t.maximum=e.max),typeof e.min=="string"&&(t["x-report-minimum"]=e.min),typeof e.max=="string"&&(t["x-report-maximum"]=e.max),t}function Mu(e){return{...e.optionsSource?{"x-report-options-source":e.optionsSource}:{},...e.dependsOn?.length?{"x-report-depends-on":[...e.dependsOn]}:{}}}function $u(e){const t=Lt(e);if(t.length)throw new Dt(t);return{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:Object.fromEntries(e.map(r=>[r.field,xu(r)])),required:e.filter(r=>r.required).map(r=>r.field),additionalProperties:!0}}function vt(e,t){const r=new Set;return t.flatMap(n=>{const o=Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0,i=o?.params??(typeof o?.template=="function"?[]:o?.template.params)??[],s=Lt(i);if(s.length)throw new Dt(s);return i.filter(a=>r.has(a.field)?!1:(r.add(a.field),!0))})}function Su(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ur(e,t,r){if(e!==void 0)try{q(e)}catch(n){r.push({path:t,message:n instanceof Error?n.message:String(n)})}}function Xo(e,t,r){if(e===void 0)return;if(!Array.isArray(e)||e.length>2048){r.push({path:t,message:"聚合应为数组且最多 2048 项"});return}const n=new Set;e.forEach((o,i)=>{const s=`${t}.${i}`;if(!Su(o)){r.push({path:s,message:"聚合应为对象"});return}const a=o.field;typeof a!="string"||!a.trim()||n.has(a)?r.push({path:`${s}.field`,message:"聚合输出字段应非空且唯一"}):n.add(a),o.numeric!==void 0&&o.numeric!=="number"&&o.numeric!=="decimal"&&r.push({path:`${s}.numeric`,message:"数值模式应为 number 或 decimal"}),o.digits!==void 0&&(!Number.isInteger(o.digits)||Number(o.digits)<0||Number(o.digits)>100)&&r.push({path:`${s}.digits`,message:"小数位应为 0–100 的整数"});try{oe({...o,field:o.valueField??a})}catch(c){r.push({path:s,message:c instanceof Error?c.message:String(c)})}})}function Eu(e,t,r){if(e===void 0)return;const n=Ls(e);for(const o of n.errors)r.push({path:t,message:o})}function Au(e,t,r){if(e!==void 0)try{Fr(e)}catch(n){r.push({path:t,message:n instanceof Error?n.message:String(n)})}}function ku(e,t,r){if(e.tree===void 0)return;const n=`${t}.tree`;try{uo(e.tree);const o=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!==o.idField)throw new Error("树形 rowKey 应与 idField 一致");if(!Array.isArray(e.columns)||!e.columns.some(i=>i&&i.field===o.labelField&&!i.hidden))throw new Error("树形布局需要可见的标签列");Array.isArray(e.computed)&&Rr(o,e.computed)}catch(o){r.push({path:n,message:o instanceof Error?o.message:String(o)})}}const Nu=1e7;class Pu extends Error{constructor(t){super(`模板校验失败:${t.slice(0,3).map(r=>`${r.path}: ${r.message}`).join("; ")}`),this.errors=t,this.name="ReportTemplateError"}}const Fu=new Set(["__proto__","prototype","constructor"]),Ou=new Set(["left","center","right","justify"]),nt=2e5,Iu=64;function C(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ru(e,t,r){const n=Object.getPrototypeOf(e),o=Array.isArray(e);if(o?n!==Array.prototype:n!==Object.prototype&&n!==null)return r.push({path:t,message:"模板对象必须使用普通 JSON 对象原型"}),!1;if(o){const i=Object.keys(e);if(i.length!==e.length||i.some(s=>!/^(0|[1-9]\d*)$/.test(s)||Number(s)>=e.length))return r.push({path:t,message:"模板数组不能包含空位或额外属性"}),!1}return Object.getOwnPropertySymbols(e).length>0?(r.push({path:t,message:"模板不能包含 Symbol 键"}),!1):!0}function Cu(e,t,r,n){return Fu.has(e)?(n.push({path:r,message:"模板不能包含可能污染原型的键"}),!1):t.get||t.set||!t.enumerable?(n.push({path:r,message:"模板不能包含访问器或不可枚举字段"}),!1):!0}function Tu(e){return e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)}function ju(e,t){const r=new Set;let n=0,o=0,i=!1;const s=(a,c,u)=>{if(!i){if(++n>nt){n===nt+1&&t.push({path:c,message:"模板超过 JSON 节点安全上限"});return}if(u>Iu){t.push({path:c,message:"模板嵌套层级过深"});return}if(typeof a=="string"){o+=a.length,o>Nu&&(i=!0,t.push({path:c,message:"模板文本超过 1000 万字符的安全上限"}));return}if(!Tu(a)){if(!a||typeof a!="object"){t.push({path:c,message:"模板只允许 JSON 值,不允许函数、undefined 或非有限数字"});return}if(r.has(a)){t.push({path:c,message:"模板不能包含循环引用"});return}if(Ru(a,c,t)){r.add(a);for(const[f,d]of Object.entries(Object.getOwnPropertyDescriptors(a))){if(Array.isArray(a)&&f==="length")continue;const l=`${c}.${f}`;if(Cu(f,d,l,t)&&s(d.value,l,u+1),n>nt||i)break}r.delete(a)}}}};s(e,"$",0)}function _(e,t,r,n,o=!1){const i=e[t];i===void 0&&!o||(typeof i!="string"||o&&!i.trim())&&n.push({path:`${r}.${t}`,message:o?"应为非空字符串":"应为字符串"})}function W(e,t,r,n,o=0,i=!1){const s=e[t];s===void 0&&!i||(typeof s!="number"||!Number.isFinite(s)||s<o)&&n.push({path:`${r}.${t}`,message:`应为大于等于 ${o} 的有限数字`})}function ae(e,t,r,n){e[t]!==void 0&&typeof e[t]!="boolean"&&n.push({path:`${r}.${t}`,message:"应为布尔值"})}function Ae(e,t,r,n=!1){e!==void 0&&!Ou.has(e)&&!(n&&e==="auto")&&r.push({path:t,message:`未知对齐方式${n?"(支持 auto)":""}`})}function re(e,t,r){if(e!==void 0){if(!C(e)){r.push({path:t,message:"样式应为对象"});return}Ae(e.align,`${t}.align`,r),e.verticalAlign!==void 0&&!["top","middle","bottom"].includes(e.verticalAlign)&&r.push({path:`${t}.verticalAlign`,message:"未知垂直对齐方式"});for(const n of["fontSize","fontSizePx","lineWidthPt","lineHeight"])W(e,n,t,r);for(const n of["letterSpacing","rotateDeg"])W(e,n,t,r,-1/0);W(e,"opacity",t,r),typeof e.opacity=="number"&&e.opacity>1&&r.push({path:`${t}.opacity`,message:"透明度不能大于 1"});for(const n of["bold","italic","underline","borderTop","borderRight","borderBottom","borderLeft"])ae(e,n,t,r);for(const n of["fontFamily","color","backgroundColor","lineColor","borderColor"])_(e,n,t,r)}}function Du(e,t,r){if(e===void 0)return;if(!Array.isArray(e)){r.push({path:t,message:"参数定义应为数组"});return}const n=new Set,o=r.length;e.forEach((i,s)=>{const a=`${t}.${s}`;if(!C(i)){r.push({path:a,message:"参数定义应为对象"});return}_(i,"field",a,r,!0),typeof i.field=="string"&&(n.has(i.field)&&r.push({path:`${a}.field`,message:"参数名重复"}),n.add(i.field)),i.type!==void 0&&!["text","number","date","month","year","dateRange","select","multiSelect","cascader","numberRange"].includes(i.type)&&r.push({path:`${a}.type`,message:"未知参数类型"});for(const c of["label","defaultValue","placeholder"])_(i,c,a,r);ae(i,"required",a,r);for(const c of["minLength","maxLength"]){const u=i[c];u!==void 0&&(typeof u!="number"||!Number.isSafeInteger(u)||u<0)&&r.push({path:`${a}.${c}`,message:"长度边界应为非负整数"})}Lu(i,a,r),i.options!==void 0&&(Array.isArray(i.options)?i.options.forEach((c,u)=>{const f=`${a}.options.${u}`;if(!C(c))r.push({path:f,message:"选项应为对象"});else for(const d of["label","value"])typeof c[d]!="string"&&r.push({path:`${f}.${d}`,message:"选项标签与值应为字符串(允许空白选项)"})}):r.push({path:`${a}.options`,message:"选项应为数组"}))}),r.length===o&&r.push(...Lt(e).map(i=>({path:i.path.replace("$.paramDefs",t),message:i.message})))}function Lu(e,t,r){for(const i of["min","max"]){const s=e[i];if(s===void 0)continue;Go(e.type,s)||["number","numberRange"].includes(e.type)&&typeof s=="number"&&Number.isFinite(s)||r.push({path:`${t}.${i}`,message:"数字使用有限数字边界,日期/月/年使用对应规范字符串边界"})}const n=typeof e.min=="number"&&typeof e.max=="number"&&e.min>e.max,o=typeof e.min=="string"&&typeof e.max=="string"&&e.min>e.max;(n||o)&&r.push({path:t,message:"最小边界不能大于最大边界"}),typeof e.minLength=="number"&&typeof e.maxLength=="number"&&e.minLength>e.maxLength&&r.push({path:t,message:"最小长度不能大于最大长度"})}function Zo(e,t,r){if(!Array.isArray(e)||e.length===0){r.push({path:t,message:"列表至少需要一列"});return}e.every(n=>C(n)&&n.hidden===!0)&&r.push({path:t,message:"列表至少需要一列可见列"}),e.forEach((n,o)=>{const i=`${t}.${o}`;if(!C(n)){r.push({path:i,message:"列应为对象"});return}if(Lo(n,i,r),n.visual!==void 0&&!vo(n.visual)&&r.push({path:`${i}.visual`,message:"列可视化配置无效,请检查类型、数值范围和颜色"}),ae(n,"hidden",i,r),ur(n.visibleWhen,`${i}.visibleWhen`,r),typeof n.header!="string"&&r.push({path:`${i}.header`,message:"表头应为字符串(允许空白表头)"}),_(n,"field",i,r,!0),W(n,"widthMm",i,r,Number.MIN_VALUE,!0),re(n.style,`${i}.style`,r),re(n.headerStyle,`${i}.headerStyle`,r),Ae(n.align,`${i}.align`,r,!0),Ae(n.headerAlign,`${i}.headerAlign`,r),n.semanticRole!==void 0&&!["identifier","dimension","measure","date","text"].includes(n.semanticRole)&&r.push({path:`${i}.semanticRole`,message:"未知列语义"}),n.format!==void 0)if(!C(n.format)||!["number","percent","date"].includes(n.format.kind))r.push({path:`${i}.format`,message:"未知列格式"});else{const s=n.format.digits;s!==void 0&&(typeof s!="number"||!Number.isInteger(s)||s<0||s>100)&&r.push({path:`${i}.format.digits`,message:"小数位应为 0–100 的整数"}),ae(n.format,"thousands",`${i}.format`,r),_(n.format,"pattern",`${i}.format`,r)}n.rules!==void 0&&(Array.isArray(n.rules)?n.rules.forEach((s,a)=>{const c=`${i}.rules.${a}`;if(!C(s)||!C(s.when)){r.push({path:c,message:"条件格式缺少 when 对象"});return}ur(s.when,`${c}.when`,r),re(s.style,`${c}.style`,r)}):r.push({path:`${i}.rules`,message:"条件格式应为数组"}))})}function Qo(e,t,r){if(e!==void 0){if(!C(e)){r.push({path:t,message:"分组应为对象"});return}_(e,"field",t,r,!0);for(const n of["headerTemplate","subtotalLabel"])_(e,n,t,r);for(const n of["headerStyle","subtotalStyle"])re(e[n],`${t}.${n}`,r);ae(e,"keepWithNext",t,r),ae(e,"repeatHeader",t,r),Xo(e.aggregates,`${t}.aggregates`,r),e.subtotal!==void 0&&(!Array.isArray(e.subtotal)||e.subtotal.some(n=>typeof n!="string"))&&r.push({path:`${t}.subtotal`,message:"小计字段应为字符串数组"})}}function Bu(e,t,r){if(!(e===void 0||typeof e=="boolean")){if(!C(e)){r.push({path:t,message:"合计应为布尔值或对象"});return}_(e,"label",t,r),Xo(e.aggregates,`${t}.aggregates`,r),re(e.style,`${t}.style`,r),e.fields!==void 0&&(!Array.isArray(e.fields)||e.fields.some(n=>typeof n!="string"))&&r.push({path:`${t}.fields`,message:"合计字段应为字符串数组"})}}function _u(e,t,r,n){const o={kind:"rect",leftMm:0,topMm:0,widthMm:1,heightMm:1,grid:e};if(Ko(o,r,n,[]),Ur(o,r,n),!C(e)||!Array.isArray(e.cells))return;const i=e.cells,s=Array.isArray(t)?t.length:0;if(i.length*s>nt){n.push({path:r,message:"表头逻辑网格超过 20 万格安全上限"});return}e.cells.length||n.push({path:`${r}.cells`,message:"表头至少需要一行"}),Array.isArray(e.colWidthsMm)&&e.colWidthsMm.length!==s&&n.push({path:`${r}.colWidthsMm`,message:"表头列宽数量应与列表列数一致"}),Array.isArray(e.rowHeightsMm)&&e.rowHeightsMm.length!==e.cells.length&&n.push({path:`${r}.rowHeightsMm`,message:"表头行高数量应与行数一致"}),Ku(i,s,r,n)}function Ku(e,t,r,n){const o=new Set;e.forEach((i,s)=>{if(!Array.isArray(i))return;let a=0;i.forEach((c,u)=>{for(;o.has(`${s}:${a}`);)a++;const f=C(c)&&typeof c.colSpan=="number"?c.colSpan:1,d=C(c)&&typeof c.rowSpan=="number"?c.rowSpan:1;(a+f>t||s+d>e.length)&&n.push({path:`${r}.cells.${s}.${u}`,message:"表头合并区域超出表头边界"});for(let l=s;l<Math.min(e.length,s+d);l++)for(let m=a;m<Math.min(t,a+f);m++)o.has(`${l}:${m}`)&&n.push({path:`${r}.cells.${s}.${u}`,message:"表头合并区域重叠"}),o.add(`${l}:${m}`);a+=f})})}function Wu(e,t,r){if(ku(e,t,r),Eu(e.computed,`${t}.computed`,r),Au(e.matrix,`${t}.matrix`,r),e.matrix&&(e.detail||e.groupBy||Array.isArray(e.groups)&&e.groups.length||e.grandTotal)&&r.push({path:`${t}.matrix`,message:"矩阵请使用自身 totals 汇总,不能同时配置普通分组、总计或主从明细"}),ur(e.rowVisibleWhen,`${t}.rowVisibleWhen`,r),e.groups!==void 0&&(!Array.isArray(e.groups)||e.groups.length>16?r.push({path:`${t}.groups`,message:"分组应为数组,最多 16 级"}):e.groups.forEach((i,s)=>Qo(i,`${t}.groups.${s}`,r))),e.detail===void 0)return;const n=e.detail,o=`${t}.detail`;if(!C(n)){r.push({path:o,message:"主从关联应为对象"});return}for(const i of["dataset","parentKey","foreignKey"])_(n,i,o,r,!0);for(const i of["rowKey","revisionField","sourceTokenField"])_(n,i,o,r,n[i]!==void 0);_(n,"label",o,r),ae(n,"header",o,r),W(n,"rowHeightMm",o,r,Number.MIN_VALUE),Zo(n.columns,`${o}.columns`,r),n.unmatched!==void 0&&n.unmatched!=="error"&&n.unmatched!=="ignore"&&r.push({path:`${o}.unmatched`,message:"未关联明细策略应为 error 或 ignore"})}function Ju(e,t,r){for(const n of["leftMm","topMm"])W(e,n,t,r,-1/0,!0);W(e,"widthMm",t,r,Number.MIN_VALUE,!0),_(e,"dataset",t,r,!0),_(e,"title",t,r);for(const n of["rowKey","revisionField","sourceTokenField"])_(e,n,t,r,e[n]!==void 0);e.headerGrid!==void 0&&_u(e.headerGrid,e.columns,`${t}.headerGrid`,r),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&r.push({path:`${t}.layout`,message:"布局应为 page 或 wide"}),Zo(e.columns,`${t}.columns`,r);for(const n of["fontSizePt","rowHeightMm"])W(e,n,t,r,Number.MIN_VALUE);W(e,"paddingMm",t,r);for(const n of["header","headerBold","headerEveryPage","border"])ae(e,n,t,r);e.cardinality!==void 0&&e.cardinality!=="record"&&r.push({path:`${t}.cardinality`,message:"单记录区域类型应为 record"}),_(e,"headerBackgroundColor",t,r),Ae(e.align,`${t}.align`,r,!0),Ae(e.headerAlign,`${t}.headerAlign`,r),re(e.headerStyle,`${t}.headerStyle`,r),Wu(e,t,r),Qo(e.groupBy,`${t}.groupBy`,r),Bu(e.grandTotal,`${t}.grandTotal`,r)}function Sn(e,t,r){Array.isArray(e.richParagraphs)&&e.richParagraphs.forEach((n,o)=>{if(!C(n))return;const i=`${t}.richParagraphs.${o}`;Ae(n.align,`${i}.align`,r);for(const s of["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"])W(n,s,i,r);Array.isArray(n.segments)&&n.segments.forEach((s,a)=>{const c=`${i}.segments.${a}`;if(!C(s)){r.push({path:c,message:"富文本片段应为对象"});return}s.kind!==void 0&&s.kind!=="text"&&s.kind!=="field"&&r.push({path:`${c}.kind`,message:"未知富文本片段类型"});for(const u of["text","field"])_(s,u,c,r);re(s.style,`${c}.style`,r)})})}function Ur(e,t,r){re(e.style,`${t}.style`,r);for(const o of["text","rawText","imageData","fallbackText","nid","rkey"])_(e,o,t,r);if(e.lines!==void 0&&(!Array.isArray(e.lines)||e.lines.some(o=>typeof o!="string"))&&r.push({path:`${t}.lines`,message:"文本行应为字符串数组"}),Sn(e,t,r),!C(e.grid))return;const n=e.grid;W(n,"gapMm",`${t}.grid`,r),W(n,"paddingMm",`${t}.grid`,r);for(const o of["colWidthsMm","rowHeightsMm"]){const i=n[o];i!==void 0&&(!Array.isArray(i)||i.some(s=>typeof s!="number"||!Number.isFinite(s)||s<0))&&r.push({path:`${t}.grid.${o}`,message:"网格尺寸应为有限非负数字数组"})}Array.isArray(n.cells)&&n.cells.forEach((o,i)=>{Array.isArray(o)&&o.forEach((s,a)=>{const c=`${t}.grid.cells.${i}.${a}`;if(s!==null){if(!C(s)){r.push({path:c,message:"网格单元格应为对象或 null"});return}for(const u of["text","rawText","numberFormat"])_(s,u,c,r);for(const u of["colSpan","rowSpan"]){const f=s[u];f!==void 0&&(typeof f!="number"||!Number.isInteger(f)||f<=0)&&r.push({path:`${c}.${u}`,message:"跨度应为正整数"})}s.value!==void 0&&s.value!==null&&!["string","number","boolean"].includes(typeof s.value)&&r.push({path:`${c}.value`,message:"Excel 原始值应为字符串、数字、布尔值或 null"}),re(s.style,`${c}.style`,r),Sn(s,c,r),s.children!==void 0&&(Array.isArray(s.children)?s.children.forEach((u,f)=>{C(u)&&Ur(u,`${c}.children.${f}`,r)}):r.push({path:`${c}.children`,message:"嵌套组件应为数组"}))}})})}function zu(e,t,r){if(!(e.flow===void 0||!Array.isArray(e.components)))try{go(e.components,e.flow)}catch(n){r.push({path:`${t}.flow`,message:n instanceof Error?n.message:String(n)})}}function Vu(e){const t=[],r=[];return ju(e,t),t.length?{ok:!1,errors:t,warnings:r}:(C(e)?(e.schemaVersion!==void 0&&e.schemaVersion!==ze&&t.push({path:"$.schemaVersion",message:"不支持的模板 schemaVersion"}),Du(e.params,"$.params",t),yo(e,t),!Array.isArray(e.pages)||e.pages.length===0?t.push({path:"$.pages",message:"模板至少需要一页"}):e.pages.forEach((n,o)=>{const i=`$.pages.${o}`;if(!C(n)){t.push({path:i,message:"页应为对象"});return}W(n,"widthMm",i,t,Number.MIN_VALUE,!0),W(n,"heightMm",i,t,Number.MIN_VALUE,!0),n.layout!==void 0&&n.layout!=="page"&&n.layout!=="wide"&&t.push({path:`${i}.layout`,message:"布局应为 page 或 wide"}),typeof n.heightMm=="number"&&n.heightMm>=5e3&&t.push({path:`${i}.heightMm`,message:"页高应小于 5000mm"});for(const s of["marginTopMm","marginBottomMm","marginLeftMm","marginRightMm"])W(n,s,i,t);typeof n.widthMm=="number"&&Number(n.marginLeftMm??0)+Number(n.marginRightMm??0)>=n.widthMm&&t.push({path:i,message:"横向页边距占满页面"}),typeof n.heightMm=="number"&&Number(n.marginTopMm??0)+Number(n.marginBottomMm??0)>=n.heightMm&&t.push({path:i,message:"纵向页边距占满页面"}),Array.isArray(n.components)?n.components.forEach((s,a)=>{const c=`${i}.components.${a}`;C(s)&&s.kind==="list"?Ju(s,c,t):(Ko(s,c,t,r),C(s)&&Ur(s,c,t))}):t.push({path:`${i}.components`,message:"组件应为数组"}),zu(n,i,t)})):t.push({path:"$",message:"模板应为对象"}),{ok:t.length===0,errors:t,warnings:r})}class Hu extends Error{constructor(t){super(t.map(r=>r.message).join(";")),this.issues=t,this.name="ReportValidationError"}}function En(e,t,r){if(!Number.isSafeInteger(e)||e<1||e>r)throw new Error(`校验 ${t} 超出预算`);return e}function Uu(e){if(e.aggregates&&e.scope!=="dataset")throw new Error("仅数据集规则允许汇总");if(e.aggregates&&(!Array.isArray(e.aggregates)||e.aggregates.length>64))throw new Error("校验汇总最多 64 项");const t=new Set;for(const r of e.aggregates??[]){if(K(r.field),t.has(r.field))throw new Error("校验汇总字段重复");t.add(r.field),r.valueField!==void 0&&K(r.valueField),r.weightField!==void 0&&K(r.weightField),Be([],{...r,field:r.valueField??r.field})}}function ei(e){if(!Array.isArray(e)||e.length>256||Object.keys(e).length!==e.length)throw new Error("校验规则最多 256 条且不允许空位");const t=new Set;return e.map(r=>{if(!r||typeof r!="object")throw new Error("校验规则应为声明式对象");if(K(r.id),t.has(r.id))throw new Error("校验规则 id 重复");if(t.add(r.id),r.field!==void 0&&K(r.field),r.dataset!==void 0&&K(r.dataset),typeof r.message!="string"||!r.message.trim()||r.message.length>2048)throw new Error("校验规则需要有界提示文案");if(r.severity!==void 0&&!["error","warning"].includes(r.severity))throw new Error("未知校验严重程度");if(r.scope!==void 0&&!["row","dataset"].includes(r.scope))throw new Error("未知校验范围");Uu(r);const n={nodes:0},o=q(r.assert,n),i=r.when?q(r.when,n):void 0;return{rule:r,assert:o,when:i,checks:n.nodes}})}function An(e){if(e?.aborted){const t=new Error("报表校验已取消");throw t.name="AbortError",t}}function Gu(e,t,r,n){const o=n&&Object.prototype.hasOwnProperty.call(t,n)?t[n]:void 0;if(o!==void 0&&typeof o!="string"&&!(typeof o=="number"&&Number.isFinite(o)))throw new Error("校验定位需要稳定的文本或数值业务键");return{ruleId:e.id,rowIndex:r,...o===void 0?{}:{rowKey:o},field:e.field,severity:e.severity??"error",message:e.message}}function Yu(e,t){const r=t.computed?.length?{fields:t.computed,formula:t.formula,signal:t.signal}:void 0;if(t.tree){const o=ho(e,t.tree,{signal:t.signal,computed:r});if(o.rows.length>1e5)throw new Error("校验展开后数据最多 100000 行");return{rows:o.rows,summaryRows:o.leaves,rowKey:t.tree.idField}}const n=r?Ot(e,r).rows:e;return{rows:n,summaryRows:n,rowKey:t.rowKey}}function qu(e,t){const r=new Set;e.forEach(n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new Error("校验数据行应为对象");if(!t)return;const o=Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0;if(!(typeof o=="string"&&o.trim())&&!(typeof o=="number"&&Number.isFinite(o)))throw new Error("校验定位需要稳定业务键");if(r.has(o))throw new Error("校验业务键重复");r.add(o)})}function Xu(e,t,r){if(!Array.isArray(e)||e.length>1e5)throw new Error("校验数据最多 100000 行");An(t.signal);const n=En(t.maxChecks??2e6,"maxChecks",1e7),o=En(t.maxIssues??1e3,"maxIssues",1e4);t.rowKey!==void 0&&K(t.rowKey);const i=Yu(e,t),{rows:s,summaryRows:a,rowKey:c}=i;qu(s,c);const u=ei(t.rules),f=u.reduce((l,m)=>l+(m.rule.scope==="dataset"?m.checks+a.length*(m.rule.aggregates?.length??0):s.length*m.checks),0);if(r.checks+=f,r.checks>n)throw new Error("整批校验超出 maxChecks 预算");const d=[];for(const l of u)(l.rule.scope==="dataset"?[Object.fromEntries((l.rule.aggregates??[]).map(h=>[h.field,Be(a,{...h,field:h.valueField??h.field})]))]:s).forEach((h,p)=>{if(An(t.signal),!h||typeof h!="object"||Array.isArray(h))throw new Error("校验数据行应为对象");if(!(l.when&&!l.when(h)||l.assert(h))){if(d.length>=o)throw new Error("校验问题超出 maxIssues 预算,请缩小范围");d.push(Gu(l.rule,h,l.rule.scope==="dataset"?void 0:p,l.rule.scope==="dataset"?void 0:c))}});return d}function Zu(e,t="allow"){if(!["allow","block"].includes(t))throw new Error("未知校验警告策略");if(!Array.isArray(e)||e.length>1e4||e.some(r=>!r||!["error","warning"].includes(r.severity)||typeof r.ruleId!="string"||!r.ruleId.trim()||typeof r.message!="string"||!r.message.trim()))throw new Error("校验问题结构无效");if(e.some(r=>r.severity==="error"||t==="block"))throw new Hu(e)}function kn(e,t,r){const n=e.get(t);if(n&&JSON.stringify(n)!==JSON.stringify(r))throw new Error("同一数据集的校验计算/业务键存在歧义,请统一绑定");e.set(t,r)}function Qu(e,t,r,n=[]){ei(t.rules);const o=[],i={checks:0};for(const[a,c]of e.entries()){const u=new Map;for(const f of c.template.pages)for(const d of f.components)d.kind==="list"&&(kn(u,d.dataset,{rowKey:d.tree?.idField??d.rowKey,computed:d.computed,tree:d.tree}),d.detail&&kn(u,d.detail.dataset,{rowKey:d.detail.rowKey}));for(const[f,d]of u){const l=t.rules.filter(m=>!m.dataset||m.dataset===f);if(l.length&&(o.push(...Xu(c.datasets[f]??[],{...t,rules:l,...d,formula:n[a],signal:r},i).map(m=>({...m,dataset:f,sourceScope:c.sourceScope}))),o.length>(t.maxIssues??1e3)))throw new Error("整批候选校验问题超出 maxIssues 预算")}}const s=new Set(e.flatMap(a=>a.template.pages.flatMap(c=>c.components.flatMap(u=>u.kind==="list"?[u.dataset,...u.detail?[u.detail.dataset]:[]]:[]))));if(t.rules.some(a=>a.dataset&&!s.has(a.dataset)))throw new Error("校验目标数据集不存在");return o}function ef(e){return!e||typeof e!="object"?!1:[e.pageIndex,e.componentIndex,e.rowIndex,e.columnIndex].every(t=>Number.isInteger(t)&&t>=0)}function tf(e){return e.value!==void 0?e.value:e.rawText??e.text??null}function rf(e,t){return e.valueType?e.valueType:typeof t=="number"?"number":typeof t=="boolean"?"boolean":t===null&&e.numberFormat&&/[0#?]/.test(e.numberFormat)?"number":"text"}function nf(e,t){if(e.derived)return"derived";if(e.editable===!1)return"cell";if(e.formula!==void 0)return"formula";if(e.children?.length||e.richParagraphs?.length)return"complex";if(t.table&&t.table.role!=="body"&&e.editable!==!0)return"structure"}function of(e,t){const r=e.table;if(r)return{id:r.id,rowIndex:r.rowIndex+t.rowIndex,role:r.role,columnKey:r.columnKeys[t.columnIndex]}}function sf(e,t,r){if(e.derived)return;if(e.source)return{...e.source};const n=t.table?.source,o=t.table?.columnKeys[r.columnIndex];if(!(!n||n.rowKey===void 0||o===void 0))return{...n,rowKey:n.rowKey,field:o}}function af(e,t,r){const n=tf(r),o=nf(r,e);return{address:{...t},cell:r,component:e,value:n,valueType:rf(r,n),table:of(e,t),source:sf(r,e,t),editable:o===void 0,readOnlyReason:o}}function ti(e){const t=new Map;return r=>{if(!ef(r))return null;const n=e.pages[r.pageIndex]?.components[r.componentIndex];if(!n?.grid)return null;let o=t.get(n);if(!o){const s=new Map;o=new Map;for(const a of to(n.grid,n.widthMm,n.heightMm).cells){const c=s.get(a.ri)??0;s.set(a.ri,c+1);const u=n.grid.cells[a.ri]?.[c];u&&o.set(`${a.ri}:${a.ci}`,u)}t.set(n,o)}const i=o.get(`${r.rowIndex}:${r.columnIndex}`);return i?af(n,r,i):null}}function cf(e){const t=[""];let r=!1,n=!1;for(const o of e)o===";"&&!r&&!n?t.push(""):t[t.length-1]+=o,o==='"'&&!n&&(r=!r),n=o==="\\"&&!n;return t}function uf(e,t){const r=cf(t),n=e===0&&r.length>2?2:e<0&&r.length>1?1:0;return{pattern:r[n],magnitude:Math.abs(e),negative:e<0&&n===0}}function ff(e){const t=[];return{text:e.replace(/"([^"]*)"|\\(.)/g,(n,o,i)=>(t.push(o??i??""),String.fromCharCode(57344+t.length-1))).replace(/\[(Black|Blue|Cyan|Green|Magenta|Red|White|Yellow|Color\d+)\]/gi,""),literals:t}}function Ie(e,t){return/[0#?@_*%[\]"\\.,/]/.test(e)?null:e.replace(/[\uE000-\uF8FF]/g,r=>t.literals[r.charCodeAt(0)-57344]??"")}function lf(e,t){const r=/^(.*?)(0)(?:\.([0#]+))?E([+-])(0+)(.*?)$/i.exec(t.text);if(!r)return null;const n=Ie(r[1],t),o=Ie(r[6],t),i=r[3]??"";if(n===null||o===null||i.length>100)return null;const[s,a]=e.magnitude.toExponential(i.length).split("e"),c=i.replace(/#/g,"").length,[u,f=""]=s.split("."),d=f.replace(/0+$/,"").padEnd(c,"0"),l=Number(a),m=l<0?"-":r[4]==="+"?"+":"",h=String(Math.abs(l)).padStart(r[5].length,"0");return`${e.negative?"-":""}${n}${u}${d?`.${d}`:""}E${m}${h}${o}`}function df(e,t){const r=/^(.*?)([#,]*0[0#]*)(?:\.([0#]+))?(%)?(.*?)$/.exec(t.text);if(!r)return Ie(t.text,t);const n=Ie(r[1],t),o=Ie(r[5],t),i=r[2],s=r[3]??"";if(n===null||o===null||s.length>100||!/^(?:0+|#+0+|#,##0+)$/.test(i))return null;const a=e.magnitude*(r[4]?100:1);if(!Number.isFinite(a))return null;const c=a.toLocaleString("en-US",{useGrouping:i.includes(","),minimumIntegerDigits:Math.min(21,i.replace(/[^0]/g,"").length),minimumFractionDigits:s.replace(/#/g,"").length,maximumFractionDigits:s.length});return`${e.negative?"-":""}${n}${c}${r[4]??""}${o}`}function mf(e,t,r){if(!t||/^(General|@)$/i.test(t))return String(e);const n=uf(e,t);if(n.pattern==="")return"";const o=ff(n.pattern),i=lf(n,o)??df(n,o);return i!==null?i:String(e)}function hf(e){return e!==void 0&&e.replace(/"[^"]*"|\\./g,"").includes("%")}class P extends Error{constructor(t){super(`Invalid report cell edit: ${t}`),this.code=t,this.name="ReportCellEditError"}}function gf(e,t){let r=e.trim();const n=t&&r.endsWith("%");if(n&&(r=r.slice(0,-1).trim()),/^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d*)?(?:[eE][+-]?\d+)?$/.test(r)&&(r=r.replace(/,/g,"")),!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(r))throw new P("number");return Number(r)/(n?100:1)}function pf(e,t){if(e===null||typeof e=="string"&&e.trim()==="")return null;if(typeof e!="string"&&typeof e!="number")throw new P("number");const r=typeof e=="number"?e:gf(e,hf(t.cell.numberFormat));if(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r))throw new P("number");return r}function yf(e){if(e===null||typeof e=="string"&&e.trim()==="")return null;if(typeof e=="boolean")return e;const t=String(e).trim().toLowerCase();if(["true","yes","是","1"].includes(t))return!0;if(["false","no","否","0"].includes(t))return!1;throw new P("boolean")}function wf(e,t){return e.valueType==="number"?pf(t,e):e.valueType==="boolean"?yf(t):t===null?null:String(t)}function bf(e,t){const r=t.cell.text,o=[["是","否"],["TRUE","FALSE"],["True","False"],["true","false"],["1","0"]].find(i=>i.includes(r??""));return o?o[e?0:1]:String(e)}function ri(e,t){return t===null?"":typeof t=="boolean"?bf(t,e):typeof t=="number"?mf(t,e.cell.numberFormat):String(t)}function ni(e,t){if(!e.editable)throw new P("readonly");const r=wf(e,t);return{address:{...e.address},table:e.table,source:e.source,previousValue:e.value,previousText:e.cell.text??"",value:r,text:ri(e,r)}}function xf(e,t){const r=t.source;if(!r)return!1;const n=e.source;return!n||["sourceScope","datasetId","rowKey","field","revision","sourceToken"].some(o=>!Object.is(n[o],r[o]))}function oi(e){const t=[];for(const r of e.template.pages)for(const n of r.components)n.kind==="list"&&(t.push(n.tree?{...n,rowKey:n.tree.idField}:n),n.detail&&t.push({...n.detail,relation:{detail:n.detail,parentRows:e.datasets[n.dataset]??[]}}));return t}function ke(e){return JSON.stringify([e.sourceScope,e.datasetId])}function Nn(e){return JSON.stringify([e.sourceScope,e.datasetId,e.rowKey])}function ii(e){const t=new Map,r=new Set;return e.forEach((n,o)=>{for(const i of oi(n)){if(!i.rowKey)continue;const s=i.relation,a=s?new Set(s.parentRows.map(c=>JSON.stringify(c[s.detail.parentKey]))):void 0;(n.datasets[i.dataset]??[]).forEach((c,u)=>{if(s&&!a.has(JSON.stringify(c[s.detail.foreignKey])))return;const f=c[i.rowKey];if(typeof f!="string"&&typeof f!="number")return;const d=`${o}:${i.dataset}:${u}:${i.rowKey}`;if(r.has(d))return;r.add(d);const l=Nn({sourceScope:n.sourceScope,datasetId:i.dataset,rowKey:f}),m=t.get(l)??[];m.push({partIndex:o,dataset:i.dataset,rowIndex:u,row:c,binding:i}),t.set(l,m)})}}),n=>{const o=t.get(Nn(n));if(!o?.length)throw new P("missing");if(new Set(o.map(i=>`${i.partIndex}:${i.dataset}`)).size!==o.length)throw new P("conflict");return o}}function si(e,t){const r=e.map(o=>({...o,datasets:{...o.datasets}})),n=new Set;for(const{row:o,field:i,value:s}of t){const a=r[o.partIndex],c=JSON.stringify([o.partIndex,o.dataset]);n.has(c)||(a.datasets[o.dataset]=[...a.datasets[o.dataset]],n.add(c)),a.datasets[o.dataset][o.rowIndex]={...a.datasets[o.dataset][o.rowIndex],[i]:s}}for(const o of n){const[i,s]=JSON.parse(o);Is(e[i].datasets[s],r[i].datasets[s])}return r}function vf(e,t,r){const n=[],o=new Set;return e.forEach((i,s)=>{for(const a of oi(i))t.has(ke({sourceScope:i.sourceScope,datasetId:a.dataset}))&&(i.datasets[a.dataset]??[]).forEach((c,u)=>{const f={partIndex:s,dataset:a.dataset,rowIndex:u,row:c,binding:a};for(const[d,l]of[[a.revisionField,r.revision],[a.sourceTokenField,r.sourceToken]]){if(!d||l===void 0)continue;const m=`${s}:${a.dataset}:${u}:${d}`;o.has(m)||(o.add(m),n.push({row:f,field:d,value:l}))}})}),n}function Mf(e,t,r){if(!r||r.revision===void 0&&r.sourceToken===void 0)return e;const n=new Set(t.edits.flatMap(o=>o.source?[ke(o.source)]:[]));return ai(e,new Map([...n].map(o=>[o,r])))}function ai(e,t){if(!t.size)return e;function r(i){const s=i.datasetId&&t.get(ke({...i,datasetId:i.datasetId}));return!s||(s.revision===void 0||Object.is(s.revision,i.revision))&&(s.sourceToken===void 0||s.sourceToken===i.sourceToken)?i:{...i,...s.revision!==void 0?{revision:s.revision}:{},...s.sourceToken!==void 0?{sourceToken:s.sourceToken}:{}}}function n(i){const s=i.map(a=>{const c=a.table?.source?r(a.table.source):void 0,u=a.table&&c!==a.table.source?{...a.table,source:c}:a.table,f=a.grid?.cells.map(l=>{const m=l.map(h=>{if(!h)return h;const p=h.source?r(h.source):void 0,w=h.children?n(h.children):void 0;return p===h.source&&w===h.children?h:{...h,source:p,children:w}});return m.some((h,p)=>h!==l[p])?m:l}),d=a.grid&&f?.some((l,m)=>l!==a.grid.cells[m])?{...a.grid,cells:f}:a.grid;return u!==a.table||d!==a.grid?{...a,table:u,grid:d}:a});return s.some((a,c)=>a!==i[c])?s:i}const o=e.pages.map(i=>{const s=n(i.components);return s!==i.components?{...i,components:s}:i});return o.some((i,s)=>i!==e.pages[s])?{...e,pages:o}:e}function Mt(e){const t=e.source;if(t)return JSON.stringify([t.sourceScope,t.datasetId,t.rowKey,t.field]);const r=e.table;if(r?.columnKey!==void 0)return JSON.stringify([r.id,r.role,r.rowIndex,r.columnKey]);const n=e.address;return JSON.stringify([n.pageIndex,n.componentIndex,n.rowIndex,n.columnIndex])}function $f(e){const t=new Map,r=ti(e);return e.pages.forEach((n,o)=>n.components.forEach((i,s)=>{if(!(!i.grid||i.table?.role!=="body"))for(let a=0;a<i.grid.cells.length;a++)for(let c=0;c<i.table.columnKeys.length;c++){const u=r({pageIndex:o,componentIndex:s,rowIndex:a,columnIndex:c});u?.source&&u.editable&&t.set(Mt(u),u)}})),t}function ci(e,t){if(++e.nodes>1e6||t>128)throw new P("limit")}function $t(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||r.get||r.set)throw new P("conflict");return r.value}function Gr(e){if(Object.getOwnPropertyDescriptor(e,"toJSON"))throw new P("conflict");const t=Object.getPrototypeOf(e);if(Array.isArray(e)&&(t!==Array.prototype||Object.keys(e).length!==e.length))throw new P("conflict");if(!(e instanceof Date)&&!Array.isArray(e)&&t!==Object.prototype&&t!==null)throw new P("conflict");for(const r of Reflect.ownKeys(e))if(!(Array.isArray(e)&&r==="length")){if(typeof r=="symbol"||!Object.getOwnPropertyDescriptor(e,r)?.enumerable)throw new P("conflict");if(e instanceof Date||Array.isArray(e)&&!/^(0|[1-9]\d*)$/.test(r))throw new P("conflict")}}function ui(e,t,r,n,o){if(ci(n,o),typeof e=="function"||typeof e=="symbol")throw new P("conflict");if(e===null||typeof e!="object")return;if(Gr(e),r.has(e))throw new P("conflict");r.add(e);const i=Object.keys(e),s=i.map(a=>$t(e,a));t.push({object:e,prototype:Object.getPrototypeOf(e),keys:i,values:s,...e instanceof Date?{date:Date.prototype.getTime.call(e)}:{},...Array.isArray(e)?{length:e.length}:{}});for(const a of s)ui(a,t,r,n,o+1);r.delete(e)}function Sf(e){const{object:t,keys:r,values:n}=e;if(Gr(t),Object.getPrototypeOf(t)!==e.prototype||Object.getOwnPropertyDescriptor(t,"toJSON")||e.date!==void 0&&!Object.is(Date.prototype.getTime.call(t),e.date)||e.length!==void 0&&t.length!==e.length)return!1;const o=Object.keys(t);return o.length===r.length&&r.every((i,s)=>o[s]===i&&Object.is($t(t,i),n[s]))}function Ef(e){const t=[];return ui(e,t,new Set,{nodes:0},0),()=>{try{return t.every(Sf)}catch{return!1}}}function St(e,t,r,n=!1){if(ci(t,r),n){if(typeof e=="function"||typeof e=="symbol")throw new P("conflict");e!==null&&typeof e=="object"&&Gr(e)}if(e===null||typeof e!="object")return e;if(e instanceof Date)return new Date(Date.prototype.getTime.call(e));if(Array.isArray(e)){const o=[];for(let i=0;i<e.length;i++)o[i]=St($t(e,String(i)),t,r+1,n);return o}return Object.fromEntries(Object.keys(e).map(o=>[o,St($t(e,o),t,r+1,n)]))}function Af(e){return St(e,{nodes:0},0,!0)}function kf(e){const t=St(e,{nodes:0},0);for(const r of t)for(const n of Object.values(r.datasets))Os(n);return t}async function Nf(e,t,r={}){return Co(e,t,{...r,knownTotalPages:void 0})}const Pn=new WeakMap;function qe(e){if(e?.aborted){const t=new Error("报表重算已取消");throw t.name="AbortError",t}}function fi(e,t){return e[t]===void 0?"":e[t]}function Pf(e,t){if(t.edits.length>1e4)throw new P("limit");const r=ti(e),n=new Set,o=[],i=t.edits.map(s=>{const a=r(s.address);if(!a?.source)throw new P("missing");const c=Mt(s);if(n.has(c))throw new P("duplicate");if(n.add(c),xf(a,s)||!Object.is(a.value,s.previousValue)||(a.cell.text??"")!==s.previousText)throw new P("conflict");return o.push(a),ni(a,s.value)});return{batch:{requestId:t.requestId,edits:i},contexts:o}}function Ff(e,t){const r=ii(e);return t.flatMap(n=>{if(!n.source)throw new P("missing");return r(n.source).map(o=>{if(!Object.is(fi(o.row,n.source.field),n.previousValue))throw new P("conflict");if(o.binding.rowKey===n.source.field)throw new P("readonly");return{row:o,field:n.source.field,value:n.value}})})}function Yt(e,t,r){const n={...e,value:t,source:{...e.source,...r?.revision===void 0?{}:{revision:r.revision},...r?.sourceToken===void 0?{}:{sourceToken:r.sourceToken}}};return n.cell={...e.cell,value:n.value,text:ri(n,n.value)},n}function Of(e,t,r){if(!r||r.revision===void 0&&r.sourceToken===void 0)return[...e];const n=new Set(t.edits.flatMap(o=>o.source?[ke(o.source)]:[]));return si(e,vf(e,n,r))}function If(e,t,r){const n=new Set(t.edits.map(o=>ke(o.source)));for(const o of n)e.set(o,{...e.get(o),...r.revision!==void 0?{revision:r.revision}:{},...r.sourceToken!==void 0?{sourceToken:r.sourceToken}:{}});return n}function Rf(e,t){let r=t.parts;const n=t.rebuild,o=[...t.validationFormulas??[]];let i=Ef(r),s=e,a;const c=new Map,u=new Map;function f(m){if(m!==s)throw new P("conflict");if(a)return a;if(!i?.())throw new P("conflict");return kf(r)}async function d(m,h,p,w={}){qe(w.signal),h={requestId:h.requestId,edits:h.edits.map(M=>({...M,address:{...M.address},source:M.source?{...M.source}:void 0,table:M.table?{...M.table}:void 0}))},p=p.map(M=>({...M,address:{...M.address},source:M.source?{...M.source}:void 0,table:M.table?{...M.table}:void 0,cell:{...M.cell}})),await new Promise(M=>setTimeout(M,0)),qe(w.signal);const y=f(m),g=si(y,Ff(y,h.edits)),x=ai(await n(g,w.signal),u);qe(w.signal);let b=!1,$=[],T="allow",j=!1;function v(M){return j=!0,$=Object.freeze(Qu(g,M,w.signal,o).map(S=>Object.freeze({...S}))),j=!1,T=M.warningPolicy??"allow",$}return w.validation&&v(w.validation),{plan:x,get validationIssues(){return $},validate:v,commit(M){if(qe(w.signal),b||s!==m)throw new P("conflict");if(M?.conflicts?.length)throw new P("conflict");if(j)throw new Error("候选规则校验未完成,不能提交");Zu($,T);const S=Of(g,h,M),R=Mf(x,h,M);if(M){const N=If(u,h,M);for(const[I,pe]of c)N.has(ke(pe.source))&&c.set(I,Yt(pe,pe.value,M))}return p.forEach((N,I)=>c.set(Mt(N),Yt(N,h.edits[I].value,M))),b=!0,a=S,r=void 0,i=void 0,s=R,Pn.set(s,l),s}}}const l={get plan(){return s},async prepare(m,h,p){const w=Pf(m,h);return d(m,w.batch,w.contexts,p)},async prepareHistory(m,h,p,w,y){if(!w.trim()||h.length>1e4)throw new P("limit");const g=f(m),x=ii(g),b=$f(m),$=new Set,j=h.map(S=>{if(!S.source)throw new P("missing");const R=Mt(S);if($.has(R))throw new P("duplicate");$.add(R);const N=b.get(R)??c.get(R);if(!N?.source)throw new P("missing");const I=x(N.source)[0];return Yt(N,fi(I.row,N.source.field))}).map((S,R)=>({context:S,edit:ni(S,h[R][p])})).filter(({edit:S})=>!Object.is(S.previousValue,S.value)),v={requestId:w,edits:j.map(({edit:S})=>S)},M=j.map(({context:S})=>S);return{batch:v,contexts:M,prepared:await d(m,v,M,y)}}};return Pn.set(e,l),l}let Cf=0;function ot(){return`report-${Date.now()}-${++Cf}`}function Me(e,t,r){if(!r?.aborted)try{const n=e?.({...t});n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{})}catch{}}function de(e){const t=e.taskId??ot(),r=(n,o,i)=>{Me(e.onEvent,{taskId:t,...e.correlationId===void 0?{}:{correlationId:e.correlationId},stage:n,status:o,...i===void 0?{}:{reportId:i}},e.signal)};return{taskId:t,progress(n,o,i){Me(e.onEvent,{taskId:t,...e.correlationId===void 0?{}:{correlationId:e.correlationId},stage:n,status:"started",completed:o,total:i},e.signal)},async run(n,o,i){r(n,"started",i);try{const s=await o();return r(n,"completed",i),s}catch(s){throw r(n,"failed",i),s}},runSync(n,o,i){r(n,"started",i);try{const s=o();return r(n,"completed",i),s}catch(s){throw r(n,"failed",i),s}}}}function Y(e){throw new Error(`数据契约无效:${e}`)}function fr(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}function Tf(e){for(const t of["description","missingMeaning"])e[t]!==void 0&&!fr(e[t])&&Y(`${t} 应为 1–4096 位非空字符串`);e.aggregation!==void 0&&!["sum","avg","min","max","count","none"].includes(e.aggregation)&&Y("未知字段聚合语义"),e.aggregation&&!["count","none"].includes(e.aggregation)&&!["number","decimal"].includes(e.type)&&Y("数值聚合仅适用于 number/decimal"),e.format!==void 0&&jf(e),e.calculation!==void 0&&(!e.calculation||!fr(e.calculation.description)||!Array.isArray(e.calculation.dependsOn)||!e.calculation.dependsOn.length||e.calculation.dependsOn.length>256||e.calculation.dependsOn.some(t=>typeof t!="string"||!t.trim())||new Set(e.calculation.dependsOn).size!==e.calculation.dependsOn.length)&&Y("计算说明需包含说明及 1–256 个唯一依赖字段")}function jf(e){const t=e.format;if((!t||!["number","percent","date"].includes(t.kind))&&Y("未知字段显示格式"),t.kind==="date"){(e.type!=="date"||t.pattern!==void 0&&(!fr(t.pattern)||t.pattern.length>128))&&Y("日期格式仅适用于日期,pattern 最多 128 位");return}["number","decimal"].includes(e.type)||Y("数值显示格式仅适用于 number/decimal"),t.digits!==void 0&&(!Number.isSafeInteger(t.digits)||t.digits<0||t.digits>100)&&Y("显示小数位应为 0–100 的整数"),t.kind==="number"&&t.thousands!==void 0&&typeof t.thousands!="boolean"&&Y("thousands 应为布尔值")}function Df(e){const t=new Map(e.map(n=>[n.field,n])),r=new Set;for(const n of e){const o=[{field:n.field,exit:!1}],i=new Set;for(;o.length;){const s=o.pop();if(s.exit){i.delete(s.field),r.add(s.field);continue}if(i.has(s.field)&&Y("字段计算依赖存在循环"),r.has(s.field))continue;const a=t.get(s.field);a||Y(`计算依赖字段未声明:${s.field}`),i.add(s.field),o.push({field:s.field,exit:!0});for(const c of a.calculation?.dependsOn??[])o.push({field:c,exit:!1})}}}const Lf=["text","number","boolean","date","decimal"],Bf=new Set(["__proto__","prototype","constructor"]);function J(e){throw new Error(`数据契约无效:${e}`)}function li(e){(!e||!Array.isArray(e.fields)||!e.fields.length||e.fields.length>2048)&&J("fields 应包含 1–2048 个字段");const t=new Set;for(const r of e.fields)(!r||typeof r.field!="string"||!r.field.trim()||Bf.has(r.field)||t.has(r.field))&&J("字段名应安全、非空且唯一"),t.add(r.field),Lf.includes(r.type)||J(`未知字段类型 ${r.type}`),Jf(r),Wf(r),Tf(r),_f(r);Kf(e,t),Df(e.fields)}function _f(e){e.enum!==void 0&&(!Array.isArray(e.enum)||!e.enum.length||e.enum.some(t=>!di(t,e.type)))&&J("enum 应为匹配字段类型的非空标量数组")}function Kf(e,t){e.rowKey!==void 0&&((typeof e.rowKey!="string"||!e.rowKey.trim()||!t.has(e.rowKey))&&J("rowKey 应为引用已声明字段的非空字符串"),e.fields.find(r=>r.field===e.rowKey)?.type==="boolean"&&J("布尔字段不能作为业务主键"))}function Wf(e){for(const t of["label","unit"])e[t]!==void 0&&typeof e[t]!="string"&&J(`${t} 应为字符串`);for(const t of["required","nullable"])e[t]!==void 0&&typeof e[t]!="boolean"&&J(`${t} 应为布尔值`);e.semanticRole!==void 0&&!["identifier","dimension","measure","date","text"].includes(e.semanticRole)&&J("未知字段语义")}function Jf(e){for(const t of["min","max","minLength","maxLength"]){const r=e[t];r!==void 0&&(!Number.isFinite(r)||t.includes("Length")&&(!Number.isInteger(r)||r<0))&&J(`${t} 无效`)}e.min!==void 0&&e.max!==void 0&&e.min>e.max&&J("min 不能超过 max"),e.minLength!==void 0&&e.maxLength!==void 0&&e.minLength>e.maxLength&&J("minLength 不能超过 maxLength"),e.type!=="number"&&(e.min!==void 0||e.max!==void 0)&&J("min/max 仅适用于 number,精确小数文本需业务校验"),["number","boolean"].includes(e.type)&&(e.minLength!==void 0||e.maxLength!==void 0)&&J("长度约束仅适用于文本类型")}function zf(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return!1;const r=Number(t[1]),n=Number(t[2]),o=Number(t[3]),i=r%4===0&&(r%100!==0||r%400===0);return r>0&&n>=1&&n<=12&&o>=1&&o<=[31,i?29:28,31,30,31,30,31,31,30,31,30,31][n-1]}function di(e,t){return t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":typeof e!="string"?!1:t==="date"?zf(e):t==="decimal"?e.length<=1e4&&/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e):!0}function Vf(e,t){if(e==null)return t.required||e===null&&t.nullable===!1?{code:"required",message:"缺少必需字段值"}:void 0;if(!di(e,t.type))return{code:"type",message:`值应为 ${t.type},不会自动转换原始值`};if(t.enum&&!t.enum.includes(e))return{code:"enum",message:"值不在允许的枚举中"};if(typeof e=="number"&&(t.min!==void 0&&e<t.min||t.max!==void 0&&e>t.max))return{code:"range",message:"数值超出范围"};if(typeof e=="string"&&!Hf(e,t))return{code:"range",message:"文本长度超出范围"}}function Hf(e,t){if(t.minLength===void 0&&t.maxLength===void 0)return!0;let r=0;for(const n of e)r++;return(t.minLength===void 0||r>=t.minLength)&&(t.maxLength===void 0||r<=t.maxLength)}function qt(e,t){const r=e??t;if(!Number.isInteger(r)||r<1)throw new Error("数据校验预算应为正整数");return r}function Uf(e,t,r){const n=Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;if((typeof n!="string"||!n.trim())&&!(typeof n=="number"&&Number.isFinite(n)))return"业务主键应为非空字符串或有限数字";const o=JSON.stringify([typeof n,n]);if(r.has(o))return"业务主键重复";r.add(o)}function Gf(e,t,r={}){li(t);const n=r.path??"$.rows",o=[],i=qt(r.maxIssues,100);if(!Array.isArray(e))return{ok:!1,issues:[{code:"row",path:n,message:"数据集应为对象数组"}]};if(e.length>qt(r.maxRows,1e5)||e.length*t.fields.length>qt(r.maxCells,2e6))return{ok:!1,issues:[{code:"budget",path:n,message:"数据校验超出行数或单元格预算"}]};const s=new Set;for(let a=0;a<e.length&&o.length<i;a++){const c=e[a];if(!c||typeof c!="object"||Array.isArray(c)){o.push({code:"row",path:`${n}[${a}]`,rowIndex:a,message:"行应为对象"});continue}Yf(c,t,a,n,s,o,i)}return{ok:o.length===0,issues:o}}function Yf(e,t,r,n,o,i,s){for(const a of t.fields){if(i.length>=s)return;const c=Vf(Object.prototype.hasOwnProperty.call(e,a.field)?e[a.field]:void 0,a);c&&i.push({...c,rowIndex:r,field:a.field,path:`${n}[${r}].${a.field}`})}if(t.rowKey&&i.length<s){const a=Uf(e,t.rowKey,o);a&&i.push({code:"row-key",path:`${n}[${r}].${t.rowKey}`,message:a,rowIndex:r,field:t.rowKey})}}function qf(e){return li(e),{$schema:"https://json-schema.org/draft/2020-12/schema",type:"array",items:{type:"object",properties:Object.fromEntries(e.fields.map(r=>[r.field,Xf(r,r.field===e.rowKey)])),required:e.fields.filter(r=>r.required||r.field===e.rowKey).map(r=>r.field),additionalProperties:!0},...e.rowKey?{"x-report-rowKey":e.rowKey}:{}}}function Xf(e,t){const r=!t&&e.nullable!==!1&&!e.required;return{type:r?[Fn(e.type),"null"]:Fn(e.type),...e.label?{title:e.label}:{},...e.description?{description:e.description}:{},...e.type==="date"?{format:"date"}:{},...e.type==="decimal"?{pattern:"^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$"}:{},...e.enum?{enum:r?[...e.enum,null]:[...e.enum]}:{},...e.min===void 0?{}:{minimum:e.min},...e.max===void 0?{}:{maximum:e.max},...Zf(e,t),...t&&e.type==="text"?{pattern:"\\S"}:{},...e.unit?{"x-report-unit":e.unit}:{},...e.semanticRole?{"x-report-semanticRole":e.semanticRole}:{},...e.aggregation?{"x-report-aggregation":e.aggregation}:{},...e.format?{"x-report-format":{...e.format}}:{},...e.missingMeaning?{"x-report-missingMeaning":e.missingMeaning}:{},...e.calculation?{"x-report-calculation":{description:e.calculation.description,dependsOn:[...e.calculation.dependsOn]}}:{}}}function Zf(e,t){const r={};return(e.minLength!==void 0||t&&e.type!=="number")&&(r.minLength=Math.max(e.minLength??0,t?1:0)),e.type==="decimal"?r.maxLength=Math.min(e.maxLength??1e4,1e4):e.maxLength!==void 0&&(r.maxLength=e.maxLength),r}function Fn(e){return e==="text"||e==="date"||e==="decimal"?"string":e}function Qf(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e,r=n=>typeof n=="string"&&n.trim().length>0&&n.length<=256;return!r(t.datasetId)||!r(t.field)||t.tableId!==void 0&&!r(t.tableId)||t.reportScope!==void 0&&(typeof t.reportScope!="string"||!t.reportScope.trim()||t.reportScope.length>4096)?!1:t.rowKey===void 0?!0:typeof t.rowKey=="string"?t.rowKey.trim().length>0&&t.rowKey.length<=1024:typeof t.rowKey=="number"&&Number.isFinite(t.rowKey)}function el(e){return e==="missing-source"||e==="not-applicable"||e==="not-calculable"}function Yr(e){return e.target!==void 0&&!Qf(e.target)?!1:e.valueState===void 0||el(e.valueState)&&e.target!==void 0}function mi(e,t,r={}){const n=new Map;for(const i of e.pages)for(const s of i.components){if(s.kind!=="list"||s.tree?.input!=="nested")continue;const a=n.get(s.dataset);if(a&&(a.childrenField??"children")!==(s.tree.childrenField??"children"))throw new Error("同一数据集的嵌套树应使用相同 childrenField");n.set(s.dataset,s.tree)}if(!n.size)return t;const o={...t};for(const[i,s]of n){const a=Math.min(s.maxRows??1e5,r.maxRows??1/0);o[i]=mo(t[i]??[],{...s,maxRows:a},r.signal)}return o}function tl(e,t,r={}){return Object.values(mi(e,t,r)).reduce((n,o)=>n+o.length,0)}function rl(e,t,r){const n=qf(r),o=e?.pages.flatMap(a=>a.components).find(a=>a.kind==="list"&&a.dataset===t&&a.tree?.input==="nested");if(!o||o.kind!=="list"||!o.tree)return n;const i=n.items,s=o.tree.childrenField??"children";return{...n,items:{$ref:"#/$defs/treeNode"},$defs:{treeNode:{...i,properties:{...i.properties,[s]:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/treeNode"}}]}}}}}}function qr(e,t){return JSON.stringify([e,t])}function hi(e,t,r){return r===void 0?qr(e,t):JSON.stringify(["shared",r])}function gi(e,t,r){return e.map(n=>{const o=n.table?{...n.table,id:r(n.table.id),...n.table.source?{source:{...n.table.source,sourceScope:t}}:{}}:void 0,i=n.grid?.cells.map(s=>s.map(a=>!a||!a.source&&!a.children?a:{...a,...a.source?{source:{...a.source,sourceScope:t}}:{},...a.children?{children:gi(a.children,t,r)}:{}}));return o||i?{...n,...o?{table:o}:{},...i?{grid:{...n.grid,cells:i}}:{}}:n})}function lr(e){return It(e.maxChartComponents),{maxPages:e.maxPages,maxCells:e.maxCells,maxChartComponents:e.maxChartComponents??Pr,usedPages:0,usedCells:0,usedChartComponents:0}}function nl(e,t){if(!e.repeat)return!1;const r=Object.prototype.hasOwnProperty.call(t,e.repeat.dataset)?t[e.repeat.dataset]:void 0;return Array.isArray(r)&&r.length===0}function ol(e){const t=r=>r.grid?.cells.reduce((n,o)=>n+o.reduce((i,s)=>i+(s?1+(s.children?.reduce((a,c)=>a+t(c),0)??0):0),0),0)??0;return e.pages.reduce((r,n)=>r+n.components.reduce((o,i)=>o+t(i),0),0)}function dr(e,t){return e===void 0?void 0:e-t}function Xt(e,t){return e===void 0?t:Math.max(1,Math.min(e,t??e))}function pi(e,t,r,n,o){It(e?.maxChartComponents);const i=dr(t.maxPages,t.usedPages),s=t.maxChartComponents-t.usedChartComponents;if(i!==void 0&&i<1&&r.pages.length&&!nl(r,n))throw new Se(0,1);if(s<1&&r.pages.some(a=>a.components.some(c=>c.kind!=="list"&&c.chartBinding)))throw new Ke(s,1);return{...e,signal:o??e?.signal,maxPages:Xt(i,e?.maxPages),maxCells:Xt(dr(t.maxCells,t.usedCells),e?.maxCells),maxChartComponents:Xt(s,e?.maxChartComponents)}}function yi(e,t){const r=ol(t.plan),n=dr(e.maxCells,e.usedCells);if(n!==void 0&&r>n)throw new _e(n,r);e.usedPages+=t.plan.pages.length,e.usedCells+=r,e.usedChartComponents+=t.chartComponents}function wi(e,t){return e instanceof Se&&t.maxPages!==void 0&&(e.limit===t.maxPages-t.usedPages||e.limit===0)?new Se(t.maxPages,t.usedPages+e.actual):e instanceof _e&&t.maxCells!==void 0?new _e(t.maxCells,t.usedCells+e.actual):e instanceof Ke&&e.limit===t.maxChartComponents-t.usedChartComponents?new Ke(t.maxChartComponents,t.usedChartComponents+e.estimated):e}class E extends Error{constructor(t,r,n){super(r),this.name="ReportSourceError",this.code=t,this.cause=n}}function Bt(e){const t=new Error("报表加载已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function G(e){if(e?.aborted)throw Bt(e)}function mr(e,t){return t?new Promise((r,n)=>{const o=()=>t.removeEventListener("abort",i),i=()=>{o(),n(Bt(t))};t.addEventListener("abort",i,{once:!0}),t.aborted&&i(),Promise.resolve(e).then(s=>{o(),r(s)},s=>{o(),n(s)})}):Promise.resolve(e)}function il(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new E("validate",`报表 ${t} 的数据集应为对象`);for(const[r,n]of Object.entries(e))if(!Array.isArray(n)||n.some(o=>!o||typeof o!="object"||Array.isArray(o)))throw new E("validate",`报表 ${t} 的数据集 ${r} 应为对象数组`)}async function sl(e,t,r){const{reportId:n,signal:o}=t;try{const i=await mr(e(t),o);G(o);const s=Vu(i);if(!s.ok)throw new E("validate",`报表 ${n} 模板校验失败:${s.errors.slice(0,3).map(a=>`${a.path}: ${a.message}`).join("; ")}`);return r.push(...s.warnings.map(a=>`${n}: ${a.path}: ${a.message}`)),i}catch(i){throw o?.aborted?Bt(o):i instanceof E?i:i instanceof Pu?new E("validate",`报表 ${n} 模板校验失败:${i.message}`,i):new E("fetch",`报表 ${n} 模板加载失败:${i instanceof Error?i.message:String(i)}`,i)}}async function al(e,t,r,n){const o=t.signal;let i;try{if(e.load)i=await mr(e.load(t),o);else if(e.provider){const s=await mr(e.provider.query(t),o);G(o),cl(s,r),i=s.datasets,n?.(r,s)}else i=e.datasets??{}}catch(s){throw o?.aborted?Bt(o):s instanceof E?s:new E("fetch",`报表 ${r} 取数失败:${s instanceof Error?s.message:String(s)}`,s)}return G(o),i}function cl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new E("validate",`报表 ${t} Provider 应返回 datasets 结果对象`);for(const r of["revision","sourceToken"])if(e[r]!==void 0&&typeof e[r]!="string")throw new E("validate",`报表 ${t} Provider ${r} 应为字符串`);if(e.diagnostics!==void 0&&(!Array.isArray(e.diagnostics)||e.diagnostics.some(r=>!r||typeof r.code!="string"||typeof r.message!="string"||!["info","warning","error"].includes(r.severity))))throw new E("validate",`报表 ${t} Provider diagnostics 不符合结构化诊断契约`);if(e.diagnostics?.some(r=>!Yr(r)))throw new E("validate",`报表 ${t} Provider 数据说明缺少有效的字段身份或值状态`)}function ul(e,t,r,n,o){try{t=mi(n,t,{maxRows:e.dataValidation?.maxRows,signal:o})}catch(i){throw new E("validate",`报表 ${r} 树形数据无效:${i instanceof Error?i.message:String(i)}`,i)}for(const[i,s]of Object.entries(e.dataSchema??{})){let a;try{a=Gf(Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0,s,{...e.dataValidation,path:`$.datasets.${i}`})}catch(c){throw new E("config",`报表 ${r} 数据集 ${i} 字段契约配置无效`,c)}if(!a.ok)throw new E("validate",`报表 ${r} 数据集 ${i} 不符合字段契约:${a.issues[0]?.message}`,{issues:a.issues})}}async function fl(e,t,r,n,o){try{let i;try{i=Af(e)}catch{}const s=i??e,a=pi(t.pagination,n,s.template,s.datasets,o),c=i?await Co(s.template,s.datasets,a):Ic(s.template,s.datasets,a);return yi(n,c),{result:c,part:s}}catch(i){G(o);const s=wi(i,n);throw new E("validate",`报表 ${r} 排版失败:${s instanceof Error?s.message:String(s)}`,s)}}function bi(e,t,r,n,o){const i=new Map,s=a=>{let c=i.get(a);return c===void 0&&(c=JSON.stringify([r,n,a]),i.set(a,c)),c};for(const a of t.pages)e.push({...a,meta:{...a.meta,reportScope:qr(r,n)},components:gi(a.components,o??hi(r,n),s)})}async function ll(e,t,r,n,o){const i=[],s=lr(n);for(const[u,f]of e.entries()){G(o);try{const d=await Nf(f.template,f.datasets,pi(t[u]?.pagination,s,f.template,f.datasets,o));yi(s,d),bi(i,d.plan,u,r[u],f.sourceScope)}catch(d){throw wi(d,s)}}const a={schemaVersion:ze,...e.some(u=>Tr(u.template))?{requiresRecalculation:!0}:{},pages:i},c=Ue(a);if(!c.ok)throw new E("validate",`重算渲染计划校验失败:${c.errors[0]?.message}`);return a}function dl(e,t={}){if(t.maxPages!==void 0&&(!Number.isSafeInteger(t.maxPages)||t.maxPages<1))throw new E("config","maxPages 应为正安全整数");if(t.maxCells!==void 0&&(!Number.isSafeInteger(t.maxCells)||t.maxCells<1))throw new E("config","maxCells 应为正安全整数");try{lr(t)}catch(o){throw new E("config","maxChartComponents 应为 1..1000000 的安全整数",o)}function r(o){const i=Object.prototype.hasOwnProperty.call(e,o)?e[o]:void 0;if(!i)throw new E("config",`未注册报表 ${o}`);if(i.sourceScope!==void 0&&(typeof i.sourceScope!="string"||!i.sourceScope.trim()||i.sourceScope.length>512))throw new E("config","sourceScope 应为不超过 512 字符的非空字符串");return i}return Object.assign(async({reportIds:o,params:i,signal:s,onWarning:a,onQueryResult:c,...u})=>{G(s);const f=de({...u,signal:s}),d=[...o],l={...i};if(d.length===0)throw new E("config","缺少报表 ID");const m=d.map(r),h=f.runSync("validate",()=>m.map(v=>$n(v.params??(typeof v.template=="function"?[]:v.template.params)??[],l))),p=[],w=[],y=lr(t),g=[];for(const[v,M]of m.entries()){G(s);const S=d[v],R={reportId:S,params:h[v],signal:s},N=typeof M.template=="function"?await f.run("query",()=>sl(M.template,R,g),S):M.template;R.params=f.runSync("validate",()=>$n(M.params??N.params??[],R.params),S);const I=await f.run("query",()=>al(M,R,S,(Wt,Ui)=>c?.(Wt,Ui,v)),S);f.runSync("validate",()=>{il(I,S),t.onDatasets?.(S,I,N),ul(M,I,S,N,s)},S),G(s);const pe=hi(v,S,M.sourceScope),{result:Qr,part:Hi}=await f.run("layout",()=>fl({template:N,datasets:I,sourceScope:pe},M,S,y,s),S);w.push(Hi),bi(p,Qr.plan,v,S,pe),g.push(...Qr.warnings.map(Wt=>`${S}: ${Wt}`))}G(s);const x={schemaVersion:ze,...w.some(v=>Tr(v.template))?{requiresRecalculation:!0}:{},pages:p},b=f.runSync("validate",()=>{const v=Ue(x);if(!v.ok)throw new E("validate",`渲染计划校验失败:${v.errors.slice(0,3).map(M=>`${M.path}: ${M.message}`).join("; ")}`);return v});g.push(...b.warnings.map(v=>`${v.path}: ${v.message}`));const $=m.map(v=>({...v,pagination:{...v.pagination}})),T={maxPages:t.maxPages,maxCells:t.maxCells,maxChartComponents:t.maxChartComponents};try{Rf(x,{parts:w,validationFormulas:$.map(v=>v.pagination?.formula),rebuild:(v,M)=>ll(v,$,d,T,M)})}catch{g.push("来源数据无法建立本地重算口径;当前预览仅支持计划内编辑,请使用可序列化模板数据启用规则重算")}const j=a??t.onWarning??(v=>console.warn("[mach-report]",v));for(const v of g)G(s),j(v);return G(s),x},{getParamDefs:o=>vt(e,o)})}const Xr=Object.freeze({maxRows:1e5,maxPages:1e4,maxCells:2e6,maxChartComponents:5e4,maxOutputBytes:1e8,maxPreparedBytes:64e6,maxDurationMs:12e4});class L extends Error{constructor(t,r,n){super(r),this.code=t,this.path=n,this.name="ReportRuntimeError"}}function O(e){if(!e?.aborted)return;if(e.reason instanceof L)throw e.reason;const t=new Error("报表执行已取消");throw t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function B(e,t,r){if(!Number.isFinite(r)||r<0)throw new L("budget",`${t} 的执行统计无效`,`$.budget.${t}`);const n=e[t];if(n!==void 0&&r>n)throw new L("budget",`${t} 超出预算 ${n}(实际 ${r})`,`$.budget.${t}`)}function xi(e){for(const[t,r]of Object.entries(e)){if(r!==void 0&&(!Number.isFinite(r)||r<=0))throw new L("budget",`${t} 应为正有限数字`,`$.budget.${t}`);if(t!=="maxDurationMs"&&r!==void 0&&!Number.isSafeInteger(r))throw new L("budget",`${t} 应为正安全整数`,`$.budget.${t}`);if(t==="maxDurationMs"&&r!==void 0&&r>2147483647)throw new L("budget","maxDurationMs 不能超过 2147483647",`$.budget.${t}`);if(t==="maxChartComponents"&&r!==void 0&&r>1e6)throw new L("budget","maxChartComponents 不能超过 1000000","$.budget.maxChartComponents")}}async function Re(e,t,r){const n=new AbortController,o=()=>n.abort(e?.reason);e?.addEventListener("abort",o,{once:!0}),e?.aborted&&o();const i=Date.now(),s=t===void 0?void 0:setTimeout(()=>n.abort(new L("timeout",`报表执行超过 ${t}ms`)),t);let a;try{O(n.signal);const c=new Promise((f,d)=>{a=()=>{try{O(n.signal)}catch(l){d(l)}},n.signal.addEventListener("abort",a,{once:!0})}),u=await Promise.race([r(n.signal),c]);if(O(n.signal),t!==void 0&&Date.now()-i>t)throw new L("timeout",`报表执行超过 ${t}ms`);return u}finally{s!==void 0&&clearTimeout(s),a&&n.signal.removeEventListener("abort",a),e?.removeEventListener("abort",o)}}function vi(e,t){me.assertOutputActive(t.signal),me.observeOutput(()=>t.onDiagnostic?.(e)),me.assertOutputActive(t.signal)}class ml extends Error{constructor(t){super(`Output contains ${t.length} known fidelity issue(s): ${t[0]?.code}`),this.diagnostics=t,this.code="output-fidelity",this.name="OutputFidelityError"}}class _t extends Error{constructor(t,r){super(r),this.code=t,this.name="ImageMediaError"}}const Zt={maxImageBytes:16*1024*1024,maxTotalImageBytes:32*1024*1024,maxImages:1e3,maxImagePixels:16e6,maxTotalImagePixels:64e6,maxImageDimension:16384};function ee(e){throw new _t("invalid-image-data",e)}function Ce(e){throw new _t("image-budget-exceeded",e)}function hl(e){const t={...Zt};for(const r of Object.keys(Zt)){const n=e[r]??Zt[r];if(!Number.isSafeInteger(n)||n<=0||n>2147483647)throw new RangeError(`${r} 图片预算须为1至2147483647的整数。`);t[r]=n}return t}function gl(e){if(e.length<33||![137,80,78,71,13,10,26,10].every((r,n)=>e[n]===r))return ee("图片内容与 PNG/JPEG 类型不一致。");const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return t.getUint32(8)!==13||String.fromCharCode(...e.subarray(12,16))!=="IHDR"?ee("PNG must begin with an IHDR header."):[t.getUint32(16),t.getUint32(20)]}const pl=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function yl(e){if(e[0]!==255||e[1]!==216)return ee("图片内容与 PNG/JPEG 类型不一致。");let t=2;for(;t+3<e.length;){if(e[t++]!==255)return ee("JPEG marker is malformed.");for(;e[t]===255;)t++;const r=e[t++];if(r===217||r===218)break;if(r===1||r>=208&&r<=215)continue;const n=e[t]*256+e[t+1];if(n<2||t+n>e.length)return ee("JPEG segment exceeds its data boundary.");if(pl.has(r))return n<8?ee("JPEG frame header is incomplete."):[e[t+5]*256+e[t+6],e[t+3]*256+e[t+4]];t+=n}return ee("JPEG has no supported dimension header.")}function wl(e,t){if(e.length>Math.ceil(t.maxImageBytes/3)*4+64)return Ce("单张图片超过字节预算。");const r=/^data:image\/(png|jpe?g);base64,([A-Za-z0-9+/]+={0,2})$/i.exec(e);if(!r||r[2].length%4)return ee("Image must contain valid PNG/JPEG base64 data.");const n=r[2],o=n.length/4*3-(n.endsWith("==")?2:n.endsWith("=")?1:0);if(o>t.maxImageBytes)return Ce("单张图片超过字节预算。");const i=r[1].toLowerCase()==="png"?"png":"jpeg",s=atob(n),a=new Uint8Array(o);for(let f=0;f<o;f++)a[f]=s.charCodeAt(f);const[c,u]=i==="png"?gl(a):yl(a);return!c||!u?ee("Image dimensions must be positive."):c>t.maxImageDimension||u>t.maxImageDimension||c*u>t.maxImagePixels?Ce("Image exceeds its decoded dimension or pixel budget."):{dataUrl:`data:image/${i};base64,${n}`,bytes:a,extension:i,width:c,height:u}}function bl(e={}){const t=hl(e),r=new Map;let n=0,o=0;return i=>{const s=i.replace(/^data:image\/(png|jpe?g);base64,/i,(u,f)=>`data:image/${f.toLowerCase()==="png"?"png":"jpeg"};base64,`),a=r.get(s);if(a)return a;if(r.size>=t.maxImages)return Ce("唯一图片数量超过预算。");const c=wl(i,t);return n+c.bytes.length>t.maxTotalImageBytes||o+c.width*c.height>t.maxTotalImagePixels?Ce("图片总字节或总像素超过预算。"):(n+=c.bytes.length,o+=c.width*c.height,r.set(s,c),c)}}class Zr extends Error{constructor(t,r){super(t.message),this.name="OutputAssetError",this.diagnostic=t,this.cause=r}}function Et(e){if(e.aborted)throw e.reason??new DOMException("The operation was aborted.","AbortError")}function xl(e){const t={maxAssets:1e3,maxImageBytes:33554432,maxTotalImageBytes:134217728,maxDurationMs:3e4,...e.assetBudget};for(const[r,n]of Object.entries(t))if(!Number.isSafeInteger(n)||n<=0||n>2147483647)throw new RangeError(`${r} must be a positive safe integer at most 2147483647.`);return t}function vl(e){const t=/^data:image\/[a-z0-9.+-]+(;base64)?,(.*)$/is.exec(e);if(!t)throw new TypeError("Asset renderers must return an image data URL.");return t[1]?Math.ceil(t[2].length*3/4):new TextEncoder().encode(decodeURIComponent(t[2])).byteLength}function Xe(e,t,r,n,o){const i={code:r,message:n,severity:"warning",format:e.options.format??"dom",pageIndex:t.pageIndex,componentIndex:t.componentIndex,componentPath:t.componentPath,kind:t.component.kind,nid:t.component.nid};if(e.diagnostics.push(i),vi(i,{...e.options,signal:e.signal}),e.options.assetFailure!=="placeholder")throw new Zr(i,o)}async function Ml(e,t,r){const n=e.options.assetRegistry?.rendererFor(t)??e.options.assetRenderers?.[t.kind];if(t.imageData||!n)return t.imageData;if(++e.rendered>e.budget.maxAssets)return Xe(e,r,"asset-budget-exceeded","Output exceeded the asset count budget.");let o;try{if(e.active=r,o=await me.waitForOutput(n({...r,signal:e.signal}),e.signal),Et(e.signal),o.length>e.budget.maxImageBytes*4+1024)return Xe(e,r,"asset-budget-exceeded","Output exceeded the image payload byte budget.");const i=vl(o);if(i>e.budget.maxImageBytes||e.bytes+i>e.budget.maxTotalImageBytes)return Xe(e,r,"asset-budget-exceeded","Output exceeded the encoded image byte budget.");/^data:image\/(png|jpe?g);base64,/i.test(o)&&e.inspectImage(o),e.bytes+=i}catch(i){if(e.signal.aborted||i instanceof Zr||i instanceof _t&&i.code==="image-budget-exceeded")throw i;return Xe(e,r,"asset-render-failed",`Asset renderer failed for ${t.kind}; output was not silently omitted.`,i)}return o}function $l(e,t){const r=e.active;if(!r){t.abort(new Error("Asset rendering exceeded maxDurationMs."));return}const n={code:"asset-budget-exceeded",message:"Asset rendering exceeded maxDurationMs.",severity:"warning",format:e.options.format??"dom",pageIndex:r.pageIndex,componentIndex:r.componentIndex,componentPath:r.componentPath,kind:r.component.kind,nid:r.component.nid};e.diagnostics.push(n);try{vi(n,{...e.options,signal:e.signal})}catch(o){t.abort(o);return}t.abort(new Zr(n))}async function Sl(e,t,r,n,o){if(!t?.children?.length)return t;const i=[];for(const[s,a]of t.children.entries())i.push(await Mi(e,a,{...r,component:a,componentPath:[...n,s]},o));return i.some((s,a)=>s!==t.children[a])?{...t,children:i}:t}async function Mi(e,t,r,n){if(Et(e.signal),n.has(t))throw new TypeError("Cyclic grid children cannot be rendered.");let o=e.cache.get(t);o||(o=Ml(e,t,r),e.cache.set(t,o));const i=await o;Et(e.signal);let s=t.grid;if(s){const a=new Set(n).add(t),c=[];for(const[u,f]of s.cells.entries()){const d=[];for(const[l,m]of f.entries())d.push(await Sl(e,m,r,[...r.componentPath,u,l],a));c.push(d)}c.some((u,f)=>u.some((d,l)=>d!==s.cells[f][l]))&&(s={...s,cells:c})}return i!==t.imageData||s!==t.grid?{...t,imageData:i,grid:s}:t}function El(e,t,r){const n=new Set,o=i=>{if(me.assertOutputActive(r),!n.has(i)){if(n.add(i),i.imageData&&/^data:image\/(png|jpe?g);base64,/i.test(i.imageData))try{t(i.imageData)}catch(s){if(!(s instanceof _t)||s.code==="image-budget-exceeded")throw s}for(const s of i.grid?.cells??[])for(const a of s)for(const c of a?.children??[])o(c)}};for(const i of e.pages)for(const s of i.components)o(s)}function Al(e){if(e.options.fidelity==="strict"&&e.diagnostics.length)throw new ml(e.diagnostics)}async function On(e,t={}){me.assertOutputActive(t.signal),Dc(e);const r=xl(t),n=bl(t);if(El(e,n,t.signal),t.signal?.aborted)throw t.signal.reason??new DOMException("The operation was aborted.","AbortError");const o=new AbortController,i=()=>o.abort(t.signal?.reason);if(t.signal?.addEventListener("abort",i,{once:!0}),!t.assetRegistry&&(!t.assetRenderers||!Object.keys(t.assetRenderers).length))return t.signal?.removeEventListener("abort",i),{plan:e,diagnostics:[]};const s={options:t,signal:o.signal,diagnostics:[],rendered:0,bytes:0,budget:r,cache:new WeakMap,inspectImage:n},a=setTimeout(()=>$l(s,o),r.maxDurationMs);try{const c=[];for(const[u,f]of e.pages.entries()){if(u<(t.start??0)||u>(t.end??e.pages.length-1)){c.push(f);continue}const d=[];for(const[l,m]of f.components.entries())d.push(await Mi(s,m,{component:m,pageIndex:u,componentIndex:l,componentPath:[]},new Set));c.push(d.some((l,m)=>l!==f.components[m])?{...f,components:d}:f)}return Et(s.signal),Al(s),{plan:c.some((u,f)=>u!==e.pages[f])?{...e,pages:c}:e,diagnostics:s.diagnostics}}finally{clearTimeout(a),t.signal?.removeEventListener("abort",i)}}function At(e=[]){return e.map(({code:t,message:r,severity:n,pageIndex:o,componentIndex:i})=>({code:t,message:r,severity:n,path:i<0?`$.pages.${o}`:`$.pages.${o}.components.${i}`}))}async function In(e,t,r=Date.now()){const n=e.prepared;if(e.fidelity==="strict"&&n.diagnostics.some(d=>d.code==="asset-render-failed"||d.code==="asset-budget-exceeded"))throw new E("validate","严格输出拒绝已有资产渲染降级,请修复组件后重新准备报表。");const o=e.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;O(e.signal);const i=e.pdf?.customFontFaces??(e.pdf?.customFontBytes?{regular:e.pdf.customFontBytes}:void 0),s=o&&i?o.createFontBytesMeasurer(i):void 0,a=de(e),c=await a.run("encode",async()=>{let d;if(e.format==="pdf"){O(e.signal);const l=await o.renderPlanToPdf(n.plan,{...e.pdf,...s?{measurer:s}:{},fidelity:e.fidelity,signal:e.signal,onProgress:(m,h)=>a.progress("encode",m,h)});d=l.bytes,n.diagnostics.push(...At(l.diagnostics)),n.diagnostics.push(...l.fidelityWarnings.map(m=>({code:"pdf-fidelity",message:m,severity:"warning"})),...l.pageErrors.map(m=>({code:"pdf-page",message:m,severity:"error"}))),l.unsupportedTextCount&&n.diagnostics.push({code:"pdf-font",message:`${l.unsupportedTextCount} 段文本包含当前字体不支持的字符`,severity:"warning"})}else{const{renderPlanToXlsx:l}=await import("@agile-team/mach-report/xlsx");O(e.signal);const m=await l(n.plan,{...e.xlsx,fidelity:e.fidelity,signal:e.signal,onProgress:(h,p)=>a.progress("encode",h,p)});d=new Uint8Array(m.buffer),n.diagnostics.push(...At(m.diagnostics)),n.diagnostics.push(...m.warnings.map(h=>({code:"xlsx-fidelity",message:h,severity:"warning"}))),n.diagnostics.push(...(m.notes??[]).map(h=>({code:"xlsx-snapshot",message:h,severity:"info"})))}return O(e.signal),d});B(t,"maxOutputBytes",c.byteLength);const{plan:u,...f}=n;return{...f,bytes:c,format:e.format,contentType:e.format==="pdf"?"application/pdf":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",stats:{...f.stats,durationMs:Date.now()-r,outputBytes:c.byteLength}}}function $i(e,t){const r=t.maxNodes??1e6;if(![t.maxBytes,r].every(f=>Number.isSafeInteger(f)&&f>0))throw t.error("budget","快照预算应为正安全整数");let n=0,o=0;const i=new Set;function s(f){if(o+=f,o>t.maxBytes)throw t.error("budget","快照超过字节预算")}function a(f,d){if(++n>r||d>64)throw t.error("budget","快照节点或深度超过预算");if(n%1024===0&&t.check?.(),typeof f=="string")return s(f.length+2),f;if(f===null||typeof f=="boolean"||typeof f=="number"&&Number.isFinite(f))return s(String(f).length),f;if(!f||typeof f!="object"||i.has(f))throw t.error("input","快照应为无循环的有限 JSON 值");return c(f,d)}function c(f,d){const l=Array.isArray(f),m=Object.getPrototypeOf(f);if(m!==(l?Array.prototype:Object.prototype)&&!(m===null&&!l)||Object.getOwnPropertySymbols(f).length)throw t.error("input","快照应为普通 JSON 对象");const h=Object.getOwnPropertyNames(f).filter(y=>!(l&&y==="length"));if(l&&(h.length!==f.length||h.some((y,g)=>y!==String(g))))throw t.error("input","快照数组应为连续数组");i.add(f),s(2);const p=Object.create(null);let w=0;for(const y of h){const g=Object.getOwnPropertyDescriptor(f,y);if(g.get||g.set||!g.enumerable||["__proto__","constructor","prototype"].includes(y))throw t.error("input","快照不允许访问器或危险键");g.value===void 0&&!l||(s((w++?1:0)+(l?0:y.length+3)),p[y]=a(g.value===void 0?null:g.value,d+1))}return i.delete(f),l?h.map(y=>p[y]):p}t.check?.();const u=JSON.stringify(a(e,0));if(new TextEncoder().encode(u).byteLength>t.maxBytes)throw t.error("budget","快照超过字节预算");return JSON.parse(u)}const kl=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Z=(e,t)=>e>>>t|e<<32-t;function Si(e,t,r){const n=new DataView(e.buffer,e.byteOffset+t,64);for(let o=0;o<16;o++)r[o]=n.getUint32(o*4);for(let o=16;o<64;o++){const i=r[o-15],s=r[o-2],a=Z(i,7)^Z(i,18)^i>>>3,c=Z(s,17)^Z(s,19)^s>>>10;r[o]=r[o-16]+a+r[o-7]+c}}function Ei(e,t){let r=e[0],n=e[1],o=e[2],i=e[3],s=e[4],a=e[5],c=e[6],u=e[7];for(let f=0;f<64;f++){const d=Z(s,6)^Z(s,11)^Z(s,25),l=s&a^~s&c,m=u+d+l+kl[f]+t[f]>>>0,h=Z(r,2)^Z(r,13)^Z(r,22),p=r&n^r&o^n&o,w=h+p>>>0;u=c,c=a,a=s,s=i+m>>>0,i=o,o=n,n=r,r=m+w>>>0}e[0]=e[0]+r,e[1]=e[1]+n,e[2]=e[2]+o,e[3]=e[3]+i,e[4]=e[4]+s,e[5]=e[5]+a,e[6]=e[6]+c,e[7]=e[7]+u}function Ai(e){const t=new Uint8Array(Math.ceil((e.byteLength+9)/64)*64);t.set(e),t[e.byteLength]=128;const r=new DataView(t.buffer);return r.setUint32(t.length-8,Math.floor(e.byteLength/536870912)),r.setUint32(t.length-4,e.byteLength*8>>>0),t}const ki=()=>new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ni=e=>Array.from(e,t=>t.toString(16).padStart(8,"0")).join("");function Rn(e){const t=Ai(e),r=ki(),n=new Uint32Array(64);for(let o=0;o<t.length;o+=64)Si(t,o,n),Ei(r,n);return Ni(r)}async function Nl(e){const t=Ai(e),r=ki(),n=new Uint32Array(64);for(let o=0;o<t.length;o+=64)o>0&&o%262144===0&&await new Promise(i=>setTimeout(i,0)),Si(t,o,n),Ei(r,n);return Ni(r)}function hr(e){return e&&{...e}}function Te(e){if(!e)return;const t=r=>{if(!(r instanceof Uint8Array)&&!(r instanceof ArrayBuffer))throw new E("validate","字体应为 Uint8Array 或 ArrayBuffer");if(r.byteLength>32e6)throw new L("budget","单份字体超过 32 MB","$.pdf");return new Uint8Array(r instanceof Uint8Array?r:new Uint8Array(r))};if(e.customFontFaces){const r=e.customFontFaces;return{customFontName:e.customFontName,customFontFaces:{regular:t(r.regular),...r.bold?{bold:t(r.bold)}:{},...r.italic?{italic:t(r.italic)}:{},...r.boldItalic?{boldItalic:t(r.boldItalic)}:{}}}}return{customFontName:e.customFontName,...e.customFontBytes?{customFontBytes:t(e.customFontBytes)}:{}}}function Pi(e){const t=e?.customFontFaces??(e?.customFontBytes?{regular:e.customFontBytes}:void 0);if(!t)return;const r=["regular","bold","italic","boldItalic"].map(n=>{const o=t[n];if(!o)return[n,null];const i=o instanceof Uint8Array?o:new Uint8Array(o);if(i.byteLength>32e6)throw new L("budget","单份字体超过 32 MB","$.pdf");return[n,Rn(i)]});return Rn(new TextEncoder().encode(JSON.stringify(r)))}const gr=new WeakMap;function Pl(e,t,r){const n=Fi(e,t,r);let o=!0;return{prepared:n,forward(){if(!o)throw new Error("报表快照只能交接一次");return o=!1,gr.set(n,t),n}}}function Fi(e,t,r){if(O(r),!Number.isSafeInteger(t)||t<=0)throw new L("budget","快照预算应为正安全整数","$.budget.maxPreparedBytes");const n=gr.get(e);if(gr.delete(e),n!==void 0&&n<=t)return e;const o=$i(e,{maxBytes:t,maxNodes:t,check:()=>O(r),error:(i,s)=>i==="budget"?new L("budget",s,"$.budget.maxPreparedBytes"):new E("validate",s)});return Ii(o),o}function Oi(e){if(e===void 0)return!0;if(!Array.isArray(e))return!1;const t=new Set;return e.every(r=>!r||typeof r!="object"||Array.isArray(r)||typeof r.reportId!="string"||!r.reportId.trim()||!Number.isSafeInteger(r.reportIndex)||r.reportIndex<0||t.has(r.reportIndex)||typeof r.reportScope!="string"||!r.reportScope.trim()||r.reportScope.length>4096||r.revision!==void 0&&typeof r.revision!="string"||r.sourceToken!==void 0&&typeof r.sourceToken!="string"?!1:(t.add(r.reportIndex),!0))}function Ii(e){if(!Oi(e.sources))throw new E("validate","准备结果来源清单无效");if(!e?.stats||["rows","pages","cells"].some(t=>!Number.isSafeInteger(e.stats[t])||e.stats[t]<0)||!Number.isFinite(e.stats.durationMs)||e.stats.durationMs<0)throw new E("validate","准备结果统计无效");if(!Array.isArray(e.diagnostics)||e.diagnostics.some(t=>!t||typeof t.code!="string"||typeof t.message!="string"||!["info","warning","error"].includes(t.severity)||!Yr(t)))throw new E("validate","准备结果诊断无效");if(!e.revisions||typeof e.revisions!="object"||Array.isArray(e.revisions)||Object.values(e.revisions).some(t=>!t||typeof t!="object"||t.revision!==void 0&&typeof t.revision!="string"||t.sourceToken!==void 0&&typeof t.sourceToken!="string"))throw new E("validate","准备结果修订无效");if(e.layout&&(!["heuristic","provided","font-bytes"].includes(e.layout.textMetrics)||e.layout.fontFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(e.layout.fontFingerprint)))throw new E("validate","准备结果字体度量标识无效")}function Fl(e){if(e.layoutPolicy!==void 0&&!["verify","preserve"].includes(e.layoutPolicy))throw new E("validate","无效的 layoutPolicy");if(e.format!=="pdf")return;if(e.layoutPolicy==="preserve"&&!e.prepared.layout?.fontFingerprint){e.prepared.diagnostics.push({code:"prepared-layout-preserved",severity:"info",message:"显式保持现有分页与几何;未验证排版字体身份,实际 PDF 输出仍遵循 fidelity 校验。"});return}const t=e.prepared.layout?.fontFingerprint,r=Pi(e.pdf);if(t===r&&(t!==void 0||e.prepared.layout?.textMetrics==="heuristic"&&!r))return;const n="已准备计划的字体度量无法与本次 PDF 字体确认一致;保持现有分页,未重新查询或排版。请在 prepare 和 exportPrepared 提供相同字体字节。";if(e.fidelity==="strict")throw new E("validate",n);e.prepared.diagnostics.push({code:"prepared-font-metrics",severity:"warning",message:n})}function Cn(e){return{...e,reportIds:[...e.reportIds],...e.params?{params:{...e.params}}:{}}}function Ri(e,t){if(t.length===0)throw new E("config","缺少报表 ID");return t.map(r=>{if(!Object.prototype.hasOwnProperty.call(e,r))throw new E("config",`未注册报表 ${r}`);return e[r]})}function Kt(e){return e.grid?.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+Kt(s),0)??0):0),0),0)??0}function Ol(e,t,r){return e.pages.reduce((n,o)=>n+o.components.reduce((i,s)=>s.kind!=="list"?i+Kt(s):i+Tc(s,t,r),0),0)}function Il(e,t=Object.keys(e)){return Ri(e,t).map((r,n)=>{const o=t[n],i=vt(e,[o]);return{id:o,params:JSON.parse(JSON.stringify(i)),paramsSchema:$u(i),datasetsSchema:Object.fromEntries(Object.entries(r.dataSchema??{}).map(([s,a])=>[s,rl(typeof r.template=="function"?void 0:r.template,s,a)])),capabilities:{save:!!r.provider?.save,export:!!r.provider?.export,templates:!!r.provider?.templates}}})}function Ci(e,t){Ri(e,t.reportIds);const r=cr(vt(e,t.reportIds),t.params),n=t.reportIds.flatMap(i=>cr(vt(e,[i]),t.params).issues),o=new Map(n.map(i=>[JSON.stringify(i),i]));return{...r,ok:o.size===0,issues:[...o.values()]}}function pr(e,t){const r=Ue(e.plan);if(!r.ok)throw new E("validate",`执行器返回无效计划:${r.errors[0]?.path}`);const n=e.plan.pages.length,o=e.plan.pages.reduce((i,s)=>i+s.components.reduce((a,c)=>a+Kt(c),0),0);return B(t,"maxRows",e.stats.rows),B(t,"maxPages",n),B(t,"maxCells",o),{...e,stats:{...e.stats,pages:n,cells:o}}}function Tn(e,t){const r=Ci(e.reports,t);if(!r.ok)throw new Dt(r.issues)}function Ti(e){const t={...Xr,...e.budget};xi(t);const r=async(o,i)=>{const s=Date.now();let a=0,c=0;const u=[],f={},d=[],l=Object.fromEntries(Object.entries(e.reports).map(([b,$])=>[b,{...$,pagination:{...e.pagination,...$.pagination,...i?{measurer:i}:{}},dataValidation:{...$.dataValidation,maxRows:Math.min(t.maxRows??1e5,$.dataValidation?.maxRows??1/0),maxCells:Math.min(t.maxCells??2e6,$.dataValidation?.maxCells??1/0)}}])),h=await dl(l,{maxPages:t.maxPages,maxCells:t.maxCells,maxChartComponents:t.maxChartComponents,onDatasets:(b,$,T)=>{try{a+=tl(T,$,{maxRows:t.maxRows,signal:o.signal})}catch(j){throw j instanceof oo?new L("budget",j.message,"$.budget.maxRows"):j}B(t,"maxRows",a),c+=Ol(T,$,l[b]?.pagination),B(t,"maxCells",c)}})({...o,params:o.params??{},onWarning:b=>u.push({code:"layout",message:b,severity:"warning"}),onQueryResult:(b,$,T=0)=>{const j=qr(T,b);Object.defineProperty(f,b,{value:{revision:$.revision,sourceToken:$.sourceToken},enumerable:!0,writable:!0}),d.push({reportId:b,reportIndex:T,reportScope:j,...$.revision===void 0?{}:{revision:$.revision},...$.sourceToken===void 0?{}:{sourceToken:$.sourceToken}}),u.push(...($.diagnostics??[]).map(v=>({...v,...v.target?{target:{...v.target,reportScope:j,...v.target.tableId?{tableId:JSON.stringify([T,b,v.target.tableId])}:{}}}:{}})))}}).catch(b=>{throw b instanceof E&&b.cause instanceof Se?new L("budget",b.cause.message,"$.budget.maxPages"):b instanceof E&&b.cause instanceof _e?new L("budget",b.cause.message,"$.budget.maxCells"):b instanceof E&&b.cause instanceof Ke?new L("budget",b.cause.message,"$.budget.maxChartComponents"):b});O(o.signal);const p=e.assets?await de(o).run("assets",()=>On(h,{...e.assets,signal:o.signal})):{plan:h,diagnostics:[]},w=p.plan;u.push(...At(p.diagnostics));const y=w.pages.reduce((b,$)=>b+$.components.reduce((T,j)=>T+Kt(j),0),0);B(t,"maxPages",w.pages.length),B(t,"maxCells",y);const g=Pi(o.pdf),x=e.pagination?.measurer||Object.values(e.reports).some(b=>b.pagination?.measurer);return{plan:w,diagnostics:u,revisions:f,sources:d,layout:{textMetrics:g?"font-bytes":x?"provided":"heuristic",...g?{fontFingerprint:g}:{}},stats:{rows:a,pages:w.pages.length,cells:y,durationMs:Date.now()-s}}},n=async o=>{const i=Date.now();if(o.format!=="pdf"&&o.format!=="xlsx")throw new E("config","不支持的报表导出格式");const s=o.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;O(o.signal);const a=o.pdf?.customFontFaces??(o.pdf?.customFontBytes?{regular:o.pdf.customFontBytes}:void 0),c=s&&a?s.createFontBytesMeasurer(a):void 0,u=await r(o,c);return O(o.signal),In({...o,prepared:u},t,i)};return{describe:o=>Il(e.reports,o),validate:o=>Ci(e.reports,o),prepare:o=>Re(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=Cn(o),u={...c,...c.pdf?{pdf:Te(c.pdf)}:{},taskId:c.taskId??ot()},f=a?p=>Me(a,p,i):void 0,d={...u,signal:i,onEvent:f};de(d).runSync("validate",()=>Tn(e,u));let l;const m=u.pdf?.customFontFaces??(u.pdf?.customFontBytes?{regular:u.pdf.customFontBytes}:void 0);if(!e.executor&&m){const p=await import("@agile-team/mach-report/pdf");O(i),l=p.createFontBytesMeasurer(m)}const h=e.executor?await e.executor.prepare(u,i,f):await r(d,l);return pr(h,t)}),exportPrepared:o=>Re(o.signal,t.maxDurationMs,async i=>{const s=Date.now(),{signal:a,onEvent:c,...u}=o,f=pr(Fi(o.prepared,t.maxPreparedBytes??64e6,i),t),d={...u,xlsx:hr(u.xlsx),prepared:f,...u.pdf?{pdf:Te(u.pdf)}:{},taskId:u.taskId??ot()};if(d.format!=="pdf"&&d.format!=="xlsx")throw new E("config","不支持的报表导出格式");const l=c?h=>Me(c,h,i):void 0;if(e.executor){if(!e.executor.exportPrepared)throw new E("config","执行器未实现 exportPrepared;请升级执行器或显式使用本地运行时");const h=await e.executor.exportPrepared(d,i,l);return B(t,"maxRows",h.stats.rows),B(t,"maxPages",h.stats.pages),B(t,"maxCells",h.stats.cells),B(t,"maxOutputBytes",h.bytes.byteLength),{...h,stats:{...h.stats,outputBytes:h.bytes.byteLength}}}const m={...d,signal:i,onEvent:l};if(de(m).runSync("validate",()=>Fl(m)),e.assets){const h=await de(m).run("assets",()=>On(f.plan,{...e.assets,signal:i}));f.plan=h.plan,f.diagnostics.push(...At(h.diagnostics))}return In(m,t,s)}),export:o=>Re(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=Cn(o),u={...c,xlsx:hr(c.xlsx),...c.pdf?{pdf:Te(c.pdf)}:{},taskId:c.taskId??ot()},f=a?m=>Me(a,m,i):void 0,d={...u,signal:i,onEvent:f};if(de(d).runSync("validate",()=>Tn(e,u)),u.format!=="pdf"&&u.format!=="xlsx")throw new E("config","不支持的报表导出格式");const l=e.executor?await e.executor.export(u,i,f):await n(d);return B(t,"maxRows",l.stats.rows),B(t,"maxPages",l.stats.pages),B(t,"maxCells",l.stats.cells),B(t,"maxOutputBytes",l.bytes.byteLength),{...l,stats:{...l.stats,outputBytes:l.bytes.byteLength}}})}}const Rl={cells:2e4,pages:20,bytes:2e6};function je(e){return e.cells>=e.limits.cells||e.pages>=e.limits.pages||e.bytes>=e.limits.bytes||e.capped}function xe(e){return++e.visits>=1e5&&(e.capped=!0),!je(e)}function ie(e){return typeof e=="string"?e.length*2:0}function jn(e,t){for(const r of e??[]){if(!xe(t))return;for(const n of r.segments){if(!xe(t))return;t.bytes+=ie(n.text)}}}function ji(e,t,r){if(r>32){t.capped=!0;return}if(xe(t)){t.bytes+=ie(e.text)+ie(e.rawText)+ie(e.imageData),jn(e.richParagraphs,t);for(const n of e.lines??[]){if(!xe(t))return;t.bytes+=ie(n)}for(const n of e.grid?.cells??[]){if(!xe(t))return;for(const o of n){if(!xe(t))return;if(o){t.cells++,t.bytes+=ie(o.text)+ie(o.rawText)+ie(o.value),jn(o.richParagraphs,t);for(const i of o.children??[]){if(je(t))return;ji(i,t,r+1)}}}}}}function Cl(e){const t={...Rl,...e.thresholds};for(const r of Object.values(t))if(!Number.isSafeInteger(r)||r<=0)throw new RangeError("导出隔离阈值应为正安全整数");return t}function Tl(e,t){const r=Cl(t),n=e.pdf?.customFontFaces?Object.values(e.pdf.customFontFaces):[e.pdf?.customFontBytes],o={pages:e.prepared.plan.pages.length,cells:0,bytes:n.reduce((a,c)=>a+(c?.byteLength??0),0),visits:0,capped:!1,limits:r};for(const a of e.prepared.plan.pages){if(je(o))break;for(const c of a.components){if(je(o))break;ji(c,o,0)}}let i=je(o)?"worker":"local",s=o.capped?"scan-limit":i==="worker"?"threshold":"small-task";return t.mode==="local"&&(i="local",s="explicit-local"),t.mode==="worker"&&(i="worker",s="explicit-worker"),Object.values(e.xlsx??{}).some(a=>typeof a=="function")&&(i="local",s="nonserializable-options"),{mode:i,reason:s,estimate:{pages:o.pages,cells:o.cells,bytes:o.bytes},hardCancellation:i==="worker"}}const ce="mach-report-worker/1";class yr extends Error{constructor(t){super(t.message),this.name=t.name,this.code=t.code,this.path=t.path,this.issues=t.issues,this.diagnostics=t.diagnostics}}function ue(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function jl(e){return ue(e)?["rows","pages","cells"].every(t=>typeof e[t]=="number"&&Number.isSafeInteger(e[t])&&e[t]>=0)&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0:!1}function Dl(e){return Array.isArray(e)&&e.every(t=>ue(t)&&typeof t.code=="string"&&typeof t.message=="string"&&["info","warning","error"].includes(t.severity)&&Yr(t))}function Ll(e){return ue(e)&&Object.values(e).every(t=>ue(t)&&(t.revision===void 0||typeof t.revision=="string")&&(t.sourceToken===void 0||typeof t.sourceToken=="string"))}function Bl(e){return e===void 0?!0:ue(e)&&["heuristic","provided","font-bytes"].includes(e.textMetrics)&&(e.fontFingerprint===void 0||typeof e.fontFingerprint=="string"&&/^[a-f0-9]{64}$/.test(e.fontFingerprint))}function _l(e,t){if(!ue(e)||!jl(e.stats)||!Dl(e.diagnostics)||!Ll(e.revisions)||!Bl(e.layout)||!Oi(e.sources))return!1;if(t==="prepare")return Ue(e.plan).ok;const r=e.format==="pdf"?"application/pdf":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";return e.bytes instanceof Uint8Array&&(e.format==="pdf"||e.format==="xlsx")&&e.contentType===r}function Di(e){if(!e||typeof e!="object")return{message:String(e)};const t={};for(const r of["code","path","field","message"]){const n=e[r];typeof n=="string"&&(t[r]=n)}return t}function Kl(e){const t=Di(e);if(!ue(e))return t;for(const r of["format","severity","kind","nid"])typeof e[r]=="string"&&(t[r]=e[r]);for(const r of["pageIndex","componentIndex"])Number.isSafeInteger(e[r])&&e[r]>=0&&(t[r]=e[r]);return Array.isArray(e.componentPath)&&e.componentPath.every(r=>Number.isSafeInteger(r)&&r>=0)&&(t.componentPath=e.componentPath),t}function Li(e){if(!(e instanceof Error))return{name:"Error",message:String(e)};const t=e;return{name:e.name,message:e.message,...typeof t.code=="string"?{code:t.code}:{},...typeof t.path=="string"?{path:t.path}:{},...Array.isArray(t.issues)?{issues:t.issues.map(Di)}:{},...Array.isArray(t.diagnostics)?{diagnostics:t.diagnostics.map(Kl)}:{}}}function Bi(e){if(!e||typeof e!="object")return!1;const t=e;return t.protocol===ce&&typeof t.id=="string"&&(t.operation==="prepare"||t.operation==="export"||t.operation==="exportPrepared")&&!!t.input&&typeof t.input=="object"}async function _i(e,t,r){try{const n=t.operation==="prepare"?await e.prepare({...t.input,onEvent:r}):t.operation==="exportPrepared"?await e.exportPrepared({...t.input,onEvent:r}):await e.export({...t.input,onEvent:r});return{protocol:ce,id:t.id,result:n}}catch(n){return{protocol:ce,id:t.id,error:Li(n)}}}function Ki(e){const t=e.result;return!t||!("bytes"in t)||!(t.bytes.buffer instanceof ArrayBuffer)?[]:[t.bytes.buffer]}function Wl(e,t){if(!ue(e)||typeof e.taskId!="string"||!e.taskId||t.taskId!==void 0&&e.taskId!==t.taskId||e.correlationId!==t.correlationId||e.reportId!==void 0&&(typeof e.reportId!="string"||!("reportIds"in t&&t.reportIds.includes(e.reportId)))||!["query","validate","layout","assets","encode"].includes(e.stage)||!["started","completed","failed"].includes(e.status))return!1;for(const r of["completed","total"])if(e[r]!==void 0&&(typeof e[r]!="number"||!Number.isFinite(e[r])||e[r]<0))return!1;return e.completed===void 0||e.total===void 0||e.completed<=e.total}class wr extends Error{constructor(t){super("报表 Worker 无法启动"),this.cause=t,this.name="ReportWorkerStartError"}}let Jl=0;function Dn(e){const t=new Error("报表 Worker 任务已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e}),t}function zl(e,t){if(!e||typeof e!="object")return;const r=e;return r.protocol===ce&&r.id===t?r:void 0}function Vl(e,t={}){const r=t.timeoutMs??12e4;if(!Number.isFinite(r)||r<=0||r>2147483647)throw new RangeError("Worker timeoutMs 应为正有限数字,且不能超过 2147483647");const n=(o,i,s,a)=>s?.aborted?Promise.reject(Dn(s.reason)):new Promise((c,u)=>{let f;try{f=e()}catch(g){u(new wr(g));return}const d=`mach-report-${Date.now()}-${++Jl}`;let l=!1,m=()=>{},h;const p=(g,x)=>{if(l)return;l=!0,h&&clearTimeout(h);let b;try{m()}catch($){b=$}s?.removeEventListener("abort",w),g??=b,Promise.resolve().then(()=>f.terminate()).then(()=>g===void 0?c(x):u(g),$=>u(g??$))},w=()=>p(Dn(s?.reason)),y=g=>{const x=zl(g,d);if(!(!x||l)){if("type"in x&&x.type==="event"){const b="event"in x?x.event:void 0;Wl(b,i)?Me(a,b,s):p(new Error("报表 Worker 返回无效阶段事件"));return}x.error&&typeof x.error.name=="string"&&typeof x.error.message=="string"?p(new yr(x.error)):_l(x.result,o)&&(o==="prepare"||"format"in x.result&&"format"in i&&x.result.format===i.format)?p(void 0,x.result):p(new Error("报表 Worker 返回无效响应"))}};try{if(m=f.subscribe(y,g=>p(g??new Error("报表 Worker 执行失败"))),l){m();return}if(s?.addEventListener("abort",w,{once:!0}),h=setTimeout(()=>p(new yr({name:"ReportRuntimeError",code:"timeout",message:`报表 Worker 执行超过 ${r}ms`})),r),s?.aborted)w();else{const{onEvent:g,signal:x,...b}=i,$=Hl(b);f.postMessage({protocol:ce,id:d,operation:o,input:b,...t.budget?{budget:t.budget}:{}},$)}}catch(g){p(g)}});return{exportPrepared:(o,i,s)=>n("exportPrepared",o,i,s),prepare:(o,i,s)=>n("prepare",o,i,s),export:(o,i,s)=>n("export",o,i,s)}}function Hl(e){return e.pdf?(e.pdf=Te(e.pdf),(e.pdf?.customFontFaces?Object.values(e.pdf.customFontFaces):[e.pdf?.customFontBytes]).filter(r=>r instanceof Uint8Array).map(r=>r.buffer)):[]}function Ul(e){if(e.mode!==void 0&&!["auto","local","worker"].includes(e.mode))throw new TypeError("无效的导出执行模式");if(e.fallback!==void 0&&!["local","error"].includes(e.fallback))throw new TypeError("无效的导出回退策略");xi({...e.budget,maxDurationMs:e.timeoutMs??e.budget?.maxDurationMs??12e4})}function Ln(e,t){me.observeOutput(()=>e.onDecision?.({...t,estimate:{...t.estimate}}))}function Bn(e,t){return{...e,mode:"local",reason:t,hardCancellation:!1}}function Gl(e,t){const r={...Xr,...t.budget},n=Pl(e.prepared,r.maxPreparedBytes,e.signal),o=pr(n.prepared,r);n.prepared.stats=o.stats;const i={...e,prepared:n.prepared,pdf:Te(e.pdf),xlsx:hr(e.xlsx)};return{request:i,forward:()=>({...i,prepared:n.forward()})}}function Yl(e,t){Ul(e);const r={...e,thresholds:{...e.thresholds},budget:{...Xr,...e.budget}},n=r.timeoutMs??r.budget.maxDurationMs??12e4,o=Ti({reports:{},budget:{...r.budget,maxDurationMs:n}}),i=new Set;let s=!1;const a=r.mode!=="worker"&&r.fallback!=="error";async function c(u,f){const d=Date.now(),l=()=>{const y=n-(Date.now()-d);if(y<=0)throw new L("timeout",`报表执行超过 ${n}ms`);return y};let m=Tl(u,r);if(m.reason==="nonserializable-options"&&r.mode==="worker")throw new TypeError("Worker 模式不接受函数选项;请使用本地模式或可序列化配置");if(m.mode==="worker"&&!t){if(!a)throw new wr(new Error("未配置 workerFactory"));m=Bn(m,"worker-unavailable")}const h=Gl(u,r),p=h.request;if(Ln(r,m),O(u.signal),m.mode==="worker")try{const y=t(l());if(!y.exportPrepared)throw new TypeError("隔离执行器缺少 exportPrepared");const{signal:g,onEvent:x,...b}=p,$=await y.exportPrepared(b,g,x);return O(g),B(r.budget,"maxOutputBytes",$.bytes.byteLength),{...$,execution:m}}catch(y){if(!(y instanceof wr)||!a)throw y;O(u.signal),m=Bn(m,"worker-start-failed"),Ln(r,m)}const w=f?await Re(u.signal,l(),y=>f({...p,signal:y})):await Re(u.signal,l(),y=>o.exportPrepared({...h.forward(),signal:y}));return O(u.signal),B(r.budget,"maxOutputBytes",w.bytes.byteLength),{...w,execution:m}}return{async exportPrepared(u,f){if(s)throw new L("closed","导出执行器已释放");if(O(u.signal),i.size>=2)throw new L("queue-full","同时导出的任务已达 2 个,请等待完成后重试");const d=new AbortController;i.add(d);const l=()=>d.abort(u.signal?.reason);u.signal?.addEventListener("abort",l,{once:!0});try{return await c({...u,signal:d.signal},f)}finally{u.signal?.removeEventListener("abort",l),i.delete(d)}},cancel(){for(const u of i)u.abort()},dispose(){s=!0;for(const u of i)u.abort()}}}async function ql(e,t){try{if(e.operation!=="exportPrepared")throw new TypeError("内置编码 Worker 仅接受 exportPrepared");return await _i(Ti({reports:{},budget:e.budget}),e,t)}catch(r){return{protocol:ce,id:e.id,error:Li(r)}}}class k extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportJobError"}}function kt(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 k("input","任务范围应非空,ID应为1–128位安全标识")}function Xl(e){const t=Array.isArray(e),r=Object.getPrototypeOf(e),n=Object.keys(e);if(r!==(t?Array.prototype:Object.prototype)&&!(r===null&&!t))throw new k("input","任务对象应为普通 JSON 对象");if(Object.getOwnPropertySymbols(e).length)throw new k("input","任务不能包含Symbol");if(Object.getOwnPropertyNames(e).filter(i=>!(t&&i==="length")).length!==n.length)throw new k("input","任务不能包含不可枚举属性");if(t&&(n.length!==e.length||n.some(i=>i!==String(Number(i))||!Number.isSafeInteger(Number(i))||Number(i)<0||Number(i)>=e.length)))throw new k("input","任务数组不能稀疏或包含额外属性");return n.sort()}function Zl(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(["__proto__","prototype","constructor"].includes(t)||r.get||r.set)throw new k("input","任务不能包含危险键或访问器");return r.value}function ne(e,t={}){const r=t.maxNodes??2e4,n=t.maxCharacters??1e6;if(!Number.isSafeInteger(r)||r<1||r>2e4||!Number.isSafeInteger(n)||n<1||n>1e6)throw new k("input","任务JSON预算无效");let o=0,i=0;const s=new Set;function a(u,f){if(++o>r||f>32)throw new k("input","任务数据超过节点或深度预算");if(typeof u=="string"){if(i+=u.length,i>n)throw new k("input","任务文本超过预算");return u}if(u===null||typeof u=="boolean"||typeof u=="number"&&Number.isFinite(u))return u;if(!u||typeof u!="object"||s.has(u))throw new k("input","任务只允许无循环的有限 JSON 值");const d=Array.isArray(u),l=Xl(u);s.add(u);const m=Object.create(null);for(const h of l){if(i+=h.length,i>n)throw new k("input","任务文本超过预算");m[h]=a(Zl(u,h),f+1)}return s.delete(u),d?Array.from({length:u.length},(h,p)=>m[String(p)]):m}const c=JSON.stringify(a(e,0));if(c.length>n)throw new k("input","任务序列化数据超过字符预算");return c}function Qt(e){return JSON.parse(JSON.stringify(e))}function Wi(e,t,r,n){if(kt(t,r),e.scope!==t||e.id!==r||e.revision!==(n??0)+1||!Number.isSafeInteger(e.revision))throw new k("input","任务身份或修订不匹配");if(![e.createdAt,e.updatedAt,e.attempt].every(o=>Number.isSafeInteger(o)&&o>=0)||!["queued","running","completed","failed","cancelled"].includes(e.status))throw new k("input","任务状态无效");if(e.lease&&(!e.lease.owner||!Number.isSafeInteger(e.lease.expiresAt)))throw new k("input","任务租约无效");if(!e.request||typeof e.request.kind!="string"||!e.request.kind.trim()||e.request.kind.length>128)throw new k("input","任务类型无效");ne(e.request.payload,{maxNodes:19e3,maxCharacters:75e4}),ne(e)}function Ql(e,t){if(e&&(e.createdAt!==t.createdAt||ne(e.request)!==ne(t.request)))throw new k("input","任务创建时间与请求不可变更,请使用新任务ID")}function ed(e,t){return e.status==="queued"||e.status==="running"&&(e.lease?.expiresAt??0)<=t}function td(e={}){const t={maxRecords:e.maxRecords??1e4,maxBytes:e.maxBytes??67108864,maxResultBytes:e.maxResultBytes??262144,controlReserveBytes:e.controlReserveBytes??4096,maxTombstones:e.maxTombstones??1e4,maxTombstoneBytes:e.maxTombstoneBytes??16777216};if(!Object.values(t).every(r=>Number.isSafeInteger(r)&&r>0)||t.controlReserveBytes<4096)throw new k("input","任务容量应为正整数,控制状态预留至少4096字节");return t}function De(e){return new TextEncoder().encode(ne(e)).byteLength}function Ji(e,t){const r={scope:e.scope,id:e.id,revision:1,request:e.request,status:"queued",createdAt:e.createdAt,updatedAt:e.createdAt,attempt:0},n={...e};delete n.result;const o=e.result===void 0?0:De(e.result);if(o>t.maxResultBytes)throw new k("capacity","任务结果超过独立预算,请保存文件引用");return Math.max(De(r)+t.controlReserveBytes,De(n))+o}function zi(e){return e.status!=="queued"&&e.status!=="running"}function rd(e){const t={...e,tombstoneRetentionMs:e.tombstoneRetentionMs??6048e5,limit:e.limit??100};if(![t.now,t.terminalBefore].every(r=>Number.isSafeInteger(r)&&r>=0)||t.terminalBefore>t.now)throw new k("input","终态清理时间应为不超过当前时间的非负整数");if(![t.tombstoneRetentionMs,t.limit].every(r=>Number.isSafeInteger(r)&&r>0)||!Number.isSafeInteger(t.now+t.tombstoneRetentionMs))throw new k("input","幂等保留期与清理批量应为正整数");return t}async function nd(e){const t=new TextEncoder().encode(ne(e)),r=globalThis.crypto?.subtle;if(!r)return Nl(t);const n=await r.digest("SHA-256",t);return Array.from(new Uint8Array(n),o=>o.toString(16).padStart(2,"0")).join("")}async function od(e,t){if(!zi(e))throw new k("input","只能归档终态任务");return{scope:e.scope,id:e.id,revision:e.revision,status:e.status,createdAt:e.createdAt,updatedAt:e.updatedAt,attempt:e.attempt,requestHash:await nd(e.request),expiresAt:t}}function id(e){if(!e||!["completed","failed","cancelled"].includes(e.status)||!/^[a-f0-9]{64}$/.test(e.requestHash))throw new k("input","任务幂等摘要无效");if(![e.revision,e.createdAt,e.updatedAt,e.attempt,e.expiresAt].every(t=>Number.isSafeInteger(t)&&t>=0)||e.revision<1)throw new k("input","任务幂等摘要时间或修订无效")}function Ge(e){return e?.code}function Le(e,t){return ge.createHash("sha256").update(JSON.stringify([e,t])).digest("hex")+".json"}async function br(e){try{return await A.promises.readFile(e,"utf8")}catch(t){if(Ge(t)==="ENOENT")return;throw t}}async function sd(e,t){const r=await br(e);if(r===void 0)return;let n;try{n=JSON.parse(r)}catch{throw new k("conflict","任务锁尚未完整写入或已损坏,拒绝自动移除")}if(!n||!Number.isSafeInteger(n.pid)||n.pid<1)throw new k("conflict","任务锁身份无效,拒绝自动移除");try{process.kill(n.pid,0)}catch(o){if(Ge(o)==="ESRCH"){await A.promises.unlink(e);return}throw o}throw new k("conflict","任务目录的写入进程仍在运行")}async function ad(e,t){if(!t)throw new k("conflict","任务目录已有写入进程;多实例请使用数据库CAS适配器");const r=e+".recovery";let n;try{n=await A.promises.open(r,"wx",384)}catch(o){throw Ge(o)==="EEXIST"?new k("conflict","任务目录恢复正在进行,请稍后重试"):o}try{return await n.writeFile(JSON.stringify({pid:process.pid})),await sd(e,!0),await A.promises.open(e,"wx",384)}finally{await n.close(),await A.promises.unlink(r)}}async function cd(e,t){const r=D.join(e,".writer-lock"),n=ge.randomUUID();let o;try{o=await A.promises.open(r,"wx",384)}catch(i){if(Ge(i)!=="EEXIST")throw i;o=await ad(r,t)}try{await o.writeFile(JSON.stringify({pid:process.pid,token:n})),await o.sync()}catch(i){throw await o.close(),await A.promises.unlink(r).catch(()=>{}),i}return{file:r,token:n,handle:o}}function ud(e,t,r,n){if("tombstone"in r){const o=r.tombstone;if(id(o),kt(o.scope,o.id),Le(o.scope,o.id)!==t)throw new k("input","持久任务摘要身份不匹配");const i=De(o);e.tombstoneBytes+=i,e.tombstones.set(t,{value:o,bytes:i})}else{if(Wi(r,r.scope,r.id,r.revision-1),Le(r.scope,r.id)!==t)throw new k("input","持久任务文件身份不匹配");const o=Ji(r,n);e.bytes+=o,e.records.set(t,{record:r,bytes:o})}if(e.bytes>n.maxBytes||e.records.size>n.maxRecords||e.tombstoneBytes>n.maxTombstoneBytes||e.tombstones.size>n.maxTombstones)throw new k("capacity","持久任务及控制状态预留超过目录预算")}async function fd(e,t){const r=await A.promises.readdir(e);for(const i of r.filter(s=>/^\.pending-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(s)))await A.promises.unlink(D.join(e,i));const n=r.filter(i=>/^[a-f0-9]{64}\.json$/.test(i));if(n.length>t.maxRecords+t.maxTombstones)throw new k("capacity","持久任务数量超过目录预算");const o={records:new Map,tombstones:new Map,bytes:0,tombstoneBytes:0};for(const i of n){const s=D.join(e,i);if((await A.promises.stat(s)).size>4e6)throw new k("capacity","持久任务文件超过单文件预算");ud(o,i,JSON.parse(await A.promises.readFile(s,"utf8")),t)}return o}async function ld(e,t,r){const n=D.join(e,`.pending-${ge.randomUUID()}`);try{const o=await A.promises.open(n,"wx",384);try{await o.writeFile(r),await o.sync()}finally{await o.close()}await A.promises.rename(n,D.join(e,t));const i=await A.promises.open(e,"r");try{await i.sync()}finally{await i.close()}}finally{await A.promises.unlink(n).catch(o=>{if(Ge(o)!=="ENOENT")throw o})}}async function dd(e){const t=D.resolve(e.directory),r=td(e);await A.promises.mkdir(t,{recursive:!0,mode:448});const n=await cd(t,e.recoverDeadOwner??!1);let o;try{o=await fd(t,r)}catch(l){throw await n.handle.close(),await A.promises.unlink(n.file),l}let i=!1,s=Promise.resolve();const a=()=>{if(i)throw new k("closed","持久任务存储已关闭")},c=l=>{a();const m=s.then(async()=>{if(JSON.parse(await A.promises.readFile(n.file,"utf8")).token!==n.token)throw new k("closed","持久任务存储写入锁已失效");return l()});return s=m.then(()=>{},()=>{}),m},u=async(l,m,h)=>{try{await ld(t,l,m)}catch(p){throw await br(D.join(t,l))===m&&h(),p}h()};return{read:async(l,m)=>{a(),kt(l,m),await s;const h=o.records.get(Le(l,m));return h?Qt(h.record):void 0},readTombstone:async(l,m)=>{a(),kt(l,m),await s;const h=o.tombstones.get(Le(l,m));return h?Qt(h.value):void 0},candidates:async(l,m)=>(a(),await s,Array.from(o.records.values(),h=>h.record).filter(h=>ed(h,l)).sort((h,p)=>h.createdAt-p.createdAt).slice(0,m).map(Qt)),compareAndSwap:async(l,m,h,p)=>{const w=JSON.parse(ne(p));return Wi(w,l,m,h),c(async()=>{const y=Le(l,m),g=o.records.get(y);if((g?.record.revision??null)!==h||o.tombstones.has(y))return!1;Ql(g?.record,w);const x=Ji(w,r),b=o.bytes-(g?.bytes??0)+x;if(b>r.maxBytes||!g&&o.records.size>=r.maxRecords)throw new k("capacity","持久任务容量已满,请清理终态任务或扩大显式预算");return await u(y,ne(w),()=>{o.records.set(y,{record:w,bytes:x}),o.bytes=b}),!0})},prune:async l=>{const m=rd(l);return c(async()=>{const h={archived:0,expired:0};for(const[p,w]of o.tombstones)w.value.expiresAt>m.now||h.expired>=m.limit||(await A.promises.unlink(D.join(t,p)),o.tombstones.delete(p),o.tombstoneBytes-=w.bytes,h.expired++);for(const[p,w]of o.records){if(!zi(w.record)||w.record.updatedAt>m.terminalBefore||h.archived+h.expired>=m.limit)continue;const y=await od(w.record,m.now+m.tombstoneRetentionMs),g=De(y);if(o.tombstones.size>=r.maxTombstones||o.tombstoneBytes+g>r.maxTombstoneBytes)break;await u(p,ne({tombstone:y}),()=>{o.tombstones.set(p,{value:y,bytes:g}),o.tombstoneBytes+=g,o.records.delete(p),o.bytes-=w.bytes}),h.archived++}if(h.expired){const p=await A.promises.open(t,"r");try{await p.sync()}finally{await p.close()}}return h})},close:async()=>{if(i)return;i=!0,await s,await n.handle.close();const l=await br(n.file);l&&JSON.parse(l).token===n.token&&await A.promises.unlink(n.file)}}}class F extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportDocumentError"}}function md(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 F("input","文档预算应为正安全整数");return t}function fe(e,t,r){if([e,t,...r===void 0?[]:[r]].some(n=>typeof n!="string"||!n.trim()||n.length>256))throw new F("input","文档 scope、id、version 应为 1–256 位非空字符串");return JSON.stringify([e,t])}function X(e,t,r){return $i(e,{maxBytes:t,maxNodes:t,check:()=>O(r),error:(n,o)=>new F(n==="budget"?"capacity":"input",o)})}function ve(e){return new TextEncoder().encode(JSON.stringify(e)).byteLength}function _n(e){if(!e||e.schemaVersion!==ze||"pages"in e||e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean")throw new F("input","文档计划头应使用当前版本,且不得携带 pages")}function Ze(e,t){e.bytes=0;for(let r=0;r<8;r++){const n=t+ve(e);if(n===e.bytes)return;e.bytes=n}throw new F("capacity","文档容量统计无效")}function hd(e,t,r=[]){const n=new Map;let o=0,i=Promise.resolve();for(const f of r){const d=fe(f.scope,f.id,f.version);if(_n(f.plan),n.has(d)||!Number.isSafeInteger(f.bytes)||f.bytes<0||!Number.isSafeInteger(f.pageCount)||f.pageCount<0||f.pageCount>t.maxPages||!["building","complete","failed"].includes(f.state)||f.revision!==f.pageCount+(f.state==="building"?0:1))throw new F("input","文档清单无效");n.set(d,X(f,t.maxManifestBytes)),o+=f.bytes}function s(f,d){if(o-(d?.bytes??0)+f.bytes>t.maxBytes||!d&&n.size>=t.maxDocuments)throw new F("capacity","文档存储容量已满,请显式清理旧文档")}if(n.size>t.maxDocuments||o>t.maxBytes)throw new F("capacity","已存文档超过预算");const a=f=>{const d=i.then(f);return i=d.then(()=>{},()=>{}),d},c=(f,d,l,m)=>{const h=n.get(fe(f,d,l));if(!h)throw new F("missing","文档不存在");if(h.version!==l||m!==void 0&&h.revision!==m)throw new F("conflict","文档已变化,请重新读取清单");return h},u=async(f,d,l)=>{const m=X(f,t.maxManifestBytes);return s(m,d),await e.write(m,l),n.set(fe(f.scope,f.id),m),o+=f.bytes-(d?.bytes??0),X(m,t.maxManifestBytes)};return{create:(f,d)=>{const l=X(f,t.maxManifestBytes,d),m=fe(l.scope,l.id,l.version);return _n(l.plan),a(async()=>{if(O(d),n.has(m))throw new F("conflict","文档已存在,不可覆盖");const h={...l,revision:0,state:"building",pageCount:0,bytes:0};return Ze(h,0),u(h)})},append:(f,d,l,m,h,p)=>{const w=X(h,t.maxPageBytes,p),y=Ue({pages:[w]});if(!y.ok)throw new F("input",y.errors[0].message);return a(async()=>{O(p);const g=c(f,d,l,m);if(g.state!=="building")throw new F("conflict","已完成文档不可追加");if(g.pageCount>=t.maxPages)throw new F("capacity","文档页数超过预算");const x={...g,revision:m+1,pageCount:g.pageCount+1};return Ze(x,g.bytes-ve(g)+ve(w)),u(x,g,{index:g.pageCount,value:w})})},complete:(f,d,l,m,h,p)=>{const w=h===void 0?void 0:X(h,t.maxManifestBytes,p);return w&&Ii({...w}),a(async()=>{O(p);const y=c(f,d,l,m);if(y.state!=="building")throw new F("conflict","文档已完成");if(w&&w.stats.pages!==y.pageCount)throw new F("input","准备结果页数与文档页数不一致");const g={...y,revision:m+1,state:"complete",...w?{metadata:w}:{}};return Ze(g,y.bytes-ve(y)),u(g,y)})},fail:(f,d,l,m,h)=>{const p=X(h,4096);if(!p||!["cancelled","generation"].includes(p.code)||typeof p.message!="string"||!p.message.trim()||p.message.length>1024)throw new F("input","文档失败状态无效");return a(async()=>{const w=c(f,d,l,m);if(w.state!=="building")throw new F("conflict","终态文档不可变更");const y={...w,state:"failed",revision:m+1,failure:p};return Ze(y,w.bytes-ve(w)),u(y,w)})},read:async(f,d,l)=>{O(l);const m=fe(f,d);await i,O(l);const h=n.get(m);return h?X(h,t.maxManifestBytes):void 0},readPage:(f,d,l,m,h)=>a(async()=>{O(h);const p=c(f,d,l);if(!Number.isSafeInteger(m)||m<0)throw new F("input","页索引应为非负安全整数");if(m>=p.pageCount)return;const w=await e.readPage(f,d,m);if(O(h),!w)throw new F("missing","已提交的文档页缺失");return X(w,t.maxPageBytes,h)}),remove:(f,d,l,m)=>a(async()=>{O(m);const h=fe(f,d,l),p=n.get(h);return p?(c(f,d,l),await e.remove(p),n.delete(h),o-=p.bytes,!0):!1})}}const xr=e=>e?.code,it=(e,t)=>ge.createHash("sha256").update(fe(e,t)).digest("hex");async function vr(e,t){const r=await A.promises.lstat(e);if(!r.isFile()||r.size>t)throw new F("capacity","文档文件类型或大小无效");return X(JSON.parse(await A.promises.readFile(e,"utf8")),t)}async function Kn(e,t){const r=`${e}.pending-${ge.randomUUID()}`;try{await A.promises.writeFile(r,JSON.stringify(t),{flag:"wx",mode:384}),await A.promises.rename(r,e)}finally{await A.promises.unlink(r).catch(n=>{if(xr(n)!=="ENOENT")throw n})}}async function gd(e,t){const r=(await A.promises.readdir(e)).filter(o=>/^[a-f0-9]{64}$/.test(o));if(r.length>t.maxDocuments)throw new F("capacity","文档数量超过目录预算");const n=[];for(const o of r){const i=D.join(e,o);if(!(await A.promises.lstat(i)).isDirectory())throw new F("input","文档目录不允许符号链接");const a=await vr(D.join(i,"manifest.json"),t.maxManifestBytes);if(it(a.scope,a.id)!==o||!Number.isSafeInteger(a.pageCount)||a.pageCount<0||a.pageCount>t.maxPages)throw new F("input","文档清单身份或页数无效");let c=ve(a);for(let u=0;u<a.pageCount;u++){const f=await A.promises.lstat(D.join(i,`${u}.json`));if(!f.isFile()||f.size>t.maxPageBytes)throw new F("capacity","文档页文件类型或大小无效");c+=f.size}if(c!==a.bytes)throw new F("input","文档字节数与已提交页不一致");for(const u of await A.promises.readdir(i)){const f=/^(\d+)\.json$/.exec(u);(f&&Number(f[1])>=a.pageCount||/\.pending-[a-f0-9-]{36}$/.test(u))&&await A.promises.unlink(D.join(i,u))}n.push(a)}return n}async function pd(e){const t=md(e),r=D.resolve(e.directory);await A.promises.mkdir(r,{recursive:!0,mode:448});const n=D.join(r,".document-writer-lock"),o=ge.randomUUID();let i;try{i=await A.promises.open(n,"wx",384)}catch(l){throw xr(l)==="EEXIST"?new F("conflict","文档目录已被占用;多实例请实现共享存储原子CAS"):l}try{await i.writeFile(JSON.stringify({pid:process.pid,token:o}))}catch(l){throw await i.close(),await A.promises.unlink(n),l}const s=async()=>{try{return(await vr(n,1024)).token===o}catch(l){if(xr(l)==="ENOENT")return!1;throw l}},a=async()=>{if(!await s())throw new F("closed","文档存储写入锁已失效")};let c=Promise.resolve(),u=!1;const f=l=>{if(u)return Promise.reject(new F("closed","文档存储已关闭"));const m=l();return c=Promise.allSettled([c,m]).then(()=>{}),m};let d;try{const l=await gd(r,t);d=hd({write:async(m,h)=>{await a();const p=D.join(r,it(m.scope,m.id));await A.promises.mkdir(p,{recursive:!0,mode:448}),h&&await Kn(D.join(p,`${h.index}.json`),h.value);try{await Kn(D.join(p,"manifest.json"),m)}catch(w){throw h?await A.promises.unlink(D.join(p,`${h.index}.json`)):m.revision===0&&await A.promises.rm(p,{recursive:!0}),w}},readPage:async(m,h,p)=>(await a(),vr(D.join(r,it(m,h),`${p}.json`),t.maxPageBytes)),remove:async m=>{await a(),await A.promises.rm(D.join(r,it(m.scope,m.id)),{recursive:!0})}},t,l)}catch(l){throw await i.close(),await A.promises.unlink(n),l}return{create:(...l)=>f(()=>d.create(...l)),append:(...l)=>f(()=>d.append(...l)),complete:(...l)=>f(()=>d.complete(...l)),fail:(...l)=>f(()=>d.fail(...l)),read:(...l)=>f(()=>d.read(...l)),readPage:(...l)=>f(()=>d.readPage(...l)),remove:(...l)=>f(()=>d.remove(...l)),close:async()=>{u||(u=!0,await c,await i.close(),await s()&&await A.promises.unlink(n))}}}function Vi(e){const t=e.filename??e.workerUrl;if(!t||e.filename&&e.workerUrl)throw new TypeError("请且仅请指定 filename 或 workerUrl");return Vl(()=>{const r=new Ne.Worker(t,e.workerOptions);return{postMessage:(n,o)=>r.postMessage(n,o),terminate:()=>r.terminate(),subscribe:(n,o)=>{const i=s=>o(new Error(`报表 Worker 在响应前退出(code ${s})`));return r.on("message",n),r.on("error",o),r.on("messageerror",o),r.on("exit",i),()=>{r.off("message",n),r.off("error",o),r.off("messageerror",o),r.off("exit",i)}}}},e)}function yd(e){const t=Ne.parentPort;if(!t)throw new Error("serveNodeReportWorker 只能在 worker_threads 中调用");const r=n=>{Bi(n)&&_i(e,n,o=>t.postMessage({protocol:ce,id:n.id,type:"event",event:o})).then(o=>t.postMessage(o,Ki(o)))};return t.on("message",r),()=>t.off("message",r)}function wd(e){return ge.createHash("sha256").update(e).digest("hex")}function bd(e={}){const t={timeoutMs:e.timeoutMs??e.budget?.maxDurationMs,budget:{...e.budget}};return Yl(e,r=>Vi({filename:typeof __filename=="string"?__filename:new URL(typeof document>"u"?require("url").pathToFileURL(__filename).href:Jt&&Jt.tagName.toUpperCase()==="SCRIPT"&&Jt.src||new URL("server-node.cjs",document.baseURI).href),workerOptions:{workerData:{machReportEncoding:"prepared-v1"}},...t,timeoutMs:r}))}if(Ne.parentPort&&Ne.workerData?.machReportEncoding==="prepared-v1"){const e=Ne.parentPort;e.on("message",t=>{Bi(t)&&ql(t,r=>e.postMessage({protocol:ce,id:t.id,type:"event",event:r})).then(r=>e.postMessage(r,Ki(r)))})}exports.ReportWorkerError=yr;exports.createNodeAutoReportExporter=bd;exports.createNodeReportExecutor=Vi;exports.openFileReportDocumentStore=pd;exports.openFileReportJobStore=dd;exports.reportArtifactSha256=wd;exports.serveNodeReportWorker=yd;