@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
@@ -24,6 +24,8 @@ export interface ColumnSettings {
24
24
  readonly format?: string;
25
25
  readonly wrapText?: boolean;
26
26
  readonly alignment?: Alignment;
27
+ /** Explicitly identifies each detail record in tagged PDF tables. Other formats retain their existing cells and presentation. */
28
+ readonly rowHeader?: boolean;
27
29
  /** Contiguous shared prefixes form merged heading rows above the leaf headers. */
28
30
  readonly groups?: readonly string[];
29
31
  }
@@ -1,6 +1,6 @@
1
1
  export function checkAbort(signal) {
2
2
  if (signal?.aborted)
3
- throw signal.reason ?? new DOMException("Export cancelled.", "AbortError");
3
+ throw signal.reason;
4
4
  }
5
5
  /** Race a pending producer or sink operation without leaving abort listeners behind. */
6
6
  export function withAbort(promise, signal) {
@@ -8,7 +8,7 @@ export function withAbort(promise, signal) {
8
8
  return Promise.resolve(promise);
9
9
  return new Promise((resolve, reject) => {
10
10
  const cleanup = () => signal.removeEventListener("abort", abort);
11
- const abort = () => { cleanup(); reject(signal.reason ?? new DOMException("Export cancelled.", "AbortError")); };
11
+ const abort = () => { cleanup(); reject(signal.reason); };
12
12
  signal.addEventListener("abort", abort, { once: true });
13
13
  Promise.resolve(promise).then(value => { cleanup(); resolve(value); }, error => { cleanup(); reject(error); });
14
14
  if (signal.aborted)
@@ -5,8 +5,9 @@ export async function withDestination(destination, operation) {
5
5
  // Native streams can belong to another browser realm; constructor identity is not portable.
6
6
  if (destination && typeof destination.getWriter === "function") {
7
7
  const writer = destination.getWriter();
8
+ // Native streams may retain accepted chunks after write resolves.
8
9
  try {
9
- return await operation({ write: bytes => writer.write(bytes) });
10
+ return await operation({ write: bytes => writer.write(new Uint8Array(bytes)) });
10
11
  }
11
12
  finally {
12
13
  writer.releaseLock();
@@ -1,7 +1,12 @@
1
1
  import { ExportCell, checkAbort, inputRows } from "../../core/index.js";
2
2
  import { datetime } from "./dates.js";
3
+ import { captureFields } from "../../internal/capture.js";
4
+ import { copyColumns } from "../../internal/rows.js";
5
+ import { copyCellPresentation } from "../../core/presentation.js";
6
+ const columnFields = ["width", "format", "wrapText", "alignment", "rowHeader", "groups"];
3
7
  /** Map an immutable CanopyX record capture to a writer without querying the grid or retaining its body. */
4
8
  export function createCanopyExport(capture, format, options = {}) {
9
+ options = captureFields(options, ["tones", "columnOptions", "unsupportedPresentation", "datetime", "xlsx", "signal", "onDiagnostic"]);
5
10
  if (format !== "xlsx" && format !== "csv" && format !== "pdf")
6
11
  throw new TypeError("Canopy export format must be xlsx, csv or pdf.");
7
12
  if (!capture || typeof capture.rows !== "function" || !capture.request)
@@ -44,7 +49,7 @@ export function createCanopyExport(capture, format, options = {}) {
44
49
  const tones = new Map(Object.entries(options.tones ?? {}).map(([name, style]) => {
45
50
  if (!style || typeof style !== "object" || Array.isArray(style))
46
51
  throw new TypeError("Tone mappings must be portable presentation objects.");
47
- return [name, Object.freeze({ ...style })];
52
+ return [name, copyCellPresentation(style)];
48
53
  }));
49
54
  const tone = (name, rowId, columnId) => {
50
55
  if (name === undefined)
@@ -68,15 +73,16 @@ export function createCanopyExport(capture, format, options = {}) {
68
73
  throw new TypeError("Invalid or duplicate Canopy export column.");
69
74
  ids.add(column.id);
70
75
  diagnostics(column.diagnostics, undefined, column.id);
71
- const override = Object.hasOwn(options.columnOptions ?? {}, column.id) ? options.columnOptions[column.id] : {};
72
- for (const key of Object.keys(override))
73
- if (!["width", "format", "wrapText", "alignment", "groups"].includes(key))
76
+ const selected = Object.hasOwn(options.columnOptions ?? {}, column.id) ? options.columnOptions[column.id] : {};
77
+ for (const key of Object.keys(selected))
78
+ if (!columnFields.includes(key))
74
79
  throw new TypeError("Unsupported Canopy column option: " + key);
75
- return Object.freeze({ id: column.id, kind: column.kind, column: Object.freeze({ ...override, key: column.id, header: column.title,
80
+ const override = captureFields(selected, columnFields);
81
+ const [captured] = copyColumns([{ ...override, key: column.id, header: column.title,
76
82
  ...(values === "raw" && column.kind === "number" ? { type: "number" } : {}),
77
83
  ...(override.wrapText === undefined && column.wrap === undefined ? {} : { wrapText: override.wrapText ?? column.wrap }),
78
- ...(override.alignment === undefined && column.alignment === undefined ? {} : { alignment: override.alignment ?? column.alignment }),
79
- ...(override.groups === undefined ? {} : { groups: Object.freeze([...override.groups]) }) }) });
84
+ ...(override.alignment === undefined && column.alignment === undefined ? {} : { alignment: override.alignment ?? column.alignment }) }]);
85
+ return Object.freeze({ id: column.id, kind: column.kind, column: Object.freeze(captured) });
80
86
  });
81
87
  const rowCount = request.recordCount;
82
88
  return Object.freeze({ columns: Object.freeze(specs.map(spec => spec.column)), rowCount, async *rows() {
@@ -1,7 +1,7 @@
1
1
  import { checkAbort, pause, rowsFromBatches, taskYieldDue } from "../../core/iteration.js";
2
2
  import { ExportBudget } from "../../core/limits.js";
3
3
  import { captureFields } from "../../internal/capture.js";
4
- import { columnOptionFields } from "../../internal/rows.js";
4
+ import { columnOptionFields, copyColumns } from "../../internal/rows.js";
5
5
  import { array, call, indexes, member } from "./api.js";
6
6
  import { headings, text, value } from "./headings.js";
7
7
  function safeOptions(options) {
@@ -77,10 +77,10 @@ export function captureDataTablesExport(host, table, options = {}, omitted) {
77
77
  for (const index of columnIndexes)
78
78
  if (member(options.columnOptions?.[index], "value") !== undefined)
79
79
  throw new TypeError("DataTables columnOptions describes columns; resolve values with project.");
80
- const columns = Object.freeze(leaf.map((label, index) => Object.freeze({
80
+ const columns = Object.freeze(copyColumns(leaf.map((label, index) => ({
81
81
  header: text(label), key: "dt:" + columnIndexes[index], ...options.columnOptions?.[columnIndexes[index]],
82
82
  ...(heading.groups[index].length ? { groups: Object.freeze(heading.groups[index]) } : {})
83
- })));
83
+ }))).map(column => Object.freeze(column)));
84
84
  // Explicit heading overrides also apply to CSV's leaf heading.
85
85
  if (!heading.structure)
86
86
  heading.rows[heading.rows.length - 1] = columns.map(column => column.header);
@@ -6,11 +6,18 @@ export function createRowProjector(columns, worksheet, signal, validate = assert
6
6
  const getters = columns.some(column => column.value);
7
7
  return (row, rowIndex = 0) => {
8
8
  if (Array.isArray(row) && !getters) {
9
- if (row.length > columns.length)
9
+ const length = row.length;
10
+ if (length > columns.length)
10
11
  throw new RangeError("Row has more values than declared columns.");
11
- for (const value of row)
12
+ // Resolve each positional value once, just like key/value projections. Returning the
13
+ // source array would let an accessor change a value after the portable-value check.
14
+ const values = new Array(length);
15
+ for (let index = 0; index < length; index++) {
16
+ const value = row[index];
12
17
  validate(value);
13
- return row;
18
+ values[index] = value;
19
+ }
20
+ return values;
14
21
  }
15
22
  if (!row || typeof row !== "object" || isDate(row))
16
23
  throw new TypeError("A row must be an array or object.");
@@ -39,7 +46,7 @@ export function createRowProjector(columns, worksheet, signal, validate = assert
39
46
  };
40
47
  }
41
48
  /** @internal Shared metadata fields for full columns and adapter-owned partial overrides. */
42
- export const columnOptionFields = ["header", "key", "value", "width", "type", "format", "wrapText", "alignment", "groups", "style", "valueFormatter"];
49
+ export const columnOptionFields = ["header", "key", "value", "width", "type", "format", "wrapText", "alignment", "rowHeader", "groups", "style", "valueFormatter"];
43
50
  export function copyColumns(columns, workbookStyles = false) {
44
51
  if (!Array.isArray(columns))
45
52
  throw new TypeError("Declare the columns in export order.");
@@ -55,6 +62,8 @@ export function copyColumns(columns, workbookStyles = false) {
55
62
  throw new TypeError("Each column needs a string header and an optional string key.");
56
63
  if (captured.value !== undefined && typeof captured.value !== "function")
57
64
  throw new TypeError("Column value getters must be functions.");
65
+ if (captured.rowHeader !== undefined && typeof captured.rowHeader !== "boolean")
66
+ throw new TypeError("Column rowHeader must be boolean.");
58
67
  if (captured.groups !== undefined) {
59
68
  if (!Array.isArray(captured.groups))
60
69
  throw new TypeError("Column groups must be an array of strings.");
@@ -33,10 +33,44 @@ export async function renderGroupedPdfTable(block, context) {
33
33
  const continuationLabels = new WeakMap();
34
34
  let pending;
35
35
  const closing = [];
36
- const summaryValues = (label, values) => Object.freeze([
36
+ const aggregatePositions = report.columns.flatMap((column, index) => Object.hasOwn(report.totals, column.key) ? [index] : []);
37
+ const summaryValues = (label, values, positions) => Object.freeze([
37
38
  new ExportCell(label, { text: label, presentation: table.options.footerPresentation }),
38
- ...values.map(value => new ExportCell(value, { presentation: table.options.footerPresentation }))
39
+ ...(positions ? positions.map(index => values[index]) : values).map(value => new ExportCell(value, { presentation: table.options.footerPresentation }))
39
40
  ]);
41
+ // Independent summaries have no detail values in non-aggregate columns. Project their
42
+ // declared operations, including zero/null results, rather than emitting label-only bands.
43
+ // Keep callback positions in the original source model after this physical projection.
44
+ const summaryLayouts = new Map();
45
+ const summaryLayout = (grand) => {
46
+ const existing = summaryLayouts.get(grand);
47
+ if (existing)
48
+ return existing;
49
+ const positions = [0, ...aggregatePositions.map(index => index + 1)];
50
+ const projected = positions.map(position => {
51
+ const column = columns[position];
52
+ if (!grand)
53
+ return column;
54
+ const { groups: _groups, ...leaf } = column;
55
+ return leaf;
56
+ });
57
+ const originalPosition = (position) => {
58
+ const columnIndex = positions[position.columnIndex];
59
+ return { ...position, columnIndex, column: columns[columnIndex] };
60
+ };
61
+ const repeatColumns = positions.flatMap((position, index) => position === 0 || table.repeatedColumns.includes(position) ? [index] : []);
62
+ const wideTable = table.options.wideTable;
63
+ const projectedSettings = { ...sharedTable,
64
+ repeatedColumns: Object.freeze(repeatColumns), options: { ...table.options, columns: projected,
65
+ ...(table.options.columnWidths === undefined ? {} : { columnWidths: positions.map(position => table.options.columnWidths[position]) }),
66
+ ...(typeof wideTable !== "object" ? {} : { wideTable: { ...wideTable, repeatColumns } }),
67
+ ...(table.options.formatValue === undefined ? {} : { formatValue: (value, position) => table.options.formatValue(value, originalPosition(position)) }),
68
+ ...(table.options.formatRuns === undefined ? {} : { formatRuns: (value, position) => table.options.formatRuns(value, originalPosition(position)) })
69
+ } };
70
+ const projectedLayout = new PdfTableLayout(projectedSettings, fonts);
71
+ summaryLayouts.set(grand, projectedLayout);
72
+ return projectedLayout;
73
+ };
40
74
  const prepareGroupContext = async () => {
41
75
  const caption = await prepareParagraph(captureCaption({ text: path.map(group => group.label).join("\n"),
42
76
  presentation: { bold: true }, spaceAfter: 4 }, pages.settings, fonts), pages.settings, fonts);
@@ -99,26 +133,46 @@ export async function renderGroupedPdfTable(block, context) {
99
133
  ...(group.label.trim() ? { bookmark: { title: group.label, level: (groupHeadingLevel + group.level) } } : {})
100
134
  }, pages.settings, fonts), pages.settings, fonts));
101
135
  const groupHeight = groupHeadings.reduce((height, heading) => height + heading.height, 0);
102
- await context.flushParagraphs((caption?.height ?? 0) + groupHeight + headingHeight + minimum);
103
- let followingHeight = groupHeight + caption.height + headingHeight + minimum;
136
+ // Newly opened semantic headings already paint the end of this path. Only the open
137
+ // ancestor prefix needs an artifact here; later physical bands still paint the full path.
138
+ const ancestorCaption = semantic && semanticDepth > 0 ? await prepareParagraph(captureCaption({
139
+ text: path.slice(0, semanticDepth).map(group => group.label).join("\n"), presentation: { bold: true }, spaceAfter: 4
140
+ }, pages.settings, fonts), pages.settings, fonts) : undefined;
141
+ const openingHeight = semantic ? (ancestorCaption?.height ?? 0) + groupHeight : caption.height;
142
+ await context.flushParagraphs(openingHeight + headingHeight + minimum);
143
+ if (ancestorCaption)
144
+ await pages.paragraphs([ancestorCaption], groupHeight + headingHeight + minimum, true, { artifact: true });
145
+ let followingHeight = groupHeight + (semantic ? 0 : caption.height) + headingHeight + minimum;
104
146
  for (const heading of groupHeadings) {
105
147
  followingHeight -= heading.height;
106
148
  await pages.beginGroup(semanticDepth++, heading, followingHeight);
107
149
  }
108
- await pages.beginTable(layout, headings, minimum, caption, continuation, false, semantic);
150
+ await pages.beginTable(layout, headings, minimum, caption, continuation, false, semantic, semantic);
109
151
  started = true;
110
152
  firstFragment = (caption?.lines.length ?? 0) > 0 || groupHeadings.some(heading => heading.lines.length > 0);
111
153
  };
112
- const semanticSubtotal = async (row, level) => {
154
+ const semanticSubtotal = async (row, level, values) => {
155
+ if (level === report.groupBy.length - 1) {
156
+ // A leaf's own subtotal shares its detail table and header identities. Keep the last
157
+ // detail/summary bundle when it fits; the existing flow owns continuation and limits.
158
+ pages.summary(row);
159
+ closing.push(row);
160
+ await finishLeaf();
161
+ await pages.endGroup(level);
162
+ semanticDepth = level;
163
+ path = path.slice(0, level);
164
+ return;
165
+ }
113
166
  await finishLeaf();
114
167
  const { caption, continuation } = await prepareGroupContext();
115
- const minimum = layout.minimumRowHeight(row);
116
- await context.flushParagraphs(caption.height + headingHeight + minimum);
168
+ const projected = summaryLayout(false), summaryHeadings = await projected.headers();
169
+ const summaryRow = await projected.data(values, 0, true), minimum = projected.minimumRowHeight(summaryRow);
170
+ await context.flushParagraphs(caption.height + await projected.blockHeight(summaryHeadings) + minimum);
117
171
  // An ancestor subtotal belongs to that ancestor's section, never the final child's table.
118
172
  // Its own visible column headings keep the separate logical summary table truthful.
119
- await pages.beginTable(layout, headings, minimum, caption, continuation, false, true);
120
- pages.summary(row);
121
- await pages.row(row, caption.lines.length > 0 || headings.length > 0);
173
+ await pages.beginTable(projected, summaryHeadings, minimum, caption, continuation, false, true);
174
+ pages.summary(summaryRow);
175
+ await pages.row(summaryRow, caption.lines.length > 0 || summaryHeadings.length > 0);
122
176
  await pages.endTable();
123
177
  await pages.endGroup(level);
124
178
  semanticDepth = level;
@@ -128,25 +182,19 @@ export async function renderGroupedPdfTable(block, context) {
128
182
  await finishLeaf();
129
183
  if (!includeGrandTotal && summary.rows !== 0)
130
184
  return;
131
- const completeColumns = summary.rows === 0 ? columns : columns.map(column => {
132
- const { groups: _groups, ...leaf } = column;
133
- return leaf;
134
- });
135
- const completeTable = settings({ ...table.options, columns: completeColumns,
136
- includeHeader: input.includeHeader ?? true });
137
- const completeLayout = summary.rows === 0 ? layout : new PdfTableLayout({ ...completeTable, budget: prepared.budget }, fonts);
185
+ const completeLayout = summary.rows === 0 ? layout : summaryLayout(true);
138
186
  const completeHeadings = summary.rows === 0 ? headings : await completeLayout.headers();
139
187
  rowIndex = -1;
140
188
  let total;
141
189
  if (includeGrandTotal) {
142
190
  context.acceptRow(false);
143
- total = await completeLayout.data(summaryValues(synchronousText(grandTotalLabel(summary), "grandTotalLabel"), summary.totals), 0, true);
191
+ total = await completeLayout.data(summaryValues(synchronousText(grandTotalLabel(summary), "grandTotalLabel"), summary.totals, summary.rows === 0 ? undefined : aggregatePositions), 0, true);
144
192
  }
145
193
  if (!completeHeadings.length && !total)
146
194
  return;
147
195
  const minimum = total ? completeLayout.minimumRowHeight(total) : 0;
148
196
  await context.flushParagraphs(await completeLayout.blockHeight(completeHeadings) + minimum);
149
- await pages.beginTable(completeLayout, completeHeadings, minimum, undefined, undefined, !semantic && summary.rows !== 0);
197
+ await pages.beginTable(completeLayout, completeHeadings, minimum);
150
198
  if (total) {
151
199
  if (semantic)
152
200
  pages.summary(total);
@@ -174,9 +222,11 @@ export async function renderGroupedPdfTable(block, context) {
174
222
  case "groupEnd": {
175
223
  rowIndex = -1;
176
224
  context.acceptRow(false);
177
- const row = await layout.data(summaryValues(synchronousText(subtotalLabel(event), "subtotalLabel"), event.totals), 0, true);
225
+ const separate = semantic && event.level !== report.groupBy.length - 1;
226
+ const values = summaryValues(synchronousText(subtotalLabel(event), "subtotalLabel"), event.totals, separate ? aggregatePositions : undefined);
227
+ const row = separate ? undefined : await layout.data(values, 0, true);
178
228
  if (semantic)
179
- await semanticSubtotal(row, event.level);
229
+ await semanticSubtotal(row, event.level, values);
180
230
  else
181
231
  closing.push(row);
182
232
  break;
@@ -3,6 +3,7 @@ import { fontProgram } from "./font.js";
3
3
  import { resolveScalar, selectFont, standardCode, validateFonts } from "./font-support.js";
4
4
  import { pdfNumber, unicodeHex } from "./objects.js";
5
5
  import { checkAbort, pause, taskYieldDue } from "../core/iteration.js";
6
+ const standardHexBytes = Object.freeze(Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0")));
6
7
  export class PdfFontResource {
7
8
  index;
8
9
  bold;
@@ -65,7 +66,7 @@ export class PdfFontResource {
65
66
  for (const char of text) {
66
67
  const cp = char.codePointAt(0);
67
68
  this.width(cp);
68
- hex += (this.program ? this.mappings.get(cp).cid : standardCode(cp)).toString(16).padStart(this.program ? 4 : 2, "0");
69
+ hex += this.program ? this.mappings.get(cp).cid.toString(16).padStart(4, "0") : standardHexBytes[standardCode(cp)];
69
70
  }
70
71
  return "<" + hex + ">";
71
72
  }
@@ -4,17 +4,25 @@ import { checkAbort, pause, taskYieldDue } from "../core/iteration.js";
4
4
  import { presentation, color } from "./settings.js";
5
5
  import { wrapShapedPdfText } from "./shaped-text.js";
6
6
  import { PdfFont } from "./font.js";
7
- /** @internal A run list is a PDF presentation value, never an alternate shared table value model. */
8
- export function capturePdfText(value, base, settings, fonts, countEmpty = true) {
9
- const input = typeof value === "string" ? [{ text: value }] : value;
7
+ import { pdfBudgetText } from "./text.js";
8
+ /** @internal Callers supply an owned, validated, frozen base presentation. A run list is a PDF presentation value, never an alternate shared table value model. */
9
+ export function capturePdfText(value, base, settings, fonts, countEmpty = true, reserveBudget = true) {
10
+ if (typeof value === "string") {
11
+ if (value.length > settings.limits.maxCellCharacters)
12
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxCellCharacters exceeded.");
13
+ if (reserveBudget && (value.length || countEmpty))
14
+ settings.budget.reserve(1, pdfBudgetText(value, settings.budget).length);
15
+ return Object.freeze({ text: value, runs: Object.freeze([Object.freeze({ text: value, style: base })]) });
16
+ }
17
+ const input = value;
10
18
  if (!Array.isArray(input)) {
11
19
  if (input && typeof input.then === "function")
12
20
  void Promise.resolve(input).catch(() => { });
13
21
  throw new TypeError("PDF text must be a string or a synchronous array of text runs.");
14
22
  }
15
- if (typeof value !== "string" && input.length > settings.limits.maxTextRuns)
23
+ if (input.length > settings.limits.maxTextRuns)
16
24
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxTextRuns exceeded.");
17
- let characters = 0;
25
+ let characters = 0, budgetCharacters = 0;
18
26
  const runs = [];
19
27
  for (const run of input) {
20
28
  if (!run || typeof run !== "object" || Object.keys(run).some(key => !["text", "bold", "italic", "color", "link", "font"].includes(key)))
@@ -30,14 +38,16 @@ export function capturePdfText(value, base, settings, fonts, countEmpty = true)
30
38
  characters += text.length;
31
39
  if (characters > settings.limits.maxCellCharacters)
32
40
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxCellCharacters exceeded.");
41
+ if (reserveBudget)
42
+ budgetCharacters += pdfBudgetText(text, settings.budget).length;
33
43
  const style = presentation({ ...base, ...(bold === undefined ? {} : { bold }), ...(italic === undefined ? {} : { italic }), ...(color === undefined ? {} : { color }) });
34
44
  if (settings.options.tagged && link !== undefined && text.length && !text.trim())
35
45
  throw new TypeError("Tagged PDF inline links require nonempty displayed text.");
36
46
  runs.push(Object.freeze({ text, style, ...(font === undefined ? {} : { font }), ...(link === undefined ? {} : { link: copyExportLink(link) }) }));
37
47
  }
38
48
  // Reserve before allocating a joined rich-text value or retaining it in a kept paragraph chain.
39
- if (characters || countEmpty)
40
- settings.budget.reserve(1, characters);
49
+ if (reserveBudget && (characters || countEmpty))
50
+ settings.budget.reserve(1, budgetCharacters);
41
51
  return Object.freeze({ text: runs.map(run => run.text).join(""), runs: Object.freeze(runs) });
42
52
  }
43
53
  /** @internal Greedy wrapping over the continuous text stream, preserving run emphasis and URI geometry. */
@@ -46,8 +56,39 @@ export async function wrapPdfText(captured, fonts, size, width, settings, wrap =
46
56
  return wrapShapedPdfText(captured, fonts, size, width, settings, wrap);
47
57
  const { signal } = settings.options, { text, runs } = captured;
48
58
  checkAbort(signal);
49
- const faces = runs.map(run => fonts.select(run.style.bold, run.style.italic, run.font));
50
- const fallback = fonts.select(), lines = [];
59
+ // Keep font-selection order while deferring a single-run face array until wrapping needs it.
60
+ const single = runs.length === 1 ? runs[0] : undefined;
61
+ const singleFace = single && fonts.select(single.style.bold, single.style.italic, single.font);
62
+ const selectedFaces = singleFace ? undefined : runs.map(run => fonts.select(run.style.bold, run.style.italic, run.font));
63
+ const fallback = fonts.select();
64
+ // Short fitting runs need no per-character layout arrays. Longer text keeps the existing
65
+ // cooperative checkpoints; controls or the first overflowing advance use the general path.
66
+ if (single && text.length > 0 && text.length < 4096) {
67
+ const run = single, font = singleFace;
68
+ let widthSoFar = 0, fits = true;
69
+ for (let offset = 0; offset < text.length;) {
70
+ const scalar = text.codePointAt(offset);
71
+ if (scalar === 9 || scalar === 10 || scalar === 13) {
72
+ fits = false;
73
+ break;
74
+ }
75
+ const advance = font.width(scalar) * size / 1000;
76
+ if (advance > width + .001 || widthSoFar + advance > width + .001) {
77
+ fits = false;
78
+ break;
79
+ }
80
+ widthSoFar += advance;
81
+ offset += scalar > 0xffff ? 2 : 1;
82
+ }
83
+ if (fits) {
84
+ if (settings.limits.maxRowLines < 1)
85
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxRowLines exceeded.");
86
+ return [{ text, width: widthSoFar, segments: [{ text, width: widthSoFar, font,
87
+ ...(run.style.color === undefined ? {} : { color: run.style.color }), ...(run.link ? { link: run.link } : {}) }],
88
+ lineHeight: font.lineHeight(size), ascent: Math.max(0, (font.program?.ascent ?? 800) * size / 1000) }];
89
+ }
90
+ }
91
+ const faces = selectedFaces ?? [singleFace], lines = [];
51
92
  let chars = [], advances = [], owners = [], measured = 0, breakAt = -1;
52
93
  let runIndex = 0, runEnd = runs[0]?.text.length ?? 0, scanned = 0;
53
94
  const emit = (count) => {