@evotecit/officeimo 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +13 -10
  2. package/bundles/officeimo-canopyx.js +813 -358
  3. package/bundles/officeimo-canopyx.mjs +700 -246
  4. package/bundles/officeimo-csv.js +29 -19
  5. package/bundles/officeimo-csv.mjs +17 -7
  6. package/bundles/officeimo-datatables.js +806 -360
  7. package/bundles/officeimo-datatables.mjs +694 -249
  8. package/bundles/officeimo-execution.js +35 -25
  9. package/bundles/officeimo-execution.mjs +17 -7
  10. package/bundles/officeimo-pdf.js +734 -289
  11. package/bundles/officeimo-pdf.mjs +685 -241
  12. package/bundles/officeimo-xlsx.js +88 -77
  13. package/bundles/officeimo-xlsx.mjs +22 -11
  14. package/bundles/officeimo.js +790 -344
  15. package/bundles/officeimo.mjs +680 -235
  16. package/dist/core/index.d.ts +2 -0
  17. package/dist/core/iteration.js +2 -2
  18. package/dist/core/sinks.js +2 -1
  19. package/dist/integrations/canopyx/source.js +13 -7
  20. package/dist/integrations/datatables/snapshot.js +3 -3
  21. package/dist/internal/rows.js +13 -4
  22. package/dist/pdf/document-grouped.js +72 -22
  23. package/dist/pdf/font-resources.js +2 -1
  24. package/dist/pdf/inline-text.js +50 -9
  25. package/dist/pdf/objects.js +188 -11
  26. package/dist/pdf/pages.js +25 -26
  27. package/dist/pdf/paragraph-layout.d.ts +2 -0
  28. package/dist/pdf/paragraph-layout.js +9 -4
  29. package/dist/pdf/session.js +1 -1
  30. package/dist/pdf/settings.d.ts +2 -0
  31. package/dist/pdf/settings.js +27 -2
  32. package/dist/pdf/structure.js +80 -28
  33. package/dist/pdf/table-band-flow.js +26 -11
  34. package/dist/pdf/table-band-plan.js +1 -3
  35. package/dist/pdf/table-layout.d.ts +4 -0
  36. package/dist/pdf/table-layout.js +22 -10
  37. package/dist/pdf/table-structure.js +28 -12
  38. package/dist/pdf/text.js +5 -0
  39. package/dist/pdf/types.d.ts +4 -2
  40. package/dist/pdf/xref.d.ts +1 -0
  41. package/dist/pdf/xref.js +30 -0
  42. package/dist/xlsx/values.js +3 -2
  43. package/dist/zip/entry.js +1 -1
  44. package/dist/zip/index.js +1 -1
  45. package/package.json +1 -1
