@evotecit/officeimo 0.1.21 → 0.1.43

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 (92) hide show
  1. package/README.md +39 -8
  2. package/bundles/officeimo-canopyx-adapter.js +56 -36
  3. package/bundles/officeimo-canopyx-adapter.min.js +1 -1
  4. package/bundles/officeimo-canopyx-adapter.min.mjs +1 -1
  5. package/bundles/officeimo-canopyx-adapter.mjs +42 -22
  6. package/bundles/officeimo-canopyx.js +420 -177
  7. package/bundles/officeimo-canopyx.min.js +1 -1
  8. package/bundles/officeimo-canopyx.min.mjs +1 -1
  9. package/bundles/officeimo-canopyx.mjs +346 -103
  10. package/bundles/officeimo-chartforgex-adapter.js +1924 -0
  11. package/bundles/officeimo-chartforgex-adapter.min.js +2 -0
  12. package/bundles/officeimo-chartforgex-adapter.min.mjs +2 -0
  13. package/bundles/officeimo-chartforgex-adapter.mjs +1910 -0
  14. package/bundles/officeimo-chartforgex.js +13594 -0
  15. package/bundles/officeimo-chartforgex.min.js +2 -0
  16. package/bundles/officeimo-chartforgex.min.mjs +2 -0
  17. package/bundles/officeimo-chartforgex.mjs +13487 -0
  18. package/bundles/officeimo-csv.js +12 -7
  19. package/bundles/officeimo-csv.min.js +1 -1
  20. package/bundles/officeimo-csv.min.mjs +1 -1
  21. package/bundles/officeimo-csv.mjs +8 -3
  22. package/bundles/officeimo-datatables-adapter.js +11 -11
  23. package/bundles/officeimo-datatables-adapter.min.js +1 -1
  24. package/bundles/officeimo-datatables-adapter.min.mjs +1 -1
  25. package/bundles/officeimo-datatables-adapter.mjs +7 -7
  26. package/bundles/officeimo-datatables.js +375 -152
  27. package/bundles/officeimo-datatables.min.js +1 -1
  28. package/bundles/officeimo-datatables.min.mjs +1 -1
  29. package/bundles/officeimo-datatables.mjs +311 -88
  30. package/bundles/officeimo-execution.js +14 -9
  31. package/bundles/officeimo-execution.min.js +1 -1
  32. package/bundles/officeimo-execution.min.mjs +1 -1
  33. package/bundles/officeimo-execution.mjs +8 -3
  34. package/bundles/officeimo-pdf.js +286 -120
  35. package/bundles/officeimo-pdf.min.js +1 -1
  36. package/bundles/officeimo-pdf.min.mjs +1 -1
  37. package/bundles/officeimo-pdf.mjs +244 -78
  38. package/bundles/officeimo-xlsx.js +93 -31
  39. package/bundles/officeimo-xlsx.min.js +1 -1
  40. package/bundles/officeimo-xlsx.min.mjs +1 -1
  41. package/bundles/officeimo-xlsx.mjs +75 -13
  42. package/bundles/officeimo.js +373 -150
  43. package/bundles/officeimo.min.js +1 -1
  44. package/bundles/officeimo.min.mjs +1 -1
  45. package/bundles/officeimo.mjs +312 -89
  46. package/dist/core/progress.js +7 -2
  47. package/dist/index.d.ts +1 -1
  48. package/dist/integrations/canopyx/index.js +9 -2
  49. package/dist/integrations/canopyx/source.js +26 -13
  50. package/dist/integrations/chartforgex/capture.d.ts +31 -0
  51. package/dist/integrations/chartforgex/capture.js +103 -0
  52. package/dist/integrations/chartforgex/index.d.ts +13 -0
  53. package/dist/integrations/chartforgex/index.js +88 -0
  54. package/dist/integrations/chartforgex/svg-drawing.d.ts +5 -0
  55. package/dist/integrations/chartforgex/svg-drawing.js +775 -0
  56. package/dist/integrations/chartforgex/svg-geometry.d.ts +23 -0
  57. package/dist/integrations/chartforgex/svg-geometry.js +304 -0
  58. package/dist/integrations/chartforgex/svg-image.d.ts +9 -0
  59. package/dist/integrations/chartforgex/svg-image.js +46 -0
  60. package/dist/integrations/chartforgex/svg-markup.d.ts +10 -0
  61. package/dist/integrations/chartforgex/svg-markup.js +124 -0
  62. package/dist/integrations/chartforgex/svg-paint.d.ts +16 -0
  63. package/dist/integrations/chartforgex/svg-paint.js +146 -0
  64. package/dist/integrations/chartforgex/types.d.ts +77 -0
  65. package/dist/integrations/chartforgex/types.js +1 -0
  66. package/dist/integrations/chartforgex/winansi.d.ts +4 -0
  67. package/dist/integrations/chartforgex/winansi.js +48 -0
  68. package/dist/integrations/chartforgex/workbook.d.ts +12 -0
  69. package/dist/integrations/chartforgex/workbook.js +137 -0
  70. package/dist/pdf/document-drawings.d.ts +1 -1
  71. package/dist/pdf/document-drawings.js +91 -17
  72. package/dist/pdf/document-images.d.ts +7 -1
  73. package/dist/pdf/document-images.js +59 -24
  74. package/dist/pdf/document-types.d.ts +3 -1
  75. package/dist/pdf/document.d.ts +2 -2
  76. package/dist/pdf/document.js +3 -1
  77. package/dist/pdf/drawing-types.d.ts +37 -10
  78. package/dist/pdf/font-resources.d.ts +1 -1
  79. package/dist/pdf/font-resources.js +6 -3
  80. package/dist/pdf/index.d.ts +1 -1
  81. package/dist/pdf/pages.js +15 -0
  82. package/dist/pdf/png.d.ts +11 -2
  83. package/dist/pdf/png.js +50 -23
  84. package/dist/pdf/session.js +3 -2
  85. package/dist/pdf/settings.d.ts +2 -2
  86. package/dist/pdf/settings.js +7 -3
  87. package/dist/xlsx/options.js +1 -1
  88. package/dist/xlsx/types.d.ts +8 -0
  89. package/dist/xlsx/workbook.js +6 -0
  90. package/dist/xlsx/worksheet.d.ts +13 -1
  91. package/dist/xlsx/worksheet.js +60 -9
  92. package/package.json +9 -2
@@ -956,15 +956,20 @@ return _exports;
956
956
  const _m14 = (() => {
957
957
  /** @internal Notify synchronously; observe an accidental promise before rejecting its unsupported use. */
958
958
  function notifyProgress(callback, progress) {
959
+ notifySynchronously("onProgress", callback, progress);
960
+ }
961
+ /** @internal Run a host notification that must finish before the export continues. A returned promise is observed,
962
+ * so its rejection is never unhandled, and the export fails instead of reporting success before the callback ends. */
963
+ function notifySynchronously(name, callback, value) {
959
964
  if (!callback)
960
965
  return;
961
- const result = callback(progress);
966
+ const result = callback(value);
962
967
  if (result && typeof result.then === "function") {
963
968
  void Promise.resolve(result).catch(() => { });
964
- throw new TypeError("onProgress must be synchronous.");
969
+ throw new TypeError(name + " must be synchronous.");
965
970
  }
966
971
  }
967
- const _exports = Object.freeze({ notifyProgress: notifyProgress });
972
+ const _exports = Object.freeze({ notifyProgress: notifyProgress, notifySynchronously: notifySynchronously });
968
973
  return _exports;
969
974
  })();
970
975
 
@@ -1199,12 +1204,16 @@ const sizes = {
1199
1204
  };
1200
1205
  /** @internal Shared capture schema for thin format adapters and the grouped writer. */
1201
1206
  const pdfOptionFields = ["columns", "signal", "onProgress", "limits", "textShaper", "textDirection", "pageSize", "orientation", "margins", "fonts", "tagged", "fontSize",
1202
- "title", "messageTop", "messageBottom", "includeHeader", "headerRows", "footer", "headerPresentation", "footerPresentation", "alternateRowColor", "padding",
1207
+ "title", "metadataTitle", "messageTop", "messageBottom", "includeHeader", "headerRows", "footer", "headerPresentation", "footerPresentation", "alternateRowColor", "padding",
1203
1208
  "columnWidths", "wideTable", "pageHeader", "pageFooter", "pageNumbers", "pageNumberLabels", "booleanText", "formatValue", "formatRuns", "compression", "paragraphStyles"];
1204
1209
  /** @internal Complete PDF limit schema used when a host combines format and shared limits. */
