@yudaocode/univer-pdfs 1.6.209 → 1.6.211

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.
package/lib/cjs/index.js CHANGED
@@ -134,6 +134,7 @@ __export(src_exports, {
134
134
  applyOcrToUnitPage: () => applyOcrToUnitPage,
135
135
  autoDetectFormFieldsOnPage: () => autoDetectFormFieldsOnPage,
136
136
  buildMinimalTestTrueTypeFont: () => buildMinimalTestTrueTypeFont,
137
+ buildOverlayImportCandidateSnapshot: () => buildOverlayImportCandidateSnapshot,
137
138
  buildPdfTemplateFromOcrFields: () => buildPdfTemplateFromOcrFields,
138
139
  canonicalJsonStringify: () => canonicalJsonStringify,
139
140
  cmykToRgb: () => cmykToRgb,
@@ -243,6 +244,7 @@ __export(src_exports, {
243
244
  normalizeBarcodeFormatType: () => normalizeBarcodeFormatType,
244
245
  normalizeBarcodePayloadForFormat: () => normalizeBarcodePayloadForFormat,
245
246
  normalizeImageCrop: () => normalizeImageCrop,
247
+ normalizePdfImportWarnings: () => normalizePdfImportWarnings,
246
248
  optimizePdfUnit: () => optimizePdfUnit,
247
249
  organizePdfBytes: () => organizePdfBytes,
248
250
  overlayDiagnosticGridOnPdfBytes: () => overlayDiagnosticGridOnPdfBytes,
@@ -22322,6 +22324,271 @@ function hasPdfMagicHeader(bytes) {
22322
22324
  }
22323
22325
  return false;
22324
22326
  }
22327
+ function countJsInActionDict(actionDict, doc, PDFArrayCtor, PDFDictCtor, PDFNameCtor, visited = /* @__PURE__ */ new Set()) {
22328
+ if (!actionDict || visited.has(actionDict)) return 0;
22329
+ visited.add(actionDict);
22330
+ let count = 0;
22331
+ const actionType = actionDict.get?.(PDFNameCtor.of("S"))?.toString?.() || "";
22332
+ const hasJsEntry = actionDict.get?.(PDFNameCtor.of("JS")) !== void 0;
22333
+ if (actionType === "/JavaScript" || hasJsEntry) {
22334
+ count += 1;
22335
+ }
22336
+ const nextObj = actionDict.lookup?.(PDFNameCtor.of("Next"));
22337
+ if (nextObj instanceof PDFDictCtor) {
22338
+ count += countJsInActionDict(nextObj, doc, PDFArrayCtor, PDFDictCtor, PDFNameCtor, visited);
22339
+ } else if (nextObj instanceof PDFArrayCtor) {
22340
+ for (let i = 0; i < nextObj.size(); i++) {
22341
+ const sub = nextObj.lookupMaybe(i, PDFDictCtor);
22342
+ if (sub) {
22343
+ count += countJsInActionDict(sub, doc, PDFArrayCtor, PDFDictCtor, PDFNameCtor, visited);
22344
+ }
22345
+ }
22346
+ }
22347
+ return count;
22348
+ }
22349
+ function inspectPdfDocumentImportWarnings(doc, pdfLib) {
22350
+ const { PDFArray: PDFArray6, PDFDict: PDFDict6, PDFName: PDFName6 } = pdfLib;
22351
+ const warnings = [];
22352
+ let acroFieldCount = 0;
22353
+ const acroFormDict = doc.catalog.lookupMaybe(PDFName6.of("AcroForm"), PDFDict6);
22354
+ if (acroFormDict) {
22355
+ try {
22356
+ acroFieldCount = doc.getForm().getFields().length;
22357
+ } catch {
22358
+ const fieldsArr = acroFormDict.lookupMaybe(PDFName6.of("Fields"), PDFArray6);
22359
+ if (fieldsArr) {
22360
+ acroFieldCount = fieldsArr.size();
22361
+ }
22362
+ }
22363
+ }
22364
+ let jsCount = 0;
22365
+ const namesDict = doc.catalog.lookupMaybe(PDFName6.of("Names"), PDFDict6);
22366
+ const jsNameTree = namesDict?.lookupMaybe(PDFName6.of("JavaScript"), PDFDict6);
22367
+ if (jsNameTree) {
22368
+ const namesArr = jsNameTree.lookupMaybe(PDFName6.of("Names"), PDFArray6);
22369
+ jsCount += namesArr ? Math.max(1, Math.floor(namesArr.size() / 2)) : 1;
22370
+ }
22371
+ const openAction = doc.catalog.lookupMaybe(PDFName6.of("OpenAction"), PDFDict6);
22372
+ if (openAction) {
22373
+ jsCount += countJsInActionDict(openAction, doc, PDFArray6, PDFDict6, PDFName6);
22374
+ }
22375
+ const catalogAA = doc.catalog.lookupMaybe(PDFName6.of("AA"), PDFDict6);
22376
+ if (catalogAA) {
22377
+ for (const [, actionRef] of catalogAA.entries()) {
22378
+ const act = doc.context.lookupMaybe(actionRef, PDFDict6);
22379
+ if (act) {
22380
+ jsCount += countJsInActionDict(act, doc, PDFArray6, PDFDict6, PDFName6);
22381
+ }
22382
+ }
22383
+ }
22384
+ let activeAnnotationCount = 0;
22385
+ let orphanWidgetCount = 0;
22386
+ for (const page of doc.getPages()) {
22387
+ const pageAA = page.node.lookupMaybe(PDFName6.of("AA"), PDFDict6);
22388
+ if (pageAA) {
22389
+ for (const [, actionRef] of pageAA.entries()) {
22390
+ const act = doc.context.lookupMaybe(actionRef, PDFDict6);
22391
+ if (act) {
22392
+ jsCount += countJsInActionDict(act, doc, PDFArray6, PDFDict6, PDFName6);
22393
+ }
22394
+ }
22395
+ }
22396
+ const annots = page.node.Annots();
22397
+ if (annots instanceof PDFArray6) {
22398
+ for (let i = 0; i < annots.size(); i++) {
22399
+ const annot = annots.lookupMaybe(i, PDFDict6);
22400
+ if (!annot) continue;
22401
+ const subtypeObj = annot.get(PDFName6.of("Subtype"));
22402
+ const subtype = subtypeObj ? subtypeObj.toString() : "";
22403
+ if (subtype === "/Widget") {
22404
+ orphanWidgetCount += 1;
22405
+ } else if (subtype !== "/Popup") {
22406
+ activeAnnotationCount += 1;
22407
+ }
22408
+ const annotAction = annot.lookupMaybe(PDFName6.of("A"), PDFDict6);
22409
+ if (annotAction) {
22410
+ jsCount += countJsInActionDict(annotAction, doc, PDFArray6, PDFDict6, PDFName6);
22411
+ }
22412
+ const annotAA = annot.lookupMaybe(PDFName6.of("AA"), PDFDict6);
22413
+ if (annotAA) {
22414
+ for (const [, actionRef] of annotAA.entries()) {
22415
+ const act = doc.context.lookupMaybe(actionRef, PDFDict6);
22416
+ if (act) {
22417
+ jsCount += countJsInActionDict(act, doc, PDFArray6, PDFDict6, PDFName6);
22418
+ }
22419
+ }
22420
+ }
22421
+ }
22422
+ }
22423
+ }
22424
+ const totalAcroFields = acroFieldCount > 0 ? acroFieldCount : orphanWidgetCount;
22425
+ if (totalAcroFields > 0) {
22426
+ warnings.push({
22427
+ code: "ACROFORM_FIELDS_DETECTED",
22428
+ message: `\u68C0\u6D4B\u5230 ${totalAcroFields} \u4E2A\u4EA4\u4E92\u5F0F AcroForm \u8868\u5355\u57DF\uFF0C\u5E95\u56FE\u53E0\u52A0\u6A21\u5F0F\u4E0B\u5C06\u6309\u9759\u6001\u9875\u9762\u4FDD\u7559\u3002`,
22429
+ count: totalAcroFields
22430
+ });
22431
+ }
22432
+ if (jsCount > 0) {
22433
+ warnings.push({
22434
+ code: "EMBEDDED_JAVASCRIPT_DETECTED",
22435
+ message: `\u68C0\u6D4B\u5230 ${jsCount} \u5904\u5185\u5D4C PDF JavaScript \u811A\u672C\uFF0C\u5BFC\u5165\u4E0E\u5BFC\u51FA\u65F6\u5DF2\u7981\u7528\u811A\u672C\u6267\u884C\u3002`,
22436
+ count: jsCount
22437
+ });
22438
+ }
22439
+ if (activeAnnotationCount > 0) {
22440
+ warnings.push({
22441
+ code: "ACTIVE_ANNOTATIONS_DETECTED",
22442
+ message: `\u68C0\u6D4B\u5230 ${activeAnnotationCount} \u4E2A\u6D3B\u52A8\u6279\u6CE8\u6216\u94FE\u63A5\u5BF9\u8C61\uFF0C\u5E95\u56FE\u53E0\u52A0\u6A21\u5F0F\u4E0B\u5C06\u6309\u9759\u6001\u5916\u89C2\u4FDD\u7559\u3002`,
22443
+ count: activeAnnotationCount
22444
+ });
22445
+ }
22446
+ return warnings;
22447
+ }
22448
+ function normalizePdfImportWarnings(raw) {
22449
+ if (!Array.isArray(raw)) return [];
22450
+ const normalized = [];
22451
+ for (let i = 0; i < raw.length; i++) {
22452
+ const item = raw[i];
22453
+ if (typeof item === "string") {
22454
+ const trimmed = item.trim();
22455
+ if (trimmed) {
22456
+ normalized.push({
22457
+ code: `IMPORT_WARNING_${i + 1}`,
22458
+ message: trimmed
22459
+ });
22460
+ }
22461
+ } else if (item && typeof item === "object" && typeof item.message === "string") {
22462
+ normalized.push({
22463
+ code: item.code || `IMPORT_WARNING_${i + 1}`,
22464
+ message: item.message,
22465
+ ...typeof item.count === "number" ? { count: item.count } : {}
22466
+ });
22467
+ }
22468
+ }
22469
+ return normalized;
22470
+ }
22471
+ function buildOverlayImportCandidateSnapshot(baseSnapshot, outcome) {
22472
+ const prevSnapshot = import_core10.Tools.deepClone(baseSnapshot);
22473
+ const existingOrder = prevSnapshot.document?.pageOrder ?? [];
22474
+ const pageSizes = outcome.pageSizes ?? [];
22475
+ const totalPages = Math.max(1, pageSizes.length || outcome.sourceDocumentRef.pageCount || 1);
22476
+ const nextPages = {};
22477
+ const nextPageOrder = [];
22478
+ const nextElementsByPage = import_core10.Tools.deepClone(prevSnapshot.editState?.elementsByPage ?? {});
22479
+ const nextElementOrderByPage = import_core10.Tools.deepClone(prevSnapshot.editState?.elementOrderByPage ?? {});
22480
+ for (let i = 0; i < totalPages; i++) {
22481
+ const pid = existingOrder[i] || `page-${(0, import_core10.generateRandomId)(6)}`;
22482
+ nextPageOrder.push(pid);
22483
+ const resolvedSize = pageSizes[i] ?? pageSizes[0] ?? prevSnapshot.document.pageSize;
22484
+ nextPages[pid] = {
22485
+ id: pid,
22486
+ title: `Page ${i + 1}`,
22487
+ sourcePageNumber: i + 1,
22488
+ pageSize: import_core10.Tools.deepClone(resolvedSize),
22489
+ backgroundColor: "#ffffff"
22490
+ };
22491
+ if (!nextElementsByPage[pid]) nextElementsByPage[pid] = {};
22492
+ if (!nextElementOrderByPage[pid]) nextElementOrderByPage[pid] = [];
22493
+ }
22494
+ return {
22495
+ ...prevSnapshot,
22496
+ sourceDocumentRef: import_core10.Tools.deepClone(outcome.sourceDocumentRef),
22497
+ document: {
22498
+ ...prevSnapshot.document,
22499
+ pageSize: import_core10.Tools.deepClone(pageSizes[0] ?? prevSnapshot.document.pageSize),
22500
+ pages: nextPages,
22501
+ pageOrder: nextPageOrder
22502
+ },
22503
+ editState: {
22504
+ ...prevSnapshot.editState,
22505
+ elementsByPage: nextElementsByPage,
22506
+ elementOrderByPage: nextElementOrderByPage
22507
+ }
22508
+ };
22509
+ }
22510
+ function normalizeAdapterImportResult(raw) {
22511
+ if (!raw || typeof raw !== "object") {
22512
+ throw new Error("[UniverPdfs] Invalid importPdf result: expected an IPdfImportOutcome or IPdfUnitData object.");
22513
+ }
22514
+ const record = raw;
22515
+ if (record.mode === "overlay") {
22516
+ const warnings = normalizePdfImportWarnings(record.warnings);
22517
+ return {
22518
+ outcome: {
22519
+ mode: "overlay",
22520
+ sourceDocumentRef: import_core10.Tools.deepClone(record.sourceDocumentRef),
22521
+ pageSizes: import_core10.Tools.deepClone(record.pageSizes ?? []),
22522
+ ...warnings.length > 0 ? { warnings } : {}
22523
+ },
22524
+ warnings
22525
+ };
22526
+ }
22527
+ if (record.mode === "snapshot") {
22528
+ const warnings = normalizePdfImportWarnings(record.warnings);
22529
+ const clonedSnapshot = import_core10.Tools.deepClone(record.snapshot);
22530
+ return {
22531
+ outcome: {
22532
+ mode: "snapshot",
22533
+ snapshot: clonedSnapshot,
22534
+ ...warnings.length > 0 ? { warnings } : {}
22535
+ },
22536
+ warnings
22537
+ };
22538
+ }
22539
+ if (record.snapshot && typeof record.snapshot === "object") {
22540
+ const warnings = normalizePdfImportWarnings(record.warnings);
22541
+ const clonedSnapshot = import_core10.Tools.deepClone(record.snapshot);
22542
+ return {
22543
+ outcome: {
22544
+ mode: "snapshot",
22545
+ snapshot: clonedSnapshot,
22546
+ ...warnings.length > 0 ? { warnings } : {}
22547
+ },
22548
+ warnings
22549
+ };
22550
+ }
22551
+ if ("schema" in record || "document" in record) {
22552
+ const warnings = normalizePdfImportWarnings(record.warnings);
22553
+ const clonedSnapshot = import_core10.Tools.deepClone(record);
22554
+ delete clonedSnapshot.warnings;
22555
+ return {
22556
+ outcome: {
22557
+ mode: "snapshot",
22558
+ snapshot: clonedSnapshot,
22559
+ ...warnings.length > 0 ? { warnings } : {}
22560
+ },
22561
+ warnings
22562
+ };
22563
+ }
22564
+ throw new Error("[UniverPdfs] Unsupported importPdf adapter return payload.");
22565
+ }
22566
+ function normalizeFormatKeys(formats) {
22567
+ if (!Array.isArray(formats)) return [];
22568
+ return formats.map((f) => String(f || "").trim().replace(/^\./, "").toLowerCase()).filter(Boolean);
22569
+ }
22570
+ function detectImportFileFormat(file) {
22571
+ const lowerName = String(file?.name || "").toLowerCase();
22572
+ const mime = String(file?.type || "").toLowerCase();
22573
+ if (lowerName.endsWith(".json") || mime === "application/json") {
22574
+ return "json";
22575
+ }
22576
+ return "pdf";
22577
+ }
22578
+ function attachSuggestedFallbackAndThrow(err, fallback) {
22579
+ if (err && typeof err === "object") {
22580
+ if (!err.suggestedFallback) {
22581
+ try {
22582
+ err.suggestedFallback = fallback;
22583
+ } catch {
22584
+ }
22585
+ }
22586
+ throw err;
22587
+ }
22588
+ const wrapped = new Error(String(err));
22589
+ wrapped.suggestedFallback = fallback;
22590
+ throw wrapped;
22591
+ }
22325
22592
  async function importPdfSource(source, options) {
22326
22593
  let bytes;
22327
22594
  let fileName = options?.fileName || "imported.pdf";
@@ -22365,8 +22632,9 @@ async function importPdfSource(source, options) {
22365
22632
  "Invalid PDF binary: missing %PDF- header signature."
22366
22633
  );
22367
22634
  }
22368
- const { PDFDocument: PDFDocument6 } = await import("pdf-lib");
22635
+ const { PDFArray: PDFArray6, PDFDict: PDFDict6, PDFDocument: PDFDocument6, PDFName: PDFName6 } = await import("pdf-lib");
22369
22636
  let pageSizes = [];
22637
+ let warnings = [];
22370
22638
  try {
22371
22639
  const doc = await PDFDocument6.load(bytes);
22372
22640
  if (doc.isEncrypted && !options?.password) {
@@ -22383,6 +22651,7 @@ async function importPdfSource(source, options) {
22383
22651
  const { width, height } = p.getSize();
22384
22652
  return { width, height, preset: "CUSTOM" };
22385
22653
  });
22654
+ warnings = inspectPdfDocumentImportWarnings(doc, { PDFArray: PDFArray6, PDFDict: PDFDict6, PDFName: PDFName6 });
22386
22655
  } catch (err) {
22387
22656
  if (err instanceof PdfImportError) {
22388
22657
  throw err;
@@ -22450,6 +22719,7 @@ async function importPdfSource(source, options) {
22450
22719
  const { width, height } = p.getSize();
22451
22720
  return { width, height, preset: "CUSTOM" };
22452
22721
  });
22722
+ warnings = inspectPdfDocumentImportWarnings(doc, { PDFArray: PDFArray6, PDFDict: PDFDict6, PDFName: PDFName6 });
22453
22723
  } catch (fallbackErr) {
22454
22724
  if (fallbackErr instanceof PdfImportError) throw fallbackErr;
22455
22725
  throw new PdfImportError(
@@ -22474,15 +22744,57 @@ async function importPdfSource(source, options) {
22474
22744
  dataUri,
22475
22745
  pageCount: pageSizes.length
22476
22746
  },
22477
- pageSizes
22747
+ pageSizes,
22748
+ warnings
22478
22749
  };
22479
22750
  }
22480
- async function fallbackReadFileAsOverlay(file, password) {
22481
- return importPdfSource(file, { fileName: file.name || "imported.pdf", password });
22751
+ async function fallbackReadFileAsOutcome(file, baseSnapshot, password) {
22752
+ if (detectImportFileFormat(file) === "json") {
22753
+ const rawText = typeof file.text === "function" ? await file.text() : new TextDecoder().decode(await file.arrayBuffer());
22754
+ let parsed;
22755
+ try {
22756
+ parsed = JSON.parse(rawText);
22757
+ } catch (err) {
22758
+ throw new PdfImportError(
22759
+ "INVALID_PDF_HEADER",
22760
+ `JSON \u6A21\u677F\u89E3\u6790\u5931\u8D25: ${err?.message || String(err)}`
22761
+ );
22762
+ }
22763
+ if (parsed?.schema === UNIVER_PDF_SCHEMA || parsed?.document && parsed?.editState) {
22764
+ return {
22765
+ mode: "snapshot",
22766
+ snapshot: createDefaultPdfUnitData({
22767
+ ...parsed,
22768
+ id: parsed.id || baseSnapshot.id
22769
+ })
22770
+ };
22771
+ }
22772
+ if (parsed?.schemas && Array.isArray(parsed.schemas)) {
22773
+ return {
22774
+ mode: "snapshot",
22775
+ snapshot: fromPdfmeTemplate(parsed, {
22776
+ id: baseSnapshot.id,
22777
+ name: (file.name || baseSnapshot.name || "Imported Template").replace(/\.json$/i, "")
22778
+ })
22779
+ };
22780
+ }
22781
+ throw new PdfImportError(
22782
+ "INVALID_PDF_HEADER",
22783
+ "\u672A\u8BC6\u522B\u7684 JSON \u6A21\u677F\u683C\u5F0F\uFF1A\u8BF7\u63D0\u4F9B\u6807\u51C6 IPdfUnitData \u6216 pdfme Template JSON\u3002"
22784
+ );
22785
+ }
22786
+ const imported = await importPdfSource(file, { fileName: file.name || "imported.pdf", password });
22787
+ return {
22788
+ mode: "overlay",
22789
+ sourceDocumentRef: imported.sourceDocumentRef,
22790
+ pageSizes: imported.pageSizes,
22791
+ ...imported.warnings?.length ? { warnings: imported.warnings } : {}
22792
+ };
22482
22793
  }
22483
22794
  var PdfIoService = class extends import_core10.Disposable {
22484
- constructor() {
22795
+ constructor(_univerInstanceService) {
22485
22796
  super();
22797
+ this._univerInstanceService = _univerInstanceService;
22486
22798
  this._adapter$ = new import_rxjs3.BehaviorSubject({ name: "frontend-default" });
22487
22799
  this.adapter$ = this._adapter$.asObservable();
22488
22800
  this._exported$ = new import_rxjs3.Subject();
@@ -22535,17 +22847,33 @@ var PdfIoService = class extends import_core10.Disposable {
22535
22847
  return this._adapter$.getValue();
22536
22848
  }
22537
22849
  setAdapter(adapter) {
22850
+ if (adapter.defaultIoTarget !== void 0) {
22851
+ this._serviceDefaultIoTarget = void 0;
22852
+ }
22538
22853
  this._adapter$.next({
22539
22854
  name: adapter.name ?? "custom-adapter",
22540
22855
  ...adapter
22541
22856
  });
22542
22857
  }
22543
22858
  patchAdapter(patch) {
22859
+ if (patch.defaultIoTarget !== void 0) {
22860
+ this._serviceDefaultIoTarget = void 0;
22861
+ }
22544
22862
  this._adapter$.next({
22545
22863
  ...this._adapter$.getValue(),
22546
22864
  ...patch
22547
22865
  });
22548
22866
  }
22867
+ getDefaultIoTarget() {
22868
+ return this._serviceDefaultIoTarget ?? this._adapter$.getValue().defaultIoTarget ?? "auto";
22869
+ }
22870
+ setDefaultIoTarget(target) {
22871
+ const normalized = target === "browser" || target === "server" || target === "auto" ? target : "auto";
22872
+ this._serviceDefaultIoTarget = normalized;
22873
+ this._adapter$.next({
22874
+ ...this._adapter$.getValue()
22875
+ });
22876
+ }
22549
22877
  getAiCopilotAdapter() {
22550
22878
  return this._aiCopilotAdapter;
22551
22879
  }
@@ -22582,7 +22910,53 @@ var PdfIoService = class extends import_core10.Disposable {
22582
22910
  }
22583
22911
  getIoCapabilities() {
22584
22912
  const adapter = this._adapter$.getValue();
22585
- const hasServerIo = Boolean(adapter.importPdf || adapter.exportPdf);
22913
+ const defaultIoTarget = this.getDefaultIoTarget();
22914
+ const serverImportPdf = Boolean(adapter.importPdf);
22915
+ const serverExportPdf = Boolean(adapter.exportPdf);
22916
+ const hasServerIo = serverImportPdf || serverExportPdf;
22917
+ const recommendedDefaultTarget = defaultIoTarget === "browser" ? "browser" : defaultIoTarget === "server" ? "server" : hasServerIo ? "server" : "browser";
22918
+ const browserFmtCfg = adapter.browserFormats && typeof adapter.browserFormats === "object" ? adapter.browserFormats : void 0;
22919
+ const browserImportList = browserFmtCfg?.import ? normalizeFormatKeys(browserFmtCfg.import) : null;
22920
+ const browserExportList = browserFmtCfg?.export ? normalizeFormatKeys(browserFmtCfg.export) : null;
22921
+ const serverImportList = adapter.serverFormats?.import ? normalizeFormatKeys(adapter.serverFormats.import) : null;
22922
+ const serverExportList = adapter.serverFormats?.export ? normalizeFormatKeys(adapter.serverFormats.export) : null;
22923
+ const importFormatKeys = /* @__PURE__ */ new Set([
22924
+ "pdf",
22925
+ "json",
22926
+ ...browserImportList ?? [],
22927
+ ...serverImportList ?? []
22928
+ ]);
22929
+ const exportFormatKeys = /* @__PURE__ */ new Set([
22930
+ "pdf",
22931
+ "json",
22932
+ ...browserExportList ?? [],
22933
+ ...serverExportList ?? []
22934
+ ]);
22935
+ const resolveTargetForCap = (serverSupported) => {
22936
+ if (defaultIoTarget === "server") return "server";
22937
+ if (defaultIoTarget === "browser") return "browser";
22938
+ return serverSupported ? "server" : "browser";
22939
+ };
22940
+ const importFormats = {};
22941
+ for (const fmt of importFormatKeys) {
22942
+ const browserSupported = adapter.browserFormats === false ? false : browserImportList !== null ? browserImportList.includes(fmt) : fmt === "pdf" || fmt === "json";
22943
+ const serverSupported = !serverImportPdf ? false : serverImportList !== null ? serverImportList.includes(fmt) : fmt === "pdf";
22944
+ importFormats[fmt] = {
22945
+ browser: browserSupported,
22946
+ server: serverSupported,
22947
+ defaultTarget: resolveTargetForCap(serverSupported)
22948
+ };
22949
+ }
22950
+ const exportFormats = {};
22951
+ for (const fmt of exportFormatKeys) {
22952
+ const browserSupported = adapter.browserFormats === false ? false : browserExportList !== null ? browserExportList.includes(fmt) : fmt === "pdf" || fmt === "json";
22953
+ const serverSupported = fmt === "pdf" ? serverExportPdf && (serverExportList !== null ? serverExportList.includes("pdf") : true) : Boolean(adapter.exportPdf || adapter.onSave) && serverExportList !== null && serverExportList.includes(fmt);
22954
+ exportFormats[fmt] = {
22955
+ browser: browserSupported,
22956
+ server: serverSupported,
22957
+ defaultTarget: resolveTargetForCap(serverSupported)
22958
+ };
22959
+ }
22586
22960
  return {
22587
22961
  browser: {
22588
22962
  importOverlayPdf: true,
@@ -22591,39 +22965,106 @@ var PdfIoService = class extends import_core10.Disposable {
22591
22965
  },
22592
22966
  server: {
22593
22967
  adapterName: adapter.name || "frontend-default",
22594
- importPdf: Boolean(adapter.importPdf),
22595
- exportPdf: Boolean(adapter.exportPdf),
22968
+ importPdf: serverImportPdf,
22969
+ exportPdf: serverExportPdf,
22596
22970
  onSave: Boolean(adapter.onSave),
22597
22971
  silentPrint: Boolean(adapter.onSilentPrint)
22598
22972
  },
22599
- recommendedDefaultTarget: hasServerIo ? "server" : "browser"
22973
+ defaultIoTarget,
22974
+ recommendedDefaultTarget,
22975
+ formats: {
22976
+ import: importFormats,
22977
+ export: exportFormats
22978
+ }
22979
+ };
22980
+ }
22981
+ _resolveBaseSnapshotForImport(context) {
22982
+ if (context?.snapshot) {
22983
+ const cloned = import_core10.Tools.deepClone(context.snapshot);
22984
+ return {
22985
+ unitId: context.unitId || cloned.id,
22986
+ baseSnapshot: cloned
22987
+ };
22988
+ }
22989
+ if (this._univerInstanceService) {
22990
+ const unit = context?.unitId ? this._univerInstanceService.getUnit(
22991
+ context.unitId,
22992
+ import_core10.UniverInstanceType.UNIVER_PDF
22993
+ ) : this._univerInstanceService.getCurrentUnitOfType(
22994
+ import_core10.UniverInstanceType.UNIVER_PDF
22995
+ );
22996
+ if (unit) {
22997
+ return {
22998
+ unitId: unit.getUnitId(),
22999
+ baseSnapshot: unit.save()
23000
+ };
23001
+ }
23002
+ }
23003
+ const fallback = createDefaultPdfUnitData(
23004
+ context?.unitId ? { id: context.unitId } : void 0
23005
+ );
23006
+ return {
23007
+ unitId: fallback.id,
23008
+ baseSnapshot: fallback
22600
23009
  };
22601
23010
  }
22602
23011
  async importPdf(file, context) {
22603
- const defaultImport = context.defaultImport ?? ((f) => fallbackReadFileAsOverlay(f, context.password));
23012
+ const report = await this.importPdfWithReport(file, context);
23013
+ return report.outcome;
23014
+ }
23015
+ async importPdfWithReport(file, context) {
23016
+ const { unitId, baseSnapshot } = this._resolveBaseSnapshotForImport(context);
22604
23017
  const adapter = this._adapter$.getValue();
22605
- const requested = context.target ?? "auto";
22606
- const effective = requested === "auto" ? adapter.importPdf ? "server" : "browser" : requested;
23018
+ const caps = this.getIoCapabilities();
23019
+ const fmt = detectImportFileFormat(file);
23020
+ const fmtCap = caps.formats.import[fmt] ?? caps.formats.import.pdf;
23021
+ const requested = context?.target ?? this.getDefaultIoTarget();
23022
+ const effective = requested === "auto" ? fmtCap.defaultTarget : requested;
23023
+ const defaultImport = async (f) => {
23024
+ if (context?.defaultImport) {
23025
+ const customRaw = await context.defaultImport(f);
23026
+ return normalizeAdapterImportResult(customRaw).outcome;
23027
+ }
23028
+ return fallbackReadFileAsOutcome(f, baseSnapshot, context?.password);
23029
+ };
23030
+ let rawResult;
22607
23031
  if (effective === "server") {
22608
- if (!adapter.importPdf) {
23032
+ if (!adapter.importPdf || !fmtCap.server) {
22609
23033
  throw new PdfIoTargetError(
22610
23034
  "\u5F53\u524D\u672A\u914D\u7F6E\u670D\u52A1\u7AEF PDF \u5BFC\u5165\u63A5\u53E3\uFF08importPdf\uFF09\uFF0C\u672A\u81EA\u52A8\u964D\u7EA7\u81F3\u6D4F\u89C8\u5668\u7AEF\uFF1B\u8BF7\u5148\u63A5\u5165\u670D\u52A1\u7AEF\u9002\u914D\u5668\u6216\u6539\u9009\u300C\u6D4F\u89C8\u5668\u5904\u7406\u300D"
22611
23035
  );
22612
23036
  }
22613
- return adapter.importPdf(file, {
22614
- unitId: context.unitId,
22615
- snapshot: context.snapshot,
22616
- defaultImport
22617
- });
22618
- }
22619
- try {
22620
- return await defaultImport(file);
22621
- } catch (err) {
22622
- if (err && typeof err === "object") {
22623
- err.suggestedFallback = "server";
23037
+ try {
23038
+ rawResult = await adapter.importPdf(file, {
23039
+ unitId,
23040
+ snapshot: import_core10.Tools.deepClone(baseSnapshot),
23041
+ defaultImport
23042
+ });
23043
+ } catch (err) {
23044
+ attachSuggestedFallbackAndThrow(err, "browser");
23045
+ }
23046
+ } else {
23047
+ if (!context?.defaultImport && !fmtCap.browser) {
23048
+ attachSuggestedFallbackAndThrow(
23049
+ new Error(`\u5F53\u524D\u6D4F\u89C8\u5668\u7AEF\u672A\u542F\u7528 .${fmt} \u683C\u5F0F\u5BFC\u5165\uFF1B\u8BF7\u5207\u6362\u4E3A\u300C\u670D\u52A1\u7AEF\u5904\u7406\u300D\u91CD\u8BD5`),
23050
+ "server"
23051
+ );
23052
+ }
23053
+ try {
23054
+ rawResult = context?.defaultImport ? await context.defaultImport(file) : await fallbackReadFileAsOutcome(file, baseSnapshot, context?.password);
23055
+ } catch (err) {
23056
+ attachSuggestedFallbackAndThrow(err, "server");
22624
23057
  }
22625
- throw err;
22626
23058
  }
23059
+ const { outcome, warnings } = normalizeAdapterImportResult(rawResult);
23060
+ const candidateSnapshot = outcome.mode === "snapshot" ? import_core10.Tools.deepClone(outcome.snapshot) : buildOverlayImportCandidateSnapshot(baseSnapshot, outcome);
23061
+ return {
23062
+ snapshot: candidateSnapshot,
23063
+ outcome,
23064
+ warnings,
23065
+ executedBy: effective,
23066
+ fileName: file?.name || (outcome.mode === "overlay" ? outcome.sourceDocumentRef.fileName : candidateSnapshot.name) || void 0
23067
+ };
22627
23068
  }
22628
23069
  async exportPdf(params) {
22629
23070
  const beforeEvent = {
@@ -22638,22 +23079,29 @@ var PdfIoService = class extends import_core10.Disposable {
22638
23079
  }
22639
23080
  const defaultExport = () => exportPdfBytes(params.snapshot, params.data, params.options);
22640
23081
  const adapter = this._adapter$.getValue();
22641
- const requested = params.target ?? "auto";
22642
- const effective = requested === "auto" ? adapter.exportPdf ? "server" : "browser" : requested;
23082
+ const caps = this.getIoCapabilities();
23083
+ const pdfExportCap = caps.formats.export.pdf;
23084
+ const requested = params.target ?? this.getDefaultIoTarget();
23085
+ const effective = requested === "auto" ? pdfExportCap.defaultTarget : requested;
22643
23086
  if (effective === "server") {
22644
- if (!adapter.exportPdf) {
23087
+ if (!adapter.exportPdf || !pdfExportCap.server) {
22645
23088
  throw new PdfIoTargetError(
22646
23089
  "\u5F53\u524D\u672A\u914D\u7F6E\u670D\u52A1\u7AEF PDF \u5BFC\u51FA\u63A5\u53E3\uFF08exportPdf\uFF09\uFF0C\u672A\u81EA\u52A8\u964D\u7EA7\u81F3\u6D4F\u89C8\u5668\u7AEF\uFF1B\u8BF7\u5148\u63A5\u5165\u670D\u52A1\u7AEF\u9002\u914D\u5668\u6216\u6539\u9009\u300C\u6D4F\u89C8\u5668\u5904\u7406\u300D"
22647
23090
  );
22648
23091
  }
22649
- const raw = await adapter.exportPdf({
22650
- unitId: params.unitId,
22651
- snapshot: params.snapshot,
22652
- data: params.data,
22653
- options: params.options,
22654
- defaultExport
22655
- });
22656
- const bytes = await normalizeBinaryToUint8Array(raw);
23092
+ let bytes;
23093
+ try {
23094
+ const raw = await adapter.exportPdf({
23095
+ unitId: params.unitId,
23096
+ snapshot: params.snapshot,
23097
+ data: params.data,
23098
+ options: params.options,
23099
+ defaultExport
23100
+ });
23101
+ bytes = await normalizeBinaryToUint8Array(raw);
23102
+ } catch (err) {
23103
+ attachSuggestedFallbackAndThrow(err, "browser");
23104
+ }
22657
23105
  this.notifyExported({
22658
23106
  unitId: params.unitId,
22659
23107
  bytes,
@@ -22662,6 +23110,12 @@ var PdfIoService = class extends import_core10.Disposable {
22662
23110
  });
22663
23111
  return bytes;
22664
23112
  }
23113
+ if (!pdfExportCap.browser) {
23114
+ attachSuggestedFallbackAndThrow(
23115
+ new Error("\u5F53\u524D\u6D4F\u89C8\u5668\u7AEF\u672A\u542F\u7528 PDF \u5BFC\u51FA\uFF1B\u8BF7\u5207\u6362\u4E3A\u300C\u670D\u52A1\u7AEF\u5904\u7406\u300D\u91CD\u8BD5"),
23116
+ "server"
23117
+ );
23118
+ }
22665
23119
  try {
22666
23120
  const bytes = await defaultExport();
22667
23121
  this.notifyExported({
@@ -22672,10 +23126,7 @@ var PdfIoService = class extends import_core10.Disposable {
22672
23126
  });
22673
23127
  return bytes;
22674
23128
  } catch (err) {
22675
- if (err && typeof err === "object") {
22676
- err.suggestedFallback = "server";
22677
- }
22678
- throw err;
23129
+ attachSuggestedFallbackAndThrow(err, "server");
22679
23130
  }
22680
23131
  }
22681
23132
  async silentPrint(params) {
@@ -22728,6 +23179,9 @@ var PdfIoService = class extends import_core10.Disposable {
22728
23179
  return true;
22729
23180
  }
22730
23181
  };
23182
+ PdfIoService = __decorateClass([
23183
+ __decorateParam(0, (0, import_core10.Optional)(import_core10.IUniverInstanceService))
23184
+ ], PdfIoService);
22731
23185
 
22732
23186
  // src/plugin.ts
22733
23187
  var UNIVER_PDFS_PLUGIN_NAME = "UNIVER_PDFS_PLUGIN";
@@ -22766,6 +23220,9 @@ var UniverPdfsPlugin = class extends import_core11.Plugin {
22766
23220
  if (this._config.io) {
22767
23221
  this._injector.get(IPdfIoService).setAdapter(this._config.io);
22768
23222
  }
23223
+ if (this._config.defaultIoTarget) {
23224
+ this._injector.get(IPdfIoService).setDefaultIoTarget(this._config.defaultIoTarget);
23225
+ }
22769
23226
  if (this._config.aiCopilot) {
22770
23227
  this._injector.get(IPdfIoService).setAiCopilotAdapter(this._config.aiCopilot);
22771
23228
  }
@@ -22923,6 +23380,7 @@ UniverPdfsPlugin = __decorateClass([
22923
23380
  applyOcrToUnitPage,
22924
23381
  autoDetectFormFieldsOnPage,
22925
23382
  buildMinimalTestTrueTypeFont,
23383
+ buildOverlayImportCandidateSnapshot,
22926
23384
  buildPdfTemplateFromOcrFields,
22927
23385
  canonicalJsonStringify,
22928
23386
  cmykToRgb,
@@ -23032,6 +23490,7 @@ UniverPdfsPlugin = __decorateClass([
23032
23490
  normalizeBarcodeFormatType,
23033
23491
  normalizeBarcodePayloadForFormat,
23034
23492
  normalizeImageCrop,
23493
+ normalizePdfImportWarnings,
23035
23494
  optimizePdfUnit,
23036
23495
  organizePdfBytes,
23037
23496
  overlayDiagnosticGridOnPdfBytes,