@@ -38,7 +38,7 @@ return _exports;
38
38
  const _m4 = (() => {
39
39
  function checkAbort(signal) {
40
40
  if (signal?.aborted)
41
- throw signal.reason ?? new DOMException("Export cancelled.", "AbortError");
41
+ throw signal.reason;
42
42
  }
43
43
  /** Race a pending producer or sink operation without leaving abort listeners behind. */
44
44
  function withAbort(promise, signal) {
@@ -46,7 +46,7 @@ function withAbort(promise, signal) {
46
46
  return Promise.resolve(promise);
47
47
  return new Promise((resolve, reject) => {
48
48
  const cleanup = () => signal.removeEventListener("abort", abort);
49
- const abort = () => { cleanup(); reject(signal.reason ?? new DOMException("Export cancelled.", "AbortError")); };
49
+ const abort = () => { cleanup(); reject(signal.reason); };
50
50
  signal.addEventListener("abort", abort, { once: true });
51
51
  Promise.resolve(promise).then(value => { cleanup(); resolve(value); }, error => { cleanup(); reject(error); });
52
52
  if (signal.aborted)
@@ -199,8 +199,9 @@ async function withDestination(destination, operation) {
199
199
  // Native streams can belong to another browser realm; constructor identity is not portable.
200
200
  if (destination && typeof destination.getWriter === "function") {
201
201
  const writer = destination.getWriter();
202
+ // Native streams may retain accepted chunks after write resolves.
202
203
  try {
203
- return await operation({ write: bytes => writer.write(bytes) });
204
+ return await operation({ write: bytes => writer.write(new Uint8Array(bytes)) });
204
205
  }
205
206
  finally {
206
207
  writer.releaseLock();
@@ -498,11 +499,18 @@ function createRowProjector(columns, worksheet, signal, validate = assertExportV
498
499
  const getters = columns.some(column => column.value);
499
500
  return (row, rowIndex = 0) => {
500
501
  if (Array.isArray(row) && !getters) {
501
- if (row.length > columns.length)
502
+ const length = row.length;
503
+ if (length > columns.length)
502
504
  throw new RangeError("Row has more values than declared columns.");
503
- for (const value of row)
505
+ // Resolve each positional value once, just like key/value projections. Returning the
506
+ // source array would let an accessor change a value after the portable-value check.
507
+ const values = new Array(length);
508
+ for (let index = 0; index < length; index++) {
509
+ const value = row[index];
504
510
  validate(value);
505
- return row;
511
+ values[index] = value;
512
+ }
513
+ return values;
506
514
  }
507
515
  if (!row || typeof row !== "object" || isDate(row))
508
516
  throw new TypeError("A row must be an array or object.");
@@ -531,7 +539,7 @@ function createRowProjector(columns, worksheet, signal, validate = assertExportV
531
539
  };
532
540
  }
533
541
  /** @internal Shared metadata fields for full columns and adapter-owned partial overrides. */
534
- const columnOptionFields = ["header", "key", "value", "width", "type", "format", "wrapText", "alignment", "groups", "style", "valueFormatter"];
542
+ const columnOptionFields = ["header", "key", "value", "width", "type", "format", "wrapText", "alignment", "rowHeader", "groups", "style", "valueFormatter"];
535
543
  function copyColumns(columns, workbookStyles = false) {
536
544
  if (!Array.isArray(columns))
537
545
  throw new TypeError("Declare the columns in export order.");
@@ -547,6 +555,8 @@ function copyColumns(columns, workbookStyles = false) {
547
555
  throw new TypeError("Each column needs a string header and an optional string key.");
548
556
  if (captured.value !== undefined && typeof captured.value !== "function")
549
557
  throw new TypeError("Column value getters must be functions.");
558
+ if (captured.rowHeader !== undefined && typeof captured.rowHeader !== "boolean")
559
+ throw new TypeError("Column rowHeader must be boolean.");
550
560
  if (captured.groups !== undefined) {
551
561
  if (!Array.isArray(captured.groups))
552
562
  throw new TypeError("Column groups must be an array of strings.");
@@ -1432,7 +1442,7 @@ class EntryWriter {
1432
1442
  closed = false;
1433
1443
  cleaned = false;
1434
1444
  lifetime = new AbortController();
1435
- abort = () => { this.fail(this.signal?.reason ?? new DOMException("Export cancelled.", "AbortError")); };
1445
+ abort = () => { this.fail(this.signal?.reason); };
1436
1446
  constructor(compression, sink, signal) {
1437
1447
  this.sink = sink;
1438
1448
  this.signal = signal;
@@ -1596,7 +1606,7 @@ class ZipWriter {
1596
1606
  /** Pending header/directory writes and source reads must also stop on explicit discard. */
1597
1607
  async acceptance(operation) {
1598
1608
  const signal = this.options.signal;
1599
- const abort = () => this.lifetime.abort(signal?.reason ?? new DOMException("Export cancelled.", "AbortError"));
1609
+ const abort = () => this.lifetime.abort(signal?.reason);
1600
1610
  signal?.addEventListener("abort", abort, { once: true });
1601
1611
  try {
1602
1612
  checkAbort(signal);
@@ -2548,12 +2558,13 @@ function sheetName(requested, names, policy, register = true) {
2548
2558
  throw new TypeError("Sheet name must be a string.");
2549
2559
  // Validate and deduplicate the decoded literal value, before ST_Xstring attribute encoding.
2550
2560
  // A requested _xHHHH_ token is literal text; the serializer protects its leading underscore.
2551
- let base = cleanXml(requested, policy).replace(/[\[\]:*?/\\]/g, "_").trim().replace(/^'+|'+$/g, "").trim();
2561
+ let base = cleanXml(requested, policy).replace(/[\[\]:*?/\\]/g, "_").replace(/^[\s']+|[\s']+$/g, "");
2562
+ // Clipping can expose an internal apostrophe or the reserved History name.
2563
+ base = clipName(base, 31).replace(/[\s']+$/g, "");
2552
2564
  if (!base)
2553
2565
  base = "Sheet";
2554
2566
  if (base.toLowerCase() === "history")
2555
2567
  base += "_";
2556
- base = clipName(base, 31);
2557
2568
  let name = base, suffix = 2;
2558
2569
  while (names.has(name.toLowerCase())) {
2559
2570
  const tail = " (" + suffix++ + ")";
@@ -5661,10 +5672,34 @@ function captureWideTable(input) {
5661
5672
  if (repeatColumns !== undefined && !Array.isArray(repeatColumns))
5662
5673
  throw new TypeError("repeatColumns must be an array.");
5663
5674
  const repeats = repeatColumns === undefined ? [] : [...repeatColumns];
5664
- if (repeats.some((value, index) => !Number.isSafeInteger(value) || value < 0 || index > 0 && value <= repeats[index - 1]))
5665
- throw new RangeError("repeatColumns must contain sorted unique nonnegative indices.");
5675
+ if (repeats.some(value => typeof value === "number" ? !Number.isSafeInteger(value) || value < 0 : typeof value !== "string" || !value.length))
5676
+ throw new RangeError("repeatColumns must contain nonnegative indices or nonempty stable keys.");
5677
+ if (repeats.every(value => typeof value === "number") && repeats.some((value, index) => index > 0 && value <= repeats[index - 1]))
5678
+ throw new RangeError("Numeric repeatColumns must contain sorted unique nonnegative indices.");
5666
5679
  return Object.freeze({ mode, ...(minimumColumnWidth === undefined ? {} : { minimumColumnWidth }), repeatColumns: Object.freeze(repeats) });
5667
5680
  }
5681
+ /** Resolve identities against this table's captured selection, without consulting a grid or opening its rows. */
5682
+ function repeatedColumns(policy, columns) {
5683
+ if (typeof policy !== "object")
5684
+ return Object.freeze([]);
5685
+ const selected = new Set();
5686
+ for (const selector of policy.repeatColumns ?? []) {
5687
+ let position;
5688
+ if (typeof selector === "number")
5689
+ position = selector;
5690
+ else {
5691
+ position = columns.findIndex(column => column.key === selector);
5692
+ if (position < 0 || columns.some((column, index) => index !== position && column.key === selector))
5693
+ throw new TypeError("repeatColumns requires an unambiguous selected column key: " + selector);
5694
+ }
5695
+ if (position >= columns.length)
5696
+ throw new RangeError("repeatColumns index exceeds the declared columns.");
5697
+ if (selected.has(position))
5698
+ throw new TypeError("repeatColumns selects the same column more than once.");
5699
+ selected.add(position);
5700
+ }
5701
+ return Object.freeze([...selected].sort((left, right) => left - right));
5702
+ }
5668
5703
  function settings(input, document = false) {
5669
5704
  const configuration = { ...capturePdfOptions(input) };
5670
5705
  configuration.booleanText = captureBooleanText(configuration.booleanText);
@@ -5766,17 +5801,76 @@ function settings(input, document = false) {
5766
5801
  }
5767
5802
  const maxImageWorkingBytes = options.limits?.maxImageWorkingBytes;
5768
5803
  return { options: { ...options, paragraphStyles }, paragraphStyles, page, margins, fontSize, padding,
5804
+ repeatedColumns: document ? Object.freeze([]) : repeatedColumns(options.wideTable, columns),
5769
5805
  limits: { ...limits, ...(maxImageWorkingBytes === undefined ? {} : { maxImageWorkingBytes }) }, budget };
5770
5806
  }
5771
5807
  const _exports = Object.freeze({ positive: _m57.positive, color: _m57.color, presentation: _m57.presentation, pdfOptionFields: pdfOptionFields, pdfLimitFields: pdfLimitFields, capturePdfOptions: capturePdfOptions, capturePdfLimits: capturePdfLimits, captureWideTable: captureWideTable, settings: settings });
5772
5808
  return _exports;
5773
5809
  })();
5774
5810
 
5811
+ const _m60 = (() => {
5812
+ /** @internal One type byte, an eight-byte offset/container number and a two-byte generation/index. */
5813
+ const pdfXrefEntryBytes = 11;
5814
+ function unsigned(bytes, offset, value, width) {
5815
+ if (!Number.isSafeInteger(value) || value < 0 || value >= 2 ** (width * 8))
5816
+ throw new RangeError("Invalid PDF cross-reference field.");
5817
+ // Bitwise shifts truncate to 32 bits. Arithmetic preserves every supported byte offset.
5818
+ for (let index = width - 1; index >= 0; index--) {
5819
+ bytes[offset + index] = value % 256;
5820
+ value = Math.floor(value / 256);
5821
+ }
5822
+ }
5823
+ /** @internal Stream a complete single-section xref, including its own ordinary-object entry.
5824
+ * A defined member index means that the location is an object-stream number rather than a byte offset. */
5825
+ function* pdfXrefChunks(locations, indices) {
5826
+ if (locations.length !== indices.length)
5827
+ throw new Error("PDF cross-reference locations must align.");
5828
+ const perChunk = Math.floor(32768 / pdfXrefEntryBytes);
5829
+ for (let first = 0; first < locations.length; first += perChunk) {
5830
+ const count = Math.min(perChunk, locations.length - first), bytes = new Uint8Array(count * pdfXrefEntryBytes);
5831
+ for (let index = 0; index < count; index++) {
5832
+ const id = first + index, position = index * pdfXrefEntryBytes, location = locations[id], member = indices.at(id);
5833
+ if (location === undefined)
5834
+ throw new Error("PDF contains unwritten objects.");
5835
+ bytes[position] = id === 0 ? 0 : member === undefined ? 1 : 2;
5836
+ unsigned(bytes, position + 1, location, 8);
5837
+ unsigned(bytes, position + 9, id === 0 ? 65535 : member ?? 0, 2);
5838
+ }
5839
+ yield bytes;
5840
+ }
5841
+ }
5842
+ const _exports = Object.freeze({ pdfXrefEntryBytes: pdfXrefEntryBytes, pdfXrefChunks: pdfXrefChunks });
5843
+ return _exports;
5844
+ })();
5845
+
5775
5846
  const _m59 = (() => {
5776
5847
  const { checkAbort, withAbort, pause, taskYieldDue } = _m4;
5777
5848
 
5778
5849
  const { OfficeIMOError } = _m2;
5779
5850
 
5851
+ const { pdfXrefChunks, pdfXrefEntryBytes } = _m60;
5852
+
5853
+ const compactObjectCount = 256, compactObjectBytes = 32768;
5854
+ const compactIndexChunkEntries = 4096;
5855
+ /** Lazy Uint16 chunks store compact membership; untouched zero slots denote ordinary objects. */
5856
+ class PdfCompactIndices {
5857
+ count;
5858
+ chunks = [];
5859
+ constructor(count) {
5860
+ this.count = count;
5861
+ }
5862
+ get length() { return this.count; }
5863
+ reserve() { this.count++; }
5864
+ set(id, member) {
5865
+ const chunk = this.chunks[Math.floor(id / compactIndexChunkEntries)] ??= new Uint16Array(compactIndexChunkEntries);
5866
+ // The current batch cap permits indices 0..255; adding one preserves index 255 as 256.
5867
+ chunk[id % compactIndexChunkEntries] = member + 1;
5868
+ }
5869
+ at(id) {
5870
+ const encoded = this.chunks[Math.floor(id / compactIndexChunkEntries)]?.[id % compactIndexChunkEntries] ?? 0;
5871
+ return encoded ? encoded - 1 : undefined;
5872
+ }
5873
+ }
5780
5874
  function pdfNumber(value) {
5781
5875
  if (!Number.isFinite(value) || Math.abs(value) > 1e9)
5782
5876
  throw new RangeError("PDF coordinates and metrics must be finite and bounded.");
@@ -5793,25 +5887,33 @@ function unicodeHex(text) {
5793
5887
  }
5794
5888
  return hex;
5795
5889
  }
5796
- /** @internal Forward-only PDF objects. Only xref offsets and page references survive a completed page. */
5890
+ /** @internal Forward-only PDF objects. Completed objects retain only their xref location. */
5797
5891
  class PdfObjects {
5798
5892
  sink;
5799
5893
  signal;
5800
5894
  maxBytes;
5895
+ compressObjects;
5801
5896
  offsets = [0];
5897
+ // A defined index changes the corresponding full-width offset into an object-stream number.
5898
+ // Membership chunks are allocated only when a compact member needs their ID range.
5899
+ compactIndices;
5900
+ compactBatch;
5901
+ compactArena;
5902
+ compactUnavailable = false;
5802
5903
  encoder = new TextEncoder();
5803
5904
  buffer = new Uint8Array(32768);
5804
5905
  buffered = 0;
5805
5906
  bytes = 0;
5806
- constructor(sink, signal, maxBytes = Number.MAX_SAFE_INTEGER) {
5907
+ constructor(sink, signal, maxBytes = Number.MAX_SAFE_INTEGER, compressObjects = false) {
5807
5908
  this.sink = sink;
5808
5909
  this.signal = signal;
5809
5910
  this.maxBytes = maxBytes;
5911
+ this.compressObjects = compressObjects;
5810
5912
  }
5811
- reserve() { this.offsets.push(undefined); return this.offsets.length - 1; }
5913
+ reserve() { this.offsets.push(undefined); this.compactIndices?.reserve(); return this.offsets.length - 1; }
5812
5914
  async raw(bytes) {
5813
5915
  checkAbort(this.signal);
5814
- if (this.bytes + bytes.length > this.maxBytes)
5916
+ if (!Number.isSafeInteger(this.bytes + bytes.length) || this.bytes + bytes.length > this.maxBytes)
5815
5917
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxOutputBytes exceeded.");
5816
5918
  this.bytes += bytes.length;
5817
5919
  for (let offset = 0; offset < bytes.length;) {
@@ -5820,21 +5922,139 @@ class PdfObjects {
5820
5922
  offset += n;
5821
5923
  this.buffered += n;
5822
5924
  if (this.buffered === this.buffer.length)
5823
- await this.flush();
5925
+ await this.flushBytes();
5824
5926
  }
5825
5927
  }
5826
5928
  async text(text) { await this.raw(this.encoder.encode(text)); }
5827
5929
  async flush() {
5930
+ await this.flushCompact();
5931
+ await this.flushBytes();
5932
+ }
5933
+ /** Publish completed page bytes without forcing a partial structure container to end. */
5934
+ async flushBytes() {
5828
5935
  if (this.buffered) {
5829
5936
  const bytes = this.buffer.subarray(0, this.buffered);
5830
5937
  await withAbort(Promise.resolve(this.sink.write(bytes)), this.signal);
5831
- this.buffer = new Uint8Array(32768);
5938
+ // The sink borrows this view until acceptance; failed or cancelled writes must not reuse it.
5832
5939
  this.buffered = 0;
5833
5940
  }
5834
5941
  if (taskYieldDue())
5835
5942
  await pause();
5836
5943
  checkAbort(this.signal);
5837
5944
  }
5945
+ /** @internal Append only when an existing compact batch can accept a member without async work. */
5946
+ tryCompactObject(id, body) {
5947
+ checkAbort(this.signal);
5948
+ this.validateObject(id);
5949
+ const batch = this.compactBatch;
5950
+ if (!batch || !this.compressObjects || this.compactUnavailable || typeof CompressionStream !== "function" ||
5951
+ body.length > compactObjectBytes || batch.ids.length + 1 >= compactObjectCount)
5952
+ return false;
5953
+ const indexBytes = String(id).length + String(batch.bodyBytes).length + 2;
5954
+ const written = this.encodeCompactBody(body, batch.bodyBytes, compactObjectBytes - batch.indexBytes - indexBytes - batch.bodyBytes - 2);
5955
+ if (written === undefined)
5956
+ return false;
5957
+ this.storeCompactBody(batch, id, written);
5958
+ return true;
5959
+ }
5960
+ /** Small logical structure values share one bounded object-stream container. Other callers keep
5961
+ * ordinary objects; unavailable deflate preserves the classic representation before packing starts. */
5962
+ async compactObject(id, body) {
5963
+ checkAbort(this.signal);
5964
+ this.validateObject(id);
5965
+ if (!this.compressObjects || this.compactUnavailable || body.length > compactObjectBytes)
5966
+ return this.object(id, body);
5967
+ if (typeof CompressionStream !== "function") {
5968
+ if (this.compactIndices)
5969
+ throw new Error("PDF object compression became unavailable.");
5970
+ this.compactUnavailable = true;
5971
+ return this.object(id, body);
5972
+ }
5973
+ const firstIndexBytes = String(id).length + 4;
5974
+ let batch = this.compactBatch;
5975
+ const indexBytes = String(id).length + String(batch?.bodyBytes ?? 0).length + 2;
5976
+ let written = batch && batch.ids.length < compactObjectCount ? this.encodeCompactBody(body, batch.bodyBytes, compactObjectBytes - batch.indexBytes - indexBytes - batch.bodyBytes - 2) : undefined;
5977
+ if (batch && written === undefined) {
5978
+ // Partial encodings only touch the uncommitted suffix. Flush the committed prefix and retry
5979
+ // the whole string so a multibyte scalar is never split between containers.
5980
+ await this.flushCompact();
5981
+ batch = undefined;
5982
+ checkAbort(this.signal);
5983
+ }
5984
+ if (!batch) {
5985
+ written = this.encodeCompactBody(body, 0, compactObjectBytes - firstIndexBytes - 1);
5986
+ if (written === undefined)
5987
+ return this.object(id, body);
5988
+ let compressor;
5989
+ // Probe before selecting the compact representation. Later batches need no idle native
5990
+ // codec while they accumulate, including while ordinary page streams are compressed.
5991
+ if (!this.compactIndices) {
5992
+ try {
5993
+ compressor = new CompressionStream("deflate");
5994
+ }
5995
+ catch {
5996
+ this.compactUnavailable = true;
5997
+ return this.object(id, body);
5998
+ }
5999
+ }
6000
+ batch = { id: this.reserve(), compressor, ids: [], bodyOffsets: [], bodyBytes: 0, indexBytes: 1 };
6001
+ this.compactIndices ??= new PdfCompactIndices(this.offsets.length);
6002
+ this.compactBatch = batch;
6003
+ }
6004
+ this.storeCompactBody(batch, id, written);
6005
+ if (batch.ids.length === compactObjectCount)
6006
+ await this.flushCompact();
6007
+ }
6008
+ storeCompactBody(batch, id, written) {
6009
+ this.offsets[id] = batch.id;
6010
+ this.compactIndices.set(id, batch.ids.length);
6011
+ batch.indexBytes += String(id).length + String(batch.bodyBytes).length + 2;
6012
+ batch.ids.push(id);
6013
+ batch.bodyOffsets.push(batch.bodyBytes);
6014
+ this.compactArena[batch.bodyBytes + written] = 10;
6015
+ batch.bodyBytes += written + 1;
6016
+ }
6017
+ /** An incomplete encoding leaves only scratch bytes beyond the committed batch prefix. */
6018
+ encodeCompactBody(body, offset, available) {
6019
+ if (available < 0)
6020
+ return undefined;
6021
+ const destination = (this.compactArena ??= new Uint8Array(compactObjectBytes)).subarray(offset, offset + available);
6022
+ if (typeof this.encoder.encodeInto === "function") {
6023
+ const result = this.encoder.encodeInto(body, destination);
6024
+ return result.read === body.length ? result.written : undefined;
6025
+ }
6026
+ // Preserve TextEncoder implementations that only expose encode().
6027
+ const bytes = this.encoder.encode(body);
6028
+ if (bytes.length > available)
6029
+ return undefined;
6030
+ destination.set(bytes);
6031
+ return bytes.length;
6032
+ }
6033
+ async flushCompact() {
6034
+ const batch = this.compactBatch;
6035
+ if (!batch)
6036
+ return;
6037
+ this.compactBatch = undefined;
6038
+ let index = "";
6039
+ for (let member = 0; member < batch.ids.length; member++)
6040
+ index += batch.ids[member] + " " + batch.bodyOffsets[member] + " ";
6041
+ const header = this.encoder.encode(index + "\n"), count = batch.ids.length;
6042
+ // Keep the index separate from the arena. Reuse waits for the compressed read or all raw
6043
+ // writes below, so later members cannot overwrite a borrowed batch body.
6044
+ const body = this.compactArena.subarray(0, batch.bodyBytes);
6045
+ batch.ids.length = 0;
6046
+ batch.bodyOffsets.length = 0;
6047
+ if (batch.compressor) {
6048
+ await this.compressedStream(batch.id, body, "/Type /ObjStm /N " + count + " /First " + header.length, batch.compressor, header);
6049
+ }
6050
+ else {
6051
+ this.start(batch.id);
6052
+ await this.text(batch.id + " 0 obj\n<< /Length " + (header.length + body.length) + " /Type /ObjStm /N " + count + " /First " + header.length + " >>\nstream\n");
6053
+ await this.raw(header);
6054
+ await this.raw(body);
6055
+ await this.text("\nendstream\nendobj\n");
6056
+ }
6057
+ }
5838
6058
  async object(id, body) {
5839
6059
  this.start(id);
5840
6060
  if (typeof body === "string") {
@@ -5858,9 +6078,12 @@ class PdfObjects {
5858
6078
  }
5859
6079
  await this.text(chunk + "\nendobj\n");
5860
6080
  }
5861
- start(id) {
5862
- if (!Number.isInteger(id) || id <= 0 || id >= this.offsets.length || this.offsets[id] !== undefined)
6081
+ validateObject(id) {
6082
+ if (!Number.isSafeInteger(id) || id <= 0 || id >= this.offsets.length || this.offsets[id] !== undefined)
5863
6083
  throw new Error("Invalid PDF object state.");
6084
+ }
6085
+ start(id) {
6086
+ this.validateObject(id);
5864
6087
  this.offsets[id] = this.bytes;
5865
6088
  }
5866
6089
  async stream(id, source, dictionary = "", compression = true, owned = false) {
@@ -5881,7 +6104,15 @@ class PdfObjects {
5881
6104
  }
5882
6105
  // Verified internal producers can transfer immutable ownership; other byte sources retain the defensive snapshot.
5883
6106
  const sourceBytes = typeof source === "string" || owned ? bytes : new Uint8Array(bytes);
5884
- const input = new ReadableStream({ start(controller) { controller.enqueue(sourceBytes); controller.close(); } });
6107
+ await this.compressedStream(id, sourceBytes, dictionary, compressor);
6108
+ }
6109
+ async compressedStream(id, sourceBytes, dictionary, compressor, prefix) {
6110
+ const input = new ReadableStream({ start(controller) {
6111
+ if (prefix)
6112
+ controller.enqueue(prefix);
6113
+ controller.enqueue(sourceBytes);
6114
+ controller.close();
6115
+ } });
5885
6116
  const reader = input.pipeThrough(compressor).getReader(), lengthId = this.reserve();
5886
6117
  let length = 0, complete = false;
5887
6118
  try {
@@ -5906,10 +6137,14 @@ class PdfObjects {
5906
6137
  }
5907
6138
  }
5908
6139
  async finish(root, info) {
5909
- if (this.offsets.slice(1).some(offset => offset === undefined))
5910
- throw new Error("PDF contains unwritten objects.");
6140
+ await this.flushCompact();
6141
+ for (let id = 1; id < this.offsets.length; id++)
6142
+ if (this.offsets[id] === undefined)
6143
+ throw new Error("PDF contains unwritten objects.");
5911
6144
  if (this.bytes > 9999999999)
5912
6145
  throw new OfficeIMOError("RESOURCE_LIMIT", "PDF exceeds classic cross-reference offset capacity.");
6146
+ if (this.compactIndices)
6147
+ return this.finishCompact(root, info);
5913
6148
  const start = this.bytes;
5914
6149
  await this.text("xref\n0 " + this.offsets.length + "\n0000000000 65535 f \n");
5915
6150
  for (let i = 1; i < this.offsets.length; i++)
@@ -5917,12 +6152,26 @@ class PdfObjects {
5917
6152
  await this.text("trailer\n<< /Size " + this.offsets.length + " /Root " + root + " 0 R /Info " + info + " 0 R >>\nstartxref\n" + start + "\n%%EOF\n");
5918
6153
  await this.flush();
5919
6154
  }
6155
+ /** Xref payloads have a known length and are emitted in bounded chunks, without another copy
6156
+ * of the document's random-access location arrays or a whole-xref compression buffer. */
6157
+ async finishCompact(root, info) {
6158
+ const id = this.reserve(), start = this.bytes, length = this.offsets.length * pdfXrefEntryBytes;
6159
+ if (!Number.isSafeInteger(length))
6160
+ throw new OfficeIMOError("RESOURCE_LIMIT", "PDF cross-reference stream is too large.");
6161
+ this.start(id);
6162
+ await this.text(id + " 0 obj\n<< /Type /XRef /Size " + this.offsets.length + " /W [1 8 2] /Root " + root + " 0 R /Info " + info +
6163
+ " 0 R /Length " + length + " >>\nstream\n");
6164
+ for (const chunk of pdfXrefChunks(this.offsets, this.compactIndices))
6165
+ await this.raw(chunk);
6166
+ await this.text("\nendstream\nendobj\nstartxref\n" + start + "\n%%EOF\n");
6167
+ await this.flushBytes();
6168
+ }
5920
6169
  }
5921
6170
  const _exports = Object.freeze({ pdfNumber: pdfNumber, unicodeHex: unicodeHex, PdfObjects: PdfObjects });
5922
6171
  return _exports;
5923
6172
  })();
5924
6173
 
5925
- const _m63 = (() => {
6174
+ const _m64 = (() => {
5926
6175
  /** @internal Bounded big-endian reader used for caller-provided TrueType programs. */
5927
6176
  class FontReader {
5928
6177
  bytes;
@@ -5951,8 +6200,8 @@ const _exports = Object.freeze({ FontReader: FontReader, checksum: checksum, ali
5951
6200
  return _exports;
5952
6201
  })();
5953
6202
 
5954
- const _m64 = (() => {
5955
- const { align4 } = _m63;
6203
+ const _m65 = (() => {
6204
+ const { align4 } = _m64;
5956
6205
 
5957
6206
  const { checkAbort, pause, taskYieldDue } = _m4;
5958
6207
 
@@ -6175,12 +6424,12 @@ const _exports = Object.freeze({ subsetTrueType: subsetTrueType, subsetTrueTypeC
6175
6424
  return _exports;
6176
6425
  })();
6177
6426
 
6178
- const _m62 = (() => {
6427
+ const _m63 = (() => {
6179
6428
  const { NotSupportedError } = _m2;
6180
6429
 
6181
- const { FontReader } = _m63;
6430
+ const { FontReader } = _m64;
6182
6431
 
6183
- const { subsetTrueType, subsetTrueTypeCooperatively } = _m64;
6432
+ const { subsetTrueType, subsetTrueTypeCooperatively } = _m65;
6184
6433
 
6185
6434
  const { checkAbort, pause, taskYieldDue } = _m4;
6186
6435
 
@@ -6419,8 +6668,8 @@ const _exports = Object.freeze({ TrueTypeFont: TrueTypeFont });
6419
6668
  return _exports;
6420
6669
  })();
6421
6670
 
6422
- const _m61 = (() => {
6423
- const { TrueTypeFont } = _m62;
6671
+ const _m62 = (() => {
6672
+ const { TrueTypeFont } = _m63;
6424
6673
 
6425
6674
  const { beginTask, checkAbort } = _m4;
6426
6675
 
@@ -6482,7 +6731,7 @@ const _exports = Object.freeze({ fontProgram: fontProgram, PdfFont: PdfFont });
6482
6731
  return _exports;
6483
6732
  })();
6484
6733
 
6485
- const _m66 = (() => {
6734
+ const _m67 = (() => {
6486
6735
  // Generated by scripts/pdf-widths.mjs from OfficeIMO.Pdf's Adobe AFM-derived metrics.
6487
6736
  const helveticaWidths = new Map([
6488
6737
  [32, [278, 278]],
@@ -6804,12 +7053,12 @@ const _exports = Object.freeze({ helveticaWidths: helveticaWidths });
6804
7053
  return _exports;
6805
7054
  })();
6806
7055
 
6807
- const _m65 = (() => {
7056
+ const _m66 = (() => {
6808
7057
  const { OfficeIMOError } = _m2;
6809
7058
 
6810
- const { PdfFont, fontProgram } = _m61;
7059
+ const { PdfFont, fontProgram } = _m62;
6811
7060
 
6812
- const { helveticaWidths } = _m66;
7061
+ const { helveticaWidths } = _m67;
6813
7062
 
6814
7063
  const winAnsiExtras = new Map([0x20ac, 0, 0x201a, 0x192, 0x201e, 0x2026, 0x2020, 0x2021, 0x2c6, 0x2030, 0x160, 0x2039, 0x152, 0, 0x17d, 0, 0, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x2dc, 0x2122, 0x161, 0x203a, 0x153, 0, 0x17e, 0x178].map((cp, i) => [cp, i + 128]));
6815
7064
  /** @internal Called after scalar support succeeds when encoding a standard-font run. */
@@ -6872,17 +7121,18 @@ const _exports = Object.freeze({ standardCode: standardCode, resolveScalar: reso
6872
7121
  return _exports;
6873
7122
  })();
6874
7123
 
6875
- const _m60 = (() => {
7124
+ const _m61 = (() => {
6876
7125
  const { NotSupportedError, OfficeIMOError } = _m2;
6877
7126
 
6878
- const { fontProgram } = _m61;
7127
+ const { fontProgram } = _m62;
6879
7128
 
6880
- const { resolveScalar, selectFont, standardCode, validateFonts } = _m65;
7129
+ const { resolveScalar, selectFont, standardCode, validateFonts } = _m66;
6881
7130
 
6882
7131
  const { pdfNumber, unicodeHex } = _m59;
6883
7132
 
6884
7133
  const { checkAbort, pause, taskYieldDue } = _m4;
6885
7134
 
7135
+ const standardHexBytes = Object.freeze(Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0")));
6886
7136
  class PdfFontResource {
6887
7137
  index;
6888
7138
  bold;
@@ -6945,7 +7195,7 @@ class PdfFontResource {
6945
7195
  for (const char of text) {
6946
7196
  const cp = char.codePointAt(0);
6947
7197
  this.width(cp);
6948
- hex += (this.program ? this.mappings.get(cp).cid : standardCode(cp)).toString(16).padStart(this.program ? 4 : 2, "0");
7198
+ hex += this.program ? this.mappings.get(cp).cid.toString(16).padStart(4, "0") : standardHexBytes[standardCode(cp)];
6949
7199
  }
6950
7200
  return "<" + hex + ">";
6951
7201
  }
@@ -7083,7 +7333,7 @@ const _exports = Object.freeze({ PdfFontResource: PdfFontResource, PdfFontResour
7083
7333
  return _exports;
7084
7334
  })();
7085
7335
 
7086
- const _m68 = (() => {
7336
+ const _m69 = (() => {
7087
7337
  const { OfficeIMOError } = _m2;
7088
7338
 
7089
7339
  const { ExportCell, assertExportValue } = _m5;
@@ -7094,6 +7344,11 @@ const { isDate } = _m6;
7094
7344
 
7095
7345
  const { defaultBooleanText } = _m18;
7096
7346
 
7347
+ /** @internal Charge displayed characters: tabs paint four spaces, while CR/LF only separate lines.
7348
+ * Raw text remains authoritative for input limits and layout. Skip normalization when no text ceiling observes it. */
7349
+ function pdfBudgetText(text, budget) {
7350
+ return budget.limits.maxTextCharacters === undefined ? text : text.replace(/[\t\r\n]/g, character => character === "\t" ? " " : "");
7351
+ }
7097
7352
  function synchronousText(value, name) {
7098
7353
  if (typeof value === "string")
7099
7354
  return value;
@@ -7185,11 +7440,11 @@ function* wrapSteps(text, font, size, width, maxCharacters, maxLines, wrap) {
7185
7440
  }
7186
7441
  return lines;
7187
7442
  }
7188
- const _exports = Object.freeze({ synchronousText: synchronousText, displayText: displayText, wrapText: wrapText, wrapTextCooperatively: wrapTextCooperatively });
7443
+ const _exports = Object.freeze({ pdfBudgetText: pdfBudgetText, synchronousText: synchronousText, displayText: displayText, wrapText: wrapText, wrapTextCooperatively: wrapTextCooperatively });
7189
7444
  return _exports;
7190
7445
  })();
7191
7446
 
7192
- const _m70 = (() => {
7447
+ const _m71 = (() => {
7193
7448
  const { NotSupportedError, OfficeIMOError } = _m2;
7194
7449
 
7195
7450
  const { checkAbort, pause, taskYieldDue, withAbort } = _m4;
@@ -7401,7 +7656,7 @@ const _exports = Object.freeze({ wrapShapedPdfText: wrapShapedPdfText });
7401
7656
  return _exports;
7402
7657
  })();
7403
7658
 
7404
- const _m69 = (() => {
7659
+ const _m70 = (() => {
7405
7660
  const { NotSupportedError, OfficeIMOError } = _m2;
7406
7661
 
7407
7662
  const { copyExportLink } = _m7;
@@ -7410,21 +7665,30 @@ const { checkAbort, pause, taskYieldDue } = _m4;
7410
7665
 
7411
7666
  const { presentation, color } = _m55;
7412
7667
 
7413
- const { wrapShapedPdfText } = _m70;
7668
+ const { wrapShapedPdfText } = _m71;
7669
+
7670
+ const { PdfFont } = _m62;
7414
7671
 
7415
- const { PdfFont } = _m61;
7672
+ const { pdfBudgetText } = _m69;
7416
7673
 
7417
- /** @internal A run list is a PDF presentation value, never an alternate shared table value model. */
7418
- function capturePdfText(value, base, settings, fonts, countEmpty = true) {
7419
- const input = typeof value === "string" ? [{ text: value }] : value;
7674
+ /** @internal Callers supply an owned, validated, frozen base presentation. A run list is a PDF presentation value, never an alternate shared table value model. */
7675
+ function capturePdfText(value, base, settings, fonts, countEmpty = true, reserveBudget = true) {
7676
+ if (typeof value === "string") {
7677
+ if (value.length > settings.limits.maxCellCharacters)
7678
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxCellCharacters exceeded.");
7679
+ if (reserveBudget && (value.length || countEmpty))
7680
+ settings.budget.reserve(1, pdfBudgetText(value, settings.budget).length);
7681
+ return Object.freeze({ text: value, runs: Object.freeze([Object.freeze({ text: value, style: base })]) });
7682
+ }
7683
+ const input = value;
7420
7684
  if (!Array.isArray(input)) {
7421
7685
  if (input && typeof input.then === "function")
7422
7686
  void Promise.resolve(input).catch(() => { });
7423
7687
  throw new TypeError("PDF text must be a string or a synchronous array of text runs.");
7424
7688
  }
7425
- if (typeof value !== "string" && input.length > settings.limits.maxTextRuns)
7689
+ if (input.length > settings.limits.maxTextRuns)
7426
7690
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxTextRuns exceeded.");
7427
- let characters = 0;
7691
+ let characters = 0, budgetCharacters = 0;
7428
7692
  const runs = [];
7429
7693
  for (const run of input) {
7430
7694
  if (!run || typeof run !== "object" || Object.keys(run).some(key => !["text", "bold", "italic", "color", "link", "font"].includes(key)))
@@ -7440,14 +7704,16 @@ function capturePdfText(value, base, settings, fonts, countEmpty = true) {
7440
7704
  characters += text.length;
7441
7705
  if (characters > settings.limits.maxCellCharacters)
7442
7706
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxCellCharacters exceeded.");
7707
+ if (reserveBudget)
7708
+ budgetCharacters += pdfBudgetText(text, settings.budget).length;
7443
7709
  const style = presentation({ ...base, ...(bold === undefined ? {} : { bold }), ...(italic === undefined ? {} : { italic }), ...(color === undefined ? {} : { color }) });
7444
7710
  if (settings.options.tagged && link !== undefined && text.length && !text.trim())
7445
7711
  throw new TypeError("Tagged PDF inline links require nonempty displayed text.");
7446
7712
  runs.push(Object.freeze({ text, style, ...(font === undefined ? {} : { font }), ...(link === undefined ? {} : { link: copyExportLink(link) }) }));
7447
7713
  }
7448
7714
  // Reserve before allocating a joined rich-text value or retaining it in a kept paragraph chain.
7449
- if (characters || countEmpty)
7450
- settings.budget.reserve(1, characters);
7715
+ if (reserveBudget && (characters || countEmpty))
7716
+ settings.budget.reserve(1, budgetCharacters);
7451
7717
  return Object.freeze({ text: runs.map(run => run.text).join(""), runs: Object.freeze(runs) });
7452
7718
  }
7453
7719
  /** @internal Greedy wrapping over the continuous text stream, preserving run emphasis and URI geometry. */
@@ -7456,8 +7722,39 @@ async function wrapPdfText(captured, fonts, size, width, settings, wrap = true)
7456
7722
  return wrapShapedPdfText(captured, fonts, size, width, settings, wrap);
7457
7723
  const { signal } = settings.options, { text, runs } = captured;
7458
7724
  checkAbort(signal);
7459
- const faces = runs.map(run => fonts.select(run.style.bold, run.style.italic, run.font));
7460
- const fallback = fonts.select(), lines = [];
7725
+ // Keep font-selection order while deferring a single-run face array until wrapping needs it.
7726
+ const single = runs.length === 1 ? runs[0] : undefined;
7727
+ const singleFace = single && fonts.select(single.style.bold, single.style.italic, single.font);
7728
+ const selectedFaces = singleFace ? undefined : runs.map(run => fonts.select(run.style.bold, run.style.italic, run.font));
7729
+ const fallback = fonts.select();
7730
+ // Short fitting runs need no per-character layout arrays. Longer text keeps the existing
7731
+ // cooperative checkpoints; controls or the first overflowing advance use the general path.
7732
+ if (single && text.length > 0 && text.length < 4096) {
7733
+ const run = single, font = singleFace;
7734
+ let widthSoFar = 0, fits = true;
7735
+ for (let offset = 0; offset < text.length;) {
7736
+ const scalar = text.codePointAt(offset);
7737
+ if (scalar === 9 || scalar === 10 || scalar === 13) {
7738
+ fits = false;
7739
+ break;
7740
+ }
7741
+ const advance = font.width(scalar) * size / 1000;
7742
+ if (advance > width + .001 || widthSoFar + advance > width + .001) {
7743
+ fits = false;
7744
+ break;
7745
+ }
7746
+ widthSoFar += advance;
7747
+ offset += scalar > 0xffff ? 2 : 1;
7748
+ }
7749
+ if (fits) {
7750
+ if (settings.limits.maxRowLines < 1)
7751
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxRowLines exceeded.");
7752
+ return [{ text, width: widthSoFar, segments: [{ text, width: widthSoFar, font,
7753
+ ...(run.style.color === undefined ? {} : { color: run.style.color }), ...(run.link ? { link: run.link } : {}) }],
7754
+ lineHeight: font.lineHeight(size), ascent: Math.max(0, (font.program?.ascent ?? 800) * size / 1000) }];
7755
+ }
7756
+ }
7757
+ const faces = selectedFaces ?? [singleFace], lines = [];
7461
7758
  let chars = [], advances = [], owners = [], measured = 0, breakAt = -1;
7462
7759
  let runIndex = 0, runEnd = runs[0]?.text.length ?? 0, scanned = 0;
7463
7760
  const emit = (count) => {
@@ -7554,19 +7851,17 @@ const _exports = Object.freeze({ capturePdfText: capturePdfText, wrapPdfText: wr
7554
7851
  return _exports;
7555
7852
  })();
7556
7853
 
7557
- const _m71 = (() => {
7854
+ const _m72 = (() => {
7558
7855
  const { OfficeIMOError } = _m2;
7559
7856
 
7560
- const { wrapPdfText } = _m69;
7857
+ const { wrapPdfText } = _m70;
7561
7858
 
7562
7859
  /** Plan without opening a source. Exact column widths never shrink in band mode. */
7563
7860
  function planTableBands(widths, settings) {
7564
7861
  const policy = settings.options.wideTable;
7565
7862
  if (typeof policy !== "object")
7566
7863
  return undefined;
7567
- const available = settings.page.width - settings.margins.left - settings.margins.right, repeats = policy.repeatColumns ?? [];
7568
- if (repeats.some(index => index >= widths.length))
7569
- throw new RangeError("repeatColumns index exceeds the declared columns.");
7864
+ const available = settings.page.width - settings.margins.left - settings.margins.right, repeats = settings.repeatedColumns;
7570
7865
  const repeated = new Set(repeats), rest = widths.map((_, index) => index).filter(index => !repeated.has(index));
7571
7866
  const prefix = repeats.reduce((sum, index) => sum + widths[index], 0);
7572
7867
  if (prefix > available + .001)
@@ -7646,7 +7941,7 @@ const _exports = Object.freeze({ planTableBands: planTableBands, projectBandRows
7646
7941
  return _exports;
7647
7942
  })();
7648
7943
 
7649
- const _m67 = (() => {
7944
+ const _m68 = (() => {
7650
7945
  const { ExportCell } = _m5;
7651
7946
 
7652
7947
  const { copyExportLink } = _m7;
@@ -7657,11 +7952,11 @@ const { createTotals } = _m12;
7657
7952
 
7658
7953
  const { presentation, positive } = _m55;
7659
7954
 
7660
- const { displayText } = _m68;
7955
+ const { displayText, pdfBudgetText } = _m69;
7661
7956
 
7662
- const { capturePdfText, wrapPdfText } = _m69;
7957
+ const { capturePdfText, wrapPdfText } = _m70;
7663
7958
 
7664
- const { planTableBands, projectBandRows, alignBandBlocks } = _m71;
7959
+ const { planTableBands, projectBandRows, alignBandBlocks } = _m72;
7665
7960
 
7666
7961
  class PdfTableLayout {
7667
7962
  settings;
@@ -7674,11 +7969,13 @@ class PdfTableLayout {
7674
7969
  totals;
7675
7970
  repeatedColumns;
7676
7971
  structuredBandRows = new WeakMap();
7972
+ /** Plain/alternate ordinary-data defaults, validated only when a column first needs them. */
7973
+ dataPresentations = [];
7677
7974
  constructor(settings, fonts) {
7678
7975
  this.settings = settings;
7679
7976
  this.fonts = fonts;
7680
7977
  const { options, padding, fontSize, page, margins } = settings, columns = options.columns, available = page.width - margins.left - margins.right;
7681
- this.repeatedColumns = new Set(typeof options.wideTable === "object" ? options.wideTable.repeatColumns : []);
7978
+ this.repeatedColumns = new Set(settings.repeatedColumns);
7682
7979
  let digit;
7683
7980
  if (options.columnWidths && options.columnWidths.length !== columns.length)
7684
7981
  throw new RangeError("columnWidths must declare one point width per column.");
@@ -7719,13 +8016,22 @@ class PdfTableLayout {
7719
8016
  this.headings = headings;
7720
8017
  this.totals = createTotals(columns, options.footer?.totals);
7721
8018
  }
7722
- async cell(value, first, span, row, style) {
8019
+ async cell(value, first, span, row, style, ordinaryData = false) {
7723
8020
  const { options, padding, fontSize, budget } = this.settings, column = options.columns[first];
7724
8021
  const own = value instanceof ExportCell ? value.presentation : undefined;
7725
8022
  const link = value instanceof ExportCell && value.link ? copyExportLink(value.link) : undefined;
7726
- const combined = presentation({ ...(column.alignment === undefined ? {} : { alignment: column.alignment }),
7727
- ...(column.wrapText === undefined ? {} : { wrapText: column.wrapText }), ...style, ...own });
7728
- const font = this.fonts.select(combined.bold, combined.italic), width = this.widths.slice(first, first + span).reduce((n, w) => n + w, 0);
8023
+ const alternate = ordinaryData && row % 2 && options.alternateRowColor ? options.alternateRowColor : undefined;
8024
+ const slot = first * 2 + (alternate ? 1 : 0), reusable = ordinaryData && own === undefined;
8025
+ let combined = reusable ? this.dataPresentations[slot] : undefined;
8026
+ if (!combined) {
8027
+ const rowStyle = ordinaryData ? alternate ? { background: alternate } : {} : style;
8028
+ combined = presentation({ ...(column.alignment === undefined ? {} : { alignment: column.alignment }),
8029
+ ...(column.wrapText === undefined ? {} : { wrapText: column.wrapText }), ...rowStyle, ...own });
8030
+ // Validate only the first reached default; an authored cell may override invalid column defaults.
8031
+ if (reusable)
8032
+ this.dataPresentations[slot] = combined;
8033
+ }
8034
+ const font = this.fonts.select(combined.bold, combined.italic), width = span === 1 ? this.widths[first] : this.widths.slice(first, first + span).reduce((n, w) => n + w, 0);
7729
8035
  const context = { rowIndex: row, columnIndex: first, column }, raw = value instanceof ExportCell ? value.value : value;
7730
8036
  let text;
7731
8037
  if (options.formatRuns && row >= 0 && !(value instanceof ExportCell && value.text !== undefined)) {
@@ -7744,10 +8050,11 @@ class PdfTableLayout {
7744
8050
  throw new TypeError("Tagged PDF cell links require nonempty displayed text.");
7745
8051
  if (link && captured.runs.some(run => run.link))
7746
8052
  throw new TypeError("A PDF cell link cannot be combined with inline run links.");
8053
+ const budgetText = pdfBudgetText(captured.text, budget);
7747
8054
  if (this.bands)
7748
- budget.release(1, captured.text.length);
8055
+ budget.release(1, budgetText.length);
7749
8056
  else
7750
- budget.cell(captured.text, captured.text.length);
8057
+ budget.cell(budgetText, budgetText.length);
7751
8058
  const lines = await wrapPdfText(captured, this.fonts, fontSize, width - padding * 2, this.settings, combined.wrapText !== false);
7752
8059
  return { first, span, width, font, style: combined, lineHeight: lines.reduce((height, line) => Math.max(height, line.lineHeight), font.lineHeight(fontSize)),
7753
8060
  ...(link ? { link } : {}), ...(this.bands ? { captured } : {}),
@@ -7846,8 +8153,8 @@ class PdfTableLayout {
7846
8153
  const value = values[column], raw = value instanceof ExportCell ? value.value : value;
7847
8154
  if (!footer)
7848
8155
  this.totals[column].accept(raw);
7849
- const style = footer ? options.footerPresentation ?? {} : index % 2 && options.alternateRowColor ? { background: options.alternateRowColor } : {};
7850
- cells.push(await this.cell(value, column, 1, index, style));
8156
+ const cell = await this.cell(value, column, 1, index, footer ? options.footerPresentation ?? {} : undefined, !footer);
8157
+ cells.push(!footer && options.columns[column].rowHeader ? { ...cell, rowHeader: true } : cell);
7851
8158
  }
7852
8159
  return this.row(cells);
7853
8160
  }
@@ -7864,7 +8171,7 @@ const _exports = Object.freeze({ PdfTableLayout: PdfTableLayout });
7864
8171
  return _exports;
7865
8172
  })();
7866
8173
 
7867
- const _m73 = (() => {
8174
+ const _m74 = (() => {
7868
8175
  const { OfficeIMOError } = _m2;
7869
8176
 
7870
8177
  const { checkAbort } = _m4;
@@ -7908,7 +8215,7 @@ class PdfTableBandFlow {
7908
8215
  await this.flush();
7909
8216
  }
7910
8217
  async row(row, allowFirstFragment = false) {
7911
- const { padding, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = this.layout.minimumRowHeight(row);
8218
+ const { padding, fontSize, options } = this.layout.settings, minimumLines = this.layout.minimumRowLines(row), minimumHeight = this.layout.minimumRowHeight(row);
7912
8219
  if (minimumHeight > this.painter.firstFullCapacity + .001 || minimumHeight > this.painter.continuationCapacity + .001)
7913
8220
  throw new RangeError("Repeated PDF identifiers must fit intact below the first and continued band headings/context.");
7914
8221
  // Keep ordinary rows intact when they fit fresh. A kept heading/caption can deliberately
@@ -7934,16 +8241,29 @@ class PdfTableBandFlow {
7934
8241
  const lines = Math.min(row.lines - first, Math.floor((this.capacity - this.height - padding * 2 + .001) / row.lineHeight));
7935
8242
  if (lines < 1)
7936
8243
  throw new RangeError("PDF page cannot fit a table line below horizontal band headings.");
7937
- const paintedLines = Math.max(lines, minimumLines), height = paintedLines * row.lineHeight + padding * 2;
8244
+ // Reserve one shared logical fragment, but paint only each band's visible cell geometry.
8245
+ const reservedLines = Math.max(lines, minimumLines), height = reservedLines * row.lineHeight + padding * 2;
7938
8246
  const projected = await this.layout.bandRows([row]);
7939
- const fragments = projected.map((rows, index) => [{ ...rows[0], lines: paintedLines, height,
7940
- cells: rows[0].cells.map(cell => {
7941
- const source = this.layout.bands[index].columns[cell.first];
7942
- const visible = this.layout.repeatedColumn(source) ? cell.lines : cell.lines.slice(first, first + lines);
7943
- const { height: _height, ...plain } = cell;
7944
- return { ...plain, lines: visible, ...(first > 0 && this.layout.repeatedColumn(source) ? { semanticArtifact: true } : {}) };
7945
- }) }]);
7946
- await this.accept({ rows: fragments, height, count: 1, completed: first + lines >= row.lines ? [row] : [] });
8247
+ const exhaustedBands = [];
8248
+ const fragments = projected.map((rows, index) => {
8249
+ let remaining = false;
8250
+ const cells = rows[0].cells.map(cell => {
8251
+ const source = this.layout.bands[index].columns[cell.first];
8252
+ const repeated = this.layout.repeatedColumn(source), visible = repeated ? cell.lines : cell.lines.slice(first, first + lines);
8253
+ if (!repeated && (visible.length > 0 || cell.link !== undefined))
8254
+ remaining = true;
8255
+ const { height: _height, ...plain } = cell;
8256
+ return { ...plain, lines: visible,
8257
+ lineHeight: visible.reduce((value, line) => Math.max(value, line.lineHeight), cell.font.lineHeight(fontSize)),
8258
+ ...(first > 0 && repeated ? { semanticArtifact: true } : {}) };
8259
+ });
8260
+ const fragmentLines = Math.max(1, ...cells.map(cell => cell.lines.length));
8261
+ const lineHeight = Math.max(this.layout.lineHeight, ...cells.filter(cell => cell.lines.length > 0).map(cell => cell.lineHeight));
8262
+ // Never omit an initial/new row, a structured block, or a nonrepeated link obligation.
8263
+ exhaustedBands.push(first > 0 && !remaining);
8264
+ return [{ ...rows[0], cells, lines: fragmentLines, lineHeight, height: fragmentLines * lineHeight + padding * 2 }];
8265
+ });
8266
+ await this.accept({ rows: fragments, height, count: 1, completed: first + lines >= row.lines ? [row] : [], exhaustedBands });
7947
8267
  first += lines;
7948
8268
  if (first < row.lines)
7949
8269
  await this.flush();
@@ -7955,7 +8275,7 @@ class PdfTableBandFlow {
7955
8275
  throw new OfficeIMOError("RESOURCE_LIMIT", "A structured PDF block exceeds maxTableWindowRows.");
7956
8276
  for (const row of rows)
7957
8277
  await this.painter.prepareRow?.(row);
7958
- await this.accept({ rows: projected, height, count: rows.length, completed: rows });
8278
+ await this.accept({ rows: projected, height, count: rows.length, completed: rows, exhaustedBands: projected.map(() => false) });
7959
8279
  }
7960
8280
  async keptRows(rows, allowFirstFragment = false) {
7961
8281
  const height = rows.reduce((sum, row) => sum + row.height, 0), fits = height <= this.painter.continuationCapacity + .001;
@@ -7969,6 +8289,8 @@ class PdfTableBandFlow {
7969
8289
  return;
7970
8290
  for (let band = 0; band < this.layout.bands.length; band++) {
7971
8291
  checkAbort(this.layout.settings.options.signal);
8292
+ if (!this.firstWindow && this.entries.length > 0 && this.entries.every(entry => entry.exhaustedBands[band]))
8293
+ continue;
7972
8294
  await this.painter.paint(band, this.headings[band], this.entries.flatMap(entry => entry.rows[band]), this.firstWindow ? this.caption : this.continuation, this.firstWindow, band === 0);
7973
8295
  }
7974
8296
  for (const entry of this.entries)
@@ -7985,7 +8307,7 @@ const _exports = Object.freeze({ PdfTableBandFlow: PdfTableBandFlow });
7985
8307
  return _exports;
7986
8308
  })();
7987
8309
 
7988
- const _m74 = (() => {
8310
+ const _m75 = (() => {
7989
8311
  /** @internal Source-cell identities survive page fragments and horizontal band projections.
7990
8312
  * Only column headers and still-owned row objects remain reachable from this table owner. */
7991
8313
  class PdfTableStructure {
@@ -7995,6 +8317,8 @@ class PdfTableStructure {
7995
8317
  cells = new WeakMap();
7996
8318
  rows = new WeakMap();
7997
8319
  columnHeaders = [];
8320
+ /** Ordinary cells without row headers share immutable dictionary references, bounded by column count. */
8321
+ ordinaryAttributes = [];
7998
8322
  headerCount = 0;
7999
8323
  headersPrepared = false;
8000
8324
  constructor(structure, table, headers) {
@@ -8035,19 +8359,30 @@ class PdfTableStructure {
8035
8359
  return row.cells.map(cell => this.cells.get(cell));
8036
8360
  const rowId = this.structure.element("TR", parent);
8037
8361
  this.rows.set(row, rowId);
8038
- const ids = [];
8039
- let rowHeaderIdentifier;
8040
- // Allocating in source-column order preserves the record's logical reading order.
8362
+ const headers = row.cells.map((cell, index) => rowHeaderIndex === undefined ? cell.rowHeader === true : index === rowHeaderIndex);
8363
+ // Allocate in source order, then resolve every row header before associating even earlier data cells.
8364
+ // Generated summary labels override detail roles so numeric subtotal cells never become row headers.
8365
+ const ids = row.cells.map((cell, index) => {
8366
+ const id = this.structure.element(headers[index] ? "TH" : "TD", rowId);
8367
+ this.cells.set(cell, id);
8368
+ return id;
8369
+ });
8370
+ const rowHeaders = [];
8371
+ for (let index = 0; index < ids.length; index++)
8372
+ if (headers[index])
8373
+ rowHeaders.push(await this.structure.identifier(ids[index]));
8041
8374
  for (let index = 0; index < row.cells.length; index++) {
8042
- const cell = row.cells[index], isRowHeader = index === rowHeaderIndex;
8375
+ const cell = row.cells[index];
8376
+ if (!rowHeaders.length && cell.span === 1 && (cell.rowSpan ?? 1) === 1) {
8377
+ const attributes = this.ordinaryAttributes[cell.first] ??=
8378
+ await this.structure.attributeReference(this.attributeDictionary(cell, this.associations(cell)));
8379
+ this.structure.setAttributes(ids[index], attributes);
8380
+ continue;
8381
+ }
8043
8382
  const associations = this.associations(cell);
8044
- if (rowHeaderIdentifier !== undefined && !isRowHeader)
8045
- associations.push(rowHeaderIdentifier);
8046
- const id = this.structure.element(isRowHeader ? "TH" : "TD", rowId, this.attributes(cell, associations, isRowHeader ? "Row" : undefined));
8047
- this.cells.set(cell, id);
8048
- ids.push(id);
8049
- if (isRowHeader)
8050
- rowHeaderIdentifier = await this.structure.identifier(id);
8383
+ if (!headers[index])
8384
+ associations.push(...rowHeaders);
8385
+ this.structure.setAttributes(ids[index], this.attributes(cell, associations, headers[index] ? "Row" : undefined));
8051
8386
  }
8052
8387
  return ids;
8053
8388
  }
@@ -8073,7 +8408,10 @@ class PdfTableStructure {
8073
8408
  return [...headers].sort((left, right) => left.order - right.order).map(header => header.identifier);
8074
8409
  }
8075
8410
  attributes(cell, headers, scope) {
8076
- return " /A << /O /Table" + (scope === undefined ? "" : " /Scope /" + scope) +
8411
+ return " /A " + this.attributeDictionary(cell, headers, scope);
8412
+ }
8413
+ attributeDictionary(cell, headers, scope) {
8414
+ return "<< /O /Table" + (scope === undefined ? "" : " /Scope /" + scope) +
8077
8415
  (cell.span > 1 ? " /ColSpan " + cell.span : "") + ((cell.rowSpan ?? 1) > 1 ? " /RowSpan " + cell.rowSpan : "") +
8078
8416
  (headers.length ? " /Headers [" + headers.map(id => "(" + id + ")").join(" ") + "]" : "") + " >>";
8079
8417
  }
@@ -8082,7 +8420,7 @@ const _exports = Object.freeze({ PdfTableStructure: PdfTableStructure });
8082
8420
  return _exports;
8083
8421
  })();
8084
8422
 
8085
- const _m75 = (() => {
8423
+ const _m76 = (() => {
8086
8424
  const { OfficeIMOError } = _m2;
8087
8425
 
8088
8426
  const { pdfNumber, unicodeHex } = _m59;
@@ -8127,7 +8465,7 @@ const _exports = Object.freeze({ linkAnnotation: linkAnnotation });
8127
8465
  return _exports;
8128
8466
  })();
8129
8467
 
8130
- const _m76 = (() => {
8468
+ const _m77 = (() => {
8131
8469
  const { OfficeIMOError } = _m2;
8132
8470
 
8133
8471
  const { unicodeHex } = _m59;
@@ -8175,7 +8513,7 @@ const _exports = Object.freeze({ captureBookmark: captureBookmark, captureSectio
8175
8513
  return _exports;
8176
8514
  })();
8177
8515
 
8178
- const _m77 = (() => {
8516
+ const _m78 = (() => {
8179
8517
  const { settings } = _m55;
8180
8518
 
8181
8519
  /** @internal Every section derives from captured document defaults, never the preceding section. */
@@ -8193,7 +8531,7 @@ const _exports = Object.freeze({ sectionSettings: sectionSettings });
8193
8531
  return _exports;
8194
8532
  })();
8195
8533
 
8196
- const _m72 = (() => {
8534
+ const _m73 = (() => {
8197
8535
  const { OfficeIMOError } = _m2;
8198
8536
 
8199
8537
  const { checkAbort } = _m4;
@@ -8202,19 +8540,19 @@ const { pdfNumber } = _m59;
8202
8540
 
8203
8541
  const { color } = _m55;
8204
8542
 
8205
- const { PdfTableBandFlow } = _m73;
8543
+ const { PdfTableBandFlow } = _m74;
8206
8544
 
8207
- const { PdfTableStructure } = _m74;
8545
+ const { PdfTableStructure } = _m75;
8208
8546
 
8209
- const { wrapText, wrapTextCooperatively, synchronousText } = _m68;
8547
+ const { wrapText, wrapTextCooperatively, synchronousText, pdfBudgetText } = _m69;
8210
8548
 
8211
- const { linkAnnotation } = _m75;
8549
+ const { linkAnnotation } = _m76;
8212
8550
 
8213
8551
  const { unicodeHex } = _m59;
8214
8552
 
8215
- const { captureSection, captureBookmark } = _m76;
8553
+ const { captureSection, captureBookmark } = _m77;
8216
8554
 
8217
- const { sectionSettings } = _m77;
8555
+ const { sectionSettings } = _m78;
8218
8556
 
8219
8557
  /** @internal One page of drawing commands and O(page count) references, never the complete report body. */
8220
8558
  class PdfPages {
@@ -8352,8 +8690,9 @@ class PdfPages {
8352
8690
  const lineActualText = !this.structure && line.actualText !== undefined && line.actualText.length > 0;
8353
8691
  if (lineActualText)
8354
8692
  this.add("/Span << /ActualText <FEFF" + unicodeHex(line.actualText) + "> >> BDC\n");
8355
- const marks = new Map();
8693
+ let marks;
8356
8694
  if (line.actualText !== undefined && this.structure && element !== undefined) {
8695
+ marks = new Map();
8357
8696
  // Allocate MCIDs/Link children in logical order, then paint the independently positioned visual order.
8358
8697
  for (const segment of [...line.segments].sort((a, b) => (a.logicalStart ?? 0) - (b.logicalStart ?? 0))) {
8359
8698
  const owner = segment.link ? this.structure.link(element, segment.link) : element;
@@ -8361,7 +8700,7 @@ class PdfPages {
8361
8700
  }
8362
8701
  }
8363
8702
  for (const segment of line.segments) {
8364
- const registered = marks.get(segment), owner = registered?.owner ?? (segment.link && this.structure && element !== undefined ? this.structure.link(element, segment.link) : element);
8703
+ const registered = marks?.get(segment), owner = registered?.owner ?? (segment.link && this.structure && element !== undefined ? this.structure.link(element, segment.link) : element);
8365
8704
  if (segment.glyphs) {
8366
8705
  const font = segment.font, n = pdfNumber, shear = font.syntheticItalic ? .213 : 0;
8367
8706
  let cursor = x, command = "q " + this.rgb(segment.color ?? "111827") + " rg " + this.rgb(segment.color ?? "111827") + " RG\nBT /" + font.name + " " + n(size) + " Tf " +
@@ -8395,7 +8734,7 @@ class PdfPages {
8395
8734
  decoration(text, x, y, width) {
8396
8735
  if (!text)
8397
8736
  return;
8398
- this.settings.budget.cell(text);
8737
+ this.settings.budget.cell(pdfBudgetText(text, this.settings.budget));
8399
8738
  const font = this.fonts.select(), lines = wrapText(text, font, this.settings.fontSize, width, this.settings.limits.maxCellCharacters, 1, false);
8400
8739
  this.text(lines[0].text, font, this.settings.fontSize, x, y);
8401
8740
  }
@@ -8456,9 +8795,7 @@ class PdfPages {
8456
8795
  }
8457
8796
  const headers = preparedHeadings ?? (tableHeadings && this.layout ? this.activeHeadings ??= await this.layout.headers() : []), headerHeight = headers.reduce((n, h) => n + h.height, 0), continuation = tableHeadings && this.layout ? this.continuationCaption : undefined;
8458
8797
  if (continuation?.lines.length) {
8459
- if (this.continuationCaptionPaints++ > 0)
8460
- this.settings.budget.cell(continuation.text.text);
8461
- else
8798
+ if (this.continuationCaptionPaints++ === 0)
8462
8799
  this.tableCaptionOwner = this.captionAnnotations(continuation, this.tableCaptionOwner);
8463
8800
  await this.paragraphs([continuation], headerHeight + lineHeight + this.settings.padding * 2, true, { artifact: true, ...(this.tableCaptionOwner === undefined ? {} : { annotationParent: this.tableCaptionOwner }) });
8464
8801
  }
@@ -8576,7 +8913,7 @@ class PdfPages {
8576
8913
  async paragraph(text, style = {}, size = this.settings.fontSize, paginate = true, headingLevel) {
8577
8914
  await this.ensureStarted();
8578
8915
  const { margins, page, limits } = this.settings, font = this.fonts.select(style.bold, style.italic), lineHeight = font.lineHeight(size);
8579
- this.settings.budget.cell(text);
8916
+ this.settings.budget.cell(pdfBudgetText(text, this.settings.budget));
8580
8917
  const lines = await wrapTextCooperatively(text, font, size, page.width - margins.left - margins.right, limits.maxCellCharacters, limits.maxRowLines, true, this.settings.options.signal);
8581
8918
  if (lineHeight > page.height - margins.top - margins.bottom)
8582
8919
  throw new RangeError("PDF page cannot fit a paragraph line at the selected font metrics.");
@@ -8619,6 +8956,8 @@ class PdfPages {
8619
8956
  if (keepTogether && visible.length)
8620
8957
  await this.reserveSpace(visible.reduce((height, paragraph) => height + paragraph.height, 0) + reservations.at(-1), "Kept PDF paragraph group");
8621
8958
  for (const [index, paragraph] of visible.entries()) {
8959
+ if (paragraph.budgetOnPaint)
8960
+ this.settings.budget.cell(pdfBudgetText(paragraph.text.text, this.settings.budget));
8622
8961
  if (paragraph.keepTogether || paragraph.keepWithNext)
8623
8962
  await this.reserveSpace(paragraph.height + reservations[index], "Kept PDF paragraph chain");
8624
8963
  const { margins, page } = this.settings;
@@ -8671,10 +9010,11 @@ class PdfPages {
8671
9010
  /** The generated summary label is a row heading; no localized text/style inference is used. */
8672
9011
  summary(row) { this.summaryRows.add(row); }
8673
9012
  /** Begin an independent table on the current page, retaining its headings on continuation pages.
8674
- * Group context uses captionArtifact: it stays visually complete without duplicating logical headings. */
8675
- async beginTable(layout, preparedHeadings, minimumDataHeight = layout.lineHeight + this.settings.padding * 2, caption, continuationCaption, headingsOnNewPageOnly = false, captionArtifact = false) {
9013
+ * Group context uses captionArtifact: it stays visually complete without duplicating logical headings.
9014
+ * An already-painted opening path only suppresses its artifact caption on that existing page. */
9015
+ async beginTable(layout, preparedHeadings, minimumDataHeight = layout.lineHeight + this.settings.padding * 2, caption, continuationCaption, headingsOnNewPageOnly = false, captionArtifact = false, openingContextAlreadyPainted = false) {
8676
9016
  if (layout.bands)
8677
- return this.beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuationCaption, captionArtifact);
9017
+ return this.beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuationCaption, captionArtifact, openingContextAlreadyPainted);
8678
9018
  await this.ensureStarted();
8679
9019
  this.layout = layout;
8680
9020
  this.paintedHeaderCells = new WeakSet();
@@ -8688,7 +9028,7 @@ class PdfPages {
8688
9028
  // Its own headings remain available when it moves or splits onto a fresh page.
8689
9029
  const initialHeadings = headingsOnNewPageOnly && this.bodyAdded && !this.structure ? [] : headings;
8690
9030
  const height = initialHeadings.reduce((n, row) => n + row.height, 0);
8691
- if (caption) {
9031
+ if (caption && !(captionArtifact && openingContextAlreadyPainted)) {
8692
9032
  await this.reserveSpace(caption.height + height + minimumDataHeight, "Kept PDF table caption and first data fragment");
8693
9033
  this.tableCaptionOwner = captionArtifact ? this.captionAnnotations(caption)
8694
9034
  : caption.lines.length ? this.structure?.element("Caption", this.tableElement) : undefined;
@@ -8710,7 +9050,7 @@ class PdfPages {
8710
9050
  this.dataTop = this.y;
8711
9051
  }
8712
9052
  /** Bind the bounded logical-window owner to the existing physical page painter. */
8713
- async beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuation, captionArtifact) {
9053
+ async beginBands(layout, preparedHeadings, minimumDataHeight, caption, continuation, captionArtifact, openingContextAlreadyPainted) {
8714
9054
  await this.ensureStarted();
8715
9055
  const logicalHeadings = preparedHeadings ?? await layout.headers(), headings = await layout.bandRows(logicalHeadings, true);
8716
9056
  const headerHeight = headings[0].reduce((sum, row) => sum + row.height, 0), { page, margins, padding } = this.settings;
@@ -8719,13 +9059,15 @@ class PdfPages {
8719
9059
  const continuationCapacity = page.height - margins.top - margins.bottom - headerHeight - (continuation?.height ?? 0);
8720
9060
  if (continuationCapacity + .001 < layout.lineHeight + padding * 2)
8721
9061
  throw new RangeError("PDF band headings and continuation context leave no room for a data line.");
8722
- if (this.y - margins.bottom - headerHeight - (caption?.height ?? 0) + .001 < minimum)
9062
+ let openingContextPainted = captionArtifact && openingContextAlreadyPainted;
9063
+ if (this.y - margins.bottom - headerHeight - (openingContextPainted ? 0 : caption?.height ?? 0) + .001 < minimum) {
8723
9064
  await this.pageBreak();
8724
- let initialOffset = page.height - margins.top - this.y;
8725
- const firstCapacity = this.y - margins.bottom - headerHeight - (caption?.height ?? 0);
9065
+ openingContextPainted = false;
9066
+ }
9067
+ const firstCapacity = this.y - margins.bottom - headerHeight - (openingContextPainted ? 0 : caption?.height ?? 0);
8726
9068
  if (firstCapacity + .001 < minimum)
8727
9069
  throw new RangeError("PDF band caption and headings leave no room for a data line.");
8728
- let captionPaints = 0, continuationPaints = 0;
9070
+ let continuationPaints = 0;
8729
9071
  this.tableElement = this.structure?.element("Table", this.groupParent);
8730
9072
  this.paintedHeaderCells = new WeakSet();
8731
9073
  let captionElement = this.structure && caption?.lines.length ? captionArtifact ? this.captionAnnotations(caption)
@@ -8739,21 +9081,16 @@ class PdfPages {
8739
9081
  this.bandFlow = new PdfTableBandFlow(layout, headings, { firstCapacity, firstFullCapacity, continuationCapacity,
8740
9082
  prepareRow: async (row) => { await this.tableStructure?.prepareHeaders(); await this.rowElements(row); },
8741
9083
  completeRow: async (row) => { await this.tableStructure?.completeRow(row.source ?? row); },
8742
- moveFirstToFreshPage: async () => { await this.pageBreak(); initialOffset = 0; },
9084
+ moveFirstToFreshPage: async () => { await this.pageBreak(); openingContextPainted = false; },
8743
9085
  paint: async (band, headers, rows, currentCaption, firstWindow, firstBand) => {
8744
9086
  if (!(firstWindow && firstBand))
8745
9087
  await this.pageBreak();
8746
- if (firstWindow && !firstBand)
8747
- this.y -= initialOffset;
8748
9088
  const frame = layout.bands[band];
8749
9089
  this.layout = { lefts: frame.lefts, lineHeight: layout.lineHeight, headers: async () => headers };
8750
9090
  this.bandCellBudget = true;
8751
9091
  try {
8752
- if (currentCaption?.lines.length) {
8753
- const paints = firstWindow ? captionPaints++ : continuationPaints++;
8754
- if (paints > 0)
8755
- this.settings.budget.cell(currentCaption.text.text);
8756
- if (!firstWindow && paints === 0)
9092
+ if (currentCaption?.lines.length && !(firstWindow && firstBand && openingContextPainted)) {
9093
+ if (!firstWindow && continuationPaints++ === 0)
8757
9094
  captionElement = this.captionAnnotations(currentCaption, captionElement);
8758
9095
  const annotationParent = captionElement;
8759
9096
  await this.paragraphs([currentCaption], headerHeight + minimum, true, firstWindow && firstBand && !captionArtifact ? { role: "Caption", keepOpen: true, ...(captionElement === undefined ? {} : { owner: captionElement }) }
@@ -8857,7 +9194,7 @@ class PdfPages {
8857
9194
  this.annotations = [];
8858
9195
  this.commandBytes = 0;
8859
9196
  this.current = 0;
8860
- await this.objects.flush();
9197
+ await this.objects.flushBytes();
8861
9198
  }
8862
9199
  async finish() {
8863
9200
  if (this.bandFlow) {
@@ -8888,7 +9225,7 @@ const _exports = Object.freeze({ PdfPages: PdfPages });
8888
9225
  return _exports;
8889
9226
  })();
8890
9227
 
8891
- const _m79 = (() => {
9228
+ const _m80 = (() => {
8892
9229
  /** @internal Incremental PDF number tree: at most 64 entries/children per retained level. */
8893
9230
  class PdfParentTree {
8894
9231
  objects;
@@ -8950,15 +9287,38 @@ const _exports = Object.freeze({ PdfParentTree: PdfParentTree });
8950
9287
  return _exports;
8951
9288
  })();
8952
9289
 
8953
- const _m78 = (() => {
9290
+ const _m79 = (() => {
8954
9291
  const { OfficeIMOError } = _m2;
8955
9292
 
8956
9293
  const { checkAbort } = _m4;
8957
9294
 
8958
9295
  const { unicodeHex } = _m59;
8959
9296
 
8960
- const { PdfParentTree } = _m79;
9297
+ const { PdfParentTree } = _m80;
8961
9298
 
9299
+ /** Same-page marked content uses integer K; cross-page MCR and annotation OBJR stay explicit. */
9300
+ function structureChild(child) {
9301
+ return typeof child === "number" ? (child < 0 ? -child - 1 + " " : child + " 0 R ") : child + " ";
9302
+ }
9303
+ function structurePrefix(element) {
9304
+ return "<< /Type /StructElem /S /" + element.role + " /P " + element.parent + " 0 R" +
9305
+ (element.markedPage === undefined ? "" : " /Pg " + element.markedPage + " 0 R") +
9306
+ (element.identifier === undefined ? "" : " /ID (" + element.identifier + ")") + " /K [";
9307
+ }
9308
+ /** Keep the same bounded small-object representation for both completion paths. */
9309
+ function compactStructureBody(element, prefix) {
9310
+ const remaining = 32768 - prefix.length - element.attributes.length - 4;
9311
+ if (remaining < 0)
9312
+ return undefined;
9313
+ let children = "";
9314
+ for (const child of element.children) {
9315
+ const token = structureChild(child);
9316
+ if (children.length + token.length > remaining)
9317
+ return undefined;
9318
+ children += token;
9319
+ }
9320
+ return prefix + children + "]" + element.attributes + " >>";
9321
+ }
8962
9322
  /** A sorted name tree retains only a small open leaf and branch at each level. */
8963
9323
  class PdfStructureIds {
8964
9324
  objects;
@@ -9048,7 +9408,7 @@ class PdfStructure {
9048
9408
  checkAbort(this.settings.options.signal);
9049
9409
  if (++this.allocated > this.settings.limits.maxStructureElements)
9050
9410
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxStructureElements exceeded.");
9051
- const id = this.objects.reserve(), element = { id, parent, role, children: [], attributes, linkIdentities: [] };
9411
+ const id = this.objects.reserve(), element = { id, parent, role, children: [], attributes };
9052
9412
  this.elements.set(id, element);
9053
9413
  const owner = this.elements.get(parent);
9054
9414
  // A continuation-only linked caption is discovered during painting, after rows may exist.
@@ -9059,6 +9419,20 @@ class PdfStructure {
9059
9419
  owner?.children.push(id);
9060
9420
  return id;
9061
9421
  }
9422
+ /** Attach resolved table associations while a source-ordered logical element is still open. */
9423
+ setAttributes(elementId, attributes) {
9424
+ const element = this.elements.get(elementId);
9425
+ if (!element)
9426
+ throw new Error("PDF structure attributes require an open logical owner.");
9427
+ element.attributes = attributes;
9428
+ }
9429
+ /** Write one immutable attribute dictionary. Its caller owns the bounded scope of reference reuse. */
9430
+ async attributeReference(dictionary) {
9431
+ checkAbort(this.settings.options.signal);
9432
+ const id = this.objects.reserve();
9433
+ await this.objects.object(id, dictionary);
9434
+ return " /A " + id + " 0 R";
9435
+ }
9062
9436
  /** Flat visual sections share the same logical Document and cumulative resource policy. */
9063
9437
  async beginSection() {
9064
9438
  await this.complete(this.section);
@@ -9092,7 +9466,8 @@ class PdfStructure {
9092
9466
  return existing;
9093
9467
  const id = this.element("Link", parent, alternativeText === undefined ? "" : " /Alt <feff" + unicodeHex(alternativeText) + ">");
9094
9468
  parents.set(parent, id);
9095
- this.elements.get(parent).linkIdentities.push(identity);
9469
+ const owner = this.elements.get(parent);
9470
+ (owner.linkIdentities ??= []).push(identity);
9096
9471
  return id;
9097
9472
  }
9098
9473
  /** Associate a native annotation in both directions: OBJR child and annotation ParentTree entry. */
@@ -9115,7 +9490,9 @@ class PdfStructure {
9115
9490
  throw new Error("Marked content requires an open logical owner.");
9116
9491
  const mcid = this.pageParents.length;
9117
9492
  this.pageParents.push(elementId);
9118
- element.children.push("<< /Type /MCR /Pg " + this.pageId + " 0 R /MCID " + mcid + " >>");
9493
+ element.markedPage ??= this.pageId;
9494
+ element.children.push(element.markedPage === this.pageId ? -(mcid + 1) :
9495
+ "<< /Type /MCR /Pg " + this.pageId + " 0 R /MCID " + mcid + " >>");
9119
9496
  return "/" + element.role + " << /MCID " + mcid + (actualText === undefined ? "" : " /ActualText <FEFF" + unicodeHex(actualText) + ">") + " >> BDC\n";
9120
9497
  }
9121
9498
  get pageDictionary() { return " /StructParents " + this.pageKey + " /Tabs /S"; }
@@ -9139,37 +9516,49 @@ class PdfStructure {
9139
9516
  if (!element)
9140
9517
  return;
9141
9518
  for (const child of element.children)
9142
- if (typeof child === "number" && this.elements.has(child))
9519
+ if (typeof child === "number" && child > 0 && !this.completeBuffered(child))
9143
9520
  await this.complete(child);
9144
9521
  checkAbort(this.settings.options.signal);
9145
- const prefix = "<< /Type /StructElem /S /" + element.role + " /P " + element.parent + " 0 R" +
9146
- (element.identifier === undefined ? "" : " /ID (" + element.identifier + ")") + " /K [";
9147
- const remaining = 32768 - prefix.length - element.attributes.length - 4;
9148
- let children = "", small = remaining >= 0;
9149
- if (small)
9150
- for (const child of element.children) {
9151
- const token = typeof child === "number" ? child + " 0 R " : child + " ";
9152
- if (children.length + token.length > remaining) {
9153
- small = false;
9154
- break;
9155
- }
9156
- children += token;
9157
- }
9522
+ const prefix = structurePrefix(element), body = compactStructureBody(element, prefix);
9158
9523
  // Most table cells/rows fit in one encoding. Large parents and alternatives remain streamed.
9159
- await this.objects.object(id, small ? prefix + children + "]" + element.attributes + " >>" : this.body(element));
9160
- for (const identity of element.linkIdentities) {
9161
- const parents = this.links.get(identity);
9162
- parents?.delete(id);
9163
- if (!parents?.size)
9164
- this.links.delete(identity);
9165
- }
9166
- this.elements.delete(id);
9167
- }
9168
- *body(element) {
9169
- yield "<< /Type /StructElem /S /" + element.role + " /P " + element.parent + " 0 R" +
9170
- (element.identifier === undefined ? "" : " /ID (" + element.identifier + ")") + " /K [";
9524
+ if (body !== undefined) {
9525
+ if (!this.objects.tryCompactObject(id, body))
9526
+ await this.objects.compactObject(id, body);
9527
+ }
9528
+ else
9529
+ await this.objects.object(id, this.body(element, prefix));
9530
+ this.releaseElement(element);
9531
+ }
9532
+ /** Close already-bufferable children without creating an async chain per leaf. A false result
9533
+ * leaves the current owner open for the existing awaited flush or ordinary-object path. */
9534
+ completeBuffered(id) {
9535
+ const element = this.elements.get(id);
9536
+ if (!element)
9537
+ return true;
9538
+ for (const child of element.children)
9539
+ if (typeof child === "number" && child > 0 && !this.completeBuffered(child))
9540
+ return false;
9541
+ checkAbort(this.settings.options.signal);
9542
+ const body = compactStructureBody(element, structurePrefix(element));
9543
+ if (body === undefined || !this.objects.tryCompactObject(id, body))
9544
+ return false;
9545
+ this.releaseElement(element);
9546
+ return true;
9547
+ }
9548
+ releaseElement(element) {
9549
+ if (element.linkIdentities)
9550
+ for (const identity of element.linkIdentities) {
9551
+ const parents = this.links.get(identity);
9552
+ parents?.delete(element.id);
9553
+ if (!parents?.size)
9554
+ this.links.delete(identity);
9555
+ }
9556
+ this.elements.delete(element.id);
9557
+ }
9558
+ *body(element, prefix) {
9559
+ yield prefix;
9171
9560
  for (const child of element.children)
9172
- yield typeof child === "number" ? child + " 0 R " : child + " ";
9561
+ yield structureChild(child);
9173
9562
  yield "]" + element.attributes + " >>";
9174
9563
  }
9175
9564
  async completeRow(cells) {
@@ -9209,7 +9598,7 @@ const _exports = Object.freeze({ PdfStructure: PdfStructure, graphicAlternative:
9209
9598
  return _exports;
9210
9599
  })();
9211
9600
 
9212
- const _m80 = (() => {
9601
+ const _m81 = (() => {
9213
9602
  const { OfficeIMOError } = _m2;
9214
9603
 
9215
9604
  const { checkAbort } = _m4;
@@ -9275,15 +9664,15 @@ return _exports;
9275
9664
  const _m58 = (() => {
9276
9665
  const { PdfObjects, unicodeHex } = _m59;
9277
9666
 
9278
- const { PdfFontResources } = _m60;
9667
+ const { PdfFontResources } = _m61;
9279
9668
 
9280
- const { PdfTableLayout } = _m67;
9669
+ const { PdfTableLayout } = _m68;
9281
9670
 
9282
- const { PdfPages } = _m72;
9671
+ const { PdfPages } = _m73;
9283
9672
 
9284
- const { PdfStructure } = _m78;
9673
+ const { PdfStructure } = _m79;
9285
9674
 
9286
- const { PdfOutlines } = _m80;
9675
+ const { PdfOutlines } = _m81;
9287
9676
 
9288
9677
  /** One resource/catalog owner shared by table convenience exports and composed documents. */
9289
9678
  class PdfWriteSession {
@@ -9300,7 +9689,7 @@ class PdfWriteSession {
9300
9689
  info;
9301
9690
  constructor(sink, settings, table = false) {
9302
9691
  this.settings = settings;
9303
- this.objects = new PdfObjects(sink, settings.options.signal, settings.budget.limits.maxOutputBytes);
9692
+ this.objects = new PdfObjects(sink, settings.options.signal, settings.budget.limits.maxOutputBytes, settings.options.compression !== false);
9304
9693
  this.root = this.objects.reserve();
9305
9694
  this.parent = this.objects.reserve();
9306
9695
  this.resources = this.objects.reserve();
@@ -9406,7 +9795,7 @@ const _exports = Object.freeze({ writePdf: writePdf, writePdfTo: writePdfTo });
9406
9795
  return _exports;
9407
9796
  })();
9408
9797
 
9409
- const _m84 = (() => {
9798
+ const _m85 = (() => {
9410
9799
  const { NotSupportedError, OfficeIMOError } = _m2;
9411
9800
 
9412
9801
  const { checkAbort, pause, taskYieldDue, withAbort } = _m4;
@@ -9673,12 +10062,12 @@ const _exports = Object.freeze({ pngPixels: pngPixels });
9673
10062
  return _exports;
9674
10063
  })();
9675
10064
 
9676
- const _m83 = (() => {
10065
+ const _m84 = (() => {
9677
10066
  const { NotSupportedError, OfficeIMOError } = _m2;
9678
10067
 
9679
10068
  const { checkAbort, pause, taskYieldDue } = _m4;
9680
10069
 
9681
- const { pngPixels } = _m84;
10070
+ const { pngPixels } = _m85;
9682
10071
 
9683
10072
  /** Shared document image resources; source objects are captured on first consumption. */
9684
10073
  class PdfDocumentImages {
@@ -9806,7 +10195,7 @@ const _exports = Object.freeze({ PdfDocumentImages: PdfDocumentImages });
9806
10195
  return _exports;
9807
10196
  })();
9808
10197
 
9809
- const _m85 = (() => {
10198
+ const _m86 = (() => {
9810
10199
  const { OfficeIMOError } = _m2;
9811
10200
 
9812
10201
  const { checkAbort, pause, taskYieldDue } = _m4;
@@ -9892,7 +10281,7 @@ const _exports = Object.freeze({ vectorCommands: vectorCommands });
9892
10281
  return _exports;
9893
10282
  })();
9894
10283
 
9895
- const _m86 = (() => {
10284
+ const _m87 = (() => {
9896
10285
  const { NotSupportedError, OfficeIMOError } = _m2;
9897
10286
 
9898
10287
  const { checkAbort, pause, taskYieldDue } = _m4;
@@ -10138,21 +10527,23 @@ const _exports = Object.freeze({ checkDrawingBlock: checkDrawingBlock, prepareDr
10138
10527
  return _exports;
10139
10528
  })();
10140
10529
 
10141
- const _m87 = (() => {
10530
+ const _m88 = (() => {
10142
10531
  const { OfficeIMOError } = _m2;
10143
10532
 
10144
- const { capturePdfText, wrapPdfText } = _m69;
10533
+ const { capturePdfText, wrapPdfText } = _m70;
10145
10534
 
10146
10535
  const { positive } = _m55;
10147
10536
 
10148
10537
  const { resolveParagraphStyle } = _m56;
10149
10538
 
10150
- const { captureBookmark } = _m76;
10539
+ const { captureBookmark } = _m77;
10151
10540
 
10152
10541
  const { captureFields } = _m10;
10153
10542
 
10543
+ const { pdfBudgetText } = _m69;
10544
+
10154
10545
  /** @internal Copy public paragraph input before any cooperative layout or source enumeration. */
10155
- function captureParagraph(block, settings, fonts) {
10546
+ function captureParagraph(block, settings, fonts, budgetOnPaint = false) {
10156
10547
  if (!block || block.kind !== "paragraph")
10157
10548
  throw new TypeError("PDF paragraph groups accept paragraph blocks only.");
10158
10549
  const { text, headingLevel, presentation: inputStyle, fontSize, keepTogether, keepWithNext, spaceBefore, spaceAfter, style: styleName, bookmark: inputBookmark } = block;
@@ -10165,7 +10556,8 @@ function captureParagraph(block, settings, fonts) {
10165
10556
  }, settings.paragraphStyles);
10166
10557
  const style = resolved.presentation ?? Object.freeze({}), size = positive(resolved.fontSize ?? settings.fontSize, "Paragraph font size", 144);
10167
10558
  const bookmark = captureBookmark(inputBookmark, settings);
10168
- return Object.freeze({ text: capturePdfText(text, style, settings, fonts, false), style, size,
10559
+ return Object.freeze({ text: capturePdfText(text, style, settings, fonts, false, !budgetOnPaint), style, size,
10560
+ ...(budgetOnPaint ? { budgetOnPaint: true } : {}),
10169
10561
  ...(headingLevel === undefined ? {} : { headingLevel }), ...(bookmark === undefined ? {} : { bookmark }),
10170
10562
  keepTogether: resolved.keepTogether ?? false, keepWithNext: resolved.keepWithNext ?? false,
10171
10563
  spaceBefore: resolved.spaceBefore ?? 0, spaceAfter: resolved.spaceAfter ?? 8 });
@@ -10176,13 +10568,16 @@ function captureCaption(caption, settings, fonts) {
10176
10568
  Object.keys(caption).some(key => !["text", "style", "fontSize", "presentation", "spaceBefore", "spaceAfter"].includes(key)))
10177
10569
  throw new TypeError("PDF captions support text, style, fontSize, presentation, spaceBefore and spaceAfter.");
10178
10570
  return captureParagraph({ ...captureFields(caption, ["text", "style", "fontSize", "presentation", "spaceBefore", "spaceAfter"]),
10179
- kind: "paragraph", keepTogether: true, keepWithNext: true }, settings, fonts);
10571
+ kind: "paragraph", keepTogether: true, keepWithNext: true }, settings, fonts, true);
10180
10572
  }
10181
10573
  /** @internal Layout is bounded by the same per-cell text and wrapped-line limits as table cells. */
10182
10574
  async function prepareParagraph(captured, settings, fonts, width = settings.page.width - settings.margins.left - settings.margins.right) {
10183
10575
  if (!captured.text.text)
10184
10576
  return { ...captured, lines: [], height: 0, firstHeight: 0 };
10185
- settings.budget.cell(captured.text.text, captured.text.text.length);
10577
+ if (!captured.budgetOnPaint) {
10578
+ const budgetText = pdfBudgetText(captured.text.text, settings.budget);
10579
+ settings.budget.cell(budgetText, budgetText.length);
10580
+ }
10186
10581
  const lines = await wrapPdfText(captured.text, fonts, captured.size, positive(width, "Paragraph width"), settings);
10187
10582
  return { ...captured, lines, height: captured.spaceBefore + lines.reduce((height, line) => height + line.lineHeight, 0) + captured.spaceAfter,
10188
10583
  firstHeight: captured.spaceBefore + lines[0].lineHeight };
@@ -10215,10 +10610,10 @@ const _exports = Object.freeze({ captureParagraph: captureParagraph, captureCapt
10215
10610
  return _exports;
10216
10611
  })();
10217
10612
 
10218
- const _m88 = (() => {
10219
- const { capturePdfText, wrapPdfText } = _m69;
10613
+ const _m89 = (() => {
10614
+ const { capturePdfText, wrapPdfText } = _m70;
10220
10615
 
10221
- const { captureParagraph, prepareParagraph } = _m87;
10616
+ const { captureParagraph, prepareParagraph } = _m88;
10222
10617
 
10223
10618
  const { resolveParagraphStyle } = _m56;
10224
10619
 
@@ -10272,7 +10667,7 @@ const _exports = Object.freeze({ captureListOptions: captureListOptions, prepare
10272
10667
  return _exports;
10273
10668
  })();
10274
10669
 
10275
- const _m90 = (() => {
10670
+ const _m91 = (() => {
10276
10671
  const { assertGroupedReportSource } = _m8;
10277
10672
 
10278
10673
  const { captureFields } = _m10;
@@ -10321,22 +10716,22 @@ const _exports = Object.freeze({ groupedPdfLabelFields: groupedPdfLabelFields, g
10321
10716
  return _exports;
10322
10717
  })();
10323
10718
 
10324
- const _m89 = (() => {
10719
+ const _m90 = (() => {
10325
10720
  const { assertGroupedReportSource, groupedReportOperation } = _m8;
10326
10721
 
10327
10722
  const { consumeRows } = _m4;
10328
10723
 
10329
10724
  const { ExportCell } = _m5;
10330
10725
 
10331
- const { captureGroupedPdfTableOptions } = _m90;
10726
+ const { captureGroupedPdfTableOptions } = _m91;
10332
10727
 
10333
10728
  const { settings } = _m55;
10334
10729
 
10335
- const { PdfTableLayout } = _m67;
10730
+ const { PdfTableLayout } = _m68;
10336
10731
 
10337
- const { captureCaption, captureParagraph, prepareParagraph } = _m87;
10732
+ const { captureCaption, captureParagraph, prepareParagraph } = _m88;
10338
10733
 
10339
- const { synchronousText } = _m68;
10734
+ const { synchronousText } = _m69;
10340
10735
 
10341
10736
  /** @internal Render one analytical source in the existing document session. Retain one detail row and
10342
10737
  * at most four closing subtotals. All captions, rows, pages, bytes and fonts use the document owners. */
@@ -10365,10 +10760,44 @@ async function renderGroupedPdfTable(block, context) {
10365
10760
  const continuationLabels = new WeakMap();
10366
10761
  let pending;
10367
10762
  const closing = [];
10368
- const summaryValues = (label, values) => Object.freeze([
10763
+ const aggregatePositions = report.columns.flatMap((column, index) => Object.hasOwn(report.totals, column.key) ? [index] : []);
10764
+ const summaryValues = (label, values, positions) => Object.freeze([
10369
10765
  new ExportCell(label, { text: label, presentation: table.options.footerPresentation }),
10370
- ...values.map(value => new ExportCell(value, { presentation: table.options.footerPresentation }))
10766
+ ...(positions ? positions.map(index => values[index]) : values).map(value => new ExportCell(value, { presentation: table.options.footerPresentation }))
10371
10767
  ]);
10768
+ // Independent summaries have no detail values in non-aggregate columns. Project their
10769
+ // declared operations, including zero/null results, rather than emitting label-only bands.
10770
+ // Keep callback positions in the original source model after this physical projection.
10771
+ const summaryLayouts = new Map();
10772
+ const summaryLayout = (grand) => {
10773
+ const existing = summaryLayouts.get(grand);
10774
+ if (existing)
10775
+ return existing;
10776
+ const positions = [0, ...aggregatePositions.map(index => index + 1)];
10777
+ const projected = positions.map(position => {
10778
+ const column = columns[position];
10779
+ if (!grand)
10780
+ return column;
10781
+ const { groups: _groups, ...leaf } = column;
10782
+ return leaf;
10783
+ });
10784
+ const originalPosition = (position) => {
10785
+ const columnIndex = positions[position.columnIndex];
10786
+ return { ...position, columnIndex, column: columns[columnIndex] };
10787
+ };
10788
+ const repeatColumns = positions.flatMap((position, index) => position === 0 || table.repeatedColumns.includes(position) ? [index] : []);
10789
+ const wideTable = table.options.wideTable;
10790
+ const projectedSettings = { ...sharedTable,
10791
+ repeatedColumns: Object.freeze(repeatColumns), options: { ...table.options, columns: projected,
10792
+ ...(table.options.columnWidths === undefined ? {} : { columnWidths: positions.map(position => table.options.columnWidths[position]) }),
10793
+ ...(typeof wideTable !== "object" ? {} : { wideTable: { ...wideTable, repeatColumns } }),
10794
+ ...(table.options.formatValue === undefined ? {} : { formatValue: (value, position) => table.options.formatValue(value, originalPosition(position)) }),
10795
+ ...(table.options.formatRuns === undefined ? {} : { formatRuns: (value, position) => table.options.formatRuns(value, originalPosition(position)) })
10796
+ } };
10797
+ const projectedLayout = new PdfTableLayout(projectedSettings, fonts);
10798
+ summaryLayouts.set(grand, projectedLayout);
10799
+ return projectedLayout;
10800
+ };
10372
10801
  const prepareGroupContext = async () => {
10373
10802
  const caption = await prepareParagraph(captureCaption({ text: path.map(group => group.label).join("\n"),
10374
10803
  presentation: { bold: true }, spaceAfter: 4 }, pages.settings, fonts), pages.settings, fonts);
@@ -10431,26 +10860,46 @@ async function renderGroupedPdfTable(block, context) {
10431
10860
  ...(group.label.trim() ? { bookmark: { title: group.label, level: (groupHeadingLevel + group.level) } } : {})
10432
10861
  }, pages.settings, fonts), pages.settings, fonts));
10433
10862
  const groupHeight = groupHeadings.reduce((height, heading) => height + heading.height, 0);
10434
- await context.flushParagraphs((caption?.height ?? 0) + groupHeight + headingHeight + minimum);
10435
- let followingHeight = groupHeight + caption.height + headingHeight + minimum;
10863
+ // Newly opened semantic headings already paint the end of this path. Only the open
10864
+ // ancestor prefix needs an artifact here; later physical bands still paint the full path.
10865
+ const ancestorCaption = semantic && semanticDepth > 0 ? await prepareParagraph(captureCaption({
10866
+ text: path.slice(0, semanticDepth).map(group => group.label).join("\n"), presentation: { bold: true }, spaceAfter: 4
10867
+ }, pages.settings, fonts), pages.settings, fonts) : undefined;
10868
+ const openingHeight = semantic ? (ancestorCaption?.height ?? 0) + groupHeight : caption.height;
10869
+ await context.flushParagraphs(openingHeight + headingHeight + minimum);
10870
+ if (ancestorCaption)
10871
+ await pages.paragraphs([ancestorCaption], groupHeight + headingHeight + minimum, true, { artifact: true });
10872
+ let followingHeight = groupHeight + (semantic ? 0 : caption.height) + headingHeight + minimum;
10436
10873
  for (const heading of groupHeadings) {
10437
10874
  followingHeight -= heading.height;
10438
10875
  await pages.beginGroup(semanticDepth++, heading, followingHeight);
10439
10876
  }
10440
- await pages.beginTable(layout, headings, minimum, caption, continuation, false, semantic);
10877
+ await pages.beginTable(layout, headings, minimum, caption, continuation, false, semantic, semantic);
10441
10878
  started = true;
10442
10879
  firstFragment = (caption?.lines.length ?? 0) > 0 || groupHeadings.some(heading => heading.lines.length > 0);
10443
10880
  };
10444
- const semanticSubtotal = async (row, level) => {
10881
+ const semanticSubtotal = async (row, level, values) => {
10882
+ if (level === report.groupBy.length - 1) {
10883
+ // A leaf's own subtotal shares its detail table and header identities. Keep the last
10884
+ // detail/summary bundle when it fits; the existing flow owns continuation and limits.
10885
+ pages.summary(row);
10886
+ closing.push(row);
10887
+ await finishLeaf();
10888
+ await pages.endGroup(level);
10889
+ semanticDepth = level;
10890
+ path = path.slice(0, level);
10891
+ return;
10892
+ }
10445
10893
  await finishLeaf();
10446
10894
  const { caption, continuation } = await prepareGroupContext();
10447
- const minimum = layout.minimumRowHeight(row);
10448
- await context.flushParagraphs(caption.height + headingHeight + minimum);
10895
+ const projected = summaryLayout(false), summaryHeadings = await projected.headers();
10896
+ const summaryRow = await projected.data(values, 0, true), minimum = projected.minimumRowHeight(summaryRow);
10897
+ await context.flushParagraphs(caption.height + await projected.blockHeight(summaryHeadings) + minimum);
10449
10898
  // An ancestor subtotal belongs to that ancestor's section, never the final child's table.
10450
10899
  // Its own visible column headings keep the separate logical summary table truthful.
10451
- await pages.beginTable(layout, headings, minimum, caption, continuation, false, true);
10452
- pages.summary(row);
10453
- await pages.row(row, caption.lines.length > 0 || headings.length > 0);
10900
+ await pages.beginTable(projected, summaryHeadings, minimum, caption, continuation, false, true);
10901
+ pages.summary(summaryRow);
10902
+ await pages.row(summaryRow, caption.lines.length > 0 || summaryHeadings.length > 0);
10454
10903
  await pages.endTable();
10455
10904
  await pages.endGroup(level);
10456
10905
  semanticDepth = level;
@@ -10460,25 +10909,19 @@ async function renderGroupedPdfTable(block, context) {
10460
10909
  await finishLeaf();
10461
10910
  if (!includeGrandTotal && summary.rows !== 0)
10462
10911
  return;
10463
- const completeColumns = summary.rows === 0 ? columns : columns.map(column => {
10464
- const { groups: _groups, ...leaf } = column;
10465
- return leaf;
10466
- });
10467
- const completeTable = settings({ ...table.options, columns: completeColumns,
10468
- includeHeader: input.includeHeader ?? true });
10469
- const completeLayout = summary.rows === 0 ? layout : new PdfTableLayout({ ...completeTable, budget: prepared.budget }, fonts);
10912
+ const completeLayout = summary.rows === 0 ? layout : summaryLayout(true);
10470
10913
  const completeHeadings = summary.rows === 0 ? headings : await completeLayout.headers();
10471
10914
  rowIndex = -1;
10472
10915
  let total;
10473
10916
  if (includeGrandTotal) {
10474
10917
  context.acceptRow(false);
10475
- total = await completeLayout.data(summaryValues(synchronousText(grandTotalLabel(summary), "grandTotalLabel"), summary.totals), 0, true);
10918
+ total = await completeLayout.data(summaryValues(synchronousText(grandTotalLabel(summary), "grandTotalLabel"), summary.totals, summary.rows === 0 ? undefined : aggregatePositions), 0, true);
10476
10919
  }
10477
10920
  if (!completeHeadings.length && !total)
10478
10921
  return;
10479
10922
  const minimum = total ? completeLayout.minimumRowHeight(total) : 0;
10480
10923
  await context.flushParagraphs(await completeLayout.blockHeight(completeHeadings) + minimum);
10481
- await pages.beginTable(completeLayout, completeHeadings, minimum, undefined, undefined, !semantic && summary.rows !== 0);
10924
+ await pages.beginTable(completeLayout, completeHeadings, minimum);
10482
10925
  if (total) {
10483
10926
  if (semantic)
10484
10927
  pages.summary(total);
@@ -10506,9 +10949,11 @@ async function renderGroupedPdfTable(block, context) {
10506
10949
  case "groupEnd": {
10507
10950
  rowIndex = -1;
10508
10951
  context.acceptRow(false);
10509
- const row = await layout.data(summaryValues(synchronousText(subtotalLabel(event), "subtotalLabel"), event.totals), 0, true);
10952
+ const separate = semantic && event.level !== report.groupBy.length - 1;
10953
+ const values = summaryValues(synchronousText(subtotalLabel(event), "subtotalLabel"), event.totals, separate ? aggregatePositions : undefined);
10954
+ const row = separate ? undefined : await layout.data(values, 0, true);
10510
10955
  if (semantic)
10511
- await semanticSubtotal(row, event.level);
10956
+ await semanticSubtotal(row, event.level, values);
10512
10957
  else
10513
10958
  closing.push(row);
10514
10959
  break;
@@ -10528,7 +10973,7 @@ const _exports = Object.freeze({ renderGroupedPdfTable: renderGroupedPdfTable })
10528
10973
  return _exports;
10529
10974
  })();
10530
10975
 
10531
- const _m82 = (() => {
10976
+ const _m83 = (() => {
10532
10977
  const { BlobByteSink, withDestination } = _m3;
10533
10978
 
10534
10979
  const { OfficeIMOError } = _m2;
@@ -10545,25 +10990,25 @@ const { settings, captureWideTable } = _m55;
10545
10990
 
10546
10991
  const { pdfNumber: n } = _m59;
10547
10992
 
10548
- const { PdfTableLayout } = _m67;
10993
+ const { PdfTableLayout } = _m68;
10549
10994
 
10550
10995
  const { PdfWriteSession } = _m58;
10551
10996
 
10552
- const { PdfDocumentImages } = _m83;
10997
+ const { PdfDocumentImages } = _m84;
10553
10998
 
10554
- const { vectorCommands } = _m85;
10999
+ const { vectorCommands } = _m86;
10555
11000
 
10556
- const { graphicAlternative } = _m78;
11001
+ const { graphicAlternative } = _m79;
10557
11002
 
10558
- const { checkDrawingBlock, prepareDrawing } = _m86;
11003
+ const { checkDrawingBlock, prepareDrawing } = _m87;
10559
11004
 
10560
- const { captureParagraph, captureCaption, prepareParagraph, checkParagraphBuffer, paragraphStartHeight } = _m87;
11005
+ const { captureParagraph, captureCaption, prepareParagraph, checkParagraphBuffer, paragraphStartHeight } = _m88;
10561
11006
 
10562
- const { captureListOptions, prepareListItem } = _m88;
11007
+ const { captureListOptions, prepareListItem } = _m89;
10563
11008
 
10564
- const { captureSection } = _m76;
11009
+ const { captureSection } = _m77;
10565
11010
 
10566
- const { renderGroupedPdfTable } = _m89;
11011
+ const { renderGroupedPdfTable } = _m90;
10567
11012
 
10568
11013
  const tableOptionFields = ["columns", "includeHeader", "headerRows", "footer", "headerPresentation", "footerPresentation", "alternateRowColor", "columnWidths", "wideTable", "formatValue", "formatRuns"];
10569
11014
  /** Capture typed columns for a single-use table source in a composed document. */
@@ -10821,18 +11266,18 @@ const _exports = Object.freeze({ pdfTable: pdfTable, writePdfDocument: writePdfD
10821
11266
  return _exports;
10822
11267
  })();
10823
11268
 
10824
- const _m81 = (() => {
11269
+ const _m82 = (() => {
10825
11270
  const { assertGroupedReportSource } = _m8;
10826
11271
 
10827
11272
  const { BlobByteSink } = _m3;
10828
11273
 
10829
- const { writePdfDocumentTo } = _m82;
11274
+ const { writePdfDocumentTo } = _m83;
10830
11275
 
10831
11276
  const { pdfOptionFields } = _m55;
10832
11277
 
10833
11278
  const { captureFields } = _m10;
10834
11279
 
10835
- const { pdfGroupedTable, groupedPdfLabelFields, groupedPdfTableFields } = _m90;
11280
+ const { pdfGroupedTable, groupedPdfLabelFields, groupedPdfTableFields } = _m91;
10836
11281
 
10837
11282
 
10838
11283
 
@@ -10866,14 +11311,14 @@ async function writeGroupedPdfTo(report, destination, configuration) {
10866
11311
  delete documentOptions.footer;
10867
11312
  return writePdfDocumentTo([pdfGroupedTable(report, tableOptions)], destination, documentOptions);
10868
11313
  }
10869
- const _exports = Object.freeze({ pdfGroupedTable: _m90.pdfGroupedTable, writeGroupedPdf: writeGroupedPdf, writeGroupedPdfTo: writeGroupedPdfTo });
11314
+ const _exports = Object.freeze({ pdfGroupedTable: _m91.pdfGroupedTable, writeGroupedPdf: writeGroupedPdf, writeGroupedPdfTo: writeGroupedPdfTo });
10870
11315
  return _exports;
10871
11316
  })();
10872
11317
 
10873
- const _m91 = (() => {
10874
- const { fontProgram } = _m61;
11318
+ const _m92 = (() => {
11319
+ const { fontProgram } = _m62;
10875
11320
 
10876
- const { resolveScalar, selectFont, validateFonts } = _m65;
11321
+ const { resolveScalar, selectFont, validateFonts } = _m66;
10877
11322
 
10878
11323
  /**
10879
11324
  * Check one text run against the writer's selected font and scalar-layout rules.
@@ -10911,11 +11356,11 @@ return _exports;
10911
11356
 
10912
11357
  const _m53 = (() => {
10913
11358
 
10914
- const _exports = Object.freeze({ writePdf: _m54.writePdf, writePdfTo: _m54.writePdfTo, writeGroupedPdf: _m81.writeGroupedPdf, writeGroupedPdfTo: _m81.writeGroupedPdfTo, pdfGroupedTable: _m81.pdfGroupedTable, createGroupedReport: _m8.createGroupedReport, writePdfDocument: _m82.writePdfDocument, writePdfDocumentTo: _m82.writePdfDocumentTo, pdfTable: _m82.pdfTable, PdfFont: _m61.PdfFont, preflightPdfText: _m91.preflightPdfText, ExportCell: _m5.ExportCell, saveBlob: _m1.saveBlob });
11359
+ const _exports = Object.freeze({ writePdf: _m54.writePdf, writePdfTo: _m54.writePdfTo, writeGroupedPdf: _m82.writeGroupedPdf, writeGroupedPdfTo: _m82.writeGroupedPdfTo, pdfGroupedTable: _m82.pdfGroupedTable, createGroupedReport: _m8.createGroupedReport, writePdfDocument: _m83.writePdfDocument, writePdfDocumentTo: _m83.writePdfDocumentTo, pdfTable: _m83.pdfTable, PdfFont: _m62.PdfFont, preflightPdfText: _m92.preflightPdfText, ExportCell: _m5.ExportCell, saveBlob: _m1.saveBlob });
10915
11360
  return _exports;
10916
11361
  })();
10917
11362
 
10918
- const _m92 = (() => {
11363
+ const _m93 = (() => {
10919
11364
  /** @internal Runtime-checked calls across the optional third-party API boundary. */
10920
11365
  function call(owner, name, ...args) {
10921
11366
  const fn = member(owner, name);
@@ -10947,12 +11392,12 @@ const _exports = Object.freeze({ call: call, member: member, array: array, index
10947
11392
  return _exports;
10948
11393
  })();
10949
11394
 
10950
- const _m93 = (() => {
11395
+ const _m94 = (() => {
10951
11396
  const { ExportCell, assertExportValue } = _m5;
10952
11397
 
10953
11398
  const { tableSpans } = _m17;
10954
11399
 
10955
- const { member } = _m92;
11400
+ const { member } = _m93;
10956
11401
 
10957
11402
  /** @internal */
10958
11403
  function value(input) {
@@ -11020,18 +11465,18 @@ const _exports = Object.freeze({ value: value, text: text, headings: headings })
11020
11465
  return _exports;
11021
11466
  })();
11022
11467
 
11023
- const _m94 = (() => {
11468
+ const _m95 = (() => {
11024
11469
  const { checkAbort, pause, rowsFromBatches, taskYieldDue } = _m4;
11025
11470
 
11026
11471
  const { ExportBudget } = _m9;
11027
11472
 
11028
11473
  const { captureFields } = _m10;
11029
11474
 
11030
- const { columnOptionFields } = _m11;
11475
+ const { columnOptionFields, copyColumns } = _m11;
11031
11476
 
11032
- const { array, call, indexes, member } = _m92;
11477
+ const { array, call, indexes, member } = _m93;
11033
11478
 
11034
- const { headings, text, value } = _m93;
11479
+ const { headings, text, value } = _m94;
11035
11480
 
11036
11481
  function safeOptions(options) {
11037
11482
  options = captureFields(options, ["rows", "columns", "modifier", "orthogonal", "stripHtml", "stripNewlines", "decodeEntities", "escapeExcelFormula", "trim", "format", "customizeData"]);
@@ -11106,10 +11551,10 @@ function captureDataTablesExport(host, table, options = {}, omitted) {
11106
11551
  for (const index of columnIndexes)
11107
11552
  if (member(options.columnOptions?.[index], "value") !== undefined)
11108
11553
  throw new TypeError("DataTables columnOptions describes columns; resolve values with project.");
11109
- const columns = Object.freeze(leaf.map((label, index) => Object.freeze({
11554
+ const columns = Object.freeze(copyColumns(leaf.map((label, index) => ({
11110
11555
  header: text(label), key: "dt:" + columnIndexes[index], ...options.columnOptions?.[columnIndexes[index]],
11111
11556
  ...(heading.groups[index].length ? { groups: Object.freeze(heading.groups[index]) } : {})
11112
- })));
11557
+ }))).map(column => Object.freeze(column)));
11113
11558
  // Explicit heading overrides also apply to CSV's leaf heading.
11114
11559
  if (!heading.structure)
11115
11560
  heading.rows[heading.rows.length - 1] = columns.map(column => column.header);
@@ -11237,7 +11682,7 @@ const _exports = Object.freeze({ createDataTablesExport: createDataTablesExport,
11237
11682
  return _exports;
11238
11683
  })();
11239
11684
 
11240
- const _m95 = (() => {
11685
+ const _m96 = (() => {
11241
11686
  const { captureFields } = _m10;
11242
11687
 
11243
11688
  const { ExportBudget } = _m9;
@@ -11294,15 +11739,15 @@ const { writePdfTo } = _m53;
11294
11739
 
11295
11740
  const { portableSheet, portableWorkbook } = _m50;
11296
11741
 
11297
- const { call, member } = _m92;
11742
+ const { call, member } = _m93;
11298
11743
 
11299
- const { value } = _m93;
11744
+ const { value } = _m94;
11300
11745
 
11301
- const { captureDataTablesExport } = _m94;
11746
+ const { captureDataTablesExport } = _m95;
11302
11747
 
11303
11748
  const { captureFields } = _m10;
11304
11749
 
11305
- const { captureCommonLimits, captureXlsxOptions, captureCsvOptions, capturePdfOptions, mergeAdapterLimits } = _m95;
11750
+ const { captureCommonLimits, captureXlsxOptions, captureCsvOptions, capturePdfOptions, mergeAdapterLimits } = _m96;
11306
11751
 
11307
11752
 
11308
11753
 
@@ -11463,7 +11908,7 @@ function registerDataTablesButtons(host, options = {}) {
11463
11908
  };
11464
11909
  }
11465
11910
  }
11466
- const _exports = Object.freeze({ createDataTablesExport: _m94.createDataTablesExport, ExportCell: _m5.ExportCell, PdfFont: _m61.PdfFont, writeDataTableTo: writeDataTableTo, exportDataTable: exportDataTable, registerDataTablesButtons: registerDataTablesButtons });
11911
+ const _exports = Object.freeze({ createDataTablesExport: _m95.createDataTablesExport, ExportCell: _m5.ExportCell, PdfFont: _m62.PdfFont, writeDataTableTo: writeDataTableTo, exportDataTable: exportDataTable, registerDataTablesButtons: registerDataTablesButtons });
11467
11912
  return _exports;
11468
11913
  })();
11469
11914
  const { createDataTablesExport, ExportCell, PdfFont, writeDataTableTo, exportDataTable, registerDataTablesButtons } = _m0;