1205
1210
  const pdfLimitFields = ["maxRows", "maxCells", "maxTextCharacters", "maxOutputBytes", "maxPages", "maxColumns", "maxTableBands", "maxTableWindowRows", "maxCellCharacters", "maxTextRuns", "maxGroupBlocks", "maxRowLines",
1206
1211
  "maxFontBytes", "maxPageBytes", "maxHyperlinks", "maxImageBytes", "maxImagePixels", "maxImageWorkingBytes", "maxVectorCommands", "maxDrawingElements", "maxStructureElements",
1207
1212
  "maxMarkedContentReferences", "maxSections", "maxBookmarks", "maxListItems", "maxParagraphStyles"];
1213
+ /** @internal Default ceilings shared by the drawing writer and its producers. */
1214
+ const pdfDrawingLimits = Object.freeze({ maxVectorCommands: 100000, maxDrawingElements: 100000 });
1215
+ /** @internal Maximum number of retained drawing levels including the leaf. */
1216
+ const pdfDrawingMaxDepth = 32;
1208
1217
  /** @internal Capture supported structural properties once, including class-based options with prototype accessors. */
1209
1218
  function capturePdfOptions(input) {
1210
1219
  if (!input || typeof input !== "object" || Array.isArray(input))
@@ -1315,7 +1324,7 @@ function settings(input, document = false) {
1315
1324
  footerPresentation: Object.freeze({ background: "eef2f6", bold: true, ...presentation(configuration.footerPresentation) }) };
1316
1325
  const budget = new ExportBudget(options.limits);
1317
1326
  const limits = { maxPages: 10000, maxColumns: 1024, maxTableBands: 64, maxTableWindowRows: 256, maxCellCharacters: 1000000, maxTextRuns: 10000, maxGroupBlocks: 256, maxRowLines: 100000, maxFontBytes: 16 * 1024 * 1024, maxPageBytes: 8 * 1024 * 1024, maxHyperlinks: 100000,
1318
- maxImageBytes: 32 * 1024 * 1024, maxImagePixels: 16 * 1024 * 1024, maxVectorCommands: 100000, maxDrawingElements: 100000,
1327
+ maxImageBytes: 32 * 1024 * 1024, maxImagePixels: 16 * 1024 * 1024, ...pdfDrawingLimits,
1319
1328
  maxStructureElements: 1000000, maxMarkedContentReferences: 2000000,
1320
1329
  maxListItems: 100000, maxParagraphStyles: 256, maxSections: 1000, maxBookmarks: 10000 };
1321
1330
  for (const key of Object.keys(limits)) {
@@ -1343,7 +1352,7 @@ function settings(input, document = false) {
1343
1352
  const fontSize = positive(options.fontSize ?? 9, "Font size", 144), padding = options.padding ?? 4;
1344
1353
  if (!Number.isFinite(padding) || padding < 0 || padding > 72)
1345
1354
  throw new RangeError("PDF padding must be from 0 through 72 points.");
1346
- for (const key of ["title", "messageTop", "messageBottom"])
1355
+ for (const key of ["title", "metadataTitle", "messageTop", "messageBottom"])
1347
1356
  if (options[key] !== undefined && typeof options[key] !== "string")
1348
1357
  throw new TypeError(key + " must be text.");
1349
1358
  for (const key of ["pageHeader", "pageFooter"])
@@ -1379,7 +1388,7 @@ function settings(input, document = false) {
1379
1388
  repeatedColumns: document ? Object.freeze([]) : repeatedColumns(options.wideTable, columns),
1380
1389
  limits: { ...limits, ...(maxImageWorkingBytes === undefined ? {} : { maxImageWorkingBytes }) }, budget };
1381
1390
  }
1382
- const _exports = Object.freeze({ positive: _m20.positive, color: _m20.color, presentation: _m20.presentation, pdfOptionFields: pdfOptionFields, pdfLimitFields: pdfLimitFields, capturePdfOptions: capturePdfOptions, capturePdfLimits: capturePdfLimits, captureWideTable: captureWideTable, settings: settings });
1391
+ const _exports = Object.freeze({ positive: _m20.positive, color: _m20.color, presentation: _m20.presentation, pdfOptionFields: pdfOptionFields, pdfLimitFields: pdfLimitFields, pdfDrawingLimits: pdfDrawingLimits, pdfDrawingMaxDepth: pdfDrawingMaxDepth, capturePdfOptions: capturePdfOptions, capturePdfLimits: capturePdfLimits, captureWideTable: captureWideTable, settings: settings });
1383
1392
  return _exports;
1384
1393
  })();
1385
1394
 
