@agile-team/mach-report 2.14.0 → 2.16.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 (282) hide show
  1. package/README.md +26 -16
  2. package/THIRD_PARTY_NOTICES.md +3 -1
  3. package/dist/{ExcelBindingWizard-CLT2p7P3.cjs → ExcelBindingWizard-CP6h2x1f.cjs} +1 -1
  4. package/dist/{ExcelBindingWizard-CvsWR8Ga.js → ExcelBindingWizard-HhB3hAJE.js} +3 -3
  5. package/dist/ParamEditor-CUQLgoxa.cjs +1 -0
  6. package/dist/ParamEditor-OKesP_nO.js +594 -0
  7. package/dist/{ReportBatchPanel-DkxTzBkD.cjs → ReportBatchPanel-cZCAMAwH.cjs} +1 -1
  8. package/dist/{ReportBatchPanel-LqVgiqp7.js → ReportBatchPanel-ruxcbfY6.js} +39 -39
  9. package/dist/ReportPreview-BcDKCLiK.js +4834 -0
  10. package/dist/ReportPreview-Bk9nLfO9.cjs +6 -0
  11. package/dist/{ReportTemplateLibrary-cQ1sqNYo.cjs → ReportTemplateLibrary-BDlNT8JN.cjs} +1 -1
  12. package/dist/{ReportTemplateLibrary-MjWEtc7X.js → ReportTemplateLibrary-DcwrH-63.js} +1 -1
  13. package/dist/{RuleEditor-BaR6xUiI.cjs → RuleEditor-BX5S8RSF.cjs} +1 -1
  14. package/dist/{RuleEditor-ChuXMlei.js → RuleEditor-CGl9XY2s.js} +5 -5
  15. package/dist/{TemplateOutlinePanel-BHKP89Xz.cjs → TemplateOutlinePanel-CGrT5DFN.cjs} +1 -1
  16. package/dist/{TemplateOutlinePanel-Dci6aRn1.js → TemplateOutlinePanel-SXCjaPKR.js} +2 -2
  17. package/dist/{TemplateReusePanel-CY5eO2Sh.cjs → TemplateReusePanel-6Z3wRFz8.cjs} +1 -1
  18. package/dist/{TemplateReusePanel-B7Gmyc1z.js → TemplateReusePanel-lHLOS9Wn.js} +2 -2
  19. package/dist/{TemplateReviewPanel-DjlX3xpt.js → TemplateReviewPanel-CJ9PLc48.js} +2 -2
  20. package/dist/{TemplateReviewPanel-JvZe9_4G.cjs → TemplateReviewPanel-Dpk7sLcF.cjs} +1 -1
  21. package/dist/analytics.cjs +1 -1
  22. package/dist/analytics.d.cts +5 -1
  23. package/dist/analytics.d.ts +5 -1
  24. package/dist/analytics.js +154 -60
  25. package/dist/artifact-integrity.json +143 -0
  26. package/dist/assets-CqIbfbTr.js +126 -0
  27. package/dist/assets-e4YSke8n.cjs +1 -0
  28. package/dist/auto-YR7a4BtF.js +240 -0
  29. package/dist/auto-uVBjX1j5.cjs +1 -0
  30. package/dist/batch-WzDIXJAt.js +220 -0
  31. package/dist/batch-z6Aw5GEY.cjs +1 -0
  32. package/dist/capabilities-DDwXr_cA.js +103 -0
  33. package/dist/capabilities-DNLyZdNw.cjs +1 -0
  34. package/dist/codes.d.cts +4 -0
  35. package/dist/codes.d.ts +4 -0
  36. package/dist/component-tree-Ca6YYfHq.js +61 -0
  37. package/dist/component-tree-DkGLEfZC.cjs +1 -0
  38. package/dist/{computed-Bvk0W15F.js → computed-C-4C2S5h.js} +3 -3
  39. package/dist/config-Dg_o8e7m.cjs +1 -0
  40. package/dist/config-XQ4qrQ7Q.js +844 -0
  41. package/dist/designer-BfQSahxq.js +5163 -0
  42. package/dist/designer-CPPdeM5_.cjs +2 -0
  43. package/dist/designer.cjs +1 -1
  44. package/dist/designer.d.cts +197 -16
  45. package/dist/designer.d.ts +197 -16
  46. package/dist/designer.js +1 -1
  47. package/dist/diagnostic-notification-B9K9We3h.cjs +1 -0
  48. package/dist/diagnostic-notification-qGAYZdkB.js +7 -0
  49. package/dist/drill-CsdjgkRM.cjs +1 -0
  50. package/dist/drill-DIGsZfyB.js +145 -0
  51. package/dist/encoding-BOGq4qYL.js +21 -0
  52. package/dist/encoding-BYF9ZTl9.cjs +1 -0
  53. package/dist/{font-loader-DHto6Lra.js → font-loader-CzI1GuBc.js} +1 -1
  54. package/dist/{font-loader-vhCT8znW.cjs → font-loader-EKLzOJxf.cjs} +1 -1
  55. package/dist/index.cjs +8 -9
  56. package/dist/index.d.cts +84 -4
  57. package/dist/index.d.ts +84 -4
  58. package/dist/index.js +829 -833
  59. package/dist/json-snapshot-D6ioHth9.js +1702 -0
  60. package/dist/json-snapshot-DknkjvxP.cjs +2 -0
  61. package/dist/licenses/_bwip-js_generic-4.11.4.txt +24 -0
  62. package/dist/licenses/_fast-csv_format-4.3.5.txt +22 -0
  63. package/dist/licenses/_fast-csv_parse-4.3.6.txt +22 -0
  64. package/dist/licenses/_pdf-lib_fontkit-1.1.1.txt +326 -0
  65. package/dist/licenses/_pdf-lib_standard-fonts-1.0.0.txt +22 -0
  66. package/dist/licenses/_pdf-lib_upng-1.0.1.txt +22 -0
  67. package/dist/licenses/_types_node-14.18.63.txt +22 -0
  68. package/dist/licenses/_types_pako-2.0.3.txt +22 -0
  69. package/dist/licenses/_types_pegjs-0.10.6.txt +22 -0
  70. package/dist/licenses/archiver-5.3.2.txt +23 -0
  71. package/dist/licenses/archiver-utils-2.1.0.txt +23 -0
  72. package/dist/licenses/archiver-utils-3.0.4.txt +23 -0
  73. package/dist/licenses/async-3.2.6.txt +20 -0
  74. package/dist/licenses/balanced-match-1.0.2.txt +22 -0
  75. package/dist/licenses/base64-js-1.5.1.txt +22 -0
  76. package/dist/licenses/big-integer-1.6.52.txt +25 -0
  77. package/dist/licenses/binary-0.3.0.txt +178 -0
  78. package/dist/licenses/bl-4.1.0.txt +14 -0
  79. package/dist/licenses/bluebird-3.4.7.txt +22 -0
  80. package/dist/licenses/brace-expansion-1.1.21.txt +22 -0
  81. package/dist/licenses/brace-expansion-2.1.7.txt +22 -0
  82. package/dist/licenses/buffer-5.7.1.txt +22 -0
  83. package/dist/licenses/buffer-crc32-0.2.13.txt +20 -0
  84. package/dist/licenses/buffer-indexof-polyfill-1.0.2.txt +23 -0
  85. package/dist/licenses/buffers-0.1.1.txt +140 -0
  86. package/dist/licenses/chainsaw-0.1.0.txt +184 -0
  87. package/dist/licenses/compress-commons-4.1.2.txt +23 -0
  88. package/dist/licenses/concat-map-0.0.1.txt +19 -0
  89. package/dist/licenses/core-util-is-1.0.3.txt +20 -0
  90. package/dist/licenses/crc-32-1.2.2.txt +202 -0
  91. package/dist/licenses/crc32-stream-4.0.3.txt +23 -0
  92. package/dist/licenses/dayjs-1.11.23.txt +22 -0
  93. package/dist/licenses/duplexer2-0.1.4.txt +27 -0
  94. package/dist/licenses/end-of-stream-1.4.5.txt +22 -0
  95. package/dist/licenses/exceljs-4.4.0.txt +23 -0
  96. package/dist/licenses/fast-csv-4.3.6.txt +22 -0
  97. package/dist/licenses/fast-png-6.4.0.txt +22 -0
  98. package/dist/licenses/fs-constants-1.0.0.txt +22 -0
  99. package/dist/licenses/fs.realpath-1.0.0.txt +44 -0
  100. package/dist/licenses/fstream-1.0.12.txt +16 -0
  101. package/dist/licenses/glob-7.2.3.txt +22 -0
  102. package/dist/licenses/graceful-fs-4.2.11.txt +16 -0
  103. package/dist/licenses/ieee754-1.2.1.txt +12 -0
  104. package/dist/licenses/immediate-3.0.6.txt +21 -0
  105. package/dist/licenses/inflight-1.0.6.txt +16 -0
  106. package/dist/licenses/inherits-2.0.4.txt +17 -0
  107. package/dist/licenses/iobuffer-5.4.0.txt +23 -0
  108. package/dist/licenses/isarray-1.0.0.txt +61 -0
  109. package/dist/licenses/jszip-3.10.2.txt +652 -0
  110. package/dist/licenses/lazystream-1.0.1.txt +24 -0
  111. package/dist/licenses/lie-3.3.0.txt +8 -0
  112. package/dist/licenses/listenercount-1.0.1.txt +6 -0
  113. package/dist/licenses/lodash.defaults-4.2.0.txt +48 -0
  114. package/dist/licenses/lodash.difference-4.5.0.txt +48 -0
  115. package/dist/licenses/lodash.escaperegexp-4.1.2.txt +48 -0
  116. package/dist/licenses/lodash.flatten-4.4.0.txt +48 -0
  117. package/dist/licenses/lodash.groupby-4.6.0.txt +48 -0
  118. package/dist/licenses/lodash.isboolean-3.0.3.txt +23 -0
  119. package/dist/licenses/lodash.isequal-4.5.0.txt +48 -0
  120. package/dist/licenses/lodash.isfunction-3.0.9.txt +48 -0
  121. package/dist/licenses/lodash.isnil-4.0.0.txt +23 -0
  122. package/dist/licenses/lodash.isplainobject-4.0.6.txt +48 -0
  123. package/dist/licenses/lodash.isundefined-3.0.1.txt +23 -0
  124. package/dist/licenses/lodash.union-4.6.0.txt +48 -0
  125. package/dist/licenses/lodash.uniq-4.5.0.txt +48 -0
  126. package/dist/licenses/minimatch-3.1.5.txt +16 -0
  127. package/dist/licenses/minimatch-5.1.9.txt +16 -0
  128. package/dist/licenses/minimist-1.2.8.txt +19 -0
  129. package/dist/licenses/mkdirp-0.5.6.txt +22 -0
  130. package/dist/licenses/node-sql-parser-5.4.0.txt +202 -0
  131. package/dist/licenses/normalize-path-3.0.0.txt +22 -0
  132. package/dist/licenses/once-1.4.0.txt +16 -0
  133. package/dist/licenses/pako-1.0.11.txt +22 -0
  134. package/dist/licenses/pako-2.2.0.txt +22 -0
  135. package/dist/licenses/path-is-absolute-1.0.1.txt +22 -0
  136. package/dist/licenses/pdf-lib-1.17.1.txt +22 -0
  137. package/dist/licenses/process-nextick-args-2.0.1.txt +20 -0
  138. package/dist/licenses/readable-stream-2.3.8.txt +48 -0
  139. package/dist/licenses/readable-stream-3.6.2.txt +48 -0
  140. package/dist/licenses/readdir-glob-1.1.3.txt +202 -0
  141. package/dist/licenses/rimraf-2.7.1.txt +16 -0
  142. package/dist/licenses/safe-buffer-5.1.2.txt +22 -0
  143. package/dist/licenses/safe-buffer-5.2.1.txt +22 -0
  144. package/dist/licenses/saxes-5.0.1.txt +397 -0
  145. package/dist/licenses/setimmediate-1.0.5.txt +21 -0
  146. package/dist/licenses/string_decoder-1.1.1.txt +49 -0
  147. package/dist/licenses/string_decoder-1.3.0.txt +49 -0
  148. package/dist/licenses/tar-stream-2.2.0.txt +22 -0
  149. package/dist/licenses/tmp-0.2.7.txt +22 -0
  150. package/dist/licenses/traverse-0.3.9.txt +25 -0
  151. package/dist/licenses/tslib-1.14.1.txt +13 -0
  152. package/dist/licenses/unzipper-0.10.14.txt +26 -0
  153. package/dist/licenses/util-deprecate-1.0.2.txt +25 -0
  154. package/dist/licenses/uuid-11.1.1.txt +10 -0
  155. package/dist/licenses/wrappy-1.0.2.txt +16 -0
  156. package/dist/licenses/xmlchars-2.2.0.txt +19 -0
  157. package/dist/licenses/zip-stream-4.1.1.txt +23 -0
  158. package/dist/matrix-CGRGkn5s.js +112 -0
  159. package/dist/matrix-gEO7ZM_u.cjs +1 -0
  160. package/dist/media-B7vnpD8k.cjs +1 -0
  161. package/dist/media-Y90dHK9z.js +70 -0
  162. package/dist/param-validation-C3HlcLLO.cjs +1 -0
  163. package/dist/param-validation-Do7Eg8Zv.js +181 -0
  164. package/dist/{pdf-AyJGb22z.cjs → pdf-ByVCb1i6.cjs} +49 -49
  165. package/dist/{pdf-8UPQebOE.js → pdf-DJ5S6ukC.js} +4924 -4872
  166. package/dist/pdf.cjs +1 -1
  167. package/dist/pdf.d.cts +20 -3
  168. package/dist/pdf.d.ts +20 -3
  169. package/dist/pdf.js +2 -2
  170. package/dist/{plugin-BGKf-Tqg.js → plugin-C2j5_mhx.js} +2 -2
  171. package/dist/{plugin-CktLH_Iy.cjs → plugin-Dr39GBRG.cjs} +1 -1
  172. package/dist/prepared-DdrjLC7L.cjs +1 -0
  173. package/dist/prepared-DqtpvRTn.js +87 -0
  174. package/dist/progress-B0ctFpKf.cjs +1 -0
  175. package/dist/progress-BXzlVbIp.js +29 -0
  176. package/dist/progress-DJBd9Rb9.cjs +1 -0
  177. package/dist/progress-Hc2vxoCs.js +52 -0
  178. package/dist/protocol-BzwMP4Vw.cjs +1 -0
  179. package/dist/protocol-kt4Iy6-3.js +90 -0
  180. package/dist/record-bindings-CZWBJ1fU.js +195 -0
  181. package/dist/record-bindings-DUX1VMlR.cjs +1 -0
  182. package/dist/{region-binding-workflow-DEJbhpCv.js → region-binding-workflow-CWNvIjkV.js} +1 -1
  183. package/dist/{region-binding-workflow-BzfbxRiR.cjs → region-binding-workflow-CqSMxQ4p.cjs} +1 -1
  184. package/dist/report-encoding-worker.cjs +1 -0
  185. package/dist/report-encoding-worker.d.ts +1 -0
  186. package/dist/report-encoding-worker.js +2 -0
  187. package/dist/{report-params-B44imUd4.js → report-params-B1RzkhJj.js} +1 -1
  188. package/dist/{report-params-SJfhKgaX.cjs → report-params-WDGrA4oP.cjs} +1 -1
  189. package/dist/rich-text-layout-ALlMoYOG.cjs +3 -0
  190. package/dist/rich-text-layout-Ct5WrY1g.js +102 -0
  191. package/dist/runtime-BjKBI530.js +168 -0
  192. package/dist/runtime-CBFEPKEs.cjs +1 -0
  193. package/dist/sbom.cdx.json +3982 -0
  194. package/dist/server/node.d.cts +106 -2
  195. package/dist/server/node.d.ts +106 -2
  196. package/dist/server-node.cjs +5 -1
  197. package/dist/server-node.js +4634 -539
  198. package/dist/server.cjs +1 -1
  199. package/dist/server.d.cts +780 -5
  200. package/dist/server.d.ts +780 -5
  201. package/dist/server.js +773 -691
  202. package/dist/sha256-BshdOkCC.cjs +1 -0
  203. package/dist/sha256-DTG-Gq8i.js +157 -0
  204. package/dist/style-67OqfNed.js +73 -0
  205. package/dist/style-C22Pbv3T.cjs +1 -0
  206. package/dist/style.css +1 -1
  207. package/dist/template-bindings-C2SpvsMU.js +58 -0
  208. package/dist/template-bindings-CEtWyiLX.cjs +1 -0
  209. package/dist/template-catalog-BtR2JmCL.js +414 -0
  210. package/dist/template-catalog-C2NLdrwB.cjs +1 -0
  211. package/dist/{template-fragments-DFUpq5QM.cjs → template-fragments-BVsbxs4a.cjs} +1 -1
  212. package/dist/{template-fragments-CLkGo6To.js → template-fragments-By0aZC1D.js} +21 -21
  213. package/dist/{template-outline-B3xVkzSv.cjs → template-outline-BwRV_eRo.cjs} +1 -1
  214. package/dist/{template-outline-CFenM1PV.js → template-outline-cnWfT_LK.js} +3 -3
  215. package/dist/template-registry-C62vpv4a.cjs +1 -0
  216. package/dist/template-registry-Cw3vRTX2.js +801 -0
  217. package/dist/textwrap-BEIg2w8y.js +110 -0
  218. package/dist/textwrap-BI-yJ6Wt.cjs +4 -0
  219. package/dist/{tree-CqcQ99NM.js → tree-CjVZLRw7.js} +1 -1
  220. package/dist/vue/async.d.cts +189 -14
  221. package/dist/vue/async.d.ts +189 -14
  222. package/dist/vue/index.d.cts +246 -22
  223. package/dist/vue/index.d.ts +246 -22
  224. package/dist/vue-async.cjs +1 -1
  225. package/dist/vue-async.js +3 -3
  226. package/dist/vue.cjs +1 -1
  227. package/dist/vue.js +80 -78
  228. package/dist/{workbook-session-BfK1yHOO.js → workbook-session-BeSO8PFB.js} +5460 -5295
  229. package/dist/{workbook-session-DNa2RHNG.cjs → workbook-session-Cbts-22R.cjs} +19 -19
  230. package/dist/worker.cjs +1 -1
  231. package/dist/worker.d.cts +104 -2
  232. package/dist/worker.d.ts +104 -2
  233. package/dist/worker.js +12 -156
  234. package/dist/xlsx-node.cjs +35 -35
  235. package/dist/xlsx-node.js +2138 -2137
  236. package/dist/xlsx.cjs +4 -4
  237. package/dist/xlsx.d.cts +24 -10
  238. package/dist/xlsx.d.ts +24 -10
  239. package/dist/xlsx.js +303 -277
  240. package/package.json +7 -4
  241. package/dist/ParamEditor-CflQV3eQ.js +0 -526
  242. package/dist/ParamEditor-vIDzvpPV.cjs +0 -1
  243. package/dist/ReportPreview-CvbqLUzM.cjs +0 -6
  244. package/dist/ReportPreview-D_ywJ_-H.js +0 -4533
  245. package/dist/assets-C2U-e-Sz.cjs +0 -4
  246. package/dist/assets-Q0wUwNrV.js +0 -217
  247. package/dist/batch-DzaTNLWI.js +0 -371
  248. package/dist/batch-xMkqYiTr.cjs +0 -1
  249. package/dist/capabilities-CK_7hizc.js +0 -63
  250. package/dist/capabilities-CsZ-pNHR.cjs +0 -1
  251. package/dist/config-0UIohTS7.cjs +0 -1
  252. package/dist/config-Dt9NtCPl.js +0 -566
  253. package/dist/data-explanation-BktvER5B.cjs +0 -1
  254. package/dist/data-explanation-C_J6jYNi.js +0 -16
  255. package/dist/defaults-DXhiM1ZD.js +0 -10
  256. package/dist/defaults-xhmcLLrf.cjs +0 -1
  257. package/dist/designer-Ci1LizA9.js +0 -5020
  258. package/dist/designer-rtmVIIdN.cjs +0 -2
  259. package/dist/grid-strokes-Cr7DwUux.cjs +0 -1
  260. package/dist/grid-strokes-DyyG1q_o.js +0 -53
  261. package/dist/json-snapshot-BeFT3Tso.js +0 -1952
  262. package/dist/json-snapshot-D1NTP2oI.cjs +0 -2
  263. package/dist/matrix-DVyWiYsd.cjs +0 -1
  264. package/dist/matrix-yZsGnldA.js +0 -227
  265. package/dist/page-window-index-CIuT4BAv.js +0 -43
  266. package/dist/page-window-index-DEjnM6IB.cjs +0 -1
  267. package/dist/param-validation-BlHHXs6u.js +0 -153
  268. package/dist/param-validation-DCK039V1.cjs +0 -1
  269. package/dist/progress-7OSZbFok.js +0 -39
  270. package/dist/progress-BnLiS5eH.cjs +0 -1
  271. package/dist/render-plan-7xpGrCEl.cjs +0 -1
  272. package/dist/render-plan-Ck6koX9L.js +0 -13
  273. package/dist/style-CQ1PK8ZB.js +0 -67
  274. package/dist/style-UgIJSA1F.cjs +0 -1
  275. package/dist/task-events-DQ276fn2.cjs +0 -1
  276. package/dist/task-events-Dpsvf_t2.js +0 -47
  277. package/dist/template-bindings-BJR4k7qZ.cjs +0 -1
  278. package/dist/template-bindings-Daui7hLF.js +0 -252
  279. package/dist/template-registry-COXDEJEM.js +0 -570
  280. package/dist/template-registry-D3SjENi6.cjs +0 -1
  281. package/dist/validate-BJ5HIWY8.cjs +0 -1
  282. package/dist/validate-CkQBWCeg.js +0 -163