@@ -1387,7 +1396,7 @@ const _m22 = (() => {
1387
1396
  const { captureFields } = _m10;
1388
1397
 
1389
1398
  /** @internal The workbook owner captures these settings before validation or adapter merging. */
1390
- const workbookOptionFields = ["signal", "onProgress", "limits", "sink", "dateMode", "compression", "invalidCharacterPolicy", "appProperties", "cellValueWriters", "oversizedText", "creator", "title", "subject", "description", "created", "modified"];
1399
+ const workbookOptionFields = ["signal", "onProgress", "limits", "sink", "dateMode", "compression", "invalidCharacterPolicy", "appProperties", "cellValueWriters", "oversizedText", "hyperlinkOverflow", "onHyperlinkOverflow", "creator", "title", "subject", "description", "created", "modified"];
1391
1400
  /** @internal Worksheet settings also used by the portable sheet owner. */
1392
1401
  const sheetOptionFields = ["columns", "includeHeader", "headerRows", "freezeHeader", "autoFilter", "boldHeader", "headerFill", "headerBorder", "headerWrap", "headerStyle", "alternatingRowStyle", "rowStyle", "cellStyle", "rowOutline", "maxOutlineLevel", "outlineSummaryBelow", "outlineSummaryRight", "columnOutlines", "rowHeight", "headerHeight", "defaultColumnWidth", "freezeColumns", "table", "autoSize", "footer", "print", "title", "mergedCells", "hyperlinks", "conditionalFormats", "dataValidation"];
1393
1402
  /** @internal Includes inherited format-specific ceilings before a wrapper combines stream settings. */
@@ -3765,7 +3774,7 @@ const { ChunkedTextSink, BlobByteSink } = _m3;
3765
3774
 
3766
3775
  const { OfficeIMOError } = _m2;
3767
3776
 
3768
- const { notifyProgress } = _m14;
3777
+ const { notifyProgress, notifySynchronously } = _m14;
3769
3778
 
3770
3779
  const { copyColumns, createRowProjector } = _m11;
3771
3780
 
@@ -3837,8 +3846,14 @@ class Worksheet {
3837
3846
  pendingCharacters = 0;
3838
3847
  reservedLayout = false;
3839
3848
  internalLinks = [];
3849
+ // Evicted entries become holes and are compacted in one pass when the links are read, keeping eviction O(1).
3840
3850
  links = [];
3851
+ evictedLinks = 0;
3841
3852
  linkedCells = new Set();
3853
+ /** Indexes in `links` of data-cell links that `hyperlinkOverflow: "drop"` may give up, in row order. */
3854
+ droppable = [];
3855
+ droppableLinks = new WeakSet();
3856
+ droppedLinks = 0;
3842
3857
  pictures = [];
3843
3858
  nativeCharts = [];
3844
3859
  conditional;
@@ -4050,7 +4065,8 @@ class Worksheet {
4050
4065
  const cell = col.letter + row;
4051
4066
  if (link || this.linkedCells.has(cell))
4052
4067
  throw new TypeError("A text-preservation cell cannot also have an external hyperlink.");
4053
- checkHyperlinkCount(this.links.length + this.internalLinks.length + 1);
4068
+ this.makeLinkRoom();
4069
+ checkHyperlinkCount(this.linkCount + 1);
4054
4070
  this.book.checkLinks(1);
4055
4071
  // Replace a generated cell's original reservation with its preview and overflow records.
4056
4072
  if (reservedCharacters !== undefined) {
@@ -4064,7 +4080,7 @@ class Worksheet {
4064
4080
  value = preserved.preview;
4065
4081
  }
4066
4082
  if (link)
4067
- this.appendHyperlink({ cell: col.letter + row, ...link });
4083
+ this.appendHyperlink({ cell: col.letter + row, ...link }, !header && !footer && !title && this.book.settings.hyperlinkOverflow === "drop");
4068
4084
  if (type === "date")
4069
4085
  value = excelDate(value, this.book.settings.dateMode);
4070
4086
  if (!header && !footer && visible && (!formula || !isSubtotalFormula(formula)))
@@ -4373,20 +4389,61 @@ class Worksheet {
4373
4389
  throw this.error;
4374
4390
  this.appendHyperlink(link);
4375
4391
  }
4376
- appendHyperlink(link) {
4392
+ appendHyperlink(link, droppable = false) {
4393
+ // Validate before any overflow decision, so a dropped link can never hide an unsafe target.
4377
4394
  const copied = copyHyperlink(link, this.book.settings.invalidCharacterPolicy);
4378
4395
  const position = cellPosition(copied.cell);
4379
4396
  if (this.layout.regions.covered(position.column, position.row))
4380
4397
  throw new TypeError("Hyperlinks cannot address a covered merged cell.");
4381
4398
  if (this.linkedCells.has(copied.cell))
4382
4399
  throw new TypeError("Duplicate hyperlink cell: " + copied.cell);
4383
- checkHyperlinkCount(this.links.length + this.internalLinks.length + 1);
4400
+ if (droppable && this.linkCount >= maximumHyperlinks) {
4401
+ this.droppedLinks++;
4402
+ return;
4403
+ }
4404
+ if (!droppable)
4405
+ this.makeLinkRoom();
4406
+ checkHyperlinkCount(this.linkCount + 1);
4384
4407
  this.book.retainLink();
4408
+ if (droppable) {
4409
+ this.droppable.push(this.links.length);
4410
+ this.droppableLinks.add(copied);
4411
+ }
4385
4412
  this.links.push(copied);
4386
4413
  this.linkedCells.add(copied.cell);
4387
4414
  }
4415
+ /** Links the worksheet holds now, not counting evicted holes. */
4416
+ get linkCount() { return this.links.length - this.evictedLinks + this.internalLinks.length; }
4417
+ /** A full worksheet gives up its latest data-cell link for a link that cannot be dropped. Hyperlinks are serialized after
4418
+ * the rows, so the cell keeps its written value. The entry becomes a hole, so other indexes stay valid until compaction. */
4419
+ makeLinkRoom() {
4420
+ if (this.linkCount < maximumHyperlinks || !this.droppable.length)
4421
+ return;
4422
+ const index = this.droppable.pop(), removed = this.links[index];
4423
+ this.links[index] = undefined;
4424
+ this.evictedLinks++;
4425
+ this.linkedCells.delete(removed.cell);
4426
+ this.book.releaseLink();
4427
+ this.droppedLinks++;
4428
+ }
4429
+ /** One ordered pass removes evicted holes and rebuilds the droppable indexes. */
4430
+ compactLinks() {
4431
+ if (this.evictedLinks) {
4432
+ const kept = [], droppable = [];
4433
+ for (const link of this.links)
4434
+ if (link) {
4435
+ if (this.droppableLinks.has(link))
4436
+ droppable.push(kept.length);
4437
+ kept.push(link);
4438
+ }
4439
+ this.links = kept;
4440
+ this.droppable = droppable;
4441
+ this.evictedLinks = 0;
4442
+ }
4443
+ return this.links;
4444
+ }
4388
4445
  /** @internal */
4389
- get hyperlinks() { return this.links; }
4446
+ get hyperlinks() { return this.compactLinks(); }
4390
4447
  /** @internal */
4391
4448
  get images() { return this.pictures; }
4392
4449
  /** @internal An empty export has no data table; it still emits the declared headers. */
@@ -4437,7 +4494,7 @@ class Worksheet {
4437
4494
  for (const binding of this.chartSources)
4438
4495
  binding.finish();
4439
4496
  this.chartSources.length = 0;
4440
- for (const link of this.links) {
4497
+ for (const link of this.compactLinks()) {
4441
4498
  const position = cellPosition(link.cell);
4442
4499
  if (position.column > this.columns.length || position.row > this.totalRows)
4443
4500
  throw new RangeError("Hyperlinks must address cells within the exported rows and columns.");
@@ -4467,8 +4524,11 @@ class Worksheet {
4467
4524
  await this.buffer.write(xml);
4468
4525
  for (const xml of dataValidationsXml(this.validations, this.headerRows, this.count, detailRanges))
4469
4526
  await this.buffer.write(xml);
4470
- if (this.links.length || this.internalLinks.length)
4471
- await this.buffer.write(hyperlinksXml(this.links, this.book.settings.invalidCharacterPolicy, this.internalLinks));
4527
+ if (this.droppedLinks)
4528
+ notifySynchronously("onHyperlinkOverflow", this.book.settings.onHyperlinkOverflow, Object.freeze({ sheetName: this.name, dropped: this.droppedLinks }));
4529
+ const links = this.compactLinks();
4530
+ if (links.length || this.internalLinks.length)
4531
+ await this.buffer.write(hyperlinksXml(links, this.book.settings.invalidCharacterPolicy, this.internalLinks));
4472
4532
  await this.buffer.write(printXml(this.options.print, this.book.settings.invalidCharacterPolicy));
4473
4533
  if (this.pictures.length || this.nativeCharts.length)
4474
4534
  await this.buffer.write('<drawing r:id="drawing"/>');
@@ -5043,6 +5103,10 @@ class Workbook {
5043
5103
  throw new RangeError("compression must be auto or store.");
5044
5104
  if (options.oversizedText !== undefined && !["reject", "preserve"].includes(options.oversizedText))
5045
5105
  throw new RangeError("oversizedText must be reject or preserve.");
5106
+ if (options.hyperlinkOverflow !== undefined && !["reject", "drop"].includes(options.hyperlinkOverflow))
5107
+ throw new RangeError("hyperlinkOverflow must be reject or drop.");
5108
+ if (options.onHyperlinkOverflow !== undefined && typeof options.onHyperlinkOverflow !== "function")
5109
+ throw new TypeError("onHyperlinkOverflow must be a function.");
5046
5110
  cleanXml("", policy);
5047
5111
  corePropertiesXml(options, policy);
5048
5112
  this.budget = new ExportBudget(options.limits);
@@ -5120,6 +5184,8 @@ class Workbook {
5120
5184
  }
5121
5185
  /** @internal Reserve a preflighted worksheet batch or one row hyperlink. */
5122
5186
  retainLink(count = 1) { this.checkLinks(count); this.links += count; }
5187
+ /** @internal A worksheet dropped a data-cell link it had retained. */
5188
+ releaseLink() { this.links--; }
5123
5189
  /** @internal */
5124
5190
  checkImage(bytes) {
5125
5191
  if (this.settings.limits?.maxImageBytes !== undefined && this.imageBytes + bytes > this.settings.limits.maxImageBytes)
@@ -7468,7 +7534,7 @@ class PdfFontResources {
7468
7534
  this.fontBytes += bytes;
7469
7535
  this.registered.add(font);
7470
7536
  }
7471
- select(bold = false, italic = false, explicit) {
7537
+ select(bold = false, italic = false, explicit, standardForMissingFace = false) {
7472
7538
  if (explicit)
7473
7539
  this.registerFont(explicit);
7474
7540
  let selections = this.selections;
@@ -7478,10 +7544,13 @@ class PdfFontResources {
7478
7544
  if (!found)
7479
7545
  this.explicitSelections.set(explicit, selections);
7480
7546
  }
7481
- const key = (bold ? 2 : 0) | (italic ? 1 : 0), existing = selections.get(key);
7547
+ const fallback = standardForMissingFace && !explicit && this.fonts !== undefined &&
7548
+ this.fonts[bold ? italic ? "boldItalic" : "bold" : italic ? "italic" : "regular"] === undefined;
7549
+ const key = (bold ? 2 : 0) | (italic ? 1 : 0) | (fallback ? 4 : 0), existing = selections.get(key);
7482
7550
  if (existing)
7483
7551
  return existing;
7484
- const { font, syntheticBold, syntheticItalic } = explicit ? { font: explicit, syntheticBold: bold, syntheticItalic: italic } : selectFont(this.fonts, bold, italic);
7552
+ const { font, syntheticBold, syntheticItalic } = explicit ? { font: explicit, syntheticBold: bold, syntheticItalic: italic } :
7553
+ selectFont(fallback ? undefined : this.fonts, bold, italic);
7485
7554
  const shared = font ? this.programs.get(font) : undefined;
7486
7555
  const resource = new PdfFontResource(this.resources.length + 1, bold, italic, font, this.objects, syntheticBold, syntheticItalic, shared, this.signal);
7487
7556
  if (!shared) {
@@ -8775,6 +8844,7 @@ class PdfPages {
8775
8844
  rectangleLefts;
8776
8845
  rectangleColumns = [];
8777
8846
  externalObjects = new Map();
8847
+ opacityStates = new Map();
8778
8848
  bandFlow;
8779
8849
  bandCellBudget = false;
8780
8850
  tableElement;
@@ -9357,6 +9427,20 @@ class PdfPages {
9357
9427
  }
9358
9428
  async pageBreak() { await this.ensureStarted(); await this.finishPage(); await this.start(false); }
9359
9429
  registerXObject(name, id) { this.externalObjects.set(name, id); }
9430
+ /** One shared constant-opacity graphics state per serialized alpha value. */
9431
+ opacityState(alpha) {
9432
+ const value = pdfNumber(alpha);
9433
+ let name = this.opacityStates.get(value);
9434
+ if (!name) {
9435
+ name = "GA" + (this.opacityStates.size + 1);
9436
+ this.opacityStates.set(value, name);
9437
+ }
9438
+ return name;
9439
+ }
9440
+ graphicsStates() {
9441
+ const entries = [...this.opacityStates].map(([alpha, name]) => "/" + name + " << /ca " + alpha + " /CA " + alpha + " >>");
9442
+ return entries.length ? " /ExtGState << " + entries.join(" ") + " >>" : "";
9443
+ }
9360
9444
  /** Height after the existing fit-to-page graphic policy, used by heading keep constraints. */
9361
9445
  graphicHeight(width, height) {
9362
9446
  const { page, margins } = this.settings;
@@ -9943,13 +10027,14 @@ class PdfWriteSession {
9943
10027
  await pages.finish();
9944
10028
  for (const font of fonts.resources)
9945
10029
  await font.write(objects, options.compression !== false);
9946
- await objects.object(this.resources, "<< /Font " + fonts.dictionary() + pages.xobjects() + " >>");
10030
+ await objects.object(this.resources, "<< /Font " + fonts.dictionary() + pages.xobjects() + pages.graphicsStates() + " >>");
9947
10031
  await objects.object(this.parent, "<< /Type /Pages /Count " + pages.references.length + " /Kids [" + pages.references.map(id => id + " 0 R").join(" ") + "] >>");
9948
10032
  if (this.structure)
9949
10033
  await this.structure.finish();
9950
10034
  await this.outlines.finish();
9951
10035
  await objects.object(this.root, "<< /Type /Catalog /Pages " + this.parent + " 0 R" + (this.structure?.catalogDictionary ?? "") + this.outlines.catalogDictionary + " >>");
9952
- await objects.object(this.info, "<< /Producer (OfficeIMO.js)" + (options.title === undefined ? "" : " /Title <feff" + unicodeHex(options.title) + ">") + " >>");
10036
+ const title = options.metadataTitle ?? options.title;
10037
+ await objects.object(this.info, "<< /Producer (OfficeIMO.js)" + (title === undefined ? "" : " /Title <feff" + unicodeHex(title) + ">") + " >>");
9953
10038
  await objects.finish(this.root, this.info);
9954
10039
  }
9955
10040
  }
@@ -10034,15 +10119,10 @@ const { Crc32 } = _m31;
10034
10119
 
10035
10120
  const signature = [137, 80, 78, 71, 13, 10, 26, 10];
10036
10121
  const unsupportedChunks = new Set(["PLTE", "tRNS", "iCCP", "sRGB", "gAMA", "cHRM", "cICP", "mDCV", "cLLI", "sBIT", "eXIf", "acTL", "fcTL", "fdAT"]);
10037
- /** Decode the static unprofiled 8-bit RGB/RGBA profile without canvas or a second compression engine. */
10038
- async function pngPixels(inputSource, maxPixels, signal, maxWorkingBytes) {
10122
+ /** Decode an owned static unprofiled PNG without canvas or a second compression engine. */
10123
+ async function pngPixels(source, shape, signal) {
10039
10124
  checkAbort(signal);
10040
- const shape = pngShape(inputSource, maxPixels);
10041
10125
  const imagePixels = shape.width * shape.height;
10042
- const workingBytes = inputSource.length + imagePixels * shape.components + (shape.components === 4 ? shape.width * 8 : 0);
10043
- if (maxWorkingBytes !== undefined && workingBytes > maxWorkingBytes)
10044
- throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageWorkingBytes exceeded by PNG source, image planes and scanlines.");
10045
- const source = new Uint8Array(inputSource);
10046
10126
  const header = await pngHeader(source, shape, signal);
10047
10127
  checkAbort(signal);
10048
10128
  let stream;
@@ -10056,9 +10136,6 @@ async function pngPixels(inputSource, maxPixels, signal, maxWorkingBytes) {
10056
10136
  }
10057
10137
  const { width, height, components } = header, rowBytes = width * components;
10058
10138
  const expected = (rowBytes + 1) * height;
10059
- // All dimensions and the exact filtered length are bounded before allocating decoded pixels.
10060
- if (!Number.isSafeInteger(expected) || expected > 0x7fffffff)
10061
- throw new OfficeIMOError("RESOURCE_LIMIT", "PNG filtered data exceeds the supported decoded byte length.");
10062
10139
  // RGBA is reconstructed one scanline at a time directly into PDF RGB/alpha planes.
10063
10140
  // It never retains an additional full interleaved RGBA image.
10064
10141
  const pixels = new Uint8Array(width * height * 3), alpha = components === 4 ? new Uint8Array(imagePixels) : undefined;
@@ -10206,20 +10283,55 @@ async function verifyPngZlibEnd(source, header, expected, signal) {
10206
10283
  reader.releaseLock();
10207
10284
  }
10208
10285
  }
10286
+ function pngChunk(source, view, offset) {
10287
+ if (offset + 12 > source.length)
10288
+ throw new TypeError("Truncated PNG chunk.");
10289
+ const length = view.getUint32(offset), end = offset + 12 + length;
10290
+ if (length > 0x7fffffff || end > source.length)
10291
+ throw new TypeError("Truncated or oversized PNG chunk.");
10292
+ const type = String.fromCharCode(...source.subarray(offset + 4, offset + 8));
10293
+ if (!/^[A-Za-z]{2}[A-Z][A-Za-z]$/.test(type))
10294
+ throw new TypeError("Invalid PNG chunk type.");
10295
+ return { length, end, type };
10296
+ }
10297
+ function checkAncillaryChunk(type) {
10298
+ if (unsupportedChunks.has(type))
10299
+ throw new NotSupportedError("PNG chunk " + type + "; normalize color, orientation, transparency or animation first");
10300
+ if (type.charCodeAt(0) < 97)
10301
+ throw new NotSupportedError("Required PNG chunk " + type);
10302
+ }
10303
+ /** Check the image profile for SVG placement without inflating pixels. Embedding still verifies CRCs and image data. */
10304
+ function pngEmbeddableSize(source) {
10305
+ const shape = pngShape(source, Infinity);
10306
+ const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
10307
+ let hasData = false, dataClosed = false;
10308
+ for (let offset = 33; offset < source.length;) {
10309
+ const { length, end, type } = pngChunk(source, view, offset);
10310
+ if (type === "IEND") {
10311
+ if (length === 0 && hasData && end === source.length)
10312
+ return shape;
10313
+ break;
10314
+ }
10315
+ if (type === "IDAT") {
10316
+ if (dataClosed)
10317
+ throw new TypeError("PNG IDAT chunks must be consecutive.");
10318
+ hasData = true;
10319
+ }
10320
+ else {
10321
+ checkAncillaryChunk(type);
10322
+ dataClosed ||= hasData;
10323
+ }
10324
+ offset = end;
10325
+ }
10326
+ throw new TypeError("PNG requires a final empty IEND after IDAT.");
10327
+ }
10209
10328
  /** Verify the complete source and critical chunk order before any decompressed image allocation. */
10210
10329
  async function pngHeader(source, shape, signal) {
10211
10330
  const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
10212
10331
  let firstData = 0, dataEnd = 0, lastDataByte = -1, dataClosed = false;
10213
10332
  for (let offset = 8; offset < source.length;) {
10214
10333
  checkAbort(signal);
10215
- if (offset + 12 > source.length)
10216
- throw new TypeError("Truncated PNG chunk.");
10217
- const length = view.getUint32(offset), end = offset + 12 + length;
10218
- if (length > 0x7fffffff || end > source.length)
10219
- throw new TypeError("Truncated or oversized PNG chunk.");
10220
- const type = String.fromCharCode(...source.subarray(offset + 4, offset + 8));
10221
- if (!/^[A-Za-z]{2}[A-Z][A-Za-z]$/.test(type))
10222
- throw new TypeError("Invalid PNG chunk type.");
10334
+ const { length, end, type } = pngChunk(source, view, offset);
10223
10335
  const crc = new Crc32();
10224
10336
  for (let p = offset + 4; p < end - 4; p += 65536) {
10225
10337
  crc.update(source.subarray(p, Math.min(end - 4, p + 65536)));
@@ -10251,17 +10363,14 @@ async function pngHeader(source, shape, signal) {
10251
10363
  throw new TypeError("PNG requires a final empty IEND after IDAT.");
10252
10364
  return { ...shape, firstData, dataEnd, lastDataByte };
10253
10365
  }
10254
- if (unsupportedChunks.has(type))
10255
- throw new NotSupportedError("PNG chunk " + type + "; normalize color, orientation, transparency or animation first");
10256
- if ((source[offset + 4] & 32) === 0)
10257
- throw new NotSupportedError("Required PNG chunk " + type);
10366
+ checkAncillaryChunk(type);
10258
10367
  }
10259
10368
  offset = end;
10260
10369
  }
10261
10370
  throw new TypeError("PNG requires a complete final IEND chunk.");
10262
10371
  }
10263
10372
  /** Check source metadata synchronously, before capturing source bytes or allocating any image plane. */
10264
- function pngShape(source, maxPixels) {
10373
+ function pngShape(source, maxPixels, maxWorkingBytes) {
10265
10374
  if (source.length < 33 || signature.some((value, index) => source[index] !== value))
10266
10375
  throw new TypeError("Invalid PNG signature or truncated IHDR.");
10267
10376
  const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
@@ -10281,6 +10390,9 @@ function pngShape(source, maxPixels) {
10281
10390
  const components = source[25] === 6 ? 4 : 3;
10282
10391
  if (!Number.isSafeInteger((width * components + 1) * height) || (width * components + 1) * height > 0x7fffffff)
10283
10392
  throw new OfficeIMOError("RESOURCE_LIMIT", "PNG filtered data exceeds the supported decoded byte length.");
10393
+ const workingBytes = source.length + width * height * components + (components === 4 ? width * 8 : 0);
10394
+ if (maxWorkingBytes !== undefined && workingBytes > maxWorkingBytes)
10395
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageWorkingBytes exceeded by PNG source, image planes and scanlines.");
10284
10396
  return { width, height, components };
10285
10397
  }
10286
10398
  function paeth(left, up, upperLeft) {
@@ -10288,7 +10400,7 @@ function paeth(left, up, upperLeft) {
10288
10400
  const a = Math.abs(prediction - left), b = Math.abs(prediction - up), c = Math.abs(prediction - upperLeft);
10289
10401
  return a <= b && a <= c ? left : b <= c ? up : upperLeft;
10290
10402
  }
10291
- const _exports = Object.freeze({ pngPixels: pngPixels });
10403
+ const _exports = Object.freeze({ pngPixels: pngPixels, pngEmbeddableSize: pngEmbeddableSize, pngShape: pngShape });
10292
10404
  return _exports;
10293
10405
  })();
10294
10406
 
@@ -10297,54 +10409,83 @@ const { NotSupportedError, OfficeIMOError } = _m2;
10297
10409
 
10298
10410
  const { checkAbort, pause, taskYieldDue } = _m4;
10299
10411
 
10300
- const { pngPixels } = _m87;
10412
+ const { pngPixels, pngShape } = _m87;
10301
10413
 
10302
10414
  /** Shared document image resources; source objects are captured on first consumption. */
10303
10415
  class PdfDocumentImages {
10304
10416
  objects;
10305
10417
  settings;
10306
10418
  images = new Map();
10419
+ snapshots = new WeakMap();
10307
10420
  bytes = 0;
10421
+ pendingBytes = 0;
10308
10422
  constructor(objects, settings) {
10309
10423
  this.objects = objects;
10310
10424
  this.settings = settings;
10311
10425
  }
10312
- async prepare(image) {
10313
- const existing = this.images.get(image);
10314
- if (existing)
10315
- return existing;
10426
+ /** Own a drawing image before preparing earlier elements can yield to the caller. */
10427
+ snapshot(image) {
10428
+ if (this.images.has(image) || this.snapshots.has(image))
10429
+ return;
10430
+ const captured = this.capture(image);
10431
+ this.snapshots.set(image, captured);
10432
+ this.pendingBytes += captured.data.length;
10433
+ }
10434
+ capture(image) {
10316
10435
  const { limits, options } = this.settings;
10436
+ checkAbort(options.signal);
10317
10437
  if (!image || typeof image !== "object")
10318
10438
  throw new TypeError("PDF images require a byte array.");
10319
- const data = image.data, format = image.format;
10439
+ const format = image.format;
10440
+ // Dimension getters may change a resizable backing buffer. Read them before measuring the byte view.
10441
+ const raw = format === "rgb" || format === "rgba" ? image : undefined;
10442
+ const widthValue = raw?.width, heightValue = raw?.height;
10443
+ const data = image.data;
10320
10444
  if (!(data instanceof Uint8Array))
10321
10445
  throw new TypeError("PDF images require a byte array.");
10322
10446
  const byteLength = data.length;
10323
- if (this.bytes + byteLength > limits.maxImageBytes)
10447
+ if (this.bytes + this.pendingBytes + byteLength > limits.maxImageBytes)
10324
10448
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageBytes exceeded.");
10325
- let width, height, components, decoded, decodedAlpha;
10326
10449
  const maximumWorkingBytes = limits.maxImageWorkingBytes;
10327
- if (format === "png")
10328
- ({ width, height, components, data: decoded, alpha: decodedAlpha } = await pngPixels(data, limits.maxImagePixels, options.signal, maximumWorkingBytes));
10329
- else if (format === "jpeg")
10330
- ({ width, height, components } = jpegSize(data));
10450
+ if (format === "png") {
10451
+ const shape = pngShape(data, limits.maxImagePixels, maximumWorkingBytes);
10452
+ return { format, shape, data: new Uint8Array(data) };
10453
+ }
10454
+ let shape;
10455
+ if (format === "jpeg")
10456
+ shape = jpegSize(data);
10331
10457
  else if (format === "rgb" || format === "rgba") {
10332
- ({ width, height } = image);
10333
- components = format === "rgba" ? 4 : 3;
10458
+ shape = { width: widthValue, height: heightValue, components: format === "rgba" ? 4 : 3 };
10334
10459
  }
10335
10460
  else
10336
10461
  throw new NotSupportedError("PDF images support unprofiled PNG/JPEG or decoded RGB/RGBA pixels.");
10462
+ const { width, height, components } = shape;
10337
10463
  if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 ||
10338
10464
  !Number.isSafeInteger(width * height) || width * height > limits.maxImagePixels)
10339
10465
  throw new OfficeIMOError("RESOURCE_LIMIT", "Image dimensions must be positive integers within maxImagePixels.");
10340
- if ((format === "rgb" || format === "rgba") && byteLength !== width * height * components)
10466
+ if (format !== "jpeg" && byteLength !== width * height * components)
10341
10467
  throw new RangeError("Raw image bytes must match width × height × channels exactly.");
10342
- if (format !== "png" && maximumWorkingBytes !== undefined && byteLength + (components === 4 ? width * height : 0) > maximumWorkingBytes)
10468
+ if (maximumWorkingBytes !== undefined && byteLength + (components === 4 ? width * height : 0) > maximumWorkingBytes)
10343
10469
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageWorkingBytes exceeded by image snapshot and alpha plane.");
10470
+ return { format, shape, data: new Uint8Array(data) };
10471
+ }
10472
+ async prepare(image) {
10473
+ const existing = this.images.get(image);
10474
+ if (existing)
10475
+ return existing;
10476
+ const { options } = this.settings, snapshot = this.snapshots.get(image);
10477
+ const source = snapshot ?? this.capture(image);
10478
+ if (snapshot) {
10479
+ this.snapshots.delete(image);
10480
+ this.pendingBytes -= source.data.length;
10481
+ }
10482
+ this.bytes += source.data.length;
10483
+ const { format } = source;
10484
+ const decoded = format === "png" ? await pngPixels(source.data, source.shape, options.signal) : undefined;
10485
+ const { width, height, components } = decoded ?? source.shape;
10344
10486
  checkAbort(options.signal);
10345
10487
  const id = this.objects.reserve(), name = "Image" + (this.images.size + 1);
10346
- this.bytes += byteLength;
10347
- const captured = decoded ?? new Uint8Array(data);
10488
+ const captured = decoded?.data ?? source.data, decodedAlpha = decoded?.alpha;
10348
10489
  let pixels = captured, alpha = decodedAlpha, mask;
10349
10490
  if (components === 4) {
10350
10491
  // Compact the owned RGBA snapshot in place. Forward writes never overwrite unread channels.
@@ -10366,20 +10507,22 @@ class PdfDocumentImages {
10366
10507
  mask = this.objects.reserve();
10367
10508
  await this.objects.stream(mask, alpha, "/Type /XObject /Subtype /Image /Width " + width + " /Height " + height + " /ColorSpace /DeviceGray /BitsPerComponent 8", options.compression !== false, true);
10368
10509
  }
10510
+ const jpegFilter = format === "jpeg" ? " /Filter /DCTDecode" +
10511
+ (source.shape.colorTransform === 0 ? " /DecodeParms << /ColorTransform 0 >>" : "") : "";
10369
10512
  const dictionary = "/Type /XObject /Subtype /Image /Width " + width + " /Height " + height + " /ColorSpace /" +
10370
10513
  (components === 1 ? "DeviceGray" : "DeviceRGB") + " /BitsPerComponent 8" + (mask ? " /SMask " + mask + " 0 R" : "") +
10371
- (format === "jpeg" ? " /Filter /DCTDecode" : "");
10514
+ jpegFilter;
10372
10515
  await this.objects.stream(id, pixels, dictionary, format === "jpeg" ? false : options.compression !== false, true);
10373
10516
  const resource = { name, id, width, height };
10374
10517
  this.images.set(image, resource);
10375
10518
  return resource;
10376
10519
  }
10377
10520
  }
10378
- /** Inspect bounded JPEG headers; JPEG entropy decoding remains the independent reader's job. */
10521
+ /** @internal Inspect bounded JPEG headers; JPEG entropy decoding remains the independent reader's job. */
10379
10522
  function jpegSize(bytes) {
10380
10523
  if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216 || bytes[bytes.length - 2] !== 255 || bytes[bytes.length - 1] !== 217)
10381
10524
  throw new TypeError("JPEG images need complete SOI/EOI markers.");
10382
- let result;
10525
+ let result, rgb = false, adobe = false;
10383
10526
  for (let p = 2; p < bytes.length;) {
10384
10527
  if (bytes[p++] !== 255)
10385
10528
  throw new TypeError("Invalid JPEG marker.");
@@ -10389,7 +10532,8 @@ function jpegSize(bytes) {
10389
10532
  if (marker === 218) {
10390
10533
  if (!result)
10391
10534
  throw new TypeError("JPEG scan precedes its frame header.");
10392
- return result;
10535
+ // PDF decoders otherwise assume a color transform for three-component JPEGs.
10536
+ return rgb && !adobe ? { ...result, colorTransform: 0 } : result;
10393
10537
  }
10394
10538
  if (marker === 217)
10395
10539
  break;
@@ -10398,6 +10542,8 @@ function jpegSize(bytes) {
10398
10542
  const length = bytes[p] * 256 + bytes[p + 1], end = p + length;
10399
10543
  if (length < 2 || end > bytes.length)
10400
10544
  throw new TypeError("Truncated JPEG segment.");
10545
+ if (marker === 238 && length >= 14 && String.fromCharCode(...bytes.subarray(p + 2, p + 7)) === "Adobe")
10546
+ adobe = true;
10401
10547
  if (marker === 226 && length >= 14 && String.fromCharCode(...bytes.subarray(p + 2, p + 14)) === "ICC_PROFILE\0")
10402
10548
  throw new NotSupportedError("Normalize ICC-profiled JPEG colors before PDF embedding.");
10403
10549
  if (marker === 225 && length >= 8 && String.fromCharCode(...bytes.subarray(p + 2, p + 8)) === "Exif\0\0")
@@ -10410,7 +10556,8 @@ function jpegSize(bytes) {
10410
10556
  throw new NotSupportedError("PDF JPEG images require grayscale or RGB components; CMYK is unsupported.");
10411
10557
  if (components === 3) {
10412
10558
  const ids = [bytes[p + 8], bytes[p + 11], bytes[p + 14]].join(",");
10413
- if (ids !== "1,2,3" && ids !== "82,71,66")
10559
+ rgb = ids === "82,71,66";
10560
+ if (ids !== "1,2,3" && !rgb)
10414
10561
  throw new NotSupportedError("Unsupported JPEG component color layout.");
10415
10562
  }
10416
10563
  if (result)
@@ -10421,7 +10568,7 @@ function jpegSize(bytes) {
10421
10568
  }
10422
10569
  throw new TypeError("JPEG image has no complete frame and scan.");
10423
10570
  }
10424
- const _exports = Object.freeze({ PdfDocumentImages: PdfDocumentImages });
10571
+ const _exports = Object.freeze({ PdfDocumentImages: PdfDocumentImages, jpegSize: jpegSize });
10425
10572
  return _exports;
10426
10573
  })();
10427
10574
 
@@ -10516,7 +10663,7 @@ const { NotSupportedError, OfficeIMOError } = _m2;
10516
10663
 
10517
10664
  const { checkAbort, pause, taskYieldDue } = _m4;
10518
10665
 
10519
- const { color, positive } = _m17;
10666
+ const { color, pdfDrawingMaxDepth, positive } = _m17;
10520
10667
 
10521
10668
  const { pdfNumber: n } = _m61;
10522
10669
 
@@ -10538,22 +10685,50 @@ function clipRectangle(value) {
10538
10685
  const clip = record(value, ["x", "y", "width", "height"], "drawing clip");
10539
10686
  return { x: coordinate(clip.x), y: coordinate(clip.y), width: positive(clip.width, "Drawing clip width", 1000000), height: positive(clip.height, "Drawing clip height", 1000000) };
10540
10687
  }
10688
+ /** A PDF dash array: 1 through 16 nonnegative lengths, not all zero, and a finite phase. */
10689
+ function dashPattern(value, offset) {
10690
+ if (value === undefined) {
10691
+ if (offset !== undefined)
10692
+ throw new TypeError("Drawing dashOffset requires dash.");
10693
+ return "";
10694
+ }
10695
+ if (!Array.isArray(value) || !value.length || value.length > 16)
10696
+ throw new TypeError("Drawing dash must list 1 through 16 nonnegative lengths with at least one positive length.");
10697
+ const lengths = Array.from(value, item => {
10698
+ if (typeof item !== "number" || !Number.isFinite(item) || item < 0 || item > 14400)
10699
+ throw new TypeError("Drawing dash lengths must be from 0 through 14,400 points.");
10700
+ return n(item);
10701
+ });
10702
+ if (lengths.every(length => length === "0"))
10703
+ throw new TypeError("Drawing dash needs a positive length after PDF rounding.");
10704
+ let phase = coordinate(offset ?? 0);
10705
+ if (phase < 0) {
10706
+ // Work in serialized thousandths of a point. Odd arrays repeat twice before the paint state repeats.
10707
+ const period = lengths.reduce((sum, length) => sum + Math.round(Number(length) * 1000), 0) * (lengths.length % 2 ? 2 : 1);
10708
+ phase = ((Math.round(phase * 1000) % period + period) % period) / 1000;
10709
+ }
10710
+ return "[" + lengths.join(" ") + "] " + n(phase) + " d\n";
10711
+ }
10541
10712
  async function cooperate(settings) {
10542
10713
  if (taskYieldDue())
10543
10714
  await pause();
10544
10715
  checkAbort(settings.options.signal);
10545
10716
  }
10546
10717
  /** Take ownership of one bounded schema before any cooperative or font work can run caller code. */
10547
- function captureDrawing(drawing, settings, used) {
10718
+ function captureDrawing(drawing, settings, used, images) {
10548
10719
  checkAbort(settings.options.signal);
10549
- const root = record(drawing, ["version", "width", "height", "elements"], "drawing");
10550
- if (root.version !== 1)
10551
- throw new NotSupportedError("Only portable drawing version 1 is supported.");
10720
+ const root = record(drawing, ["version", "width", "height", "elements", "standardFonts"], "drawing");
10721
+ const standardFonts = root.standardFonts;
10722
+ if (standardFonts !== undefined && typeof standardFonts !== "boolean")
10723
+ throw new TypeError("Drawing standardFonts must be boolean.");
10724
+ const version = root.version;
10725
+ if (version !== 1 && version !== 2)
10726
+ throw new NotSupportedError("Only portable drawing versions 1 and 2 are supported.");
10552
10727
  const width = positive(root.width, "Drawing width"), height = positive(root.height, "Drawing height");
10553
10728
  let commands = used.commands, elements = used.elements;
10554
10729
  const ancestors = new Set();
10555
10730
  function path(value) {
10556
- record(value, ["kind", "commands", "fill", "stroke", "strokeWidth", "fillRule", "lineCap", "lineJoin"], "drawing path");
10731
+ record(value, ["kind", "commands", "fill", "stroke", "strokeWidth", "fillRule", "lineCap", "lineJoin", "miterLimit", "dash", "dashOffset"], "drawing path");
10557
10732
  const source = value.commands;
10558
10733
  if (!Array.isArray(source))
10559
10734
  throw new TypeError("Drawing path commands must be an array.");
@@ -10575,6 +10750,10 @@ function captureDrawing(drawing, settings, used) {
10575
10750
  throw new TypeError("Invalid drawing lineCap.");
10576
10751
  if (lineJoin !== undefined && !["miter", "round", "bevel"].includes(lineJoin))
10577
10752
  throw new TypeError("Invalid drawing lineJoin.");
10753
+ const miterLimit = positive(value.miterLimit ?? 10, "Drawing miter limit", 1000000);
10754
+ if (miterLimit < 1)
10755
+ throw new RangeError("Drawing miter limit must be at least 1.");
10756
+ const dash = dashPattern(value.dash, value.dashOffset);
10578
10757
  for (let i = 0; i < snapshot.length; i++) {
10579
10758
  const c = snapshot[i];
10580
10759
  if (!c || typeof c !== "object")
@@ -10607,11 +10786,12 @@ function captureDrawing(drawing, settings, used) {
10607
10786
  if (!started)
10608
10787
  throw new TypeError("A drawing path needs at least one command.");
10609
10788
  return { kind: "path", commands: copied, style: (fill === undefined ? "" : fill + " rg\n") + (stroke === undefined ? "" : stroke + " RG\n" + n(strokeWidth) + " w\n") +
10610
- String(["butt", "round", "square"].indexOf(lineCap ?? "butt")) + " J\n" + String(["miter", "round", "bevel"].indexOf(lineJoin ?? "miter")) + " j\n10 M\n",
10789
+ String(["butt", "round", "square"].indexOf(lineCap ?? "butt")) + " J\n" + String(["miter", "round", "bevel"].indexOf(lineJoin ?? "miter")) +
10790
+ " j\n" + n(miterLimit) + " M\n" + dash,
10611
10791
  paint: (fill !== undefined && stroke !== undefined ? "B" : fill !== undefined ? "f" : "S") + (fill !== undefined && fillRule === "evenodd" ? "*" : "") + "\n" };
10612
10792
  }
10613
10793
  function text(value) {
10614
- record(value, ["kind", "text", "x", "y", "font", "fontSize", "color"], "drawing text");
10794
+ record(value, ["kind", "text", "x", "y", "font", "fontSize", "color", "anchor", "rotation"], "drawing text");
10615
10795
  const snapshot = value.text, slot = value.font;
10616
10796
  if (typeof snapshot !== "string")
10617
10797
  throw new TypeError("Drawing text must be a string.");
@@ -10622,14 +10802,33 @@ function captureDrawing(drawing, settings, used) {
10622
10802
  if (!["regular", "bold", "italic", "boldItalic"].includes(slot))
10623
10803
  throw new TypeError("Invalid drawing font slot.");
10624
10804
  const x = coordinate(value.x), y = coordinate(value.y), size = positive(value.fontSize, "Drawing font size"), foreground = color(value.color);
10805
+ const anchor = value.anchor, rotation = value.rotation ?? 0;
10806
+ if (anchor !== undefined && !["start", "middle", "end"].includes(anchor))
10807
+ throw new TypeError("Invalid drawing text anchor.");
10808
+ if (typeof rotation !== "number" || !Number.isFinite(rotation) || Math.abs(rotation) > 360)
10809
+ throw new RangeError("Drawing text rotation must be finite degrees within -360 through 360.");
10625
10810
  settings.budget.cell(snapshot);
10626
- return { kind: "text", text: snapshot, x, y, size, color: foreground, font: slot };
10811
+ // Quarter turns stay exact so upright and vertical axis labels keep integral matrices.
10812
+ const turn = rotation % 90 === 0 ? (((rotation / 90) % 4) + 4) % 4 : -1, radians = rotation * Math.PI / 180;
10813
+ const cos = turn < 0 ? Math.cos(radians) : [1, 0, -1, 0][turn], sin = turn < 0 ? Math.sin(radians) : [0, 1, 0, -1][turn];
10814
+ return { kind: "text", text: snapshot, x, y, size, color: foreground, font: slot, anchor: anchor === "middle" ? .5 : anchor === "end" ? 1 : 0, cos, sin };
10815
+ }
10816
+ function image(value) {
10817
+ record(value, ["kind", "image", "x", "y", "width", "height", "opacity"], "drawing image");
10818
+ const x = coordinate(value.x), y = coordinate(value.y), suppliedOpacity = value.opacity;
10819
+ const opacity = suppliedOpacity === undefined ? 1 : suppliedOpacity;
10820
+ const width = positive(value.width, "Drawing image width", 1000000), height = positive(value.height, "Drawing image height", 1000000);
10821
+ if (typeof opacity !== "number" || !(opacity >= 0 && opacity <= 1))
10822
+ throw new RangeError("Drawing image opacity must be from 0 through 1.");
10823
+ const source = value.image;
10824
+ images.snapshot(source);
10825
+ return { kind: "image", image: source, x, y, width, height, opacity };
10627
10826
  }
10628
10827
  function children(input, depth) {
10629
10828
  if (!Array.isArray(input))
10630
10829
  throw new TypeError("Drawing elements must be an array.");
10631
- if (depth > 32 && input.length)
10632
- throw new RangeError("Drawing groups support at most 32 element levels.");
10830
+ if (depth > pdfDrawingMaxDepth && input.length)
10831
+ throw new RangeError("Drawing groups support at most " + pdfDrawingMaxDepth + " element levels.");
10633
10832
  if (elements + input.length > settings.limits.maxDrawingElements)
10634
10833
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxDrawingElements exceeded.");
10635
10834
  checkAbort(settings.options.signal);
@@ -10647,6 +10846,8 @@ function captureDrawing(drawing, settings, used) {
10647
10846
  output.push(path(value));
10648
10847
  else if (kind === "text")
10649
10848
  output.push(text(value));
10849
+ else if (kind === "image" && version === 2)
10850
+ output.push(image(value));
10650
10851
  else if (kind === "group") {
10651
10852
  record(value, ["kind", "clip", "elements"], "drawing group");
10652
10853
  const clipValue = value.clip, clip = clipValue === undefined ? undefined : clipRectangle(clipValue);
@@ -10663,29 +10864,35 @@ function captureDrawing(drawing, settings, used) {
10663
10864
  }
10664
10865
  const plan = children(root.elements, 1);
10665
10866
  checkAbort(settings.options.signal);
10666
- return { width, height, plan, commands: commands - used.commands, elements: elements - used.elements };
10867
+ return { width, height, plan, commands: commands - used.commands, elements: elements - used.elements, standardFonts: standardFonts === true };
10667
10868
  }
10668
10869
  /** Preflight and paint owned records. The existing font owner retains glyph maps and subsets. */
10669
- async function prepareDrawing(drawing, settings, fonts, used) {
10870
+ async function prepareDrawing(drawing, settings, fonts, used, resources) {
10670
10871
  // A drawing's bounded capture is synchronous; yielding here would leave later caller records borrowed.
10671
- const captured = captureDrawing(drawing, settings, used), drawingFonts = new Map();
10872
+ const { images } = resources, captured = captureDrawing(drawing, settings, used, images), drawingFonts = new Map();
10672
10873
  function fontFor(slot) {
10673
10874
  const existing = drawingFonts.get(slot);
10674
10875
  if (existing)
10675
10876
  return existing;
10676
- const font = fonts.select(slot === "bold" || slot === "boldItalic", slot === "italic" || slot === "boldItalic");
10677
- if (!font.program || font.syntheticBold || font.syntheticItalic)
10877
+ const font = fonts.select(slot === "bold" || slot === "boldItalic", slot === "italic" || slot === "boldItalic", undefined, captured.standardFonts);
10878
+ if (font.syntheticBold || font.syntheticItalic || !font.program && !captured.standardFonts)
10678
10879
  throw new NotSupportedError("Drawing text without an exact embedded font face at fonts." + slot);
10679
10880
  drawingFonts.set(slot, font);
10680
10881
  return font;
10681
10882
  }
10682
10883
  // The work budget belongs to the drawing, including short runs in separate sibling groups.
10683
10884
  let preflightCharacters = 0, preflightElements = 0;
10885
+ const imageNames = new Map();
10684
10886
  async function preflight(nodes) {
10685
10887
  for (let i = 0; i < nodes.length; i++) {
10686
10888
  const node = nodes[i];
10687
10889
  if (node.kind === "group")
10688
10890
  await preflight(node.children);
10891
+ else if (node.kind === "image" && !imageNames.has(node.image)) {
10892
+ const resource = await images.prepare(node.image);
10893
+ resources.registerImage(resource.name, resource.id);
10894
+ imageNames.set(node.image, resource.name);
10895
+ }
10689
10896
  else if (node.kind === "text") {
10690
10897
  const font = fontFor(node.font);
10691
10898
  for (const character of node.text) {
@@ -10728,9 +10935,23 @@ async function prepareDrawing(drawing, settings, fonts, used) {
10728
10935
  }
10729
10936
  add(node.paint);
10730
10937
  }
10938
+ else if (node.kind === "image") {
10939
+ // Image space is a unit square with a bottom-left origin; the drawing's y axis points down.
10940
+ if (node.opacity < 1)
10941
+ add("/" + resources.opacity(node.opacity) + " gs\n");
10942
+ add([node.width, 0, 0, -node.height, node.x, node.y + node.height].map(n).join(" ") + " cm /" + imageNames.get(node.image) + " Do\n");
10943
+ }
10731
10944
  else {
10732
10945
  const font = fontFor(node.font);
10733
- add(node.color + " rg\nBT /" + font.name + " " + n(node.size) + " Tf 0 Tr 1 0 0 -1 " + n(node.x) + " " + n(node.y) + " Tm <");
10946
+ let shift = 0;
10947
+ if (node.anchor) {
10948
+ for (const character of node.text)
10949
+ shift += font.width(character.codePointAt(0));
10950
+ shift *= node.size / 1000 * node.anchor;
10951
+ }
10952
+ // Text space is upright in the drawing's downward y axis; rotation turns the baseline clockwise about its anchor.
10953
+ add(node.color + " rg\nBT /" + font.name + " " + n(node.size) + " Tf 0 Tr " +
10954
+ [node.cos, node.sin, node.sin, -node.cos, node.x - shift * node.cos, node.y - shift * node.sin].map(n).join(" ") + " Tm <");
10734
10955
  let chunk = "";
10735
10956
  for (const character of node.text) {
10736
10957
  chunk += character;
@@ -11453,7 +11674,9 @@ async function writePdfDocumentTo(blocks, destination, configuration = {}) {
11453
11674
  const inputDrawing = block.drawing, capturedCaption = snapshotCaption(block.caption), alternative = graphicAlternative(block, pages.settings), alignment = graphicAlignment(block.alignment);
11454
11675
  if (capturedCaption && alternative === undefined)
11455
11676
  throw new TypeError("A captioned PDF graphic requires alternativeText and cannot be decorative.");
11456
- const drawing = await prepareDrawing(inputDrawing, pages.settings, fonts, { commands, elements: drawingElements }), caption = await prepareCaption(capturedCaption);
11677
+ const drawing = await prepareDrawing(inputDrawing, pages.settings, fonts, { commands, elements: drawingElements }, {
11678
+ images, registerImage: (name, id) => pages.registerXObject(name, id), opacity: alpha => pages.opacityState(alpha)
11679
+ }), caption = await prepareCaption(capturedCaption);
11457
11680
  commands += drawing.commands;
11458
11681
  drawingElements += drawing.elements;
11459
11682
  await flushParagraphs((caption?.height ?? 0) + pages.graphicHeight(drawing.width, drawing.height));
@@ -11828,19 +12051,29 @@ function canopyIdentityValue(value) {
11828
12051
  const original = rawIdentities.get(value);
11829
12052
  return original === undefined ? value.value : original;
11830
12053
  }
11831
- function badgeText(input) {
11832
- if (!Array.isArray(input) || input.length > 64)
11833
- throw new TypeError("Canopy cell badges must be a bounded array of { text, tone?, title? }.");
11834
- const labels = [];
12054
+ // Grids accept any number of badges. Exports keep the first labels that stay readable and fit an Excel text cell,
12055
+ // and report how many were left out instead of failing the whole document.
12056
+ const maximumBadges = 64, maximumCellText = 32767;
12057
+ function badgeText(input, text) {
12058
+ if (!Array.isArray(input))
12059
+ throw new TypeError("Canopy cell badges must be an array of { text, tone?, title? }.");
12060
+ let labels = "", kept = 0, dropped = 0;
11835
12061
  for (const badge of input) {
11836
- const text = typeof badge === "string" ? badge : badge && typeof badge === "object" ? badge.text : undefined;
11837
- if (typeof text !== "string")
11838
- throw new TypeError("Canopy cell badges must be a bounded array of { text, tone?, title? }.");
11839
- const label = text.trim();
11840
- if (label)
11841
- labels.push(label);
12062
+ const value = typeof badge === "string" ? badge : badge && typeof badge === "object" ? badge.text : undefined;
12063
+ if (typeof value !== "string")
12064
+ throw new TypeError("Canopy cell badges must be an array of { text, tone?, title? }.");
12065
+ const label = value.trim();
12066
+ if (!label)
12067
+ continue;
12068
+ const next = labels ? labels + badgeSeparator + label : label;
12069
+ if (kept >= maximumBadges || (text ? text.length + badgeSeparator.length : 0) + next.length > maximumCellText) {
12070
+ dropped++;
12071
+ continue;
12072
+ }
12073
+ labels = next;
12074
+ kept++;
11842
12075
  }
11843
- return labels.length ? labels.join(badgeSeparator) : undefined;
12076
+ return { labels: labels || undefined, dropped };
11844
12077
  }
11845
12078
  /** Map an immutable CanopyX record capture to a writer without querying the grid or retaining its body. */
11846
12079
  function createCanopyExport(capture, format, options = {}) {
@@ -11957,11 +12190,14 @@ function prepareCanopyExport(capture, format, options = {}) {
11957
12190
  // History captures already carry their frozen latest scalar (or null).
11958
12191
  // Columns read by an emitted native rule keep the raw scalar the rule compares, so the label goes to the text only.
11959
12192
  const relativeLabel = spec.kind === "text" && cell.diagnostics?.includes("relative-link") && !ruleOperands.has(spec.id);
11960
- const badges = cell.badges === undefined ? undefined : badgeText(cell.badges);
12193
+ const badged = cell.badges === undefined ? undefined : badgeText(cell.badges, cell.text), badges = badged?.labels;
12194
+ if (badged?.dropped)
12195
+ fallback({ code: "BADGES_TRUNCATED:" + badged.dropped, rowId: row.id, columnId: spec.id });
11961
12196
  const text = badges ? cell.text ? cell.text + badgeSeparator + badges : badges : cell.text;
11962
12197
  // Badges belong to the visible label, so a badged text cell exports that composed label rather than a raw/label hybrid.
11963
12198
  // Typed columns keep their scalar, and native rule operands keep the raw value the rule compares; both carry badges in the text only.
11964
- const badgedValue = !!badges && values === "raw" && !relativeLabel && spec.kind === "text" && !ruleOperands.has(spec.id);
12199
+ // A cell whose badges were all left out still exports its captured label, as it would with the badges.
12200
+ const badgedValue = (!!badges || !!badged?.dropped) && values === "raw" && !relativeLabel && spec.kind === "text" && !ruleOperands.has(spec.id);
11965
12201
  let value = values === "display" || relativeLabel || badgedValue ? text : cell.value;
11966
12202
  if (format === "xlsx" && values === "raw" && spec.kind === "datetime" && typeof value === "string")
11967
12203
  value = datetime(value, dateMode, clock);
@@ -12867,7 +13103,7 @@ return _exports;
12867
13103
  const _m0 = (() => {
12868
13104
  const { BlobByteSink, ExportCell } = _m1;
12869
13105
 
12870
- const { notifyProgress } = _m14;
13106
+ const { notifyProgress, notifySynchronously } = _m14;
12871
13107
 
12872
13108
  const { captureFields } = _m10;
12873
13109
 
@@ -12952,7 +13188,14 @@ async function writeCanopyTo(capture, format, destination, options = {}) {
12952
13188
  freezeHeader: xlsx.sheet?.freezeHeader ?? (xlsx.sheet?.includeHeader !== false),
12953
13189
  freezeColumns: xlsx.sheet?.freezeColumns ?? (pinned ? pinned + (grouped ? 1 : 0) : 0),
12954
13190
  conditionalFormats: [...rules, ...(xlsx.sheet?.conditionalFormats ?? [])] };
12955
- const settings = { ...xlsx, ...stream, columns: source.columns, sheet, dateMode: xlsx.dateMode ?? request.timeZone, limits: formatLimits };
13191
+ // Data-cell links past Excel's per-worksheet limit keep their label; the worksheet reserves every link it cannot drop.
13192
+ const linkFallback = canopyDiagnostics(format, { ...selected, unsupportedPresentation: "text" }), onHyperlinkOverflow = xlsx.onHyperlinkOverflow;
13193
+ const settings = { ...xlsx, ...stream, columns: source.columns, sheet, dateMode: xlsx.dateMode ?? request.timeZone, limits: formatLimits,
13194
+ hyperlinkOverflow: xlsx.hyperlinkOverflow ?? "drop",
13195
+ onHyperlinkOverflow: (overflow) => {
13196
+ notifySynchronously("onHyperlinkOverflow", onHyperlinkOverflow, overflow);
13197
+ linkFallback({ code: "LINKS_TRUNCATED:" + overflow.dropped });
13198
+ } };
12956
13199
  if (grouped || about)
12957
13200
  return writeCanopyWorkbook(source, grouped, destination, settings, capturedLabels, about);
12958
13201
  return writeXlsxTo(source.rows(), destination, settings);