@@ -1 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const W=require("node:worker_threads"),j=require("node:crypto"),h=require("node:fs"),R=require("node:path");function z(e,t,r){if(!r?.aborted)try{const o=e?.({...t});o&&typeof o.then=="function"&&Promise.resolve(o).catch(()=>{})}catch{}}function H(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e,r=o=>typeof o=="string"&&o.trim().length>0&&o.length<=256;return!r(t.datasetId)||!r(t.field)||t.tableId!==void 0&&!r(t.tableId)?!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 Z(e){return e==="missing-source"||e==="not-applicable"||e==="not-calculable"}function Q(e){return e.target!==void 0&&!H(e.target)?!1:e.valueState===void 0||Z(e.valueState)&&e.target!==void 0}function V(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 G(e,t,r){V(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:"派生结果标记应为布尔值"}),F(e.source,`${t}.source`,r,!0),e.formula!==void 0&&typeof e.formula!="string"&&r.push({path:`${t}.formula`,message:"单元格公式应为字符串"})}function F(e,t,r,o=!1){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e)){r.push({path:t,message:"业务来源应为对象"});return}const n=e;for(const s of["datasetId",...o?["field"]:[]])(typeof n[s]!="string"||!n[s].trim())&&r.push({path:`${t}.${s}`,message:"业务标识应为非空字符串"});for(const s of["rowKey","revision"]){const i=n[s];i===void 0&&!(o&&s==="rowKey")||typeof i!="string"&&!(typeof i=="number"&&Number.isFinite(i))&&r.push({path:`${t}.${s}`,message:"业务键及修订号应为字符串或有限数字"})}n.sourceToken!==void 0&&typeof n.sourceToken!="string"&&r.push({path:`${t}.sourceToken`,message:"来源令牌应为字符串"})}function X(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 Y(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 ee(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return[{path:"",message:"code must be an object."}];const r=e,o=[...X(r),...Y(r,t)];for(const i of Object.keys(r))["value","symbology","errorCorrection","quietZoneModules","showText"].includes(i)||o.push({path:i,message:"Unknown symbol option."});const n=r.symbology==="ean13"||r.symbology==="ean8",s=t==="qrcode"?4:n?11:10;return r.quietZoneModules!==void 0&&(!Number.isSafeInteger(r.quietZoneModules)||Number(r.quietZoneModules)<s||Number(r.quietZoneModules)>64)&&o.push({path:"quietZoneModules",message:`Quiet zone must contain ${s}–64 whole modules.`}),o}const te=new Set(["text","image","barcode","qrcode","chart","line","rect","ellipse"]);function A(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function re(e,t,r,o){const n=e[t];(typeof n!="number"||!Number.isFinite(n))&&o.push({path:`${r}.${t}`,message:`应为有限数字,实际 ${JSON.stringify(n)}`})}function ne(e,t,r){if(e!==void 0){const o=`${t}.table`;if(!A(e))r.push({path:o,message:"逻辑表来源应为对象"});else{F(e.source,`${o}.source`,r),(typeof e.id!="string"||!e.id.trim())&&r.push({path:`${o}.id`,message:"逻辑表 ID 应为非空字符串"});const n=e.role;["header","body","group-header","subtotal","grand-total"].includes(n)||r.push({path:`${o}.role`,message:"未知逻辑表行角色"});const s=e.rowIndex;(typeof s!="number"||!Number.isInteger(s)||(n==="header"?s!==-1:s<0))&&r.push({path:`${o}.rowIndex`,message:"表头索引应为 -1,内容行索引应为非负整数"}),(!Array.isArray(e.columnKeys)||e.columnKeys.some(i=>typeof i!="string"))&&r.push({path:`${o}.columnKeys`,message:"逻辑列字段应为字符串数组"}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&r.push({path:`${o}.layout`,message:"布局应为 page 或 wide"}),e.title!==void 0&&typeof e.title!="string"&&r.push({path:`${o}.title`,message:"逻辑表名称应为字符串"})}}}function oe(e,t,r,o){if(e!==void 0)if(!A(e)||!Array.isArray(e.cells))r.push({path:`${t}.grid.cells`,message:"grid.cells 应为二维数组"});else{const n=e.paddingMm;n!==void 0&&(typeof n!="number"||!Number.isFinite(n)||n<0)&&r.push({path:`${t}.grid.paddingMm`,message:"单元格内距应为有限非负数"}),e.cells.forEach((s,i)=>{if(!Array.isArray(s)){r.push({path:`${t}.grid.cells.${i}`,message:"行应为数组"});return}s.forEach((d,y)=>{if(d==null)return;const u=`${t}.grid.cells.${i}.${y}`;if(!A(d)){r.push({path:u,message:"网格单元格应为对象或 null"});return}G(d,u,r),Array.isArray(d.children)&&d.children.forEach((b,k)=>{U(b,`${t}.grid.cells.${i}.${y}.children.${k}`,r,o)})})})}}function se(e,t,r){e!==void 0&&(Array.isArray(e)?e.forEach((o,n)=>{(!A(o)||!Array.isArray(o.segments))&&r.push({path:`${t}.richParagraphs.${n}`,message:"段落缺少 segments 数组"})}):r.push({path:`${t}.richParagraphs`,message:"richParagraphs 应为数组"}))}function U(e,t,r,o=[]){if(!A(e)){r.push({path:t,message:"组件应为对象"});return}const n=e.kind;typeof n!="string"?r.push({path:`${t}.kind`,message:"组件缺少 kind 字符串"}):te.has(n)||o.push({path:`${t}.kind`,message:`未知组件类型 ${JSON.stringify(n)},将以兜底方式渲染`});for(const s of["leftMm","topMm","widthMm","heightMm"])re(e,s,t,r);typeof e.leftMm=="number"&&e.leftMm<-100&&r.push({path:`${t}.leftMm`,message:"几何数值异常(leftMm<-100)"});for(const s of["widthMm","heightMm"])typeof e[s]=="number"&&e[s]<0&&r.push({path:`${t}.${s}`,message:"组件尺寸不能为负数"});ne(e.table,t,r),ie(e.code,n,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"}),oe(e.grid,t,r,o),se(e.richParagraphs,t,r)}function ie(e,t,r,o){if(e!==void 0)for(const n of ee(e,t))o.push({path:`${r}.code${n.path?`.${n.path}`:""}`,message:n.message})}function D(e,t,r){if(!A(e))return;e.binding!==void 0&&r.push({path:`${t}.binding`,message:"渲染计划不允许未解析字段绑定"});const o=e.grid;!A(o)||!Array.isArray(o.cells)||o.cells.forEach((n,s)=>{Array.isArray(n)&&n.forEach((i,d)=>{!A(i)||!Array.isArray(i.children)||i.children.forEach((y,u)=>D(y,`${t}.grid.cells.${s}.${d}.children.${u}`,r))})})}function ae(e,t,r,o=[]){if(!A(e)){r.push({path:t,message:"页应为对象"});return}const n=e.pageWidthMm,s=e.pageHeightMm;(typeof n!="number"||!Number.isFinite(n)||n<=0)&&r.push({path:`${t}.pageWidthMm`,message:`页宽非法: ${JSON.stringify(n)}`}),(typeof s!="number"||!(s>0&&s<5e3))&&r.push({path:`${t}.pageHeightMm`,message:`页高非法: ${JSON.stringify(s)}`}),e.layout!==void 0&&e.layout!=="page"&&e.layout!=="wide"&&r.push({path:`${t}.layout`,message:"布局应为 page 或 wide"});const i=e.components;Array.isArray(i)?Array.isArray(i)&&i.forEach((d,y)=>{U(d,`${t}.components.${y}`,r,o),D(d,`${t}.components.${y}`,r)}):r.push({path:`${t}.components`,message:"components 应为数组"})}function ce(e){const t=[],r=[],o=A(e)?e.pages:void 0;if(A(e)&&e.requiresRecalculation!==void 0&&typeof e.requiresRecalculation!="boolean"&&t.push({path:"$.requiresRecalculation",message:"重算能力要求应为布尔值"}),!Array.isArray(o))t.push({path:"$.pages",message:e==null?"渲染计划为空":"渲染计划缺少 pages 数组"});else{o.forEach((s,i)=>ae(s,`$.pages.${i}`,t,r)),o.length>2e3&&r.push({path:"$.pages",message:`页数异常大(${o.length} 页),渲染与打印耗时可能显著增加`});const n=o.reduce((s,i)=>s+(A(i)&&Array.isArray(i.components)?i.components.length:0),0);n>5e4&&r.push({path:"$.pages",message:`组件总数异常大(${n} 个),可能触发浏览器性能限制`})}return{ok:t.length===0,errors:t,warnings:r}}const M="mach-report-worker/1";class J 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 v(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function fe(e){return v(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 ue(e){return Array.isArray(e)&&e.every(t=>v(t)&&typeof t.code=="string"&&typeof t.message=="string"&&["info","warning","error"].includes(t.severity)&&Q(t))}function pe(e){return v(e)&&Object.values(e).every(t=>v(t)&&(t.revision===void 0||typeof t.revision=="string")&&(t.sourceToken===void 0||typeof t.sourceToken=="string"))}function de(e){return e===void 0?!0:v(e)&&["heuristic","provided","font-bytes"].includes(e.textMetrics)&&(e.fontFingerprint===void 0||typeof e.fontFingerprint=="string"&&/^[a-f0-9]{64}$/.test(e.fontFingerprint))}function me(e,t){if(!v(e)||!fe(e.stats)||!ue(e.diagnostics)||!pe(e.revisions)||!de(e.layout))return!1;if(t==="prepare")return ce(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 C(e){if(!e||typeof e!="object")return{message:String(e)};const t={};for(const r of["code","path","field","message"]){const o=e[r];typeof o=="string"&&(t[r]=o)}return t}function ye(e){const t=C(e);if(!v(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 le(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(C)}:{},...Array.isArray(t.diagnostics)?{diagnostics:t.diagnostics.map(ye)}:{}}}function he(e){if(!e||typeof e!="object")return!1;const t=e;return t.protocol===M&&typeof t.id=="string"&&(t.operation==="prepare"||t.operation==="export"||t.operation==="exportPrepared")&&!!t.input&&typeof t.input=="object"}async function ge(e,t,r){try{const o=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:M,id:t.id,result:o}}catch(o){return{protocol:M,id:t.id,error:le(o)}}}function we(e){const t=e.result;return!t||!("bytes"in t)||!(t.bytes.buffer instanceof ArrayBuffer)?[]:[t.bytes.buffer]}function be(e,t){if(!v(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}let Ae=0;function P(e){const t=new Error("报表 Worker 任务已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e}),t}function xe(e,t){if(!e||typeof e!="object")return;const r=e;return r.protocol===M&&r.id===t?r:void 0}function $e(e,t={}){const r=t.timeoutMs??12e4;if(!Number.isFinite(r)||r<=0||r>2147483647)throw new RangeError("Worker timeoutMs 应为正有限数字,且不能超过 2147483647");const o=(n,s,i,d)=>i?.aborted?Promise.reject(P(i.reason)):new Promise((y,u)=>{let b;try{b=e()}catch(l){u(l);return}const k=`mach-report-${Date.now()}-${++Ae}`;let p=!1,f=()=>{},c;const m=(l,w)=>{p||(p=!0,c&&clearTimeout(c),f(),i?.removeEventListener("abort",g),Promise.resolve().then(()=>b.terminate()).then(()=>l===void 0?y(w):u(l),N=>u(l??N)))},g=()=>m(P(i?.reason)),x=l=>{const w=xe(l,k);if(!(!w||p)){if("type"in w&&w.type==="event"){const N="event"in w?w.event:void 0;be(N,s)?z(d,N,i):m(new Error("报表 Worker 返回无效阶段事件"));return}w.error&&typeof w.error.name=="string"&&typeof w.error.message=="string"?m(new J(w.error)):me(w.result,n)&&(n==="prepare"||"format"in w.result&&"format"in s&&w.result.format===s.format)?m(void 0,w.result):m(new Error("报表 Worker 返回无效响应"))}};try{if(f=b.subscribe(x,l=>m(l??new Error("报表 Worker 执行失败"))),p){f();return}if(i?.addEventListener("abort",g,{once:!0}),c=setTimeout(()=>m(new J({name:"ReportRuntimeError",code:"timeout",message:`报表 Worker 执行超过 ${r}ms`})),r),i?.aborted)g();else{const{onEvent:l,signal:w,...N}=s;b.postMessage({protocol:M,id:k,operation:n,input:N})}}catch(l){m(l)}});return{exportPrepared:(n,s,i)=>o("exportPrepared",n,s,i),prepare:(n,s,i)=>o("prepare",n,s,i),export:(n,s,i)=>o("export",n,s,i)}}const ke=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]),$=(e,t)=>e>>>t|e<<32-t;function Ne(e,t,r){const o=new DataView(e.buffer,e.byteOffset+t,64);for(let n=0;n<16;n++)r[n]=o.getUint32(n*4);for(let n=16;n<64;n++){const s=r[n-15],i=r[n-2],d=$(s,7)^$(s,18)^s>>>3,y=$(i,17)^$(i,19)^i>>>10;r[n]=r[n-16]+d+r[n-7]+y}}function Se(e,t){let r=e[0],o=e[1],n=e[2],s=e[3],i=e[4],d=e[5],y=e[6],u=e[7];for(let b=0;b<64;b++){const k=$(i,6)^$(i,11)^$(i,25),p=i&d^~i&y,f=u+k+p+ke[b]+t[b]>>>0,c=$(r,2)^$(r,13)^$(r,22),m=r&o^r&n^o&n,g=c+m>>>0;u=y,y=d,d=i,i=s+f>>>0,s=n,n=o,o=r,r=f+g>>>0}e[0]=e[0]+r,e[1]=e[1]+o,e[2]=e[2]+n,e[3]=e[3]+s,e[4]=e[4]+i,e[5]=e[5]+d,e[6]=e[6]+y,e[7]=e[7]+u}function Re(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 ve=()=>new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Me=e=>Array.from(e,t=>t.toString(16).padStart(8,"0")).join("");async function Ee(e){const t=Re(e),r=ve(),o=new Uint32Array(64);for(let n=0;n<t.length;n+=64)n>0&&n%262144===0&&await new Promise(s=>setTimeout(s,0)),Ne(t,n,o),Se(r,o);return Me(r)}class a extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportJobError"}}function T(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 a("input","任务范围应非空,ID应为1–128位安全标识")}function Ie(e){const t=Array.isArray(e),r=Object.getPrototypeOf(e),o=Object.keys(e);if(r!==(t?Array.prototype:Object.prototype)&&!(r===null&&!t))throw new a("input","任务对象应为普通 JSON 对象");if(Object.getOwnPropertySymbols(e).length)throw new a("input","任务不能包含Symbol");if(Object.getOwnPropertyNames(e).filter(s=>!(t&&s==="length")).length!==o.length)throw new a("input","任务不能包含不可枚举属性");if(t&&(o.length!==e.length||o.some(s=>s!==String(Number(s))||!Number.isSafeInteger(Number(s))||Number(s)<0||Number(s)>=e.length)))throw new a("input","任务数组不能稀疏或包含额外属性");return o.sort()}function Oe(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(["__proto__","prototype","constructor"].includes(t)||r.get||r.set)throw new a("input","任务不能包含危险键或访问器");return r.value}function S(e,t={}){const r=t.maxNodes??2e4,o=t.maxCharacters??1e6;if(!Number.isSafeInteger(r)||r<1||r>2e4||!Number.isSafeInteger(o)||o<1||o>1e6)throw new a("input","任务JSON预算无效");let n=0,s=0;const i=new Set;function d(u,b){if(++n>r||b>32)throw new a("input","任务数据超过节点或深度预算");if(typeof u=="string"){if(s+=u.length,s>o)throw new a("input","任务文本超过预算");return u}if(u===null||typeof u=="boolean"||typeof u=="number"&&Number.isFinite(u))return u;if(!u||typeof u!="object"||i.has(u))throw new a("input","任务只允许无循环的有限 JSON 值");const k=Array.isArray(u),p=Ie(u);i.add(u);const f=Object.create(null);for(const c of p){if(s+=c.length,s>o)throw new a("input","任务文本超过预算");f[c]=d(Oe(u,c),b+1)}return i.delete(u),k?Array.from({length:u.length},(c,m)=>f[String(m)]):f}const y=JSON.stringify(d(e,0));if(y.length>o)throw new a("input","任务序列化数据超过字符预算");return y}function q(e){return JSON.parse(JSON.stringify(e))}function _(e,t,r,o){if(T(t,r),e.scope!==t||e.id!==r||e.revision!==(o??0)+1||!Number.isSafeInteger(e.revision))throw new a("input","任务身份或修订不匹配");if(![e.createdAt,e.updatedAt,e.attempt].every(n=>Number.isSafeInteger(n)&&n>=0)||!["queued","running","completed","failed","cancelled"].includes(e.status))throw new a("input","任务状态无效");if(e.lease&&(!e.lease.owner||!Number.isSafeInteger(e.lease.expiresAt)))throw new a("input","任务租约无效");if(!e.request||typeof e.request.kind!="string"||!e.request.kind.trim()||e.request.kind.length>128)throw new a("input","任务类型无效");S(e.request.payload,{maxNodes:19e3,maxCharacters:75e4}),S(e)}function Te(e,t){if(e&&(e.createdAt!==t.createdAt||S(e.request)!==S(t.request)))throw new a("input","任务创建时间与请求不可变更,请使用新任务ID")}function je(e,t){return e.status==="queued"||e.status==="running"&&(e.lease?.expiresAt??0)<=t}function qe(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 a("input","任务容量应为正整数,控制状态预留至少4096字节");return t}function E(e){return new TextEncoder().encode(S(e)).byteLength}function K(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},o={...e};delete o.result;const n=e.result===void 0?0:E(e.result);if(n>t.maxResultBytes)throw new a("capacity","任务结果超过独立预算,请保存文件引用");return Math.max(E(r)+t.controlReserveBytes,E(o))+n}function L(e){return e.status!=="queued"&&e.status!=="running"}function Je(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 a("input","终态清理时间应为不超过当前时间的非负整数");if(![t.tombstoneRetentionMs,t.limit].every(r=>Number.isSafeInteger(r)&&r>0)||!Number.isSafeInteger(t.now+t.tombstoneRetentionMs))throw new a("input","幂等保留期与清理批量应为正整数");return t}async function Be(e){const t=new TextEncoder().encode(S(e)),r=globalThis.crypto?.subtle;if(!r)return Ee(t);const o=await r.digest("SHA-256",t);return Array.from(new Uint8Array(o),n=>n.toString(16).padStart(2,"0")).join("")}async function Pe(e,t){if(!L(e))throw new a("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 Be(e.request),expiresAt:t}}function We(e){if(!e||!["completed","failed","cancelled"].includes(e.status)||!/^[a-f0-9]{64}$/.test(e.requestHash))throw new a("input","任务幂等摘要无效");if(![e.revision,e.createdAt,e.updatedAt,e.attempt,e.expiresAt].every(t=>Number.isSafeInteger(t)&&t>=0)||e.revision<1)throw new a("input","任务幂等摘要时间或修订无效")}function O(e){return e?.code}function I(e,t){return j.createHash("sha256").update(JSON.stringify([e,t])).digest("hex")+".json"}async function B(e){try{return await h.promises.readFile(e,"utf8")}catch(t){if(O(t)==="ENOENT")return;throw t}}async function Fe(e,t){const r=await B(e);if(r===void 0)return;let o;try{o=JSON.parse(r)}catch{throw new a("conflict","任务锁尚未完整写入或已损坏,拒绝自动移除")}if(!o||!Number.isSafeInteger(o.pid)||o.pid<1)throw new a("conflict","任务锁身份无效,拒绝自动移除");try{process.kill(o.pid,0)}catch(n){if(O(n)==="ESRCH"){await h.promises.unlink(e);return}throw n}throw new a("conflict","任务目录的写入进程仍在运行")}async function Ue(e,t){if(!t)throw new a("conflict","任务目录已有写入进程;多实例请使用数据库CAS适配器");const r=e+".recovery";let o;try{o=await h.promises.open(r,"wx",384)}catch(n){throw O(n)==="EEXIST"?new a("conflict","任务目录恢复正在进行,请稍后重试"):n}try{return await o.writeFile(JSON.stringify({pid:process.pid})),await Fe(e,!0),await h.promises.open(e,"wx",384)}finally{await o.close(),await h.promises.unlink(r)}}async function De(e,t){const r=R.join(e,".writer-lock"),o=j.randomUUID();let n;try{n=await h.promises.open(r,"wx",384)}catch(s){if(O(s)!=="EEXIST")throw s;n=await Ue(r,t)}try{await n.writeFile(JSON.stringify({pid:process.pid,token:o})),await n.sync()}catch(s){throw await n.close(),await h.promises.unlink(r).catch(()=>{}),s}return{file:r,token:o,handle:n}}function Ce(e,t,r,o){if("tombstone"in r){const n=r.tombstone;if(We(n),T(n.scope,n.id),I(n.scope,n.id)!==t)throw new a("input","持久任务摘要身份不匹配");const s=E(n);e.tombstoneBytes+=s,e.tombstones.set(t,{value:n,bytes:s})}else{if(_(r,r.scope,r.id,r.revision-1),I(r.scope,r.id)!==t)throw new a("input","持久任务文件身份不匹配");const n=K(r,o);e.bytes+=n,e.records.set(t,{record:r,bytes:n})}if(e.bytes>o.maxBytes||e.records.size>o.maxRecords||e.tombstoneBytes>o.maxTombstoneBytes||e.tombstones.size>o.maxTombstones)throw new a("capacity","持久任务及控制状态预留超过目录预算")}async function _e(e,t){const r=await h.promises.readdir(e);for(const s of r.filter(i=>/^\.pending-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(i)))await h.promises.unlink(R.join(e,s));const o=r.filter(s=>/^[a-f0-9]{64}\.json$/.test(s));if(o.length>t.maxRecords+t.maxTombstones)throw new a("capacity","持久任务数量超过目录预算");const n={records:new Map,tombstones:new Map,bytes:0,tombstoneBytes:0};for(const s of o){const i=R.join(e,s);if((await h.promises.stat(i)).size>4e6)throw new a("capacity","持久任务文件超过单文件预算");Ce(n,s,JSON.parse(await h.promises.readFile(i,"utf8")),t)}return n}async function Ke(e,t,r){const o=R.join(e,`.pending-${j.randomUUID()}`);try{const n=await h.promises.open(o,"wx",384);try{await n.writeFile(r),await n.sync()}finally{await n.close()}await h.promises.rename(o,R.join(e,t));const s=await h.promises.open(e,"r");try{await s.sync()}finally{await s.close()}}finally{await h.promises.unlink(o).catch(n=>{if(O(n)!=="ENOENT")throw n})}}async function Le(e){const t=R.resolve(e.directory),r=qe(e);await h.promises.mkdir(t,{recursive:!0,mode:448});const o=await De(t,e.recoverDeadOwner??!1);let n;try{n=await _e(t,r)}catch(p){throw await o.handle.close(),await h.promises.unlink(o.file),p}let s=!1,i=Promise.resolve();const d=()=>{if(s)throw new a("closed","持久任务存储已关闭")},y=p=>{d();const f=i.then(async()=>{if(JSON.parse(await h.promises.readFile(o.file,"utf8")).token!==o.token)throw new a("closed","持久任务存储写入锁已失效");return p()});return i=f.then(()=>{},()=>{}),f},u=async(p,f,c)=>{try{await Ke(t,p,f)}catch(m){throw await B(R.join(t,p))===f&&c(),m}c()};return{read:async(p,f)=>{d(),T(p,f),await i;const c=n.records.get(I(p,f));return c?q(c.record):void 0},readTombstone:async(p,f)=>{d(),T(p,f),await i;const c=n.tombstones.get(I(p,f));return c?q(c.value):void 0},candidates:async(p,f)=>(d(),await i,Array.from(n.records.values(),c=>c.record).filter(c=>je(c,p)).sort((c,m)=>c.createdAt-m.createdAt).slice(0,f).map(q)),compareAndSwap:async(p,f,c,m)=>{const g=JSON.parse(S(m));return _(g,p,f,c),y(async()=>{const x=I(p,f),l=n.records.get(x);if((l?.record.revision??null)!==c||n.tombstones.has(x))return!1;Te(l?.record,g);const w=K(g,r),N=n.bytes-(l?.bytes??0)+w;if(N>r.maxBytes||!l&&n.records.size>=r.maxRecords)throw new a("capacity","持久任务容量已满,请清理终态任务或扩大显式预算");return await u(x,S(g),()=>{n.records.set(x,{record:g,bytes:w}),n.bytes=N}),!0})},prune:async p=>{const f=Je(p);return y(async()=>{const c={archived:0,expired:0};for(const[m,g]of n.tombstones)g.value.expiresAt>f.now||c.expired>=f.limit||(await h.promises.unlink(R.join(t,m)),n.tombstones.delete(m),n.tombstoneBytes-=g.bytes,c.expired++);for(const[m,g]of n.records){if(!L(g.record)||g.record.updatedAt>f.terminalBefore||c.archived+c.expired>=f.limit)continue;const x=await Pe(g.record,f.now+f.tombstoneRetentionMs),l=E(x);if(n.tombstones.size>=r.maxTombstones||n.tombstoneBytes+l>r.maxTombstoneBytes)break;await u(m,S({tombstone:x}),()=>{n.tombstones.set(m,{value:x,bytes:l}),n.tombstoneBytes+=l,n.records.delete(m),n.bytes-=g.bytes}),c.archived++}if(c.expired){const m=await h.promises.open(t,"r");try{await m.sync()}finally{await m.close()}}return c})},close:async()=>{if(s)return;s=!0,await i,await o.handle.close();const p=await B(o.file);p&&JSON.parse(p).token===o.token&&await h.promises.unlink(o.file)}}}function ze(e){const t=e.filename??e.workerUrl;if(!t||e.filename&&e.workerUrl)throw new TypeError("请且仅请指定 filename 或 workerUrl");return $e(()=>{const r=new W.Worker(t,e.workerOptions);return{postMessage:o=>r.postMessage(o),terminate:()=>r.terminate(),subscribe:(o,n)=>{const s=i=>n(new Error(`报表 Worker 在响应前退出(code ${i})`));return r.on("message",o),r.on("error",n),r.on("messageerror",n),r.on("exit",s),()=>{r.off("message",o),r.off("error",n),r.off("messageerror",n),r.off("exit",s)}}}},e)}function He(e){const t=W.parentPort;if(!t)throw new Error("serveNodeReportWorker 只能在 worker_threads 中调用");const r=o=>{he(o)&&ge(e,o,n=>t.postMessage({protocol:M,id:o.id,type:"event",event:n})).then(n=>t.postMessage(n,we(n)))};return t.on("message",r),()=>t.off("message",r)}function Ze(e){return j.createHash("sha256").update(e).digest("hex")}exports.ReportWorkerError=J;exports.createNodeReportExecutor=ze;exports.openFileReportJobStore=Le;exports.reportArtifactSha256=Ze;exports.serveNodeReportWorker=He;
1
+ "use strict";var Eo=Object.create;var gr=Object.defineProperty;var ko=Object.getOwnPropertyDescriptor;var Po=Object.getOwnPropertyNames;var No=Object.getPrototypeOf,Io=Object.prototype.hasOwnProperty;var Fo=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Po(t))!Io.call(e,o)&&o!==r&&gr(e,o,{get:()=>t[o],enumerable:!(n=ko(t,o))||n.enumerable});return e};var Fe=(e,t,r)=>(r=e!=null?Eo(No(e)):{},Fo(t||!e||!e.__esModule?gr(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ne=require("./progress-DJBd9Rb9.cjs"),pe=require("node:worker_threads"),Xe=require("node:crypto"),F=require("node:fs"),X=require("node:path");var ht=typeof document<"u"?document.currentScript:null;const Bt=1.35,_t=10.5,jr='"Microsoft YaHei", sans-serif',Ro="1.0.0-mach",Ne=Ro,Lr=/[\u3000-\u9fff\uff00-\uffef]/,se=new Uint8Array(128);{for(const e of"iljtf.,:;'`|!()[]")se[e.charCodeAt(0)]=1;for(const e of"mwMW@")se[e.charCodeAt(0)]=2;for(let e=48;e<=57;e++)se[e]=3;for(let e=65;e<=90;e++)se[e]=4;se[32]=5}const To=[.54,.26,.95,.59,.67,.3];function Oo(e){const t=e.charCodeAt(0);return t<128?To[se[t]]:Lr.test(e)?1:/[A-Z]/.test(e)?.67:.54}const Kt={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+=Oo(a);return n&&(s*=1.04),(s*r+o*Math.max(0,Array.from(e).length-1))*i}};function Co(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
+ `){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(Lr.test(s)){i(),n.push({text:s,widthMm:r.measureMm(s,t),cjk:!0});continue}o+=s}return i(),n}function Qe(e,t,r,n=Kt){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 Co(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 l of u.text)n.measureMm(i+l,r)>t&&i.length>0&&c(),i+=l,s=n.measureMm(i,r)}return c(),o}const De=1e3;function ie(e){if(!Number.isSafeInteger(e)||e<0||e>De*2)throw new Error("十进制精度超出预算");return 10n**BigInt(e)}function et(e){if(e.coefficient.toString().length>De*2||e.scale>De*2)throw new Error("十进制结果超出精度预算");return e}function z(e){if(typeof e!="string"&&!(typeof e=="number"&&Number.isFinite(e)))throw new Error("十进制参数必须是有限数字或十进制文本");const t=String(e);if(t.length>De)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 et(i<0?{coefficient:s*ie(-i),scale:0}:{coefficient:s,scale:i})}function Dr(e,t){const r=Math.max(e.scale,t.scale);return[e.coefficient*ie(r-e.scale),t.coefficient*ie(r-t.scale),r]}function xt(e,t){const[r,n]=Dr(e,t);return r<n?-1:r>n?1:0}function Be(e,t){const[r,n,o]=Dr(e,t);return et({coefficient:r+n,scale:o})}function Wt(e,t){return et({coefficient:e.coefficient*t.coefficient,scale:e.scale+t.scale})}function Br(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 tt(e){if(!Number.isInteger(e)||e<0||e>100)throw new Error("十进制小数位应为 0–100 的整数")}function vt(e,t,r=20){if(tt(r),t.coefficient===0n)throw new Error("不能除以零");const n=t.scale-e.scale+r,o=e.coefficient*ie(Math.max(0,n)),i=t.coefficient*ie(Math.max(0,-n));return et({coefficient:Br(o,i),scale:r})}function Ht(e,t){let r=e.coefficient,n=e.scale;t!==void 0&&(tt(t),r=t>=n?r*ie(t-n):Br(r,ie(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 hr(e,t,r=!1,n=!1){let o=z(e);n&&(o=Wt(o,{coefficient:100n,scale:0}));const[i,s]=Ht(o,t).split(".");return`${r?i.replace(/\B(?=(\d{3})+(?!\d))/g,","):i}${s===void 0?"":`.${s}`}${n?"%":""}`}function _r(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 jo(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 Mt(e,t){return e.toLocaleString("en-US",{minimumFractionDigits:t,maximumFractionDigits:t})}function Lo(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 Do(e,t,r){return r!=null?t?Mt(e,r):e.toFixed(r):t?Mt(e):String(e)}function pr(e){const t=typeof e=="number"?e:Number(String(e).replace(/,/g,""));return Number.isFinite(t)?t:null}function Jt(e,t){if(e==null||e===""||!t)return String(e??"");switch(t.kind){case"number":{if(typeof e=="string")try{return hr(e,t.digits,t.thousands===!0)}catch{return e}const r=pr(e);return r==null?String(e):Do(r,t.thousands===!0,t.digits)}case"percent":{if(typeof e=="string")try{return hr(e,t.digits??2,!0,!0)}catch{return e}const r=pr(e);return r==null?String(e):`${Mt(r*100,t.digits??2)}%`}case"date":{const r=t.pattern??"YYYY-MM-DD",n=e instanceof Date?e:jo(String(e));return n?Lo(n,r):String(e)}default:return String(e)}}function ye(e,t){const r=e[t.field];if(r==null||r==="")return!1;if(typeof t.value=="number"||t.numeric!==void 0){let i;try{i=xt(z(r),z(t.value))}catch{return!1}if(!Number.isFinite(i))return!1;switch(t.op){case">":return i>0;case">=":return i>=0;case"<":return i<0;case"<=":return i<=0;case"==":return i===0;case"!=":return i!==0}}const n=String(r),o=String(t.value);switch(t.op){case"==":return n===o;case"!=":return n!==o;case">":return n>o;case">=":return n>=o;case"<":return n<o;case"<=":return n<=o}return!1}const Bo=["sum","count","avg","min","max","weightedAvg"];function yr(e){if(typeof e!="number"||!Number.isFinite(e))throw new Error("聚合度量必须是有限数字,不能隐式转换;小数文本请显式选择 decimal");return e}function _e(e,t){return t&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function _o(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=_e(c,e.field);if(e.op==="count"){(!e.field||u!=null)&&t++;return}if(u==null)return;const f=yr(u),l=e.op==="weightedAvg"?_e(c,e.weightField):1;if(l==null)return;const d=yr(l);if(e.op==="weightedAvg"&&d<0)throw new Error("加权平均的权重不能为负数");["sum","avg","weightedAvg"].includes(e.op)&&a(f*d),o+=d,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 Ko(e){let t=0,r=z("0"),n=z("0"),o,i;return{add(s){const a=_e(s,e.field);if(e.op==="count"){(!e.field||a!=null)&&t++;return}if(a==null)return;const c=e.op==="weightedAvg"?_e(s,e.weightField):"1";if(c==null)return;const u=z(a),f=z(c);if(e.op==="weightedAvg"&&f.coefficient<0n)throw new Error("加权平均的权重不能为负数");["sum","avg","weightedAvg"].includes(e.op)&&(r=Be(r,Wt(u,f))),e.op==="weightedAvg"&&(n=Be(n,f)),(!o||xt(u,o)<0)&&(o=u),(!i||xt(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=vt(r,z(t),e.digits)),e.op==="weightedAvg"&&(s=vt(r,n,e.digits)),Ht(s,e.digits)}}}function ge(e){if(e.digits!==void 0&&tt(e.digits),e.numeric!==void 0&&e.numeric!=="number"&&e.numeric!=="decimal")throw new Error("未知聚合数值模式");if(!Bo.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"?Ko(e):_o(e)}function St(e,t){const r=ge(t);for(const n of e)r.add(n);return r.value()}const Wo=new Set(["__proto__","prototype","constructor"]);function de(e){if(typeof e!="string"||!e.trim()||Wo.has(e))throw new Error("计算字段应为安全的非空字段名")}function zt(e){return e===null||["string","boolean"].includes(typeof e)||typeof e=="number"&&Number.isFinite(e)}function Ho(e){if(e.some(t=>typeof t!="number"||!Number.isFinite(t)))throw new Error("算术参数必须是有限数字;空值和小数文本不会隐式转换");return e}function Jo(e,t){const r=Ho(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 zo(e,t,r){const n=t.map(z);let o;return e==="add"?o=n.reduce(Be):e==="multiply"?o=n.reduce(Wt):e==="subtract"?o=Be(n[0],{...n[1],coefficient:-n[1].coefficient}):o=vt(n[0],n[1],r),Ht(o,r)}function Vo(e,t,r){return r.nulls!=="error"&&t.some(n=>n==null)||e==="divide"&&r.divisionByZero==="null"&&(r.numeric==="decimal"?z(t[1]).coefficient===0n:t[1]===0)?null:r.numeric==="decimal"?zo(e,t,r.digits):Jo(e,t)}function Uo(e,t){e.field!==void 0&&de(e.field),e.weightField!==void 0&&de(e.weightField);const r={op:e.aggregate,field:e.field,weightField:e.weightField,numeric:t.numeric,digits:t.digits};St([],r);const n=new WeakMap;return o=>{let i=n.get(o.rows);if(!i){try{i={value:St(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 Go(e,t){for(const r of e){const n=r(t);if(n!=null)return n}return null}function Vt(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 Uo(e,t);if("field"in e){de(e.field);const o=e.field;return({row:i})=>Object.prototype.hasOwnProperty.call(i,o)?i[o]:void 0}if("value"in e){if(!zt(e.value))throw new Error("常量应为有限 JSON 标量");return()=>e.value}return qo(e,t,r,n)}function qo(e,t,r,n){if(!["add","subtract","multiply","divide","coalesce"].includes(e.op)||!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<2||["subtract","divide"].includes(e.op)&&e.args.length!==2)throw new Error("运算参数数量不正确");const o=e.args.map(i=>Vt(i,t,r,n+1));return e.op==="coalesce"?i=>Go(o,i):i=>Vo(e.op,o.map(s=>s(i)),t)}function Yo(e){Vt(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)};return r(e),[...t]}function Zo(e){if(de(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&&tt(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 字段");Xo(e)}function Xo(e){if(e.groupBy!==void 0){if(!Array.isArray(e.groupBy)||e.groupBy.length>16)throw new Error("计算分组最多 16 级");e.groupBy.forEach(de)}if(e.dependsOn!==void 0){if(!Array.isArray(e.dependsOn)||e.dependsOn.length>2048)throw new Error("计算依赖超出预算");e.dependsOn.forEach(de)}}function Kr(e){return[...new Set([...typeof e.expression=="string"?e.dependsOn??[]:Yo(e.expression),...e.groupBy??[]])]}function Wr(e){if(!Array.isArray(e)||e.length>2048)throw new Error("计算字段应为数组且最多2048项");const t=new Map;for(const s of e){if(Zo(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 Kr(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 Qo(e){try{const t=Wr(e);return{valid:!0,errors:[],order:t.map(r=>r.field),fields:e.map(r=>({field:r.field,dependencies:Kr(r),scope:r.scope??"row"}))}}catch(t){return{valid:!1,errors:[t instanceof Error?t.message:String(t)],fields:[],order:[]}}}function ei(e){return Wr(e.fields).map(t=>{if(typeof t.expression!="string")return{definition:t,read:Vt(t.expression,t)};if(!e.formula)throw new Error("字符串公式需要显式配置 formula adapter");const r=t.expression;return{definition:t,read:n=>e.formula.evaluate(r,n)}})}function ti(e,t){return JSON.stringify(t.map(r=>{const n=Object.prototype.hasOwnProperty.call(e,r)?e[r]:null;if(n!=null&&!zt(n))throw new Error("分组字段应为有限 JSON 标量");return[typeof n,n??null]}))}function ri(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=ti(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 ni(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 wr(e){if(e?.aborted){const t=new Error("数据计算已取消");throw t.name="AbortError",t}}function oi(e,t,r,n,o,i){try{const s=e.read({row:t,rowIndex:r,rows:n});if(s!==void 0&&!zt(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 Ut(e,t){ni(e,t),wr(t.signal);const r=ei(t),n=[],o=e.map((i,s)=>{if(!i||typeof i!="object"||Array.isArray(i))throw new Error(`第 ${s+1} 行应为对象`);return{...i}});for(const i of r){const s=ri(o,i.definition);o.forEach((a,c)=>{wr(t.signal),oi(i,a,c,s(a),t,n)})}return{rows:o,issues:n}}function ii(e,t){const r=()=>t.measures.map(c=>ge(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 l=n.get(u.key);l||(l={label:u.label,cells:new Map,...t.totals?{totals:r()}:{}},n.set(u.key,l)),t.check(n.size,o.size);let d=l.cells.get(f.key);if(d||(d=r(),l.cells.set(f.key,d)),a(d,c),!t.totals)continue;let m=i.get(f.key);m||(m=r(),i.set(f.key,m)),a(l.totals,c),a(m,c),a(s,c)}return{groups:n,columns:o,columnTotals:i,totals:s}}function Ke(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 si(e){for(const t of["maxRows","maxColumns","maxInputRows","maxCells"])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 Hr(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(si(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(ge({...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("矩阵度量字段应非空")}function Jr(e,t){if(Hr(t),!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(Ke(s,t.rowFields).key),n.add(Ke(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 ai(e,t){Jr(e,t);const r=ii(e,{row:s=>Ke(s,t.rowFields),column:s=>Ke(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],l)=>({key:u,label:f,field:`c${l}_${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 l=0;for(const d of r.groups.values())n[l++][u.field]=(f?d.totals?.[a]:d.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}}class zr extends Error{constructor(t){super(`树节点超出行数预算 ${t}`),this.limit=t,this.code="tree-row-limit",this.name="TreeRowLimitError"}}function pt(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 Gt(e){return{rows:pt(e.maxRows,1e5,1e6,"树行数预算"),depth:pt(e.maxDepth,64,256,"树深度预算"),visits:pt(e.maxAggregationVisits,1e6,1e7,"树聚合访问预算")}}function Vr(e){return typeof e=="string"&&!!e.trim()}function ae(e){return Vr(e)&&!["__proto__","prototype","constructor"].includes(e)}function Ur(e){if(Vr(e)||typeof e=="number"&&Number.isFinite(e))return e;throw new Error("树节点业务键应为非空字符串或有限数字")}function Gr(e){return JSON.stringify([typeof e,e])}function qr(e){return[e.idField,...e.input==="flat"?[e.parentField??""]:[e.childrenField??"children"]]}function qt(e,t){const r=qr(e);if(t?.some(n=>n.scope&&n.scope!=="row"||r.includes(n.field)))throw new Error("树形布局仅支持不覆盖结构键的当前行计算")}function le(e){if(!e?.aborted)return;const t=new Error("树报表处理已取消");throw t.name="AbortError",t}function ci(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||!ae(n.field)||r.has(n.field))throw new Error("树聚合输出字段应安全、非空且唯一");for(const o of[n.valueField,n.weightField])if(o!==void 0&&!ae(o))throw new Error("树聚合来源字段应安全且非空");if([...qr(e),e.labelField].includes(n.field))throw new Error("树聚合不能覆盖结构键或标签字段");r.add(n.field),ge({...n,field:n.valueField??n.field})}}function ui(e){if(!ae(e.idField)||!ae(e.labelField))throw new Error("树需要安全的业务键和标签字段");if(e.input==="flat"&&(!ae(e.parentField)||e.parentField===e.idField))throw new Error("扁平树需要独立的父键字段");if(e.childrenField!==void 0&&!ae(e.childrenField))throw new Error("子节点字段应安全且非空");if(e.input==="nested"&&[e.idField,e.labelField].includes(e.childrenField??"children"))throw new Error("子节点字段不能覆盖业务键或标签字段")}function Yr(e){if(!e||typeof e!="object"||!["flat","nested"].includes(e.input))throw new Error("树输入应为 flat 或 nested");if(ui(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");Gt(e),ci(e)}function Zr(e,t,r,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("树节点应为对象");if(r.size>=n.rows)throw new zr(n.rows);const o=Ur(e[t.idField]),i=Gr(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 fi(e,t,r,n,o){for(const s of e)le(o),Zr(s,t,r,n);const i=[];for(const s of r.values()){le(o);const a=s.row[t.parentField];if(a==null){i.push(s);continue}const c=r.get(Gr(Ur(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 di(e,t,r,n,o){const i=[],s=[{rows:e,next:0}];for(;s.length;){le(o);const a=s[s.length-1];if(a.next>=a.rows.length){s.pop();continue}const c=Zr(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 li(e,t,r,n){const o=[],i=[{nodes:e,next:0}];for(;i.length;){le(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 mi(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=>ge({...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(le(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 Xr(e,t,r){if(Yr(t),le(r),!Array.isArray(e))throw new Error("树数据应为节点数组");const n=Gt(t),o=new Map,i=t.input==="flat"?fi(e,t,o,n,r):di(e,t,o,n,r);return li(i,o.size,n,r)}function Qr(e,t,r){return Xr(e,t,r).map(n=>n.original)}function gi(e,t,r={}){const n=Xr(e,t,r.signal);if(qt(t,r.computed?.fields),r.computed?.fields.length){const o=Ut(n.map(i=>i.row),{...r.computed,signal:r.signal}).rows;n.forEach((i,s)=>{i.row=o[s]})}return mi(n,t,Gt(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 hi(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,l=u?.rowSpan??1;let d=0;for(let m=c;m<c+f;m++){t.has(m)&&d++;for(let g=s+1;g<s+l;g++)n.add(`${g}:${m}`)}d&&a.push(u?{...u,colSpan:d}:null),c+=f}return a});return{...e,cells:o,colWidthsMm:r}}function pi(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:hi(e.headerGrid,t,r.map(n=>n.widthMm))}:{}}}function Yt(e){return e.kind==="list"?e.id:e.nid}function yi(e){return e.kind==="list"?!1:e.pageAnchor!==void 0||e.kind==="text"&&typeof e.text=="string"&&/\{(?:page|totalPages)\}/.test(e.text)}function wi(e,t){const r=e.filter(o=>t.componentIds.includes(Yt(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 bi(e,t){if(!t)return e.map(n=>({components:[n]}));const r=new Map(e.map(n=>[Yt(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 en(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(yi(o))continue;const i=Yt(o);if(!i||r.has(i))throw new Error("流式排版组件应具有唯一标识");r.add(i)}if($i(e,t,r,n),n.size!==r.size)throw new Error("流式排版必须显式包含每个非锚点组件")}function $i(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)}wi(e,i),o=i.topMm+i.heightMm}}function*xi(e){const{page:t}=e;en(t.components,t.flow);let r=0,n=0;for(const o of bi(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,l)=>Math.max(f,l.topMm-i.topMm+(l.kind==="list"?e.height(l):l.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 l=c+f.topMm-i.topMm;f.kind==="list"?(yield*e.list(f,l,d=>{u=s?d:Math.max(u,d)}),e.active()):e.append({...f,topMm:l})}n=u,r=i.topMm+i.heightMm}}function vi(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))}function rt(e){return e.pages.some(t=>t.components.some(r=>r.kind==="list"&&vi(r)))}const Mi=96;function Si(e,t=Mi){return e*t/72}function Zt(e,t=96,r=_t){if(e?.fontSizePx!=null)return{fontSizePt:e.fontSizePx*72/t,fontSizePx:e.fontSizePx};const n=e?.fontSize??r;return{fontSizePt:n,fontSizePx:Si(n,t)}}function Ai(e){return e?.lineHeight??Bt}function V(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 Ei(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 ki(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 tn(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 Xt(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 Pi(e,t){let r=V({fontSize:e.fontSizePt??_t,bold:e.headerBold??!0,align:"center",verticalAlign:"middle",backgroundColor:e.headerBackgroundColor},t.style);return e.headerAlign!==void 0&&(r.align=e.headerAlign),r=V(r,e.headerStyle),t.headerAlign!==void 0&&(r.align=t.headerAlign),V(r,t.headerStyle)}const Ni=new Set(["__proto__","prototype","constructor"]);function G(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Oe(e){return typeof e=="string"&&!!e.trim()&&!Ni.has(e)}function We(e,t,r,n){for(const o of Object.keys(e))t.includes(o)||n.push({path:`${r}.${o}`,message:"存在未知配置字段"})}function Ii(e,t,r){if(e!==void 0){if(!G(e)||!["number","percent","date"].includes(String(e.kind))){r.push({path:t,message:"绑定格式应为 number、percent 或 date"});return}We(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 Fi(e,t,r){const n=e.binding;if(n===void 0)return;const o=`${t}.binding`;if(!G(n)){r.push({path:o,message:"字段绑定应为对象"});return}(!["text","image","barcode","qrcode"].includes(String(e.kind))||e.grid!==void 0)&&r.push({path:o,message:"绑定仅支持独立文本、图片、条码与二维码组件"}),We(n,["field","format","prefix","suffix","emptyText"],o,r),Oe(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:"应为字符串"});Ii(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 Ri(e,t){if(!G(e)){t.push({path:"$.repeat",message:"逐记录配置应为对象"});return}We(e,["dataset","rowKey","copies"],"$.repeat",t),Oe(e.dataset)||t.push({path:"$.repeat.dataset",message:"数据集应为安全的非空名称"}),e.rowKey!==void 0&&!Oe(e.rowKey)&&t.push({path:"$.repeat.rowKey",message:"业务主键应为安全的非空字段名"});const r=e.copies;r!==void 0&&(G(r)?(We(r,["field"],"$.repeat.copies",t),Oe(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 rn(e,t,r,n){if(!G(e))return;Fi(e,t,n),e.binding!==void 0&&!r&&n.push({path:`${t}.binding`,message:"字段绑定需要模板 repeat 数据集;普通报表请使用列表字段"}),r&&e.kind==="list"&&n.push({path:t,message:"逐记录标签使用固定组件;动态列表请使用普通报表模板"});const o=e.grid;G(o)&&Array.isArray(o.cells)&&o.cells.forEach((i,s)=>{Array.isArray(i)&&i.forEach((a,c)=>{G(a)&&Array.isArray(a.children)&&a.children.forEach((u,f)=>rn(u,`${t}.grid.cells.${s}.${c}.children.${f}`,r,n))})})}function nn(e,t){const r=e.repeat!==void 0;r&&Ri(e.repeat,t),Array.isArray(e.pages)&&e.pages.forEach((n,o)=>{if(!G(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(rn(s,c,r,t),!r||!G(s))return;const{leftMm:u,topMm:f,widthMm:l,heightMm:d}=s;[u,f,l,d,n.widthMm,n.heightMm].every(m=>typeof m=="number"&&Number.isFinite(m))&&(Number(u)<0||Number(f)<0||Number(u)+Number(l)>Number(n.widthMm)+.001||Number(f)+Number(d)>Number(n.heightMm)+.001)&&t.push({path:c,message:"标签组件超出纸张边界,请调整位置或尺寸"})})})}const Ti=512,br=256*1024;function Oi(){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=Qe(n,o,i,s),f=a.length+u.reduce((l,d)=>l+d.length,0);if(f<=br){for(;e.size>=Ti||t+f>br;){const l=e.keys().next().value;t-=e.get(l).units,e.delete(l)}e.set(a,{lines:u.slice(),units:f}),t+=f}return u}}function Ci(e){return typeof e=="string"&&/^data:image\/(png|jpe?g);base64,[A-Za-z0-9+/\r\n]+=*$/.test(e)}class W 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 Qt(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 W(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 W(i,"绑定值应为字符串、有限数字、布尔值或空值",n,t)}function ji(e,t,r={}){const n=Qt(t,e.field,r);return n==null||n===""?e.emptyText??"":`${e.prefix??""}${Jt(n,e.format)}${e.suffix??""}`}class oe extends Error{constructor(t,r){super(`报表页数超出上限 ${t}(至少 ${r} 页)`),this.limit=t,this.actual=r,this.code="page-limit",this.name="PaginatePageLimitError"}}class ue extends Error{constructor(t,r){super(`报表单元格数量超出上限 ${t}(至少 ${r} 格)`),this.limit=t,this.actual=r,this.code="cell-limit",this.name="PaginateCellLimitError"}}const Li=1e4,$r=25e4;function er(e){if(e?.aborted)throw e.reason??new DOMException("标签生成已取消","AbortError")}function on(e,t,r){const n=typeof e.copies=="object"?Qt(t,e.copies.field,r):e.copies??1;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>1e3)throw new W(`$.datasets.${r.dataset}[${r.rowIndex}]`,"每条记录复制数必须是 1..1000 的数值型整数",r.rowIndex,typeof e.copies=="object"?e.copies.field:void 0);return n}function sn(e,t,r){if(e.rowKey===void 0)return;const n=Qt(t,e.rowKey,r);if(typeof n=="string"&&n.trim()||typeof n=="number"&&Number.isFinite(n))return n;throw new W(`$.datasets.${r.dataset}[${r.rowIndex}].${e.rowKey}`,"业务主键必须是非空字符串或有限数字",r.rowIndex,e.rowKey)}function Di(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 Bi(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 W(`$.datasets.${n.dataset}`,"逐记录标签数据集缺失,应提供对象数组(允许空数组)");const i=new Set,s=r.maxPages??Li,a=Di(e);let c=0,u=0;for(const[f,l]of o.entries()){if(er(r.signal),!l||typeof l!="object"||Array.isArray(l))throw new W(`$.datasets.${n.dataset}[${f}]`,"标签记录应为对象",f);const d={rowIndex:f,dataset:n.dataset},m=sn(n,l,d);if(m!==void 0){const h=JSON.stringify([typeof m,m]);if(i.has(h))throw new W(`$.datasets.${n.dataset}[${f}].${n.rowKey}`,"业务主键重复;请先确认记录来源,避免重复打印标签",f,n.rowKey);i.add(h)}const g=on(n,l,d);if(c+=g*e.pages.length,u+=g*a,c>s)throw new oe(s,c);if(u>$r)throw new W("$.repeat",`标签组件总量(含网格行、槽位及嵌套组件)超过安全预算 ${$r},请分批生成`,f)}return o}function _i(e,t,r){if(!e.binding)return e;const{binding:n,...o}=e,i=ji(n,t.row,t);if(e.kind==="image"){if(!i)return;if(!Ci(i))throw new W(`${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 Ki(e,t,r){if(e.kind!=="text"||e.grid||e.richParagraphs?.length)return e;const n=e.style??{},o=Zt(n).fontSizePt,i=e.text??e.lines?.join(`
5
+ `)??"";if(i.length>16384)throw new W(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??Kt),a=s.length*o*Ai(n)*25.4/72;if(a>e.heightMm+.05)throw new W(r,`标签文字需要约 ${a.toFixed(2)}mm 高,超出 ${e.heightMm}mm;请增大文本区域、减少内容或调整字号`,t.rowIndex,e.binding?.field);return{...e,lines:s}}function an(e,t,r){er(t.options.signal);const n=_i(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 l=an(u,t,`${r}.grid.cells.${s}.${c}.children.${f}`);return l?[l]:[]})}:a))}),Ki(o===n.grid?n:{...n,grid:o},t,r)}function Wi(e,t,r,n,o,i){return{...e,components:e.components.flatMap((s,a)=>{const c=an(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*Hi(e,t,r){const n=[];if(nn(e,n),n.length)throw new W(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=Bi(e,t,r),s=Oi();for(const[a,c]of i.entries()){const u={row:c,rowIndex:a,dataset:o.dataset,options:r,wrapText:s},f=on(o,c,u),l=sn(o,c,u);for(let d=0;d<f;d++)for(const[m,g]of e.pages.entries())er(r.signal),yield{page:Wi(g,m,u,d,f,l),pageIndex:m}}}function Ji(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 He(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 Ee(e){return e.components.reduce((t,r)=>r.kind!=="list"&&r.pageAnchor==="header"?Math.max(t,r.topMm+r.heightMm):t,0)}function cn(e,t){let r=e.textMetrics.get(t);if(!r){const n=Zt(t).fontSizePt;r={measureOptions:{fontSizePt:n,fontFamily:t.fontFamily??jr,italic:t.italic,bold:t.bold,letterSpacingPt:t.letterSpacing},lineMm:n*(t.lineHeight??Bt)*25.4/72},e.textMetrics.set(t,r)}return r}function zi(e){if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function tr(e,t){const r=e.fontSizePt??_t,n=e.paddingMm??1,o=e.columns.map(h=>h.align??h.style?.align??e.align??"left"),i=e.columns.map((h,w)=>({...V({fontSize:r,verticalAlign:"middle"},h.style),align:o[w]==="auto"?"left":o[w]})),s=i.map((h,w)=>o[w]==="auto"?{left:h,center:{...h,align:"center"},right:{...h,align:"right"}}:void 0),a=e.columns.map((h,w)=>h.rules?.map($=>{const p=s[w];if(p)return{left:V(p.left,$.style),center:V(p.center,$.style),right:V(p.right,$.style)};const x=V(i[w],$.style);return{left:x,center:x,right:x}})),c=e.columns.map(h=>Pi(e,h)),u=e.columns.map(h=>h.header);let f=e.rowHeightMm??0;for(let h=0;h<u.length;h++){const w=c[h],$=Zt(w).fontSizePt,p=Qe(u[h],e.columns[h].widthMm-n*2,{fontSizePt:$,fontFamily:w.fontFamily??jr,italic:w.italic,bold:w.bold,letterSpacingPt:w.letterSpacing},t),x=$*(w.lineHeight??Bt)*25.4/72;f=Math.max(f,Math.max(p.length,1)*x+n*2)}const l=u.map((h,w)=>({text:h,style:c[w]})),d=e.border===!1?{borderTop:!1,borderRight:!1,borderBottom:!1,borderLeft:!1}:{borderBottom:!0,borderLeft:!0,borderRight:!0,borderTop:!0},m=e.columns.map(h=>h.widthMm),g=Vi(e.headerGrid,m,{cells:[l],colWidthsMm:m,rowHeightsMm:[f],paddingMm:n});return{fontSizePt:r,paddingMm:n,cellStyles:i,autoStyles:s,ruleStyles:a,textMetrics:new WeakMap,numberFormats:e.columns.map(h=>_r(h.format)),derivedFields:new Set(e.computed?.map(h=>h.field)),borderStyle:d,headerHeightMm:g.rowHeightsMm.reduce((h,w)=>h+w,0),headerGrid:g,colWidthsMm:m,columns:e.columns}}function Vi(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 Ui(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 ke(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=c.visibleWhen&&!ye(t,c.visibleWhen)?null:t[c.field],f=e.autoStyles[a]?tn(u,c.format,c.semanticRole):"left";let l=e.autoStyles[a]?.[f]??e.cellStyles[a];if(c.rules)for(let p=0;p<c.rules.length;p++){const x=c.rules[p];if(ye(t,x.when)){l=e.ruleStyles[a][p][f];break}}const d=c.format?Jt(u,c.format):Xt(u),m=Gi(e,c,o);l=qi(e,c,l,o);const g=cn(e,l),h=Qe(d,Math.max(1,c.widthMm-e.paddingMm*2-m),g.measureOptions,r);i=Math.max(i,h.length*g.lineMm+e.paddingMm*2);const w=zi(u),$={text:d,style:l};w!==void 0&&($.value=w),Ui($,c,e.numberFormats[a]),Yi($,c,e,o,m),e.derivedFields.has(c.field)&&($.derived=!0,$.editable=!1),c.visibleWhen&&u===null&&!ye(t,c.visibleWhen)&&($.editable=!1),s[a]=$}return{grid:{cells:[s],colWidthsMm:e.colWidthsMm,rowHeightsMm:[i],paddingMm:e.paddingMm},heightMm:i}}function Gi(e,t,r){return!r||t.field!==e.tree.list.tree.labelField?0:Ei(e.tree.list,t,r,e.paddingMm)}function qi(e,t,r,n){return!n||t.field!==e.tree.list.tree.labelField||r.align==="left"?r:{...r,align:"left"}}function Yi(e,t,r,n,o=0){n&&(o&&(e.indentMm=o),ki(e,t,n,r.tree.list))}function un(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*fn(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=un(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,Xt(i[0][n.field])),firstRow:i[0],group:n,depth:r,rows:i},yield*fn(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 dn(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=St(t,{...i,field:i.valueField??i.field});return[i.field,{text:Jt(a,s),...a===null?{}:{value:a},...typeof a=="number"?{numberFormat:_r(s)}:{}}]}))}function ln(e,t){const r=e.findIndex(n=>t.includes(n.field));return r<0?1:r}function we(e,t,r,n,o,i){const s=[],a=Math.max(0,Math.min(i,e.columns.length)),c=V({fontSize:e.fontSizePt},o);a&&s.push({text:r,colSpan:a,style:{bold:!0,...c}});for(let d=a;d<e.columns.length;d++){const m=e.columns[d],g=n.get(m.field),h=e.autoStyles[d]?.[tn(g?.value,m.format)]??e.cellStyles[d];s.push({...g,text:g?.text??"",style:V(h,o)})}const u={text:r,colSpan:e.columns.length,style:{bold:!0,...c}},f=a?[s]:[[u],s],l=f.map(d=>Zi(e,d,t));return{grid:{cells:f,colWidthsMm:e.colWidthsMm,rowHeightsMm:l,paddingMm:e.paddingMm},heightMm:l.reduce((d,m)=>d+m,0)}}function Zi(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=cn(e,i.style),u=Qe(i.text??"",s-e.paddingMm*2,c.measureOptions,r);n=Math.max(n,u.length*c.lineMm+e.paddingMm*2)}return n}function Xi(e,t,r){const{templatePage:n,current:o,warnings:i,nextId:s,pushCurrent:a}=r,c=()=>He(n,o),u=Math.max(o.marginTopMm,Ee(n)),f=n.layout==="wide"?Ee(n):u,l={id:r.tableId,columnKeys:e.columns.map(b=>b.field),...e.layout===void 0?{}:{layout:e.layout},...e.title===void 0?{}:{title:e.title}},d=new Map,m=new Map,g={kind:"rect",leftMm:e.leftMm,topMm:0,widthMm:e.widthMm,heightMm:t.headerHeightMm,grid:t.headerGrid,nid:s("listh"),table:{...l,role:"header",rowIndex:-1},style:t.borderStyle,...e.meta?{meta:e.meta}:{}},h=b=>o.components.push({...g,topMm:b});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&&(h(w),w+=t.headerHeightMm+r.mmPerRow);function $(){const b=Math.max(r.flow||n.layout==="wide"?0:e.topMm,f);return(e.header!==!1&&e.headerEveryPage!==!1?b+t.headerHeightMm:f)+[...m.values()].reduce((E,O)=>E+O.heightMm,0)}function p(){const b=n.layout==="wide"?0:o.marginBottomMm;return Math.min(n.heightMm-b,He(n,o))-$()}function x(b){if(w+b<=c())return;a(),o.components=[],o.heightMm=n.heightMm,n.layout==="wide"&&(o.marginTopMm=0,o.marginBottomMm=0);const v=Math.max(r.flow||n.layout==="wide"?0:e.topMm,f);e.header!==!1&&e.headerEveryPage!==!1?(h(v),w=v+t.headerHeightMm):w=f;for(const E of m.values())M(E,"listgr","group-header")}function y(b,v,E,O){const P=p();if(r.flow&&b.heightMm>P+.001)throw new Error(`流式列表 ${e.id??e.dataset} 的单行高度超出单页可用范围`);b.heightMm>P&&i.push(`列表 ${e.id??e.dataset} 行高 ${b.heightMm.toFixed(2)}mm 超出单页可用高度 ${P.toFixed(2)}mm,预览与打印可能截断内容`),x(b.heightMm),M(b,v,E,O)}function M(b,v,E,O){const P=b.table?.id??l.id,R=E==="header"?-1:d.get(P)??0;E!=="header"&&d.set(P,R+b.grid.cells.length),o.components.push({kind:"rect",leftMm:e.leftMm,topMm:w,widthMm:e.widthMm,heightMm:b.heightMm,grid:b.grid,nid:s(v),table:{...l,...b.table,role:E,rowIndex:R,...O?{source:O}:{}},style:t.borderStyle,...e.meta?{meta:e.meta}:{}}),w+=b.heightMm}function T(b){b<=p()&&x(b)}return{keepTogether:T,placeGridRow:y,setGroupHeader:(b,v)=>{v?m.set(b,v):m.delete(b)},bottom:()=>w}}function Qi(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 nt(e,t){const r=new Map;if(!e.rowKey)return r;const n=new Set;for(const o of t){const i=Qi(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 es(e,t,r,n,o){if(!e.grandTotal)return;const i=typeof e.grandTotal=="object"?e.grandTotal:void 0,s=ot(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=we(r,n.measurer,i?.label??"合计",dn(e.columns,t,a,c),i?.style??{},ln(e.columns,[...a,...c.map(f=>f.field)]));o.placeGridRow(u,"listgt","grand-total")}function Pe(e){if(e?.aborted){const t=new Error("报表排版已取消");throw t.name="AbortError",t}}function ot(e){const t=e.groups??(e.groupBy?[e.groupBy]:[]);if(t.length>16)throw new Error("列表最多支持 16 级分组");return t}function rr(e){const t=pi(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 ts(e,t,r){const n=e.detail;if(!n)return;const o=new Set;for(const u of t){const f=At(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(!mn(f)&&n.unmatched==="ignore")continue;const l=At(f);if(!o.has(l)){if(n.unmatched!=="ignore")throw new Error(`明细数据集 ${n.dataset} 存在未关联的业务键`);continue}const d=s.get(l);d?d.push(u):s.set(l,[u]),a.push(u)}const c=rr({...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:{...tr(c,r.measurer),rowHeightFloorMm:c.rowHeightMm??0},rows:s,sources:nt(c,a)}}function mn(e){return typeof e=="string"&&!!e.trim()||typeof e=="number"&&Number.isFinite(e)}function At(e){if(!mn(e))throw new Error("主从关联键必须是非空字符串或有限数字");return un(e)}function*rs(e,t,r,n,o){if(!r)return;const i=r.rows.get(At(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({...we(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)Pe(n.signal),o.placeGridRow({...ke(r.inter,a,n.measurer),table:s},"listdr","body",r.sources.get(a)),yield*n.takePages()}function ns(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=ai(t,e.matrix),n=r.columns.map((i,s)=>({...i,widthMm:s===0?e.matrix.rowWidthMm??40:e.matrix.columnWidthMm??28,editable:!1,align:s===0?"center":"right"})),o={...e,columns:n,headerGrid:void 0,rowKey:void 0,revisionField:void 0,sourceTokenField:void 0};return e.layout==="wide"&&(o.widthMm=n.reduce((i,s)=>i+s.widthMm,0)),{list:o,rows:r.rows}}function gn(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("树形布局需要可见的标签列");qt(e.tree,e.computed)}function os(e,t,r){gn(e);const n=gi(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=nt(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 is(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 hn(e,t,r){const n=r.prepared.get(e);if(n)return n;const o=is(e,t);if(o)return r.prepared.set(e,o),o;if(e.tree){const c=os(e,t,r);return r.prepared.set(e,c),c}let i=e.computed?.length?Ut(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(c=>ye(c,e.rowVisibleWhen)));const a=ns(e,i);if(!e.matrix){const c=nt(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 ss(e,t,r,n){if(!n.flow)return;const{current:o,templatePage:i}=n,s=Math.max(o.marginTopMm,Ee(i)),a=Math.max(n.startTop??e.topMm,s),c=(e.header===!1?0:t.headerHeightMm)+(r[0]?ke(t,r[0],n.measurer).heightMm:0);a+c<=He(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,Ee(i)))}function*as(e,t,r){const n=hn(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??nt(e,o),s=rr(e),a=ot(s),c={...tr(s,r.measurer),rowHeightFloorMm:s.rowHeightMm??0,...n.treeRows?{tree:{list:s,rows:n.treeRows}}:{}};ss(s,c,o,r);const u=Xi(s,c,r),f=ts(s,o,r);let l;for(const d of fn(o,a)){if(Pe(r.signal),d.kind==="row")u.placeGridRow(l??ke(c,d.row,r.measurer),"listr","body",i.get(d.row)),l=void 0,yield*r.takePages(),yield*rs(s,d.row,f,r,u);else if(d.kind==="groupHeader"){const m=we(c,r.measurer,d.label,new Map,d.group.headerStyle??{},s.columns.length);l??=ke(c,d.firstRow,r.measurer);const g=a.slice(d.depth+1).reduce((h,w)=>h+we(c,r.measurer,(w.headerTemplate??"{value}").replace(/\{value\}/g,Xt(d.firstRow[w.field])),new Map,w.headerStyle??{},s.columns.length).heightMm,0);d.group.keepWithNext!==!1&&u.keepTogether(m.heightMm+g+l.heightMm),u.placeGridRow(m,"listg","group-header"),d.group.repeatHeader&&u.setGroupHeader(d.depth,m)}else if(d.kind==="subtotal"){const m=d.group.subtotal??[],g=d.group.aggregates??[],h=we(c,r.measurer,d.label,dn(s.columns,d.rows,m,g),d.group.subtotalStyle??{},ln(s.columns,[...m,...g.map(w=>w.field)]));u.placeGridRow(h,"listst","subtotal")}else u.setGroupHeader(d.depth);yield*r.takePages()}es(s,n.totalRows??o,c,r,u),r.finished?.(u.bottom()),yield*r.takePages()}function it(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 st(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=>st(o,t))}:{}}:null))}}:{}}}function cs(e){let t=!1;for(const r of e.pages)for(const n of r.components)it(n)&&st(n,o=>(o.includes("{totalPages}")&&(t=!0),o));return t}function us(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(st(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 nr(e){return e.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+pn(s),0)??0):0),0),0)}function pn(e){return e.grid?nr(e.grid):0}function yn(e){for(const t of["maxPages","maxCells","knownTotalPages"])if(e[t]!==void 0&&(!Number.isSafeInteger(e[t])||e[t]<1))throw new RangeError(`${t} 应为正安全整数`)}function fs(e,t){const r=hn(e,t.datasets[e.dataset]??[],t),n=rr(r.list),o={...tr(n,t.measurer),rowHeightFloorMm:n.rowHeightMm??0};return(n.header===!1?0:o.headerHeightMm)+r.rows.reduce((i,s)=>i+ke(o,s,t.measurer).heightMm,0)}function*ds(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??""} 输出为空`),as(i,Array.isArray(c)?c:[],{...e,tableId:`${e.tableId}:${n.get(i)}`,startTop:s,finished:a,flow:!!t.flow})};if(t.flow){yield*xi({page:t,active:()=>Pe(e.signal),top:()=>Math.max(r.marginTopMm,Ee(t)),bottom:()=>He(t,r),append:i=>{r.components.push(i)},nextPage:()=>{e.pushCurrent(),r.components=[],r.heightMm=t.heightMm,t.layout==="wide"&&(r.marginTopMm=0,r.marginBottomMm=0)},takePages:e.takePages,height:i=>fs(i,e),list:o});return}for(const i of t.components)it(i)||(i.kind==="list"?yield*o(i):r.components.push(i))}function*Et(e,t,r,n,o,i=new WeakMap){let s=0,a=0,c=0;const u=f=>`${f}_${(++s).toString(36)}`;for(const{pageIndex:f,page:l}of Hi(e,t,r)){Pe(r.signal);const d=Ji(l),m=l.components.filter(it);let g=[];const h=($=!1)=>{if(Pe(r.signal),r.maxPages!==void 0&&a>=r.maxPages)throw new oe(r.maxPages,a+1);if(r.maxCells!==void 0&&(c+=[...d.components,...m].reduce((p,x)=>p+pn(x),0),c>r.maxCells))throw new ue(r.maxCells,c);g.push(us(l,d,m,++a,$,o))},w=()=>{const $=g;return g=[],$};yield*ds({templatePage:l,current:d,warnings:n,nextId:u,pushCurrent:h,takePages:w,datasets:t,signal:r.signal,formula:r.formula,prepared:i,measurer:r.measurer??Kt,mmPerRow:r.mmPerRow??0,tableId:`table:${f}`}),h(!0),yield*w()}}function*ls(e,t,r={}){yn(r);const n=cs(e),o=new WeakMap;let i=r.knownTotalPages;if(n&&i===void 0){i=0;for(const c of Et(e,t,r,[],void 0,o))i++}const s=[];let a=0;for(const c of Et(e,t,r,s,i,o)){for(;a<s.length;a++)r.onWarning?.(s[a]);yield c}}function ms(e,t,r={}){const n=typeof r=="number"?{mmPerRow:r}:r;yn(n);const o=[],i=[...Et(e,t,n,o,n.knownTotalPages)];for(const s of i)s.components=s.components.map(a=>it(a)?st(a,c=>c.replace(/\{totalPages\}/g,String(i.length))):a);return o.forEach(s=>n.onWarning?.(s)),{plan:{schemaVersion:Ne,...rt(e)?{requiresRecalculation:!0}:{},pages:i},warnings:o}}function gs(e){const t=e.columns.find(i=>!i.hidden)?.field;if(!t)return{groups:0,total:0};const r=ot(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 hs(e,t,r){gn(e);const n=Qr(t[e.dataset]??[],e.tree,r),o=e.columns.filter(s=>!s.hidden).length,i=e.header===!1?0:e.headerGrid?nr(e.headerGrid):o;return n.length*o+i+ +!!e.grandTotal*2*o}function ps(e,t,r={}){if(e.tree)return hs(e,t,r.signal);if(e.matrix){let c=t[e.dataset]??[];e.computed?.length&&(c=Ut(c,{fields:e.computed,...r}).rows),e.rowVisibleWhen&&(c=c.filter(f=>ye(f,e.rowVisibleWhen)));const u=Jr(c,e.matrix);return u.cells+u.columnCount}const n=t[e.dataset]?.length??0,o=e.columns.filter(c=>!c.hidden).length,i=ot(e).length,s=gs(e);let a=(n*(1+2*i+s.groups)+ +!!e.grandTotal*(1+s.total))*o;if(a+=e.header===!1?0:e.headerGrid?nr(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 Ce(e){return!!e&&typeof e=="object"}function wn(e,t,r,n,o){if(++o.nodes>1e6)return{path:t,message:"组件树超过100万个结构节点预算"};if(Ce(e)){if(r>64)return{path:t,message:"组件嵌套超过64层预算"};if(n.has(e))return{path:t,message:"组件树包含循环引用"};if(!(!Ce(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(!(!Ce(c)||!Array.isArray(c.children)))for(const[u,f]of c.children.entries()){const l=wn(f,`${t}.grid.cells.${i}.${a}.children.${u}`,r+1,n,o);if(l)return l}}}finally{n.delete(e)}}}}function or(e,t="$.components",r={nodes:0}){for(const[n,o]of e.entries()){const i=wn(o,`${t}.${n}`,0,new Set,r);if(i)return i}}function bn(e){const t={nodes:0};for(const[r,n]of e.entries()){if(!Ce(n)||!Array.isArray(n.components))continue;const o=or(n.components,`$.pages.${r}.components`,t);if(o)return o}}function ys(e){const t=bn(e.pages);if(t)throw new TypeError(`${t.path}: ${t.message}`)}function ws(e,t,r){e!==void 0&&(typeof e!="string"||!e.trim()||e.length>4096)&&r.push({path:t,message:"来源范围应为不超过 4096 字符的非空字符串"})}function $n(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 bs(e,t,r){$n(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:"派生结果标记应为布尔值"}),xn(e.source,`${t}.source`,r,!0),e.formula!==void 0&&typeof e.formula!="string"&&r.push({path:`${t}.formula`,message:"单元格公式应为字符串"})}function xn(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;ws(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 $s(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 xs(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 vs(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return[{path:"",message:"code must be an object."}];const r=e,n=[...$s(r),...xs(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 Ms=new Set(["text","image","barcode","qrcode","chart","line","rect","ellipse"]);function K(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Je(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 Ss(e,t,r,n){const o=e[t];(typeof o!="number"||!Number.isFinite(o))&&n.push({path:`${r}.${t}`,message:`应为有限数字,实际 ${Je(o)}`})}function As(e,t,r){if(e!==void 0){const n=`${t}.table`;if(!K(e))r.push({path:n,message:"逻辑表来源应为对象"});else{xn(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 Es(e,t,r,n){if(e!==void 0)if(!K(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(!K(a)){r.push({path:u,message:"网格单元格应为对象或 null"});return}bs(a,u,r),vn(a.richParagraphs,u,r),Array.isArray(a.children)&&a.children.forEach((f,l)=>{ir(f,`${t}.grid.cells.${s}.${c}.children.${l}`,r,n)})})})}}function ze(e,t,r,n){e!==void 0&&!t.includes(e)&&n.push({path:r,message:"未知富文本属性值"})}function kt(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 ks(e,t,r){if(e!==void 0){if(!K(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:"富文本样式应为布尔值"});kt(e,["fontSize","fontSizePx","lineWidthPt","lineHeight","opacity"],t,r),kt(e,["letterSpacing","rotateDeg"],t,r,-1/0),typeof e.opacity=="number"&&e.opacity>1&&r.push({path:`${t}.opacity`,message:"透明度不能大于1"}),ze(e.align,["left","center","right","justify"],`${t}.align`,r),ze(e.verticalAlign,["top","middle","bottom"],`${t}.verticalAlign`,r)}}function Ps(e,t,r){if(!K(e)){r.push({path:t,message:"富文本片段应为对象"});return}ze(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:"富文本内容应为字符串"});ks(e.style,`${t}.style`,r)}function vn(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(!K(n)||!Array.isArray(n.segments)){r.push({path:i,message:"段落缺少 segments 数组"});return}ze(n.align,["left","center","right","justify"],`${i}.align`,r),kt(n,["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"],i,r),n.segments.forEach((s,a)=>Ps(s,`${i}.segments.${a}`,r))})}}function Mn(e,t,r,n=[]){const o=or([e],t);if(o){r.push(o);return}ir(e,t,r,n)}function ir(e,t,r,n=[]){if(!K(e)){r.push({path:t,message:"组件应为对象"});return}const o=e.kind;typeof o!="string"?r.push({path:`${t}.kind`,message:"组件缺少 kind 字符串"}):Ms.has(o)||n.push({path:`${t}.kind`,message:`未知组件类型 ${Je(o)},将以兜底方式渲染`});for(const i of["leftMm","topMm","widthMm","heightMm"])Ss(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:"组件尺寸不能为负数"});As(e.table,t,r),Ns(e.code,o,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"}),Es(e.grid,t,r,n),vn(e.richParagraphs,t,r)}function Ns(e,t,r,n){if(e!==void 0)for(const o of vs(e,t))n.push({path:`${r}.code${o.path?`.${o.path}`:""}`,message:o.message})}function Sn(e,t,r){if(!K(e))return;e.binding!==void 0&&r.push({path:`${t}.binding`,message:"渲染计划不允许未解析字段绑定"});const n=e.grid;!K(n)||!Array.isArray(n.cells)||n.cells.forEach((o,i)=>{Array.isArray(o)&&o.forEach((s,a)=>{!K(s)||!Array.isArray(s.children)||s.children.forEach((c,u)=>Sn(c,`${t}.grid.cells.${i}.${a}.children.${u}`,r))})})}function Is(e,t,r,n=[]){if(!K(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:`页宽非法: ${Je(o)}`}),(typeof i!="number"||!(i>0&&i<5e3))&&r.push({path:`${t}.pageHeightMm`,message:`页高非法: ${Je(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=or(s,`${t}.components`);if(a){r.push(a);return}s.forEach((c,u)=>{ir(c,`${t}.components.${u}`,r,n),Sn(c,`${t}.components.${u}`,r)})}}function at(e){const t=[],r=[],n=K(e)?e.pages:void 0;if(K(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=bn(n);if(o)return{ok:!1,errors:[...t,o],warnings:r};n.forEach((s,a)=>Is(s,`$.pages.${a}`,t,r)),n.length>2e3&&r.push({path:"$.pages",message:`页数异常大(${n.length} 页),渲染与打印耗时可能显著增加`});const i=n.reduce((s,a)=>s+(K(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 Fs(e){const t=[];return e.optionsSource!==void 0&&((e.type!=="select"||typeof e.optionsSource!="string"||!/^[\w][\w.:-]{0,127}$/.test(e.optionsSource))&&t.push("远程选项来源应为 select 的有效来源键(最多 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 Rs(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 Ve(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 sr(e){return e.length===4&&/^\d{4}$/.test(e)&&e!=="0000"}function An(e){return e.length===7&&/^\d{4}-(?:0[1-9]|1[0-2])$/.test(e)&&sr(e.slice(0,4))}function En(e){const[t,r,n]=e.split("/");if(!(n!==void 0||!t||!r||!Ve(t)||!Ve(r)||t>r))return{start:t,end:r}}function kn(e,t){return typeof t!="string"?!1:e==="month"?An(t):e==="year"?sr(t):(e==="date"||e==="dateRange")&&Ve(t)}function Ts(e,t){if(e==="date"&&!Ve(t))return"应为有效的 YYYY-MM-DD 日期";if(e==="month"&&!An(t))return"应为有效的 YYYY-MM 月份";if(e==="year"&&!sr(t))return"应为 0001 至 9999 的四位年份";if(e==="dateRange"&&!En(t))return"应为完整且有序的 YYYY-MM-DD/YYYY-MM-DD 日期范围"}class ct extends Error{constructor(t){super(t.map(r=>`${r.field}: ${r.message}`).join("; ")),this.issues=t,this.code="params",this.name="ReportParamValidationError"}}function Pn(e){return/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e)&&Number.isFinite(Number(e))}function Nn(e,t){if(e.type==="number"&&!Pn(t))return[["type","应为有限数字"]];const r=Ts(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(...Os(e,t)),n}function Os(e,t){const r=e.type==="dateRange"?En(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 Cs(e){const t=[];for(const o of["min","max"]){const i=e[o];if(i===void 0)continue;kn(e.type,i)||e.type==="number"&&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,...js(e)]}function js(e){const t=[];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 ut(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 Bs(n,t).map(a=>({code:"definition",field:i,path:`$.paramDefs.${o}`,message:a}))});return r.length?r:Rs(e).map(({index:n,message:o})=>({code:"definition",field:e[n].field,path:`$.paramDefs.${n}`,message:o}))}function Ls(e){return Array.isArray(e)&&e.every(t=>!!t&&typeof t=="object"&&typeof t.value=="string"&&typeof t.label=="string")}function Ds(e){const t=[];return e.type!==void 0&&!["text","number","date","month","year","dateRange","select"].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&&!Ls(e.options)&&t.push("选项应为包含字符串 label/value 的数组"),[...t,...Fs(e)]}function Bs(e,t){if(!e||typeof e!="object"||Array.isArray(e))return["参数定义项应为对象"];const r=Ds(e);return typeof e.field!="string"||!e.field.trim()||t.has(e.field)?r.push("参数名应为非空且不重复的字符串"):t.add(e.field),r.length||(r.push(...Cs(e)),r.length)||(e.options&&new Set(e.options.map(n=>n.value)).size!==e.options.length&&r.push("选项值不能重复"),e.defaultValue!==void 0&&(e.required&&!e.defaultValue.trim()?r.push("必填参数的默认值不能为空"):e.defaultValue.trim()&&r.push(...Nn(e,e.defaultValue).map(([,n])=>`默认值${n}`)))),r}function _s(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 Pt(e){return e==null||typeof e=="string"&&!e.trim()}function Nt(e,t={}){const r=Object.create(null),n=Object.create(null),o=ut(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};_s(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,a=(f,l)=>o.push({code:f,path:`$.params.${i.field}`,field:i.field,message:l});if(Pt(s)){i.required&&a("required","此参数为必填项"),typeof s=="string"&&(r[i.field]=s),delete n[i.field];continue}if(typeof s!="string"&&!(typeof s=="number"&&Number.isFinite(s))){a("type","参数应为字符串或有限数字");continue}const c=String(s);r[i.field]=c,Nn(i,c).forEach(([f,l])=>a(f,l)),n[i.field]=i.type==="number"&&Pn(c)?Number(c):c}return o.push(...Ks(e,r)),{ok:o.length===0,values:r,typedValues:n,issues:o}}function Ks(e,t){return e.flatMap(r=>!Pt(t[r.field])&&r.dependsOn?.some(n=>Pt(t[n]))?[{code:"dependency",path:`$.params.${r.field}`,field:r.field,message:"请先填写联动依赖的上级参数"}]:[])}function xr(e,t={}){const r=Nt(e,t);if(!r.ok)throw new ct(r.issues);return r.values}function Ws(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 Hs(e){const t={type:e.type==="number"?"number":"string",title:e.label??e.field,...Ws(e)};return e.required&&e.type!=="number"&&!t.pattern&&(t.pattern="\\S"),e.type==="select"&&e.options&&(t.enum=e.options.map(r=>r.value)),Object.assign(t,Js(e)),e.defaultValue!==void 0&&(e.type!=="number"||e.defaultValue.trim())&&(t.default=e.type==="number"?Number(e.defaultValue):e.defaultValue),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),typeof e.min=="number"&&(t.minimum=e.min),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 Js(e){return{...e.optionsSource?{"x-report-options-source":e.optionsSource}:{},...e.dependsOn?.length?{"x-report-depends-on":[...e.dependsOn]}:{}}}function zs(e){const t=ut(e);if(t.length)throw new ct(t);return{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:Object.fromEntries(e.map(r=>[r.field,Hs(r)])),required:e.filter(r=>r.required).map(r=>r.field),additionalProperties:!0}}function Ue(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=ut(i);if(s.length)throw new ct(s);return i.filter(a=>r.has(a.field)?!1:(r.add(a.field),!0))})}function In(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function It(e,t,r){if(e!==void 0){if(!In(e)){r.push({path:t,message:"条件应为对象"});return}(typeof e.field!="string"||!e.field.trim())&&r.push({path:`${t}.field`,message:"条件需要字段"}),e.numeric!==void 0&&e.numeric!=="number"&&e.numeric!=="decimal"&&r.push({path:`${t}.numeric`,message:"未知条件数值模式"}),[">",">=","<","<=","==","!="].includes(e.op)||r.push({path:`${t}.op`,message:"未知条件运算符"}),typeof e.value!="string"&&!(typeof e.value=="number"&&Number.isFinite(e.value))&&r.push({path:`${t}.value`,message:"条件值应为字符串或有限数字"})}}function Fn(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(!In(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{ge({...o,field:o.valueField??a})}catch(c){r.push({path:s,message:c instanceof Error?c.message:String(c)})}})}function Vs(e,t,r){if(e===void 0)return;const n=Qo(e);for(const o of n.errors)r.push({path:t,message:o})}function Us(e,t,r){if(e!==void 0)try{Hr(e)}catch(n){r.push({path:t,message:n instanceof Error?n.message:String(n)})}}function Gs(e,t,r){if(e.tree===void 0)return;const n=`${t}.tree`;try{Yr(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)&&qt(o,e.computed)}catch(o){r.push({path:n,message:o instanceof Error?o.message:String(o)})}}class qs extends Error{constructor(t){super(`模板校验失败:${t.slice(0,3).map(r=>`${r.path}: ${r.message}`).join("; ")}`),this.errors=t,this.name="ReportTemplateError"}}const Ys=new Set(["__proto__","prototype","constructor"]),Zs=new Set(["left","center","right","justify"]),je=2e5,Xs=64,Qs=1e7;function N(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ea(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 ta(e,t,r,n){return Ys.has(e)?(n.push({path:r,message:"模板不能包含可能污染原型的键"}),!1):t.get||t.set||!t.enumerable?(n.push({path:r,message:"模板不能包含访问器或不可枚举字段"}),!1):!0}function ra(e){return e===null||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)}function na(e,t){const r=new Set;let n=0,o=0,i=!1;const s=(a,c,u)=>{if(!i){if(++n>je){n===je+1&&t.push({path:c,message:"模板超过 JSON 节点安全上限"});return}if(u>Xs){t.push({path:c,message:"模板嵌套层级过深"});return}if(typeof a=="string"){o+=a.length,o>Qs&&(i=!0,t.push({path:c,message:"模板文本超过 1000 万字符的安全上限"}));return}if(!ra(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(ea(a,c,t)){r.add(a);for(const[f,l]of Object.entries(Object.getOwnPropertyDescriptors(a))){if(Array.isArray(a)&&f==="length")continue;const d=`${c}.${f}`;if(ta(f,l,d,t)&&s(l.value,d,u+1),n>je||i)break}r.delete(a)}}}};s(e,"$",0)}function C(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 B(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 Q(e,t,r,n){e[t]!==void 0&&typeof e[t]!="boolean"&&n.push({path:`${r}.${t}`,message:"应为布尔值"})}function me(e,t,r,n=!1){e!==void 0&&!Zs.has(e)&&!(n&&e==="auto")&&r.push({path:t,message:`未知对齐方式${n?"(支持 auto)":""}`})}function q(e,t,r){if(e!==void 0){if(!N(e)){r.push({path:t,message:"样式应为对象"});return}me(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"])B(e,n,t,r);for(const n of["letterSpacing","rotateDeg"])B(e,n,t,r,-1/0);B(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"])Q(e,n,t,r);for(const n of["fontFamily","color","backgroundColor","lineColor","borderColor"])C(e,n,t,r)}}function oa(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(!N(i)){r.push({path:a,message:"参数定义应为对象"});return}C(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"].includes(i.type)&&r.push({path:`${a}.type`,message:"未知参数类型"});for(const c of["label","defaultValue","placeholder"])C(i,c,a,r);Q(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:"长度边界应为非负整数"})}ia(i,a,r),i.options!==void 0&&(Array.isArray(i.options)?i.options.forEach((c,u)=>{const f=`${a}.options.${u}`;if(!N(c))r.push({path:f,message:"选项应为对象"});else for(const l of["label","value"])typeof c[l]!="string"&&r.push({path:`${f}.${l}`,message:"选项标签与值应为字符串(允许空白选项)"})}):r.push({path:`${a}.options`,message:"选项应为数组"}))}),r.length===o&&r.push(...ut(e).map(i=>({path:i.path.replace("$.paramDefs",t),message:i.message})))}function ia(e,t,r){for(const i of["min","max"]){const s=e[i];if(s===void 0)continue;kn(e.type,s)||e.type==="number"&&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 Rn(e,t,r){if(!Array.isArray(e)||e.length===0){r.push({path:t,message:"列表至少需要一列"});return}e.every(n=>N(n)&&n.hidden===!0)&&r.push({path:t,message:"列表至少需要一列可见列"}),e.forEach((n,o)=>{const i=`${t}.${o}`;if(!N(n)){r.push({path:i,message:"列应为对象"});return}if($n(n,i,r),Q(n,"hidden",i,r),It(n.visibleWhen,`${i}.visibleWhen`,r),typeof n.header!="string"&&r.push({path:`${i}.header`,message:"表头应为字符串(允许空白表头)"}),C(n,"field",i,r,!0),B(n,"widthMm",i,r,Number.MIN_VALUE,!0),q(n.style,`${i}.style`,r),q(n.headerStyle,`${i}.headerStyle`,r),me(n.align,`${i}.align`,r,!0),me(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(!N(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 的整数"}),Q(n.format,"thousands",`${i}.format`,r),C(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(!N(s)||!N(s.when)){r.push({path:c,message:"条件格式缺少 when 对象"});return}It(s.when,`${c}.when`,r),C(s.when,"field",`${c}.when`,r,!0),[">",">=","<","<=","==","!="].includes(s.when.op)||r.push({path:`${c}.when.op`,message:"未知条件运算符"}),typeof s.when.value!="number"&&typeof s.when.value!="string"&&r.push({path:`${c}.when.value`,message:"条件值应为数字或字符串"}),q(s.style,`${c}.style`,r)}):r.push({path:`${i}.rules`,message:"条件格式应为数组"}))})}function Tn(e,t,r){if(e!==void 0){if(!N(e)){r.push({path:t,message:"分组应为对象"});return}C(e,"field",t,r,!0);for(const n of["headerTemplate","subtotalLabel"])C(e,n,t,r);for(const n of["headerStyle","subtotalStyle"])q(e[n],`${t}.${n}`,r);Q(e,"keepWithNext",t,r),Q(e,"repeatHeader",t,r),Fn(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 sa(e,t,r){if(!(e===void 0||typeof e=="boolean")){if(!N(e)){r.push({path:t,message:"合计应为布尔值或对象"});return}C(e,"label",t,r),Fn(e.aggregates,`${t}.aggregates`,r),q(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 aa(e,t,r,n){const o={kind:"rect",leftMm:0,topMm:0,widthMm:1,heightMm:1,grid:e};if(Mn(o,r,n,[]),ar(o,r,n),!N(e)||!Array.isArray(e.cells))return;const i=e.cells,s=Array.isArray(t)?t.length:0;if(i.length*s>je){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:"表头行高数量应与行数一致"}),ca(i,s,r,n)}function ca(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=N(c)&&typeof c.colSpan=="number"?c.colSpan:1,l=N(c)&&typeof c.rowSpan=="number"?c.rowSpan:1;(a+f>t||s+l>e.length)&&n.push({path:`${r}.cells.${s}.${u}`,message:"表头合并区域超出表头边界"});for(let d=s;d<Math.min(e.length,s+l);d++)for(let m=a;m<Math.min(t,a+f);m++)o.has(`${d}:${m}`)&&n.push({path:`${r}.cells.${s}.${u}`,message:"表头合并区域重叠"}),o.add(`${d}:${m}`);a+=f})})}function ua(e,t,r){if(Gs(e,t,r),Vs(e.computed,`${t}.computed`,r),Us(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 汇总,不能同时配置普通分组、总计或主从明细"}),It(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)=>Tn(i,`${t}.groups.${s}`,r))),e.detail===void 0)return;const n=e.detail,o=`${t}.detail`;if(!N(n)){r.push({path:o,message:"主从关联应为对象"});return}for(const i of["dataset","parentKey","foreignKey"])C(n,i,o,r,!0);for(const i of["rowKey","revisionField","sourceTokenField"])C(n,i,o,r,n[i]!==void 0);C(n,"label",o,r),Q(n,"header",o,r),B(n,"rowHeightMm",o,r,Number.MIN_VALUE),Rn(n.columns,`${o}.columns`,r),n.unmatched!==void 0&&n.unmatched!=="error"&&n.unmatched!=="ignore"&&r.push({path:`${o}.unmatched`,message:"未关联明细策略应为 error 或 ignore"})}function fa(e,t,r){for(const n of["leftMm","topMm"])B(e,n,t,r,-1/0,!0);B(e,"widthMm",t,r,Number.MIN_VALUE,!0),C(e,"dataset",t,r,!0),C(e,"title",t,r);for(const n of["rowKey","revisionField","sourceTokenField"])C(e,n,t,r,e[n]!==void 0);e.headerGrid!==void 0&&aa(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"}),Rn(e.columns,`${t}.columns`,r);for(const n of["fontSizePt","rowHeightMm"])B(e,n,t,r,Number.MIN_VALUE);B(e,"paddingMm",t,r);for(const n of["header","headerBold","headerEveryPage","border"])Q(e,n,t,r);e.cardinality!==void 0&&e.cardinality!=="record"&&r.push({path:`${t}.cardinality`,message:"单记录区域类型应为 record"}),C(e,"headerBackgroundColor",t,r),me(e.align,`${t}.align`,r,!0),me(e.headerAlign,`${t}.headerAlign`,r),q(e.headerStyle,`${t}.headerStyle`,r),ua(e,t,r),Tn(e.groupBy,`${t}.groupBy`,r),sa(e.grandTotal,`${t}.grandTotal`,r)}function vr(e,t,r){Array.isArray(e.richParagraphs)&&e.richParagraphs.forEach((n,o)=>{if(!N(n))return;const i=`${t}.richParagraphs.${o}`;me(n.align,`${i}.align`,r);for(const s of["lineHeight","spaceBeforeMm","spaceAfterMm","indentMm"])B(n,s,i,r);Array.isArray(n.segments)&&n.segments.forEach((s,a)=>{const c=`${i}.segments.${a}`;if(!N(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"])C(s,u,c,r);q(s.style,`${c}.style`,r)})})}function ar(e,t,r){q(e.style,`${t}.style`,r);for(const o of["text","rawText","imageData","fallbackText","nid","rkey"])C(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:"文本行应为字符串数组"}),vr(e,t,r),!N(e.grid))return;const n=e.grid;B(n,"gapMm",`${t}.grid`,r),B(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(!N(s)){r.push({path:c,message:"网格单元格应为对象或 null"});return}for(const u of["text","rawText","numberFormat"])C(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"}),q(s.style,`${c}.style`,r),vr(s,c,r),s.children!==void 0&&(Array.isArray(s.children)?s.children.forEach((u,f)=>{N(u)&&ar(u,`${c}.children.${f}`,r)}):r.push({path:`${c}.children`,message:"嵌套组件应为数组"}))}})})}function da(e,t,r){if(!(e.flow===void 0||!Array.isArray(e.components)))try{en(e.components,e.flow)}catch(n){r.push({path:`${t}.flow`,message:n instanceof Error?n.message:String(n)})}}function la(e){const t=[],r=[];return na(e,t),t.length?{ok:!1,errors:t,warnings:r}:(N(e)?(e.schemaVersion!==void 0&&e.schemaVersion!==Ne&&t.push({path:"$.schemaVersion",message:"不支持的模板 schemaVersion"}),oa(e.params,"$.params",t),nn(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(!N(n)){t.push({path:i,message:"页应为对象"});return}B(n,"widthMm",i,t,Number.MIN_VALUE,!0),B(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"])B(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}`;N(s)&&s.kind==="list"?fa(s,c,t):(Mn(s,c,t,r),N(s)&&ar(s,c,t))}):t.push({path:`${i}.components`,message:"组件应为数组"}),da(n,i,t)})):t.push({path:"$",message:"模板应为对象"}),{ok:t.length===0,errors:t,warnings:r})}function ma(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 Mr(e,t,r){return e?.length?ma(e,t):Array.from({length:r},(n,o)=>({pos:t*o/r,size:t/r}))}function ga(e,t,r){const n=e.cells??[],o=Math.max(n.length,1),i=e.colWidthsMm?.length??Math.max(1,...n.map(p=>Array.isArray(p)?p.length:0)),s=Mr(e.colWidthsMm,t,i),a=p=>p<=0?0:p>=i?s[s.length-1].pos+s[s.length-1].size:s[p].pos,c=Mr(e.rowHeightsMm,r,o),u=p=>p<=0?0:p>=o?c[c.length-1].pos+c[c.length-1].size:c[p].pos,f=new Set,l=(p,x)=>`${p}:${x}`,d=[],m=new Set,g=new Set,h=(p,x)=>`v${p}:${x}`,w=(p,x)=>`h${p}:${x}`;n.forEach((p,x)=>{if(!Array.isArray(p))return;let y=0;for(const M of p){for(;y<i&&f.has(l(x,y));)y++;if(y>=i)break;const T=Math.max(1,Math.min(M?.colSpan??1,i-y)),I=Math.max(1,M?.rowSpan??1),b=Math.min(o,x+I),v=Math.min(i,y+T);for(let P=x;P<b;P++)for(let R=y;R<v;R++)f.add(l(P,R));for(let P=y+1;P<v;P++)for(let R=x;R<b;R++)m.add(h(P,R));for(let P=x+1;P<b;P++)for(let R=y;R<v;R++)g.add(w(P,R));const E=a(y),O=u(x);d.push({ri:x,ci:y,cell:M??{},xMm:E,yMm:O,widthMm:a(v)-E,heightMm:u(b)-O}),y=v}});const $=[];for(let p=1;p<i;p++){let x=-1;for(let y=0;y<=o;y++){const M=y<o&&!m.has(h(p,y));M&&x<0&&(x=y),!M&&x>=0&&($.push({kind:"v",pos:a(p),from:u(x),to:u(y)}),x=-1)}}for(let p=1;p<o;p++){let x=-1;for(let y=0;y<=i;y++){const M=y<i&&!g.has(w(p,y));M&&x<0&&(x=y),!M&&x>=0&&($.push({kind:"h",pos:u(p),from:a(x),to:a(y)}),x=-1)}}return{columns:s,rows:c,cells:d,edges:$}}function ha(e){return!e||typeof e!="object"?!1:[e.pageIndex,e.componentIndex,e.rowIndex,e.columnIndex].every(t=>Number.isInteger(t)&&t>=0)}function pa(e){return e.value!==void 0?e.value:e.rawText??e.text??null}function ya(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 wa(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 ba(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 $a(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 xa(e,t,r){const n=pa(r),o=wa(r,e);return{address:{...t},cell:r,component:e,value:n,valueType:ya(r,n),table:ba(e,t),source:$a(r,e,t),editable:o===void 0,readOnlyReason:o}}function On(e){const t=new Map;return r=>{if(!ha(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 ga(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?xa(n,r,i):null}}function va(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 Ma(e,t){const r=va(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 Sa(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 be(e,t){return/[0#?@_*%[\]"\\.,/]/.test(e)?null:e.replace(/[\uE000-\uF8FF]/g,r=>t.literals[r.charCodeAt(0)-57344]??"")}function Aa(e,t){const r=/^(.*?)(0)(?:\.([0#]+))?E([+-])(0+)(.*?)$/i.exec(t.text);if(!r)return null;const n=be(r[1],t),o=be(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("."),l=f.replace(/0+$/,"").padEnd(c,"0"),d=Number(a),m=d<0?"-":r[4]==="+"?"+":"",g=String(Math.abs(d)).padStart(r[5].length,"0");return`${e.negative?"-":""}${n}${u}${l?`.${l}`:""}E${m}${g}${o}`}function Ea(e,t){const r=/^(.*?)([#,]*0[0#]*)(?:\.([0#]+))?(%)?(.*?)$/.exec(t.text);if(!r)return be(t.text,t);const n=be(r[1],t),o=be(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 ka(e,t,r){if(!t||/^(General|@)$/i.test(t))return String(e);const n=Ma(e,t);if(n.pattern==="")return"";const o=Sa(n.pattern),i=Aa(n,o)??Ea(n,o);return i!==null?i:String(e)}function Pa(e){return e!==void 0&&e.replace(/"[^"]*"|\\./g,"").includes("%")}class k extends Error{constructor(t){super(`Invalid report cell edit: ${t}`),this.code=t,this.name="ReportCellEditError"}}function Na(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 k("number");return Number(r)/(n?100:1)}function Ia(e,t){if(e===null||typeof e=="string"&&e.trim()==="")return null;if(typeof e!="string"&&typeof e!="number")throw new k("number");const r=typeof e=="number"?e:Na(e,Pa(t.cell.numberFormat));if(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r))throw new k("number");return r}function Fa(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 k("boolean")}function Ra(e,t){return e.valueType==="number"?Ia(t,e):e.valueType==="boolean"?Fa(t):t===null?null:String(t)}function Ta(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 Cn(e,t){return t===null?"":typeof t=="boolean"?Ta(t,e):typeof t=="number"?ka(t,e.cell.numberFormat):String(t)}function jn(e,t){if(!e.editable)throw new k("readonly");const r=Ra(e,t);return{address:{...e.address},table:e.table,source:e.source,previousValue:e.value,previousText:e.cell.text??"",value:r,text:Cn(e,r)}}function Oa(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 Ln(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 he(e){return JSON.stringify([e.sourceScope,e.datasetId])}function Sr(e){return JSON.stringify([e.sourceScope,e.datasetId,e.rowKey])}function Dn(e){const t=new Map,r=new Set;return e.forEach((n,o)=>{for(const i of Ln(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 l=`${o}:${i.dataset}:${u}:${i.rowKey}`;if(r.has(l))return;r.add(l);const d=Sr({sourceScope:n.sourceScope,datasetId:i.dataset,rowKey:f}),m=t.get(d)??[];m.push({partIndex:o,dataset:i.dataset,rowIndex:u,row:c,binding:i}),t.set(d,m)})}}),n=>{const o=t.get(Sr(n));if(!o?.length)throw new k("missing");if(new Set(o.map(i=>`${i.partIndex}:${i.dataset}`)).size!==o.length)throw new k("conflict");return o}}function Bn(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=`${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}}return r}function Ca(e,t,r){const n=[],o=new Set;return e.forEach((i,s)=>{for(const a of Ln(i))t.has(he({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[l,d]of[[a.revisionField,r.revision],[a.sourceTokenField,r.sourceToken]]){if(!l||d===void 0)continue;const m=`${s}:${a.dataset}:${u}:${l}`;o.has(m)||(o.add(m),n.push({row:f,field:l,value:d}))}})}),n}function ja(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?[he(o.source)]:[]));return _n(e,new Map([...n].map(o=>[o,r])))}function _n(e,t){if(!t.size)return e;function r(i){const s=i.datasetId&&t.get(he({...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(d=>{const m=d.map(g=>{if(!g)return g;const h=g.source?r(g.source):void 0,w=g.children?n(g.children):void 0;return h===g.source&&w===g.children?g:{...g,source:h,children:w}});return m.some((g,h)=>g!==d[h])?m:d}),l=a.grid&&f?.some((d,m)=>d!==a.grid.cells[m])?{...a.grid,cells:f}:a.grid;return u!==a.table||l!==a.grid?{...a,table:u,grid:l}: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 Ge(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 La(e){const t=new Map,r=On(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(Ge(u),u)}})),t}function Kn(e,t){if(++e.nodes>1e6||t>128)throw new k("limit")}function cr(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||r.get||r.set)throw new k("conflict");return r.value}function Wn(e){if(Object.getOwnPropertyDescriptor(e,"toJSON"))throw new k("conflict");const t=Object.getPrototypeOf(e);if(!(e instanceof Date)&&!Array.isArray(e)&&t!==Object.prototype&&t!==null)throw new k("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 k("conflict");if(e instanceof Date||Array.isArray(e)&&!/^(0|[1-9]\d*)$/.test(r))throw new k("conflict")}}function Hn(e,t,r,n,o){if(Kn(n,o),typeof e=="function"||typeof e=="symbol")throw new k("conflict");if(e===null||typeof e!="object")return;if(Wn(e),r.has(e))throw new k("conflict");r.add(e);const i=Object.keys(e),s=i.map(a=>cr(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)Hn(a,t,r,n,o+1);r.delete(e)}function Da(e){const{object:t,keys:r,values:n}=e;if(Wn(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(cr(t,i),n[s]))}function Ba(e){const t=[];return Hn(e,t,new Set,{nodes:0},0),()=>{try{return t.every(Da)}catch{return!1}}}function Ft(e,t,r){return Kn(t,r),e===null||typeof e!="object"?e:e instanceof Date?new Date(Date.prototype.getTime.call(e)):Array.isArray(e)?e.map(n=>Ft(n,t,r+1)):Object.fromEntries(Object.keys(e).map(n=>[n,Ft(cr(e,n),t,r+1)]))}function _a(e){return Ft(e,{nodes:0},0)}async function Ka(e,t,r={}){const n=[],o={...r,knownTotalPages:void 0};for(const i of ls(e,t,o))n.push(i),n.length%8===0&&await new Promise(s=>setTimeout(s,0));if(r.signal?.aborted){const i=new Error("报表重算已取消");throw i.name="AbortError",i}return{schemaVersion:Ne,...rt(e)?{requiresRecalculation:!0}:{},pages:n}}const Ar=new WeakMap;function Re(e){if(e?.aborted){const t=new Error("报表重算已取消");throw t.name="AbortError",t}}function Jn(e,t){return e[t]===void 0?"":e[t]}function Wa(e,t){if(t.edits.length>1e4)throw new k("limit");const r=On(e),n=new Set,o=[],i=t.edits.map(s=>{const a=r(s.address);if(!a?.source)throw new k("missing");const c=Ge(s);if(n.has(c))throw new k("duplicate");if(n.add(c),Oa(a,s)||!Object.is(a.value,s.previousValue)||(a.cell.text??"")!==s.previousText)throw new k("conflict");return o.push(a),jn(a,s.value)});return{batch:{requestId:t.requestId,edits:i},contexts:o}}function Ha(e,t){const r=Dn(e);return t.flatMap(n=>{if(!n.source)throw new k("missing");return r(n.source).map(o=>{if(!Object.is(Jn(o.row,n.source.field),n.previousValue))throw new k("conflict");if(o.binding.rowKey===n.source.field)throw new k("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:Cn(n,n.value)},n}function Ja(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?[he(o.source)]:[]));return Bn(e,Ca(e,n,r))}function za(e,t,r){const n=new Set(t.edits.map(o=>he(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 Va(e,t){let r=t.parts;const n=t.rebuild;let o=Ba(r),i=e,s;const a=new Map,c=new Map;function u(d){if(d!==i)throw new k("conflict");if(s)return s;if(!o?.())throw new k("conflict");return _a(r)}async function f(d,m,g,h={}){Re(h.signal),m={requestId:m.requestId,edits:m.edits.map(y=>({...y,address:{...y.address},source:y.source?{...y.source}:void 0,table:y.table?{...y.table}:void 0}))},g=g.map(y=>({...y,address:{...y.address},source:y.source?{...y.source}:void 0,table:y.table?{...y.table}:void 0,cell:{...y.cell}})),await new Promise(y=>setTimeout(y,0)),Re(h.signal);const w=u(d),$=Bn(w,Ha(w,m.edits)),p=_n(await n($,h.signal),c);Re(h.signal);let x=!1;return{plan:p,commit(y){if(Re(h.signal),x||i!==d)throw new k("conflict");if(y?.conflicts?.length)throw new k("conflict");const M=Ja($,m,y),T=ja(p,m,y);if(y){const I=za(c,m,y);for(const[b,v]of a)I.has(he(v.source))&&a.set(b,yt(v,v.value,y))}return g.forEach((I,b)=>a.set(Ge(I),yt(I,m.edits[b].value,y))),x=!0,s=M,r=void 0,o=void 0,i=T,Ar.set(i,l),i}}}const l={get plan(){return i},async prepare(d,m,g){const h=Wa(d,m);return f(d,h.batch,h.contexts,g)},async prepareHistory(d,m,g,h,w){if(!h.trim()||m.length>1e4)throw new k("limit");const $=u(d),p=Dn($),x=La(d),y=new Set,T=m.map(v=>{if(!v.source)throw new k("missing");const E=Ge(v);if(y.has(E))throw new k("duplicate");y.add(E);const O=x.get(E)??a.get(E);if(!O?.source)throw new k("missing");const P=p(O.source)[0];return yt(O,Jn(P.row,O.source.field))}).map((v,E)=>({context:v,edit:jn(v,m[E][g])})).filter(({edit:v})=>!Object.is(v.previousValue,v.value)),I={requestId:h,edits:T.map(({edit:v})=>v)},b=T.map(({context:v})=>v);return{batch:I,contexts:b,prepared:await f(d,I,b,w)}}};return Ar.set(e,l),l}let Ua=0;function Le(){return`report-${Date.now()}-${++Ua}`}function fe(e,t,r){if(!r?.aborted)try{const n=e?.({...t});n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{})}catch{}}function re(e){const t=e.taskId??Le(),r=(n,o,i)=>{fe(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){fe(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 Ga(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 qa(e){return e==="missing-source"||e==="not-applicable"||e==="not-calculable"}function ur(e){return e.target!==void 0&&!Ga(e.target)?!1:e.valueState===void 0||qa(e.valueState)&&e.target!==void 0}const Ya=["text","number","boolean","date","decimal"],Za=new Set(["__proto__","prototype","constructor"]);function _(e){throw new Error(`数据契约无效:${e}`)}function zn(e){(!e||!Array.isArray(e.fields)||!e.fields.length||e.fields.length>2048)&&_("fields 应包含 1–2048 个字段");const t=new Set;for(const r of e.fields)(!r||typeof r.field!="string"||!r.field.trim()||Za.has(r.field)||t.has(r.field))&&_("字段名应安全、非空且唯一"),t.add(r.field),Ya.includes(r.type)||_(`未知字段类型 ${r.type}`),tc(r),ec(r),Xa(r);Qa(e,t)}function Xa(e){e.enum!==void 0&&(!Array.isArray(e.enum)||!e.enum.length||e.enum.some(t=>!Vn(t,e.type)))&&_("enum 应为匹配字段类型的非空标量数组")}function Qa(e,t){e.rowKey!==void 0&&((typeof e.rowKey!="string"||!e.rowKey.trim()||!t.has(e.rowKey))&&_("rowKey 应为引用已声明字段的非空字符串"),e.fields.find(r=>r.field===e.rowKey)?.type==="boolean"&&_("布尔字段不能作为业务主键"))}function ec(e){for(const t of["label","unit"])e[t]!==void 0&&typeof e[t]!="string"&&_(`${t} 应为字符串`);for(const t of["required","nullable"])e[t]!==void 0&&typeof e[t]!="boolean"&&_(`${t} 应为布尔值`);e.semanticRole!==void 0&&!["identifier","dimension","measure","date","text"].includes(e.semanticRole)&&_("未知字段语义")}function tc(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))&&_(`${t} 无效`)}e.min!==void 0&&e.max!==void 0&&e.min>e.max&&_("min 不能超过 max"),e.minLength!==void 0&&e.maxLength!==void 0&&e.minLength>e.maxLength&&_("minLength 不能超过 maxLength"),e.type!=="number"&&(e.min!==void 0||e.max!==void 0)&&_("min/max 仅适用于 number,精确小数文本需业务校验"),["number","boolean"].includes(e.type)&&(e.minLength!==void 0||e.maxLength!==void 0)&&_("长度约束仅适用于文本类型")}function rc(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 Vn(e,t){return t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":typeof e!="string"?!1:t==="date"?rc(e):t==="decimal"?e.length<=1e4&&/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e):!0}function nc(e,t){if(e==null)return t.required||e===null&&t.nullable===!1?{code:"required",message:"缺少必需字段值"}:void 0;if(!Vn(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"&&!oc(e,t))return{code:"range",message:"文本长度超出范围"}}function oc(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 wt(e,t){const r=e??t;if(!Number.isInteger(r)||r<1)throw new Error("数据校验预算应为正整数");return r}function ic(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 sc(e,t,r={}){zn(t);const n=r.path??"$.rows",o=[],i=wt(r.maxIssues,100);if(!Array.isArray(e))return{ok:!1,issues:[{code:"row",path:n,message:"数据集应为对象数组"}]};if(e.length>wt(r.maxRows,1e5)||e.length*t.fields.length>wt(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}ac(c,t,a,n,s,o,i)}return{ok:o.length===0,issues:o}}function ac(e,t,r,n,o,i,s){for(const a of t.fields){if(i.length>=s)return;const c=nc(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=ic(e,t.rowKey,o);a&&i.push({code:"row-key",path:`${n}[${r}].${t.rowKey}`,message:a,rowIndex:r,field:t.rowKey})}}function cc(e){return zn(e),{$schema:"https://json-schema.org/draft/2020-12/schema",type:"array",items:{type:"object",properties:Object.fromEntries(e.fields.map(r=>[r.field,uc(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 uc(e,t){const r=!t&&e.nullable!==!1&&!e.required;return{type:r?[Er(e.type),"null"]:Er(e.type),...e.label?{title:e.label}:{},...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},...fc(e,t),...t&&e.type==="text"?{pattern:"\\S"}:{},...e.unit?{"x-report-unit":e.unit}:{},...e.semanticRole?{"x-report-semanticRole":e.semanticRole}:{}}}function fc(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 Er(e){return e==="text"||e==="date"||e==="decimal"?"string":e}function Un(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]=Qr(t[i]??[],{...s,maxRows:a},r.signal)}return o}function dc(e,t,r={}){return Object.values(Un(e,t,r)).reduce((n,o)=>n+o.length,0)}function lc(e,t,r){const n=cc(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 fr(e,t){return JSON.stringify([e,t])}function Gn(e,t,r){return r===void 0?fr(e,t):JSON.stringify(["shared",r])}function qn(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:qn(a.children,t,r)}:{}}));return o||i?{...n,...o?{table:o}:{},...i?{grid:{...n.grid,cells:i}}:{}}:n})}class S extends Error{constructor(t,r,n){super(r),this.name="ReportSourceError",this.code=t,this.cause=n}}function ft(e){const t=new Error("报表加载已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function H(e){if(e?.aborted)throw ft(e)}function Rt(e,t){return t?new Promise((r,n)=>{const o=()=>t.removeEventListener("abort",i),i=()=>{o(),n(ft(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 mc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new S("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 S("validate",`报表 ${t} 的数据集 ${r} 应为对象数组`)}async function gc(e,t,r){const{reportId:n,signal:o}=t;try{const i=await Rt(e(t),o);H(o);const s=la(i);if(!s.ok)throw new S("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?ft(o):i instanceof S?i:i instanceof qs?new S("validate",`报表 ${n} 模板校验失败:${i.message}`,i):new S("fetch",`报表 ${n} 模板加载失败:${i instanceof Error?i.message:String(i)}`,i)}}async function hc(e,t,r,n){const o=t.signal;let i;try{if(e.load)i=await Rt(e.load(t),o);else if(e.provider){const s=await Rt(e.provider.query(t),o);H(o),pc(s,r),i=s.datasets,n?.(r,s)}else i=e.datasets??{}}catch(s){throw o?.aborted?ft(o):s instanceof S?s:new S("fetch",`报表 ${r} 取数失败:${s instanceof Error?s.message:String(s)}`,s)}return H(o),i}function pc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new S("validate",`报表 ${t} Provider 应返回 datasets 结果对象`);for(const r of["revision","sourceToken"])if(e[r]!==void 0&&typeof e[r]!="string")throw new S("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 S("validate",`报表 ${t} Provider diagnostics 不符合结构化诊断契约`);if(e.diagnostics?.some(r=>!ur(r)))throw new S("validate",`报表 ${t} Provider 数据说明缺少有效的字段身份或值状态`)}function yc(e,t,r,n,o){try{t=Un(n,t,{maxRows:e.dataValidation?.maxRows,signal:o})}catch(i){throw new S("validate",`报表 ${r} 树形数据无效:${i instanceof Error?i.message:String(i)}`,i)}for(const[i,s]of Object.entries(e.dataSchema??{})){let a;try{a=sc(Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0,s,{...e.dataValidation,path:`$.datasets.${i}`})}catch(c){throw new S("config",`报表 ${r} 数据集 ${i} 字段契约配置无效`,c)}if(!a.ok)throw new S("validate",`报表 ${r} 数据集 ${i} 不符合字段契约:${a.issues[0]?.message}`,{issues:a.issues})}}function Yn(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 Zn(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 Xn(e,t,r,n){return{...e,signal:n??e?.signal,...t===void 0?{}:{maxPages:Math.max(1,Math.min(t,e?.maxPages??t))},...r===void 0?{}:{maxCells:Math.max(1,Math.min(r,e?.maxCells??r))}}}function wc(e,t,r,n,o,i){const s=o.maxPages===void 0?void 0:o.maxPages-o.usedPages,a=o.maxCells===void 0?void 0:o.maxCells-o.usedCells;try{if(s!==void 0&&s<1&&e.pages.length&&!Yn(e,t))throw new oe(0,1);const c=Xn(r.pagination,s,a,i),u=ms(e,t,c),f=Zn(u.plan);if(a!==void 0&&f>a)throw new ue(a,f);return{...u,cells:f}}catch(c){let u=c;throw c instanceof oe&&o.maxPages!==void 0&&c.limit===s&&(u=new oe(o.maxPages,o.usedPages+c.actual)),c instanceof ue&&o.maxCells!==void 0&&(u=new ue(o.maxCells,o.usedCells+c.actual)),new S("validate",`报表 ${n} 排版失败:${u instanceof Error?u.message:String(u)}`,u)}}function Qn(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:fr(r,n)},components:qn(a.components,o??Gn(r,n),s)})}async function bc(e,t,r,n,o){const i=[];let s=0;for(const[u,f]of e.entries()){H(o);const l=n.maxPages===void 0?void 0:n.maxPages-i.length,d=n.maxCells===void 0?void 0:n.maxCells-s;if(l!==void 0&&l<1&&f.template.pages.length&&!Yn(f.template,f.datasets))throw new oe(n.maxPages,i.length+1);const m=await Ka(f.template,f.datasets,Xn(t[u]?.pagination,l,d,o));if(s+=Zn(m),n.maxCells!==void 0&&s>n.maxCells)throw new ue(n.maxCells,s);Qn(i,m,u,r[u],f.sourceScope)}const a={schemaVersion:Ne,...e.some(u=>rt(u.template))?{requiresRecalculation:!0}:{},pages:i},c=at(a);if(!c.ok)throw new S("validate",`重算渲染计划校验失败:${c.errors[0]?.message}`);return a}function $c(e,t={}){if(t.maxPages!==void 0&&(!Number.isSafeInteger(t.maxPages)||t.maxPages<1))throw new S("config","maxPages 应为正安全整数");if(t.maxCells!==void 0&&(!Number.isSafeInteger(t.maxCells)||t.maxCells<1))throw new S("config","maxCells 应为正安全整数");function r(o){const i=Object.prototype.hasOwnProperty.call(e,o)?e[o]:void 0;if(!i)throw new S("config",`未注册报表 ${o}`);if(i.sourceScope!==void 0&&(typeof i.sourceScope!="string"||!i.sourceScope.trim()||i.sourceScope.length>512))throw new S("config","sourceScope 应为不超过 512 字符的非空字符串");return i}return Object.assign(async({reportIds:o,params:i,signal:s,onWarning:a,onQueryResult:c,...u})=>{H(s);const f=re({...u,signal:s}),l=[...o],d={...i};if(l.length===0)throw new S("config","缺少报表 ID");const m=l.map(r),g=f.runSync("validate",()=>m.map(b=>xr(b.params??(typeof b.template=="function"?[]:b.template.params)??[],d))),h=[],w=[];let $=0;const p=[];for(const[b,v]of m.entries()){H(s);const E=l[b],O={reportId:E,params:g[b],signal:s},P=typeof v.template=="function"?await f.run("query",()=>gc(v.template,O,p),E):v.template;O.params=f.runSync("validate",()=>xr(v.params??P.params??[],O.params),E);const R=await f.run("query",()=>hc(v,O,E,(gt,Ao)=>c?.(gt,Ao,b)),E);f.runSync("validate",()=>{mc(R,E),t.onDatasets?.(E,R,P),yc(v,R,E,P,s)},E),H(s);const mt=f.runSync("layout",()=>wc(P,R,v,E,{maxPages:t.maxPages,usedPages:h.length,maxCells:t.maxCells,usedCells:$},s),E);$+=mt.cells;const mr=Gn(b,E,v.sourceScope);w.push({template:P,datasets:R,sourceScope:mr}),Qn(h,mt.plan,b,E,mr),p.push(...mt.warnings.map(gt=>`${E}: ${gt}`))}H(s);const x={schemaVersion:Ne,...w.some(b=>rt(b.template))?{requiresRecalculation:!0}:{},pages:h},y=f.runSync("validate",()=>{const b=at(x);if(!b.ok)throw new S("validate",`渲染计划校验失败:${b.errors.slice(0,3).map(v=>`${v.path}: ${v.message}`).join("; ")}`);return b});p.push(...y.warnings.map(b=>`${b.path}: ${b.message}`));const M=m.map(b=>({...b,pagination:{...b.pagination}})),T={maxPages:t.maxPages,maxCells:t.maxCells};try{Va(x,{parts:w,rebuild:(b,v)=>bc(b,M,l,T,v)})}catch{p.push("来源数据无法建立本地重算口径;当前预览仅支持计划内编辑,请使用可序列化模板数据启用规则重算")}const I=a??t.onWarning??(b=>console.warn("[mach-report]",b));for(const b of p)H(s),I(b);return H(s),x},{getParamDefs:o=>Ue(e,o)})}const dr=Object.freeze({maxRows:1e5,maxPages:1e4,maxCells:2e6,maxOutputBytes:1e8,maxPreparedBytes:64e6,maxDurationMs:12e4});class D extends Error{constructor(t,r,n){super(r),this.code=t,this.path=n,this.name="ReportRuntimeError"}}function L(e){if(!e?.aborted)return;if(e.reason instanceof D)throw e.reason;const t=new Error("报表执行已取消");throw t.name="AbortError",Object.defineProperty(t,"cause",{value:e.reason}),t}function j(e,t,r){if(!Number.isFinite(r)||r<0)throw new D("budget",`${t} 的执行统计无效`,`$.budget.${t}`);const n=e[t];if(n!==void 0&&r>n)throw new D("budget",`${t} 超出预算 ${n}(实际 ${r})`,`$.budget.${t}`)}function eo(e){for(const[t,r]of Object.entries(e)){if(r!==void 0&&(!Number.isFinite(r)||r<=0))throw new D("budget",`${t} 应为正有限数字`,`$.budget.${t}`);if(t!=="maxDurationMs"&&r!==void 0&&!Number.isSafeInteger(r))throw new D("budget",`${t} 应为正安全整数`,`$.budget.${t}`);if(t==="maxDurationMs"&&r!==void 0&&r>2147483647)throw new D("budget","maxDurationMs 不能超过 2147483647",`$.budget.${t}`)}}async function $e(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 D("timeout",`报表执行超过 ${t}ms`)),t);let a;try{L(n.signal);const c=new Promise((f,l)=>{a=()=>{try{L(n.signal)}catch(d){l(d)}},n.signal.addEventListener("abort",a,{once:!0})}),u=await Promise.race([r(n.signal),c]);if(L(n.signal),t!==void 0&&Date.now()-i>t)throw new D("timeout",`报表执行超过 ${t}ms`);return u}finally{s!==void 0&&clearTimeout(s),a&&n.signal.removeEventListener("abort",a),e?.removeEventListener("abort",o)}}function to(e,t){ne.assertOutputActive(t.signal),ne.observeOutput(()=>t.onDiagnostic?.(e)),ne.assertOutputActive(t.signal)}class dt extends Error{constructor(t,r){super(r),this.code=t,this.name="ImageMediaError"}}const bt={maxImageBytes:16*1024*1024,maxTotalImageBytes:32*1024*1024,maxImages:1e3,maxImagePixels:16e6,maxTotalImagePixels:64e6,maxImageDimension:16384};function U(e){throw new dt("invalid-image-data",e)}function xe(e){throw new dt("image-budget-exceeded",e)}function xc(e){const t={...bt};for(const r of Object.keys(bt)){const n=e[r]??bt[r];if(!Number.isSafeInteger(n)||n<=0||n>2147483647)throw new RangeError(`${r} 图片预算须为1至2147483647的整数。`);t[r]=n}return t}function vc(e){if(e.length<33||![137,80,78,71,13,10,26,10].every((r,n)=>e[n]===r))return U("图片内容与 PNG/JPEG 类型不一致。");const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return t.getUint32(8)!==13||String.fromCharCode(...e.subarray(12,16))!=="IHDR"?U("PNG must begin with an IHDR header."):[t.getUint32(16),t.getUint32(20)]}const Mc=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]);function Sc(e){if(e[0]!==255||e[1]!==216)return U("图片内容与 PNG/JPEG 类型不一致。");let t=2;for(;t+3<e.length;){if(e[t++]!==255)return U("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 U("JPEG segment exceeds its data boundary.");if(Mc.has(r))return n<8?U("JPEG frame header is incomplete."):[e[t+5]*256+e[t+6],e[t+3]*256+e[t+4]];t+=n}return U("JPEG has no supported dimension header.")}function Ac(e,t){if(e.length>Math.ceil(t.maxImageBytes/3)*4+64)return xe("单张图片超过字节预算。");const r=/^data:image\/(png|jpe?g);base64,([A-Za-z0-9+/]+={0,2})$/i.exec(e);if(!r||r[2].length%4)return U("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 xe("单张图片超过字节预算。");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"?vc(a):Sc(a);return!c||!u?U("Image dimensions must be positive."):c>t.maxImageDimension||u>t.maxImageDimension||c*u>t.maxImagePixels?xe("Image exceeds its decoded dimension or pixel budget."):{dataUrl:`data:image/${i};base64,${n}`,bytes:a,extension:i,width:c,height:u}}function Ec(e={}){const t=xc(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 xe("唯一图片数量超过预算。");const c=Ac(i,t);return n+c.bytes.length>t.maxTotalImageBytes||o+c.width*c.height>t.maxTotalImagePixels?xe("图片总字节或总像素超过预算。"):(n+=c.bytes.length,o+=c.width*c.height,r.set(s,c),c)}}class lr extends Error{constructor(t,r){super(t.message),this.name="OutputAssetError",this.diagnostic=t,this.cause=r}}function qe(e){if(e.aborted)throw e.reason??new DOMException("The operation was aborted.","AbortError")}function kc(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 Pc(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 Te(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),to(i,{...e.options,signal:e.signal}),e.options.assetFailure!=="placeholder")throw new lr(i,o)}async function Nc(e,t,r){const n=e.options.assetRenderers?.[t.kind];if(t.imageData||!n)return t.imageData;if(++e.rendered>e.budget.maxAssets)return Te(e,r,"asset-budget-exceeded","Output exceeded the asset count budget.");let o;try{if(e.active=r,o=await ne.waitForOutput(n({...r,signal:e.signal}),e.signal),qe(e.signal),o.length>e.budget.maxImageBytes*4+1024)return Te(e,r,"asset-budget-exceeded","Output exceeded the image payload byte budget.");const i=Pc(o);if(i>e.budget.maxImageBytes||e.bytes+i>e.budget.maxTotalImageBytes)return Te(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 lr||i instanceof dt&&i.code==="image-budget-exceeded")throw i;return Te(e,r,"asset-render-failed",`Asset renderer failed for ${t.kind}; output was not silently omitted.`,i)}return o}function Ic(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{to(n,{...e.options,signal:e.signal})}catch(o){t.abort(o);return}t.abort(new lr(n))}async function Fc(e,t,r,n,o){if(!t?.children?.length)return t;const i=[];for(const[s,a]of t.children.entries())i.push(await ro(e,a,{...r,component:a,componentPath:[...n,s]},o));return i.some((s,a)=>s!==t.children[a])?{...t,children:i}:t}async function ro(e,t,r,n){if(qe(e.signal),n.has(t))throw new TypeError("Cyclic grid children cannot be rendered.");let o=e.cache.get(t);o||(o=Nc(e,t,r),e.cache.set(t,o));const i=await o;qe(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 l=[];for(const[d,m]of f.entries())l.push(await Fc(e,m,r,[...r.componentPath,u,d],a));c.push(l)}c.some((u,f)=>u.some((l,d)=>l!==s.cells[f][d]))&&(s={...s,cells:c})}return i!==t.imageData||s!==t.grid?{...t,imageData:i,grid:s}:t}function Rc(e,t,r){const n=new Set,o=i=>{if(ne.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 dt)||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)}async function kr(e,t={}){ne.assertOutputActive(t.signal),ys(e);const r=kc(t),n=Ec(t);if(Rc(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.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(()=>Ic(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 l=[];for(const[d,m]of f.components.entries())l.push(await ro(s,m,{component:m,pageIndex:u,componentIndex:d,componentPath:[]},new Set));c.push(l.some((d,m)=>d!==f.components[m])?{...f,components:l}:f)}return qe(s.signal),{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 Ye(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 Pr(e,t,r=Date.now()){const n=e.prepared,o=e.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;L(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=re(e),c=await a.run("encode",async()=>{let l;if(e.format==="pdf"){L(e.signal);const d=await o.renderPlanToPdf(n.plan,{...e.pdf,...s?{measurer:s}:{},fidelity:e.fidelity,signal:e.signal,onProgress:(m,g)=>a.progress("encode",m,g)});l=d.bytes,n.diagnostics.push(...Ye(d.diagnostics)),n.diagnostics.push(...d.fidelityWarnings.map(m=>({code:"pdf-fidelity",message:m,severity:"warning"})),...d.pageErrors.map(m=>({code:"pdf-page",message:m,severity:"error"}))),d.unsupportedTextCount&&n.diagnostics.push({code:"pdf-font",message:`${d.unsupportedTextCount} 段文本包含当前字体不支持的字符`,severity:"warning"})}else{const{renderPlanToXlsx:d}=await import("@agile-team/mach-report/xlsx");L(e.signal);const m=await d(n.plan,{...e.xlsx,fidelity:e.fidelity,signal:e.signal,onProgress:(g,h)=>a.progress("encode",g,h)});l=new Uint8Array(m.buffer),n.diagnostics.push(...Ye(m.diagnostics)),n.diagnostics.push(...m.warnings.map(g=>({code:"xlsx-fidelity",message:g,severity:"warning"})))}return L(e.signal),l});j(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 Tc(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,l){if(++n>r||l>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,l)}function c(f,l){const d=Array.isArray(f),m=Object.getPrototypeOf(f);if(m!==(d?Array.prototype:Object.prototype)&&!(m===null&&!d)||Object.getOwnPropertySymbols(f).length)throw t.error("input","快照应为普通 JSON 对象");const g=Object.getOwnPropertyNames(f).filter($=>!(d&&$==="length"));if(d&&(g.length!==f.length||g.some(($,p)=>$!==String(p))))throw t.error("input","快照数组应为连续数组");i.add(f),s(2);const h=Object.create(null);let w=0;for(const $ of g){const p=Object.getOwnPropertyDescriptor(f,$);if(p.get||p.set||!p.enumerable||["__proto__","constructor","prototype"].includes($))throw t.error("input","快照不允许访问器或危险键");p.value===void 0&&!d||(s((w++?1:0)+(d?0:$.length+3)),h[$]=a(p.value===void 0?null:p.value,l+1))}return i.delete(f),d?g.map($=>h[$]):h}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 Oc=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]),J=(e,t)=>e>>>t|e<<32-t;function no(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=J(i,7)^J(i,18)^i>>>3,c=J(s,17)^J(s,19)^s>>>10;r[o]=r[o-16]+a+r[o-7]+c}}function oo(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 l=J(s,6)^J(s,11)^J(s,25),d=s&a^~s&c,m=u+l+d+Oc[f]+t[f]>>>0,g=J(r,2)^J(r,13)^J(r,22),h=r&n^r&o^n&o,w=g+h>>>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 io(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 so=()=>new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ao=e=>Array.from(e,t=>t.toString(16).padStart(8,"0")).join("");function Nr(e){const t=io(e),r=so(),n=new Uint32Array(64);for(let o=0;o<t.length;o+=64)no(t,o,n),oo(r,n);return ao(r)}async function Cc(e){const t=io(e),r=so(),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)),no(t,o,n),oo(r,n);return ao(r)}function Tt(e){return e&&{...e}}function ve(e){if(!e)return;const t=r=>{if(!(r instanceof Uint8Array)&&!(r instanceof ArrayBuffer))throw new S("validate","字体应为 Uint8Array 或 ArrayBuffer");if(r.byteLength>32e6)throw new D("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 co(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 D("budget","单份字体超过 32 MB","$.pdf");return[n,Nr(i)]});return Nr(new TextEncoder().encode(JSON.stringify(r)))}const Ot=new WeakMap;function jc(e,t,r){const n=uo(e,t,r);let o=!0;return{prepared:n,forward(){if(!o)throw new Error("报表快照只能交接一次");return o=!1,Ot.set(n,t),n}}}function uo(e,t,r){if(L(r),!Number.isSafeInteger(t)||t<=0)throw new D("budget","快照预算应为正安全整数","$.budget.maxPreparedBytes");const n=Ot.get(e);if(Ot.delete(e),n!==void 0&&n<=t)return e;const o=Tc(e,{maxBytes:t,maxNodes:t,check:()=>L(r),error:(i,s)=>i==="budget"?new D("budget",s,"$.budget.maxPreparedBytes"):new S("validate",s)});return Lc(o),o}function fo(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 Lc(e){if(!fo(e.sources))throw new S("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 S("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)||!ur(t)))throw new S("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 S("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 S("validate","准备结果字体度量标识无效")}function Dc(e){if(e.layoutPolicy!==void 0&&!["verify","preserve"].includes(e.layoutPolicy))throw new S("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=co(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 S("validate",n);e.prepared.diagnostics.push({code:"prepared-font-metrics",severity:"warning",message:n})}function Ir(e){return{...e,reportIds:[...e.reportIds],...e.params?{params:{...e.params}}:{}}}function lo(e,t){if(t.length===0)throw new S("config","缺少报表 ID");return t.map(r=>{if(!Object.prototype.hasOwnProperty.call(e,r))throw new S("config",`未注册报表 ${r}`);return e[r]})}function lt(e){return e.grid?.cells.reduce((t,r)=>t+r.reduce((n,o)=>n+(o?1+(o.children?.reduce((i,s)=>i+lt(s),0)??0):0),0),0)??0}function Bc(e,t,r){return e.pages.reduce((n,o)=>n+o.components.reduce((i,s)=>s.kind!=="list"?i+lt(s):i+ps(s,t,r),0),0)}function _c(e,t=Object.keys(e)){return lo(e,t).map((r,n)=>{const o=t[n],i=Ue(e,[o]);return{id:o,params:JSON.parse(JSON.stringify(i)),paramsSchema:zs(i),datasetsSchema:Object.fromEntries(Object.entries(r.dataSchema??{}).map(([s,a])=>[s,lc(typeof r.template=="function"?void 0:r.template,s,a)])),capabilities:{save:!!r.provider?.save,export:!!r.provider?.export,templates:!!r.provider?.templates}}})}function mo(e,t){lo(e,t.reportIds);const r=Nt(Ue(e,t.reportIds),t.params),n=t.reportIds.flatMap(i=>Nt(Ue(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 Ct(e,t){const r=at(e.plan);if(!r.ok)throw new S("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+lt(c),0),0);return j(t,"maxRows",e.stats.rows),j(t,"maxPages",n),j(t,"maxCells",o),{...e,stats:{...e.stats,pages:n,cells:o}}}function Fr(e,t){const r=mo(e.reports,t);if(!r.ok)throw new ct(r.issues)}function go(e){const t={...dr,...e.budget};eo(t);const r=async(o,i)=>{const s=Date.now();let a=0,c=0;const u=[],f={},l=[],d=Object.fromEntries(Object.entries(e.reports).map(([y,M])=>[y,{...M,pagination:{...e.pagination,...M.pagination,...i?{measurer:i}:{}},dataValidation:{...M.dataValidation,maxRows:Math.min(t.maxRows??1e5,M.dataValidation?.maxRows??1/0),maxCells:Math.min(t.maxCells??2e6,M.dataValidation?.maxCells??1/0)}}])),g=await $c(d,{maxPages:t.maxPages,maxCells:t.maxCells,onDatasets:(y,M,T)=>{try{a+=dc(T,M,{maxRows:t.maxRows,signal:o.signal})}catch(I){throw I instanceof zr?new D("budget",I.message,"$.budget.maxRows"):I}j(t,"maxRows",a),c+=Bc(T,M,d[y]?.pagination),j(t,"maxCells",c)}})({...o,params:o.params??{},onWarning:y=>u.push({code:"layout",message:y,severity:"warning"}),onQueryResult:(y,M,T=0)=>{const I=fr(T,y);Object.defineProperty(f,y,{value:{revision:M.revision,sourceToken:M.sourceToken},enumerable:!0,writable:!0}),l.push({reportId:y,reportIndex:T,reportScope:I,...M.revision===void 0?{}:{revision:M.revision},...M.sourceToken===void 0?{}:{sourceToken:M.sourceToken}}),u.push(...(M.diagnostics??[]).map(b=>({...b,...b.target?{target:{...b.target,reportScope:I,...b.target.tableId?{tableId:JSON.stringify([T,y,b.target.tableId])}:{}}}:{}})))}}).catch(y=>{throw y instanceof S&&y.cause instanceof oe?new D("budget",y.cause.message,"$.budget.maxPages"):y instanceof S&&y.cause instanceof ue?new D("budget",y.cause.message,"$.budget.maxCells"):y});L(o.signal);const h=e.assets?await re(o).run("assets",()=>kr(g,{...e.assets,signal:o.signal})):{plan:g,diagnostics:[]},w=h.plan;u.push(...Ye(h.diagnostics));const $=w.pages.reduce((y,M)=>y+M.components.reduce((T,I)=>T+lt(I),0),0);j(t,"maxPages",w.pages.length),j(t,"maxCells",$);const p=co(o.pdf),x=e.pagination?.measurer||Object.values(e.reports).some(y=>y.pagination?.measurer);return{plan:w,diagnostics:u,revisions:f,sources:l,layout:{textMetrics:p?"font-bytes":x?"provided":"heuristic",...p?{fontFingerprint:p}:{}},stats:{rows:a,pages:w.pages.length,cells:$,durationMs:Date.now()-s}}},n=async o=>{const i=Date.now();if(o.format!=="pdf"&&o.format!=="xlsx")throw new S("config","不支持的报表导出格式");const s=o.format==="pdf"?await import("@agile-team/mach-report/pdf"):void 0;L(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 L(o.signal),Pr({...o,prepared:u},t,i)};return{describe:o=>_c(e.reports,o),validate:o=>mo(e.reports,o),prepare:o=>$e(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=Ir(o),u={...c,...c.pdf?{pdf:ve(c.pdf)}:{},taskId:c.taskId??Le()},f=a?h=>fe(a,h,i):void 0,l={...u,signal:i,onEvent:f};re(l).runSync("validate",()=>Fr(e,u));let d;const m=u.pdf?.customFontFaces??(u.pdf?.customFontBytes?{regular:u.pdf.customFontBytes}:void 0);if(!e.executor&&m){const h=await import("@agile-team/mach-report/pdf");L(i),d=h.createFontBytesMeasurer(m)}const g=e.executor?await e.executor.prepare(u,i,f):await r(l,d);return Ct(g,t)}),exportPrepared:o=>$e(o.signal,t.maxDurationMs,async i=>{const s=Date.now(),{signal:a,onEvent:c,...u}=o,f=Ct(uo(o.prepared,t.maxPreparedBytes??64e6,i),t),l={...u,xlsx:Tt(u.xlsx),prepared:f,...u.pdf?{pdf:ve(u.pdf)}:{},taskId:u.taskId??Le()};if(l.format!=="pdf"&&l.format!=="xlsx")throw new S("config","不支持的报表导出格式");const d=c?g=>fe(c,g,i):void 0;if(e.executor){if(!e.executor.exportPrepared)throw new S("config","执行器未实现 exportPrepared;请升级执行器或显式使用本地运行时");const g=await e.executor.exportPrepared(l,i,d);return j(t,"maxRows",g.stats.rows),j(t,"maxPages",g.stats.pages),j(t,"maxCells",g.stats.cells),j(t,"maxOutputBytes",g.bytes.byteLength),{...g,stats:{...g.stats,outputBytes:g.bytes.byteLength}}}const m={...l,signal:i,onEvent:d};if(re(m).runSync("validate",()=>Dc(m)),e.assets){const g=await re(m).run("assets",()=>kr(f.plan,{...e.assets,signal:i}));f.plan=g.plan,f.diagnostics.push(...Ye(g.diagnostics))}return Pr(m,t,s)}),export:o=>$e(o.signal,t.maxDurationMs,async i=>{const{signal:s,onEvent:a,...c}=Ir(o),u={...c,xlsx:Tt(c.xlsx),...c.pdf?{pdf:ve(c.pdf)}:{},taskId:c.taskId??Le()},f=a?m=>fe(a,m,i):void 0,l={...u,signal:i,onEvent:f};if(re(l).runSync("validate",()=>Fr(e,u)),u.format!=="pdf"&&u.format!=="xlsx")throw new S("config","不支持的报表导出格式");const d=e.executor?await e.executor.export(u,i,f):await n(l);return j(t,"maxRows",d.stats.rows),j(t,"maxPages",d.stats.pages),j(t,"maxCells",d.stats.cells),j(t,"maxOutputBytes",d.bytes.byteLength),{...d,stats:{...d.stats,outputBytes:d.bytes.byteLength}}})}}const Kc={cells:2e4,pages:20,bytes:2e6};function Me(e){return e.cells>=e.limits.cells||e.pages>=e.limits.pages||e.bytes>=e.limits.bytes||e.capped}function ce(e){return++e.visits>=1e5&&(e.capped=!0),!Me(e)}function Z(e){return typeof e=="string"?e.length*2:0}function Rr(e,t){for(const r of e??[]){if(!ce(t))return;for(const n of r.segments){if(!ce(t))return;t.bytes+=Z(n.text)}}}function ho(e,t,r){if(r>32){t.capped=!0;return}if(ce(t)){t.bytes+=Z(e.text)+Z(e.rawText)+Z(e.imageData),Rr(e.richParagraphs,t);for(const n of e.lines??[]){if(!ce(t))return;t.bytes+=Z(n)}for(const n of e.grid?.cells??[]){if(!ce(t))return;for(const o of n){if(!ce(t))return;if(o){t.cells++,t.bytes+=Z(o.text)+Z(o.rawText)+Z(o.value),Rr(o.richParagraphs,t);for(const i of o.children??[]){if(Me(t))return;ho(i,t,r+1)}}}}}}function Wc(e){const t={...Kc,...e.thresholds};for(const r of Object.values(t))if(!Number.isSafeInteger(r)||r<=0)throw new RangeError("导出隔离阈值应为正安全整数");return t}function Hc(e,t){const r=Wc(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(Me(o))break;for(const c of a.components){if(Me(o))break;ho(c,o,0)}}let i=Me(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 ee="mach-report-worker/1";class jt 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 te(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Jc(e){return te(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 zc(e){return Array.isArray(e)&&e.every(t=>te(t)&&typeof t.code=="string"&&typeof t.message=="string"&&["info","warning","error"].includes(t.severity)&&ur(t))}function Vc(e){return te(e)&&Object.values(e).every(t=>te(t)&&(t.revision===void 0||typeof t.revision=="string")&&(t.sourceToken===void 0||typeof t.sourceToken=="string"))}function Uc(e){return e===void 0?!0:te(e)&&["heuristic","provided","font-bytes"].includes(e.textMetrics)&&(e.fontFingerprint===void 0||typeof e.fontFingerprint=="string"&&/^[a-f0-9]{64}$/.test(e.fontFingerprint))}function Gc(e,t){if(!te(e)||!Jc(e.stats)||!zc(e.diagnostics)||!Vc(e.revisions)||!Uc(e.layout)||!fo(e.sources))return!1;if(t==="prepare")return at(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 po(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 qc(e){const t=po(e);if(!te(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 yo(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(po)}:{},...Array.isArray(t.diagnostics)?{diagnostics:t.diagnostics.map(qc)}:{}}}function wo(e){if(!e||typeof e!="object")return!1;const t=e;return t.protocol===ee&&typeof t.id=="string"&&(t.operation==="prepare"||t.operation==="export"||t.operation==="exportPrepared")&&!!t.input&&typeof t.input=="object"}async function bo(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:ee,id:t.id,result:n}}catch(n){return{protocol:ee,id:t.id,error:yo(n)}}}function $o(e){const t=e.result;return!t||!("bytes"in t)||!(t.bytes.buffer instanceof ArrayBuffer)?[]:[t.bytes.buffer]}function Yc(e,t){if(!te(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 Lt extends Error{constructor(t){super("报表 Worker 无法启动"),this.cause=t,this.name="ReportWorkerStartError"}}let Zc=0;function Tr(e){const t=new Error("报表 Worker 任务已取消");return t.name="AbortError",Object.defineProperty(t,"cause",{value:e}),t}function Xc(e,t){if(!e||typeof e!="object")return;const r=e;return r.protocol===ee&&r.id===t?r:void 0}function Qc(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(Tr(s.reason)):new Promise((c,u)=>{let f;try{f=e()}catch(p){u(new Lt(p));return}const l=`mach-report-${Date.now()}-${++Zc}`;let d=!1,m=()=>{},g;const h=(p,x)=>{if(d)return;d=!0,g&&clearTimeout(g);let y;try{m()}catch(M){y=M}s?.removeEventListener("abort",w),p??=y,Promise.resolve().then(()=>f.terminate()).then(()=>p===void 0?c(x):u(p),M=>u(p??M))},w=()=>h(Tr(s?.reason)),$=p=>{const x=Xc(p,l);if(!(!x||d)){if("type"in x&&x.type==="event"){const y="event"in x?x.event:void 0;Yc(y,i)?fe(a,y,s):h(new Error("报表 Worker 返回无效阶段事件"));return}x.error&&typeof x.error.name=="string"&&typeof x.error.message=="string"?h(new jt(x.error)):Gc(x.result,o)&&(o==="prepare"||"format"in x.result&&"format"in i&&x.result.format===i.format)?h(void 0,x.result):h(new Error("报表 Worker 返回无效响应"))}};try{if(m=f.subscribe($,p=>h(p??new Error("报表 Worker 执行失败"))),d){m();return}if(s?.addEventListener("abort",w,{once:!0}),g=setTimeout(()=>h(new jt({name:"ReportRuntimeError",code:"timeout",message:`报表 Worker 执行超过 ${r}ms`})),r),s?.aborted)w();else{const{onEvent:p,signal:x,...y}=i,M=eu(y);f.postMessage({protocol:ee,id:l,operation:o,input:y,...t.budget?{budget:t.budget}:{}},M)}}catch(p){h(p)}});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 eu(e){return e.pdf?(e.pdf=ve(e.pdf),(e.pdf?.customFontFaces?Object.values(e.pdf.customFontFaces):[e.pdf?.customFontBytes]).filter(r=>r instanceof Uint8Array).map(r=>r.buffer)):[]}function tu(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("无效的导出回退策略");eo({...e.budget,maxDurationMs:e.timeoutMs??e.budget?.maxDurationMs??12e4})}function Or(e,t){ne.observeOutput(()=>e.onDecision?.({...t,estimate:{...t.estimate}}))}function Cr(e,t){return{...e,mode:"local",reason:t,hardCancellation:!1}}function ru(e,t){const r={...dr,...t.budget},n=jc(e.prepared,r.maxPreparedBytes,e.signal),o=Ct(n.prepared,r);n.prepared.stats=o.stats;const i={...e,prepared:n.prepared,pdf:ve(e.pdf),xlsx:Tt(e.xlsx)};return{request:i,forward:()=>({...i,prepared:n.forward()})}}function nu(e,t){tu(e);const r={...e,thresholds:{...e.thresholds},budget:{...dr,...e.budget}},n=r.timeoutMs??r.budget.maxDurationMs??12e4,o=go({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 l=Date.now(),d=()=>{const $=n-(Date.now()-l);if($<=0)throw new D("timeout",`报表执行超过 ${n}ms`);return $};let m=Hc(u,r);if(m.reason==="nonserializable-options"&&r.mode==="worker")throw new TypeError("Worker 模式不接受函数选项;请使用本地模式或可序列化配置");if(m.mode==="worker"&&!t){if(!a)throw new Lt(new Error("未配置 workerFactory"));m=Cr(m,"worker-unavailable")}const g=ru(u,r),h=g.request;if(Or(r,m),L(u.signal),m.mode==="worker")try{const $=t(d());if(!$.exportPrepared)throw new TypeError("隔离执行器缺少 exportPrepared");const{signal:p,onEvent:x,...y}=h,M=await $.exportPrepared(y,p,x);return L(p),j(r.budget,"maxOutputBytes",M.bytes.byteLength),{...M,execution:m}}catch($){if(!($ instanceof Lt)||!a)throw $;L(u.signal),m=Cr(m,"worker-start-failed"),Or(r,m)}const w=f?await $e(u.signal,d(),$=>f({...h,signal:$})):await $e(u.signal,d(),$=>o.exportPrepared({...g.forward(),signal:$}));return L(u.signal),j(r.budget,"maxOutputBytes",w.bytes.byteLength),{...w,execution:m}}return{async exportPrepared(u,f){if(s)throw new D("closed","导出执行器已释放");if(L(u.signal),i.size>=2)throw new D("queue-full","同时导出的任务已达 2 个,请等待完成后重试");const l=new AbortController;i.add(l);const d=()=>l.abort(u.signal?.reason);u.signal?.addEventListener("abort",d,{once:!0});try{return await c({...u,signal:l.signal},f)}finally{u.signal?.removeEventListener("abort",d),i.delete(l)}},cancel(){for(const u of i)u.abort()},dispose(){s=!0;for(const u of i)u.abort()}}}async function ou(e,t){try{if(e.operation!=="exportPrepared")throw new TypeError("内置编码 Worker 仅接受 exportPrepared");return await bo(go({reports:{},budget:e.budget}),e,t)}catch(r){return{protocol:ee,id:e.id,error:yo(r)}}}class A extends Error{constructor(t,r){super(r),this.code=t,this.name="ReportJobError"}}function Ze(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 A("input","任务范围应非空,ID应为1–128位安全标识")}function iu(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 A("input","任务对象应为普通 JSON 对象");if(Object.getOwnPropertySymbols(e).length)throw new A("input","任务不能包含Symbol");if(Object.getOwnPropertyNames(e).filter(i=>!(t&&i==="length")).length!==n.length)throw new A("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 A("input","任务数组不能稀疏或包含额外属性");return n.sort()}function su(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(["__proto__","prototype","constructor"].includes(t)||r.get||r.set)throw new A("input","任务不能包含危险键或访问器");return r.value}function Y(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 A("input","任务JSON预算无效");let o=0,i=0;const s=new Set;function a(u,f){if(++o>r||f>32)throw new A("input","任务数据超过节点或深度预算");if(typeof u=="string"){if(i+=u.length,i>n)throw new A("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 A("input","任务只允许无循环的有限 JSON 值");const l=Array.isArray(u),d=iu(u);s.add(u);const m=Object.create(null);for(const g of d){if(i+=g.length,i>n)throw new A("input","任务文本超过预算");m[g]=a(su(u,g),f+1)}return s.delete(u),l?Array.from({length:u.length},(g,h)=>m[String(h)]):m}const c=JSON.stringify(a(e,0));if(c.length>n)throw new A("input","任务序列化数据超过字符预算");return c}function $t(e){return JSON.parse(JSON.stringify(e))}function xo(e,t,r,n){if(Ze(t,r),e.scope!==t||e.id!==r||e.revision!==(n??0)+1||!Number.isSafeInteger(e.revision))throw new A("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 A("input","任务状态无效");if(e.lease&&(!e.lease.owner||!Number.isSafeInteger(e.lease.expiresAt)))throw new A("input","任务租约无效");if(!e.request||typeof e.request.kind!="string"||!e.request.kind.trim()||e.request.kind.length>128)throw new A("input","任务类型无效");Y(e.request.payload,{maxNodes:19e3,maxCharacters:75e4}),Y(e)}function au(e,t){if(e&&(e.createdAt!==t.createdAt||Y(e.request)!==Y(t.request)))throw new A("input","任务创建时间与请求不可变更,请使用新任务ID")}function cu(e,t){return e.status==="queued"||e.status==="running"&&(e.lease?.expiresAt??0)<=t}function uu(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 A("input","任务容量应为正整数,控制状态预留至少4096字节");return t}function Se(e){return new TextEncoder().encode(Y(e)).byteLength}function vo(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:Se(e.result);if(o>t.maxResultBytes)throw new A("capacity","任务结果超过独立预算,请保存文件引用");return Math.max(Se(r)+t.controlReserveBytes,Se(n))+o}function Mo(e){return e.status!=="queued"&&e.status!=="running"}function fu(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 A("input","终态清理时间应为不超过当前时间的非负整数");if(![t.tombstoneRetentionMs,t.limit].every(r=>Number.isSafeInteger(r)&&r>0)||!Number.isSafeInteger(t.now+t.tombstoneRetentionMs))throw new A("input","幂等保留期与清理批量应为正整数");return t}async function du(e){const t=new TextEncoder().encode(Y(e)),r=globalThis.crypto?.subtle;if(!r)return Cc(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 lu(e,t){if(!Mo(e))throw new A("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 du(e.request),expiresAt:t}}function mu(e){if(!e||!["completed","failed","cancelled"].includes(e.status)||!/^[a-f0-9]{64}$/.test(e.requestHash))throw new A("input","任务幂等摘要无效");if(![e.revision,e.createdAt,e.updatedAt,e.attempt,e.expiresAt].every(t=>Number.isSafeInteger(t)&&t>=0)||e.revision<1)throw new A("input","任务幂等摘要时间或修订无效")}function Ie(e){return e?.code}function Ae(e,t){return Xe.createHash("sha256").update(JSON.stringify([e,t])).digest("hex")+".json"}async function Dt(e){try{return await F.promises.readFile(e,"utf8")}catch(t){if(Ie(t)==="ENOENT")return;throw t}}async function gu(e,t){const r=await Dt(e);if(r===void 0)return;let n;try{n=JSON.parse(r)}catch{throw new A("conflict","任务锁尚未完整写入或已损坏,拒绝自动移除")}if(!n||!Number.isSafeInteger(n.pid)||n.pid<1)throw new A("conflict","任务锁身份无效,拒绝自动移除");try{process.kill(n.pid,0)}catch(o){if(Ie(o)==="ESRCH"){await F.promises.unlink(e);return}throw o}throw new A("conflict","任务目录的写入进程仍在运行")}async function hu(e,t){if(!t)throw new A("conflict","任务目录已有写入进程;多实例请使用数据库CAS适配器");const r=e+".recovery";let n;try{n=await F.promises.open(r,"wx",384)}catch(o){throw Ie(o)==="EEXIST"?new A("conflict","任务目录恢复正在进行,请稍后重试"):o}try{return await n.writeFile(JSON.stringify({pid:process.pid})),await gu(e,!0),await F.promises.open(e,"wx",384)}finally{await n.close(),await F.promises.unlink(r)}}async function pu(e,t){const r=X.join(e,".writer-lock"),n=Xe.randomUUID();let o;try{o=await F.promises.open(r,"wx",384)}catch(i){if(Ie(i)!=="EEXIST")throw i;o=await hu(r,t)}try{await o.writeFile(JSON.stringify({pid:process.pid,token:n})),await o.sync()}catch(i){throw await o.close(),await F.promises.unlink(r).catch(()=>{}),i}return{file:r,token:n,handle:o}}function yu(e,t,r,n){if("tombstone"in r){const o=r.tombstone;if(mu(o),Ze(o.scope,o.id),Ae(o.scope,o.id)!==t)throw new A("input","持久任务摘要身份不匹配");const i=Se(o);e.tombstoneBytes+=i,e.tombstones.set(t,{value:o,bytes:i})}else{if(xo(r,r.scope,r.id,r.revision-1),Ae(r.scope,r.id)!==t)throw new A("input","持久任务文件身份不匹配");const o=vo(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 A("capacity","持久任务及控制状态预留超过目录预算")}async function wu(e,t){const r=await F.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 F.promises.unlink(X.join(e,i));const n=r.filter(i=>/^[a-f0-9]{64}\.json$/.test(i));if(n.length>t.maxRecords+t.maxTombstones)throw new A("capacity","持久任务数量超过目录预算");const o={records:new Map,tombstones:new Map,bytes:0,tombstoneBytes:0};for(const i of n){const s=X.join(e,i);if((await F.promises.stat(s)).size>4e6)throw new A("capacity","持久任务文件超过单文件预算");yu(o,i,JSON.parse(await F.promises.readFile(s,"utf8")),t)}return o}async function bu(e,t,r){const n=X.join(e,`.pending-${Xe.randomUUID()}`);try{const o=await F.promises.open(n,"wx",384);try{await o.writeFile(r),await o.sync()}finally{await o.close()}await F.promises.rename(n,X.join(e,t));const i=await F.promises.open(e,"r");try{await i.sync()}finally{await i.close()}}finally{await F.promises.unlink(n).catch(o=>{if(Ie(o)!=="ENOENT")throw o})}}async function $u(e){const t=X.resolve(e.directory),r=uu(e);await F.promises.mkdir(t,{recursive:!0,mode:448});const n=await pu(t,e.recoverDeadOwner??!1);let o;try{o=await wu(t,r)}catch(d){throw await n.handle.close(),await F.promises.unlink(n.file),d}let i=!1,s=Promise.resolve();const a=()=>{if(i)throw new A("closed","持久任务存储已关闭")},c=d=>{a();const m=s.then(async()=>{if(JSON.parse(await F.promises.readFile(n.file,"utf8")).token!==n.token)throw new A("closed","持久任务存储写入锁已失效");return d()});return s=m.then(()=>{},()=>{}),m},u=async(d,m,g)=>{try{await bu(t,d,m)}catch(h){throw await Dt(X.join(t,d))===m&&g(),h}g()};return{read:async(d,m)=>{a(),Ze(d,m),await s;const g=o.records.get(Ae(d,m));return g?$t(g.record):void 0},readTombstone:async(d,m)=>{a(),Ze(d,m),await s;const g=o.tombstones.get(Ae(d,m));return g?$t(g.value):void 0},candidates:async(d,m)=>(a(),await s,Array.from(o.records.values(),g=>g.record).filter(g=>cu(g,d)).sort((g,h)=>g.createdAt-h.createdAt).slice(0,m).map($t)),compareAndSwap:async(d,m,g,h)=>{const w=JSON.parse(Y(h));return xo(w,d,m,g),c(async()=>{const $=Ae(d,m),p=o.records.get($);if((p?.record.revision??null)!==g||o.tombstones.has($))return!1;au(p?.record,w);const x=vo(w,r),y=o.bytes-(p?.bytes??0)+x;if(y>r.maxBytes||!p&&o.records.size>=r.maxRecords)throw new A("capacity","持久任务容量已满,请清理终态任务或扩大显式预算");return await u($,Y(w),()=>{o.records.set($,{record:w,bytes:x}),o.bytes=y}),!0})},prune:async d=>{const m=fu(d);return c(async()=>{const g={archived:0,expired:0};for(const[h,w]of o.tombstones)w.value.expiresAt>m.now||g.expired>=m.limit||(await F.promises.unlink(X.join(t,h)),o.tombstones.delete(h),o.tombstoneBytes-=w.bytes,g.expired++);for(const[h,w]of o.records){if(!Mo(w.record)||w.record.updatedAt>m.terminalBefore||g.archived+g.expired>=m.limit)continue;const $=await lu(w.record,m.now+m.tombstoneRetentionMs),p=Se($);if(o.tombstones.size>=r.maxTombstones||o.tombstoneBytes+p>r.maxTombstoneBytes)break;await u(h,Y({tombstone:$}),()=>{o.tombstones.set(h,{value:$,bytes:p}),o.tombstoneBytes+=p,o.records.delete(h),o.bytes-=w.bytes}),g.archived++}if(g.expired){const h=await F.promises.open(t,"r");try{await h.sync()}finally{await h.close()}}return g})},close:async()=>{if(i)return;i=!0,await s,await n.handle.close();const d=await Dt(n.file);d&&JSON.parse(d).token===n.token&&await F.promises.unlink(n.file)}}}function So(e){const t=e.filename??e.workerUrl;if(!t||e.filename&&e.workerUrl)throw new TypeError("请且仅请指定 filename 或 workerUrl");return Qc(()=>{const r=new pe.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 xu(e){const t=pe.parentPort;if(!t)throw new Error("serveNodeReportWorker 只能在 worker_threads 中调用");const r=n=>{wo(n)&&bo(e,n,o=>t.postMessage({protocol:ee,id:n.id,type:"event",event:o})).then(o=>t.postMessage(o,$o(o)))};return t.on("message",r),()=>t.off("message",r)}function vu(e){return Xe.createHash("sha256").update(e).digest("hex")}function Mu(e={}){const t={timeoutMs:e.timeoutMs??e.budget?.maxDurationMs,budget:{...e.budget}};return nu(e,r=>So({filename:typeof __filename=="string"?__filename:new URL(typeof document>"u"?require("url").pathToFileURL(__filename).href:ht&&ht.tagName.toUpperCase()==="SCRIPT"&&ht.src||new URL("server-node.cjs",document.baseURI).href),workerOptions:{workerData:{machReportEncoding:"prepared-v1"}},...t,timeoutMs:r}))}if(pe.parentPort&&pe.workerData?.machReportEncoding==="prepared-v1"){const e=pe.parentPort;e.on("message",t=>{wo(t)&&ou(t,r=>e.postMessage({protocol:ee,id:t.id,type:"event",event:r})).then(r=>e.postMessage(r,$o(r)))})}exports.ReportWorkerError=jt;exports.createNodeAutoReportExporter=Mu;exports.createNodeReportExecutor=So;exports.openFileReportJobStore=$u;exports.reportArtifactSha256=vu;exports.serveNodeReportWorker=xu;