@univerjs-pro/exchange-node 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.cjs CHANGED
@@ -54,13 +54,13 @@ __export(index_exports, {
54
54
  importFileToSnapshot: () => importFileToSnapshot
55
55
  });
56
56
  module.exports = __toCommonJS(index_exports);
57
- var import_collaboration = require("@univerjs-pro/collaboration"), import_core = require("@univerjs/core"), import_node_path = require("node:path"), import_promises = require("node:fs/promises"), import_node_buffer2 = require("node:buffer");
57
+ var import_collaboration = require("@univerjs-pro/collaboration"), import_core = require("@univerjs/core"), import_node_path2 = require("node:path"), import_promises = require("node:fs/promises"), import_node_buffer2 = require("node:buffer");
58
58
 
59
59
  // src/binding.ts
60
- var import_node_module = require("node:module"), import_node_process = __toESM(require("node:process"), 1);
60
+ var import_node_module = require("node:module"), import_node_process = __toESM(require("node:process"), 1), import_node_path = require("node:path"), import_node_fs = require("node:fs");
61
61
 
62
62
  // src/types.ts
63
- var ExchangeFormat = /* @__PURE__ */ ((ExchangeFormat2) => (ExchangeFormat2.XLS = "xls", ExchangeFormat2.XLSX = "xlsx", ExchangeFormat2.CSV = "csv", ExchangeFormat2.TSV = "tsv", ExchangeFormat2.DOC = "doc", ExchangeFormat2.DOCX = "docx", ExchangeFormat2.PPT = "ppt", ExchangeFormat2.PPTX = "pptx", ExchangeFormat2.PDF = "pdf", ExchangeFormat2))(ExchangeFormat || {}), FormulaCalculationMode = /* @__PURE__ */ ((FormulaCalculationMode2) => (FormulaCalculationMode2.FORCED = "forced", FormulaCalculationMode2.WHEN_EMPTY = "when_empty", FormulaCalculationMode2.NO = "no", FormulaCalculationMode2))(FormulaCalculationMode || {}), CsvTypeInferenceMode = /* @__PURE__ */ ((CsvTypeInferenceMode2) => (CsvTypeInferenceMode2.OFF = "off", CsvTypeInferenceMode2.SAFE = "safe", CsvTypeInferenceMode2.AGGRESSIVE = "aggressive", CsvTypeInferenceMode2))(CsvTypeInferenceMode || {}), CsvQuoteStyle = /* @__PURE__ */ ((CsvQuoteStyle2) => (CsvQuoteStyle2.MINIMAL = "minimal", CsvQuoteStyle2.ALWAYS = "always", CsvQuoteStyle2))(CsvQuoteStyle || {}), CsvLineEnding = /* @__PURE__ */ ((CsvLineEnding2) => (CsvLineEnding2.LF = "lf", CsvLineEnding2.CRLF = "cr_lf", CsvLineEnding2))(CsvLineEnding || {}), CsvValueMode = /* @__PURE__ */ ((CsvValueMode2) => (CsvValueMode2.DISPLAY = "display", CsvValueMode2.RAW = "raw", CsvValueMode2))(CsvValueMode || {}), CsvFormulaMode = /* @__PURE__ */ ((CsvFormulaMode2) => (CsvFormulaMode2.CACHED = "cached", CsvFormulaMode2.EXPRESSION = "expression", CsvFormulaMode2))(CsvFormulaMode || {}), BaseImportMode = /* @__PURE__ */ ((BaseImportMode2) => (BaseImportMode2.TABLES = "tables", BaseImportMode2.SHEETS = "sheets", BaseImportMode2.HYBRID = "hybrid", BaseImportMode2.AUTO = "auto", BaseImportMode2))(BaseImportMode || {}), BaseTypeInference = /* @__PURE__ */ ((BaseTypeInference2) => (BaseTypeInference2.NONE = "none", BaseTypeInference2.SAFE = "safe", BaseTypeInference2.AGGRESSIVE = "aggressive", BaseTypeInference2))(BaseTypeInference || {}), BaseFormulaPolicy = /* @__PURE__ */ ((BaseFormulaPolicy2) => (BaseFormulaPolicy2.VALUES = "values", BaseFormulaPolicy2.TEXT = "text", BaseFormulaPolicy2.FAIL = "fail", BaseFormulaPolicy2.CONVERT_THEN_VALUES = "convertThenValues", BaseFormulaPolicy2))(BaseFormulaPolicy || {}), BaseImagePolicy = /* @__PURE__ */ ((BaseImagePolicy2) => (BaseImagePolicy2.SAFE = "safe", BaseImagePolicy2.CELL_ONLY = "cell-only", BaseImagePolicy2.MEDIA_TABLE = "media-table", BaseImagePolicy2.NONE = "none", BaseImagePolicy2))(BaseImagePolicy || {}), BaseHeaderPolicy = /* @__PURE__ */ ((BaseHeaderPolicy2) => (BaseHeaderPolicy2.FIRST_ROW = "firstRow", BaseHeaderPolicy2.NONE = "none", BaseHeaderPolicy2))(BaseHeaderPolicy || {}), BaseExportMode = /* @__PURE__ */ ((BaseExportMode2) => (BaseExportMode2.TABLES = "tables", BaseExportMode2.RANGES = "ranges", BaseExportMode2))(BaseExportMode || {}), BaseAttachmentPolicy = /* @__PURE__ */ ((BaseAttachmentPolicy2) => (BaseAttachmentPolicy2.HYBRID = "hybrid", BaseAttachmentPolicy2.MANIFEST = "manifest", BaseAttachmentPolicy2.LINKS = "links", BaseAttachmentPolicy2.NONE = "none", BaseAttachmentPolicy2))(BaseAttachmentPolicy || {}), DocxCompatibilityMode = /* @__PURE__ */ ((DocxCompatibilityMode2) => (DocxCompatibilityMode2.TRADITIONAL = "traditional", DocxCompatibilityMode2.MODERN = "modern", DocxCompatibilityMode2))(DocxCompatibilityMode || {}), ExchangeErrorCode = /* @__PURE__ */ ((ExchangeErrorCode2) => (ExchangeErrorCode2.INVALID_ARGUMENT = "INVALID_ARGUMENT", ExchangeErrorCode2.UNSUPPORTED_FORMAT = "UNSUPPORTED_FORMAT", ExchangeErrorCode2.INVALID_FILE = "INVALID_FILE", ExchangeErrorCode2.INCOMPLETE_SNAPSHOT = "INCOMPLETE_SNAPSHOT", ExchangeErrorCode2.IO_ERROR = "IO_ERROR", ExchangeErrorCode2.NATIVE_LOAD_FAILED = "NATIVE_LOAD_FAILED", ExchangeErrorCode2.CONVERSION_FAILED = "CONVERSION_FAILED", ExchangeErrorCode2.LICENSE_EXPORT_QUOTA_EXCEEDED = "LICENSE_EXPORT_QUOTA_EXCEEDED", ExchangeErrorCode2.LICENSE_INVALID = "LICENSE_INVALID", ExchangeErrorCode2.LICENSE_POLICY_INVALID = "LICENSE_POLICY_INVALID", ExchangeErrorCode2.LICENSE_NOT_YET_EFFECTIVE = "LICENSE_NOT_YET_EFFECTIVE", ExchangeErrorCode2.LICENSE_UNIT_TYPE_REJECTED = "LICENSE_UNIT_TYPE_REJECTED", ExchangeErrorCode2.LICENSE_VERSION_NOT_ALLOWED = "LICENSE_VERSION_NOT_ALLOWED", ExchangeErrorCode2.LICENSE_CONCURRENCY_TIMEOUT = "LICENSE_CONCURRENCY_TIMEOUT", ExchangeErrorCode2.LICENSE_USAGE_STATE_INVALID = "LICENSE_USAGE_STATE_INVALID", ExchangeErrorCode2.LICENSE_USAGE_STORAGE_ERROR = "LICENSE_USAGE_STORAGE_ERROR", ExchangeErrorCode2))(ExchangeErrorCode || {}), ExchangeError = class extends Error {
63
+ var ExchangeFormat = /* @__PURE__ */ ((ExchangeFormat2) => (ExchangeFormat2.XLS = "xls", ExchangeFormat2.XLSX = "xlsx", ExchangeFormat2.CSV = "csv", ExchangeFormat2.TSV = "tsv", ExchangeFormat2.DOC = "doc", ExchangeFormat2.DOCX = "docx", ExchangeFormat2.PPT = "ppt", ExchangeFormat2.PPTX = "pptx", ExchangeFormat2.PDF = "pdf", ExchangeFormat2.MERMAID = "mermaid", ExchangeFormat2))(ExchangeFormat || {}), FormulaCalculationMode = /* @__PURE__ */ ((FormulaCalculationMode2) => (FormulaCalculationMode2.FORCED = "forced", FormulaCalculationMode2.WHEN_EMPTY = "when_empty", FormulaCalculationMode2.NO = "no", FormulaCalculationMode2))(FormulaCalculationMode || {}), CsvTypeInferenceMode = /* @__PURE__ */ ((CsvTypeInferenceMode2) => (CsvTypeInferenceMode2.OFF = "off", CsvTypeInferenceMode2.SAFE = "safe", CsvTypeInferenceMode2.AGGRESSIVE = "aggressive", CsvTypeInferenceMode2))(CsvTypeInferenceMode || {}), CsvQuoteStyle = /* @__PURE__ */ ((CsvQuoteStyle2) => (CsvQuoteStyle2.MINIMAL = "minimal", CsvQuoteStyle2.ALWAYS = "always", CsvQuoteStyle2))(CsvQuoteStyle || {}), CsvLineEnding = /* @__PURE__ */ ((CsvLineEnding2) => (CsvLineEnding2.LF = "lf", CsvLineEnding2.CRLF = "cr_lf", CsvLineEnding2))(CsvLineEnding || {}), CsvValueMode = /* @__PURE__ */ ((CsvValueMode2) => (CsvValueMode2.DISPLAY = "display", CsvValueMode2.RAW = "raw", CsvValueMode2))(CsvValueMode || {}), CsvFormulaMode = /* @__PURE__ */ ((CsvFormulaMode2) => (CsvFormulaMode2.CACHED = "cached", CsvFormulaMode2.EXPRESSION = "expression", CsvFormulaMode2))(CsvFormulaMode || {}), BaseImportMode = /* @__PURE__ */ ((BaseImportMode2) => (BaseImportMode2.TABLES = "tables", BaseImportMode2.SHEETS = "sheets", BaseImportMode2.HYBRID = "hybrid", BaseImportMode2.AUTO = "auto", BaseImportMode2))(BaseImportMode || {}), BaseTypeInference = /* @__PURE__ */ ((BaseTypeInference2) => (BaseTypeInference2.NONE = "none", BaseTypeInference2.SAFE = "safe", BaseTypeInference2.AGGRESSIVE = "aggressive", BaseTypeInference2))(BaseTypeInference || {}), BaseFormulaPolicy = /* @__PURE__ */ ((BaseFormulaPolicy2) => (BaseFormulaPolicy2.VALUES = "values", BaseFormulaPolicy2.TEXT = "text", BaseFormulaPolicy2.FAIL = "fail", BaseFormulaPolicy2.CONVERT_THEN_VALUES = "convertThenValues", BaseFormulaPolicy2))(BaseFormulaPolicy || {}), BaseImagePolicy = /* @__PURE__ */ ((BaseImagePolicy2) => (BaseImagePolicy2.SAFE = "safe", BaseImagePolicy2.CELL_ONLY = "cell-only", BaseImagePolicy2.MEDIA_TABLE = "media-table", BaseImagePolicy2.NONE = "none", BaseImagePolicy2))(BaseImagePolicy || {}), BaseHeaderPolicy = /* @__PURE__ */ ((BaseHeaderPolicy2) => (BaseHeaderPolicy2.FIRST_ROW = "firstRow", BaseHeaderPolicy2.NONE = "none", BaseHeaderPolicy2))(BaseHeaderPolicy || {}), BaseExportMode = /* @__PURE__ */ ((BaseExportMode2) => (BaseExportMode2.TABLES = "tables", BaseExportMode2.RANGES = "ranges", BaseExportMode2))(BaseExportMode || {}), BaseAttachmentPolicy = /* @__PURE__ */ ((BaseAttachmentPolicy2) => (BaseAttachmentPolicy2.HYBRID = "hybrid", BaseAttachmentPolicy2.MANIFEST = "manifest", BaseAttachmentPolicy2.LINKS = "links", BaseAttachmentPolicy2.NONE = "none", BaseAttachmentPolicy2))(BaseAttachmentPolicy || {}), DocxCompatibilityMode = /* @__PURE__ */ ((DocxCompatibilityMode2) => (DocxCompatibilityMode2.TRADITIONAL = "traditional", DocxCompatibilityMode2.MODERN = "modern", DocxCompatibilityMode2))(DocxCompatibilityMode || {}), ExchangeErrorCode = /* @__PURE__ */ ((ExchangeErrorCode2) => (ExchangeErrorCode2.INVALID_ARGUMENT = "INVALID_ARGUMENT", ExchangeErrorCode2.UNSUPPORTED_FORMAT = "UNSUPPORTED_FORMAT", ExchangeErrorCode2.INVALID_FILE = "INVALID_FILE", ExchangeErrorCode2.INCOMPLETE_SNAPSHOT = "INCOMPLETE_SNAPSHOT", ExchangeErrorCode2.IO_ERROR = "IO_ERROR", ExchangeErrorCode2.NATIVE_LOAD_FAILED = "NATIVE_LOAD_FAILED", ExchangeErrorCode2.CONVERSION_FAILED = "CONVERSION_FAILED", ExchangeErrorCode2.LICENSE_EXPORT_QUOTA_EXCEEDED = "LICENSE_EXPORT_QUOTA_EXCEEDED", ExchangeErrorCode2.LICENSE_INVALID = "LICENSE_INVALID", ExchangeErrorCode2.LICENSE_POLICY_INVALID = "LICENSE_POLICY_INVALID", ExchangeErrorCode2.LICENSE_NOT_YET_EFFECTIVE = "LICENSE_NOT_YET_EFFECTIVE", ExchangeErrorCode2.LICENSE_UNIT_TYPE_REJECTED = "LICENSE_UNIT_TYPE_REJECTED", ExchangeErrorCode2.LICENSE_VERSION_NOT_ALLOWED = "LICENSE_VERSION_NOT_ALLOWED", ExchangeErrorCode2.LICENSE_CONCURRENCY_TIMEOUT = "LICENSE_CONCURRENCY_TIMEOUT", ExchangeErrorCode2.LICENSE_USAGE_STATE_INVALID = "LICENSE_USAGE_STATE_INVALID", ExchangeErrorCode2.LICENSE_USAGE_STORAGE_ERROR = "LICENSE_USAGE_STORAGE_ERROR", ExchangeErrorCode2))(ExchangeErrorCode || {}), ExchangeError = class extends Error {
64
64
  constructor(code, message, options) {
65
65
  super(message, options);
66
66
  this.code = code;
@@ -76,7 +76,7 @@ function errorMessage(error) {
76
76
  }
77
77
  function validateBinding(binding) {
78
78
  try {
79
- if (!binding || typeof binding.__internalExchangeConfigProtocolVersion != "function" || binding.__internalExchangeConfigProtocolVersion() !== 1 || typeof binding.__internalExchangeConfigure != "function" || typeof binding.__internalExchangeGetExportQuota != "function" || typeof binding.exchangeExportSnapshot != "function")
79
+ if (!binding || typeof binding.__internalExchangeConfigProtocolVersion != "function" || binding.__internalExchangeConfigProtocolVersion() !== 1 || typeof binding.__internalExchangeConfigure != "function" || typeof binding.__internalExchangeGetExportQuota != "function" || typeof binding.exchangeExportSnapshot != "function" || typeof binding.exchangeApplyImportFileReferences != "function" || typeof binding.exchangeExportRequirements != "function")
80
80
  throw new ExchangeError("NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */, "Incompatible native exchange configuration protocol.");
81
81
  return binding;
82
82
  } catch (error) {
@@ -86,7 +86,22 @@ function validateBinding(binding) {
86
86
  async function loadNativeBinding() {
87
87
  if (nativeBinding)
88
88
  return nativeBinding;
89
- let errors = [];
89
+ let errors = [], runtimeDirectory = import_node_process.default.env.UNIVER_NODE_SDK_RUNTIME_DIR_OVERRIDE;
90
+ if (runtimeDirectory !== void 0)
91
+ try {
92
+ if (!(0, import_node_path.isAbsolute)(runtimeDirectory))
93
+ throw new Error("Expected an absolute runtime directory path.");
94
+ if (!(0, import_node_fs.statSync)(runtimeDirectory).isDirectory())
95
+ throw new Error("Expected a runtime directory.");
96
+ let nativeLibraryPath = (0, import_node_path.join)(runtimeDirectory, "univer-exchange-node.node"), loaded = { exports: {} };
97
+ return import_node_process.default.dlopen(loaded, nativeLibraryPath), nativeBinding = validateBinding(loaded.exports), nativeBindingSource = "UNIVER_NODE_SDK_RUNTIME_DIR_OVERRIDE", nativeBinding;
98
+ } catch (error) {
99
+ throw new ExchangeError(
100
+ "NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */,
101
+ `Failed to load native exchange binding from UNIVER_NODE_SDK_RUNTIME_DIR_OVERRIDE: ${errorMessage(error)}`,
102
+ { cause: error }
103
+ );
104
+ }
90
105
  try {
91
106
  return nativeBinding = validateBinding(nodeRequire("@univerjs-pro/exchange-node-binding")), nativeBindingSource = "@univerjs-pro/exchange-node-binding", nativeBinding;
92
107
  } catch (error) {
@@ -105,6 +120,24 @@ async function loadNativeBinding() {
105
120
  `)
106
121
  );
107
122
  }
123
+ async function loadBoardBinding() {
124
+ let binding = await loadNativeBinding();
125
+ if (typeof binding.__internalExchangeBoardProtocolVersion != "function" || binding.__internalExchangeBoardProtocolVersion() !== 1 || typeof binding.exchangeCompileMermaid != "function")
126
+ throw new ExchangeError(
127
+ "NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */,
128
+ "Board/Mermaid requires a native exchange binding with Board protocol 1. Upgrade @univerjs-pro/exchange-node-binding."
129
+ );
130
+ return binding;
131
+ }
132
+ async function loadBoardFilesBinding() {
133
+ let binding = await loadBoardBinding();
134
+ if (typeof binding.exchangeCollectImportFiles != "function")
135
+ throw new ExchangeError(
136
+ "NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */,
137
+ "Board resource callbacks require a newer @univerjs-pro/exchange-node-binding. Upgrade the SDK and binding together."
138
+ );
139
+ return binding;
140
+ }
108
141
 
109
142
  // src/errors.ts
110
143
  function structuredExchangeError(error, ErrorClass = ExchangeError) {
@@ -140,6 +173,29 @@ function createSnapshotCollector() {
140
173
  };
141
174
  }
142
175
 
176
+ // src/file-storage.ts
177
+ var import_node_crypto = require("node:crypto");
178
+ async function storeFileReferences(inputs, files, ErrorClass = ExchangeError) {
179
+ let groups = /* @__PURE__ */ new Map();
180
+ for (let { id, ...file } of inputs) {
181
+ let hash = (0, import_node_crypto.createHash)("sha256").update(file.bytes).digest("hex"), group = groups.get(hash) ?? { file, ids: [] };
182
+ group.ids.push(id), groups.set(hash, group);
183
+ }
184
+ let references = /* @__PURE__ */ new Map();
185
+ for (let { file, ids } of groups.values()) {
186
+ let decision = await files.store(file);
187
+ if (decision?.mode !== "inline") {
188
+ if (decision?.mode !== "reference" || typeof decision.source != "string" || !decision.source.trim())
189
+ throw new ErrorClass(
190
+ "INVALID_ARGUMENT" /* INVALID_ARGUMENT */,
191
+ 'files.store must return { mode: "inline" } or { mode: "reference", source }'
192
+ );
193
+ for (let id of ids) references.set(id, decision.source);
194
+ }
195
+ }
196
+ return references;
197
+ }
198
+
143
199
  // src/snapshot.ts
144
200
  var import_node_buffer = require("node:buffer");
145
201
  function bufferView(bytes) {
@@ -166,7 +222,7 @@ function toNativeSnapshot(value) {
166
222
  ])
167
223
  )), snapshot.workbook = workbook;
168
224
  }
169
- for (let kind of ["doc", "slide"]) {
225
+ for (let kind of ["doc", "slide", "board"]) {
170
226
  let owner = source[kind];
171
227
  owner && (snapshot[kind] = takeMetadata(owner, kind, metadata));
172
228
  }
@@ -188,7 +244,7 @@ function restoreMetadata(snapshot, metadata) {
188
244
  let sheets = snapshot.workbook?.sheets;
189
245
  owner = entry.ownerId ? sheets?.[entry.ownerId] : void 0;
190
246
  } else {
191
- if (entry.kind !== "workbook" && entry.kind !== "doc" && entry.kind !== "slide")
247
+ if (entry.kind !== "workbook" && entry.kind !== "doc" && entry.kind !== "slide" && entry.kind !== "board")
192
248
  throw new TypeError(`unsupported native snapshot metadata kind ${entry.kind}`);
193
249
  owner = snapshot[entry.kind];
194
250
  }
@@ -228,8 +284,62 @@ var FORMAT_BY_EXTENSION = {
228
284
  ".docx": "docx" /* DOCX */,
229
285
  ".ppt": "ppt" /* PPT */,
230
286
  ".pptx": "pptx" /* PPTX */,
231
- ".pdf": "pdf" /* PDF */
287
+ ".pdf": "pdf" /* PDF */,
288
+ ".mmd": "mermaid" /* MERMAID */,
289
+ ".mermaid": "mermaid" /* MERMAID */
290
+ }, CallbackFailure = class extends Error {
291
+ constructor(failure) {
292
+ super("application callback failed");
293
+ this.failure = failure;
294
+ }
295
+ failure;
232
296
  };
297
+ async function callbackResult(action) {
298
+ try {
299
+ return await action();
300
+ } catch (failure) {
301
+ throw new CallbackFailure(failure);
302
+ }
303
+ }
304
+ function invalidArgument(message) {
305
+ return new ExchangeError("INVALID_ARGUMENT" /* INVALID_ARGUMENT */, message);
306
+ }
307
+ function isOfficeHost(options) {
308
+ return options.type === import_core.UniverInstanceType.UNIVER_SHEET && options.format === "xlsx" /* XLSX */ || options.type === import_core.UniverInstanceType.UNIVER_DOC && options.format === "docx" /* DOCX */ || (options.type === import_core.UniverInstanceType.UNIVER_SLIDE || isBoard(options.type)) && options.format === "pptx" /* PPTX */;
309
+ }
310
+ function isPdfHost(options) {
311
+ return options.type === import_core.UniverInstanceType.UNIVER_PDF && options.format === "pdf" /* PDF */;
312
+ }
313
+ function isBoard(type) {
314
+ return type === import_core.UniverInstanceType.UNIVER_BOARD;
315
+ }
316
+ function validateImportFiles(options) {
317
+ let files = options.files;
318
+ if (files !== void 0) {
319
+ if (files === null || typeof files != "object" || typeof files.store != "function")
320
+ throw invalidArgument("Invalid argument: files.store must be a function.");
321
+ if (options.type === import_core.UniverInstanceType.UNIVER_BASE)
322
+ throw invalidArgument("files is supported only for Sheet, Doc, Slide, Board and PDF imports");
323
+ return files;
324
+ }
325
+ }
326
+ function validateExportResources(options) {
327
+ let { files, ole } = options;
328
+ if (files === void 0 && ole === void 0) return {};
329
+ if (!isOfficeHost(options) && !isPdfHost(options))
330
+ throw invalidArgument("files and ole export options require Sheet/XLSX, Doc/DOCX or Slide/Board PPTX or PDF");
331
+ if (files !== void 0 && (files === null || typeof files != "object" || typeof files.load != "function"))
332
+ throw invalidArgument("Invalid argument: files.load must be a function.");
333
+ if (ole !== void 0) {
334
+ if (ole === null || typeof ole != "object") throw invalidArgument("Invalid argument: ole.");
335
+ let { attachmentSource = "original", loadOnlineUnit } = ole;
336
+ if (attachmentSource !== "original" && attachmentSource !== "online")
337
+ throw invalidArgument('ole.attachmentSource must be "original" or "online"');
338
+ if (attachmentSource === "online" && typeof loadOnlineUnit != "function")
339
+ throw invalidArgument('ole.loadOnlineUnit is required when ole.attachmentSource is "online"');
340
+ }
341
+ return { files, ole };
342
+ }
233
343
  function pdfAdapter(type, format) {
234
344
  if (type !== import_core.UniverInstanceType.UNIVER_PDF && format !== "pdf" /* PDF */)
235
345
  return;
@@ -286,7 +396,7 @@ async function getExportQuota(options = {}) {
286
396
  function resolveFormat(fileName, format) {
287
397
  if (format)
288
398
  return format;
289
- let inferred = FORMAT_BY_EXTENSION[(0, import_node_path.extname)(fileName).toLowerCase()];
399
+ let inferred = FORMAT_BY_EXTENSION[(0, import_node_path2.extname)(fileName).toLowerCase()];
290
400
  if (!inferred)
291
401
  throw new ExchangeError(
292
402
  "UNSUPPORTED_FORMAT" /* UNSUPPORTED_FORMAT */,
@@ -304,16 +414,19 @@ function nativeUnitType(type) {
304
414
  return "doc";
305
415
  case import_core.UniverInstanceType.UNIVER_SLIDE:
306
416
  return "slide";
417
+ case import_core.UniverInstanceType.UNIVER_BOARD:
418
+ return "board";
307
419
  default:
308
420
  throw new ExchangeError("INVALID_ARGUMENT" /* INVALID_ARGUMENT */, `Unsupported Univer unit type: ${type}`);
309
421
  }
310
422
  }
311
- function nativeImportOptions(options, fileName) {
423
+ function nativeImportOptions(options, fileName, collectFiles) {
312
424
  return {
313
425
  format: resolveFormat(fileName, options.format),
314
426
  unitType: nativeUnitType(options.type),
315
427
  fileName,
316
428
  unitId: options.unitId,
429
+ collectFiles: collectFiles || void 0,
317
430
  minSheetRowCount: "minSheetRowCount" in options ? options.minSheetRowCount : void 0,
318
431
  minSheetColumnCount: "minSheetColumnCount" in options ? options.minSheetColumnCount : void 0,
319
432
  compatibilityMode: "compatibilityMode" in options ? options.compatibilityMode : void 0,
@@ -340,18 +453,89 @@ function nativeExportOptions(options) {
340
453
  attachmentPolicy: options.attachmentPolicy,
341
454
  mapping: options.mapping
342
455
  } : void 0,
343
- formulaCalculation: "formulaCalculation" in options ? options.formulaCalculation : void 0
456
+ formulaCalculation: "formulaCalculation" in options ? options.formulaCalculation : void 0,
457
+ ole: options.ole !== void 0 ? { attachmentSource: options.ole.attachmentSource ?? "original" } : void 0,
458
+ files: options.files !== void 0 || void 0
344
459
  };
345
460
  }
346
- async function importSnapshot(input, options, fileName) {
461
+ async function importSnapshot(input, options, fileName, files) {
347
462
  try {
348
- let result = await (await loadNativeBinding()).exchangeImportToSnapshot(
463
+ let binding = await loadNativeBinding(), result = await binding.exchangeImportToSnapshot(
349
464
  input,
350
- JSON.stringify(nativeImportOptions(options, fileName))
465
+ JSON.stringify(nativeImportOptions(options, fileName, files !== void 0))
351
466
  );
352
- return fromNativeSnapshot(result);
467
+ return files && (result = await applyImportFiles(binding, result, files)), fromNativeSnapshot(result);
353
468
  } catch (error) {
354
- throw exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
469
+ throw error instanceof CallbackFailure ? error : exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
470
+ }
471
+ }
472
+ async function applyImportFiles(binding, result, files) {
473
+ let stored = await storeFileReferences(
474
+ (result.files ?? []).map((file) => ({
475
+ id: file.id,
476
+ name: file.name,
477
+ mimeType: file.mimeType,
478
+ size: file.size,
479
+ bytes: file.data
480
+ })),
481
+ { store: (file) => callbackResult(() => files.store(file)) }
482
+ ), references = Array.from(stored, ([id, source]) => ({ id, source }));
483
+ return references.length > 0 && (result = await binding.exchangeApplyImportFileReferences(result, JSON.stringify(references))), result;
484
+ }
485
+ async function collectExportResources(binding, input, nativeOptions, files, ole) {
486
+ let online = ole?.attachmentSource === "online";
487
+ if (!files && !online) return;
488
+ let resources = { files: [], children: [] }, provided = /* @__PURE__ */ new Set(), loaded = /* @__PURE__ */ new Map();
489
+ for (; ; ) {
490
+ let known = {
491
+ files: resources.files.map(({ data: _data, ...reference }) => reference),
492
+ children: resources.children
493
+ }, missing = JSON.parse(
494
+ await binding.exchangeExportRequirements(input, nativeOptions, known)
495
+ );
496
+ if (missing.files.length === 0 && missing.units.length === 0) return resources;
497
+ if (missing.files.length > 0 && !files)
498
+ throw invalidArgument(
499
+ `Export needs files.load to resolve ${missing.files.length} stored reference(s)`
500
+ );
501
+ for (let ref of missing.files) {
502
+ let key = `file\0${ref.unitId}\0${ref.kind}\0${ref.sourceType}\0${ref.source}`;
503
+ if (provided.has(key))
504
+ throw new ExchangeError("CONVERSION_FAILED" /* CONVERSION_FAILED */, `Export still requires ${ref.source} after it was resolved`);
505
+ provided.add(key);
506
+ let storageKey = JSON.stringify([ref.unitId, ref.sourceType, ref.source]), bytes = loaded.get(storageKey);
507
+ if (!bytes) {
508
+ let content = await callbackResult(
509
+ () => files.load({
510
+ sourceType: ref.sourceType,
511
+ source: ref.source,
512
+ unitId: ref.unitId
513
+ })
514
+ );
515
+ if (!(content?.bytes instanceof Uint8Array))
516
+ throw invalidArgument("files.load must return { bytes: Uint8Array }");
517
+ bytes = content.bytes, loaded.set(storageKey, bytes);
518
+ }
519
+ resources.files.push({ ...ref, data: bufferView(bytes) });
520
+ }
521
+ for (let unit of missing.units) {
522
+ let key = `unit\0${unit.unitId}`;
523
+ if (!online || provided.has(key))
524
+ throw new ExchangeError("CONVERSION_FAILED" /* CONVERSION_FAILED */, `Export still requires Unit ${unit.unitId} after it was provided`);
525
+ provided.add(key);
526
+ let child;
527
+ try {
528
+ child = await ole.loadOnlineUnit({
529
+ unitId: unit.unitId,
530
+ type: unit.type
531
+ });
532
+ } catch (failure) {
533
+ throw new CallbackFailure(failure);
534
+ }
535
+ if (!child || typeof child != "object" || !child.snapshot || !Array.isArray(child.sheetBlocks))
536
+ throw invalidArgument("ole.loadOnlineUnit must return an ISnapshotWithBlocks");
537
+ resources.children.push({ unitId: unit.unitId, unitType: unit.type, snapshot: toNativeSnapshot(child) });
538
+ }
355
539
  }
356
540
  }
357
541
  async function snapshotToMemory(snapshot, type) {
@@ -363,6 +547,8 @@ async function snapshotToMemory(snapshot, type) {
363
547
  return await (0, import_collaboration.transformSnapshotToBaseData)(snapshot.snapshot, snapshot.sheetBlocks);
364
548
  case import_core.UniverInstanceType.UNIVER_DOC:
365
549
  return (0, import_collaboration.transformSnapshotToDocumentData)(snapshot.snapshot);
550
+ case import_core.UniverInstanceType.UNIVER_BOARD:
551
+ return (0, import_collaboration.transformSnapshotToBoardData)(snapshot.snapshot);
366
552
  case import_core.UniverInstanceType.UNIVER_SLIDE:
367
553
  return (0, import_collaboration.transformSnapshotToSlideData)(snapshot.snapshot);
368
554
  default:
@@ -379,6 +565,10 @@ async function memoryToSnapshot(data, options) {
379
565
  throw new ExchangeError("INVALID_ARGUMENT" /* INVALID_ARGUMENT */, "Export data must have a non-empty id");
380
566
  let rev = data.rev ?? 0, collector = createSnapshotCollector();
381
567
  switch (options.type) {
568
+ case import_core.UniverInstanceType.UNIVER_BOARD: {
569
+ let board = data, { snapshot } = await (0, import_collaboration.transformBoardDataToSnapshot)(board.resources, board, unitId, rev, collector.service);
570
+ return { snapshot, sheetBlocks: [] };
571
+ }
382
572
  case import_core.UniverInstanceType.UNIVER_SHEET: {
383
573
  let workbook = normalizeWorkbookSheetOrder(data), { snapshot } = await (0, import_collaboration.transformWorkbookDataToSnapshot)(
384
574
  { metadata: void 0 },
@@ -436,24 +626,44 @@ async function readInput(path) {
436
626
  async function importResult(input, options, fileName, asSnapshot) {
437
627
  let result;
438
628
  try {
439
- let adapter = pdfAdapter(options.type, resolveFormat(fileName, options.format));
440
- if (adapter) {
441
- let converted = await adapter.import(input, { fileName, unitId: options.unitId });
629
+ if (typeof fileName != "string" || fileName.trim().length === 0)
630
+ throw invalidArgument("fileName must be a non-empty string, even when format is provided.");
631
+ let format = resolveFormat(fileName, options.format), files = validateImportFiles(options);
632
+ if (format === "mermaid" /* MERMAID */ || isBoard(options.type)) {
633
+ if (!isBoard(options.type) || format !== "mermaid" /* MERMAID */)
634
+ throw invalidArgument("Board imports require Mermaid format.");
635
+ let adapter = import_runtime.default.getMermaid();
636
+ if (!adapter) throw invalidArgument("Mermaid import requires @univerjs-pro/exchange-node/mermaid.");
637
+ let converted = await adapter.import(input, { ...options, fileName });
638
+ if (files) {
639
+ let binding = await loadBoardFilesBinding(), aggregate = await adapter.toSnapshot(converted.value), collected = await binding.exchangeCollectImportFiles(toNativeSnapshot(aggregate)), snapshot = fromNativeSnapshot(await applyImportFiles(binding, collected, files));
640
+ result = { value: asSnapshot ? snapshot : await snapshotToMemory(snapshot, options.type), diagnostics: converted.diagnostics };
641
+ } else
642
+ result = {
643
+ value: asSnapshot ? await adapter.toSnapshot(converted.value) : converted.value,
644
+ diagnostics: converted.diagnostics
645
+ };
646
+ } else if (pdfAdapter(options.type, format)) {
647
+ let adapter = import_runtime.default.getPdf(), converted = await adapter.import(input, {
648
+ fileName,
649
+ unitId: options.unitId,
650
+ files: files && { store: (file) => callbackResult(() => files.store(file)) }
651
+ });
442
652
  result = {
443
653
  value: asSnapshot ? await adapter.toSnapshot(converted.value) : converted.value,
444
654
  diagnostics: converted.diagnostics
445
655
  };
446
656
  } else {
447
- let snapshot = await importSnapshot(input, options, fileName);
657
+ let snapshot = await importSnapshot(input, options, fileName, files);
448
658
  result = { value: asSnapshot ? snapshot : await snapshotToMemory(snapshot, options.type), diagnostics: [] };
449
659
  }
450
660
  } catch (error) {
451
- throw exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
661
+ throw error instanceof CallbackFailure ? error.failure : exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
452
662
  }
453
663
  return await deliverDiagnostics(options, result.diagnostics), result.value;
454
664
  }
455
665
  async function importFile(path, options) {
456
- return importResult(await readInput(path), options, options.fileName ?? (0, import_node_path.basename)(path), !1);
666
+ return importResult(await readInput(path), options, options.fileName ?? (0, import_node_path2.basename)(path), !1);
457
667
  }
458
668
  async function importBuffer(input, options) {
459
669
  return importResult(input, options, options.fileName, !1);
@@ -462,7 +672,7 @@ async function importFileToSnapshot(path, options) {
462
672
  return importResult(
463
673
  await readInput(path),
464
674
  options,
465
- options.fileName ?? (0, import_node_path.basename)(path),
675
+ options.fileName ?? (0, import_node_path2.basename)(path),
466
676
  !0
467
677
  );
468
678
  }
@@ -472,12 +682,15 @@ async function importBufferToSnapshot(input, options) {
472
682
  async function exportResult(data, options, isSnapshot, captured) {
473
683
  let result;
474
684
  try {
475
- let config = await captured, adapter = pdfAdapter(options.type, options.format);
685
+ let config = await captured, { files, ole } = validateExportResources(options), adapter = pdfAdapter(options.type, options.format);
476
686
  if (adapter) {
477
687
  let unit = isSnapshot ? adapter.fromSnapshot(data) : data;
478
688
  result = await adapter.export(
479
689
  unit,
480
- { strictResources: "strictResources" in options ? options.strictResources : void 0 },
690
+ {
691
+ strictResources: "strictResources" in options ? options.strictResources : void 0,
692
+ files: files && { load: (ref) => callbackResult(() => files.load(ref)) }
693
+ },
481
694
  config
482
695
  );
483
696
  } else {
@@ -491,13 +704,15 @@ async function exportResult(data, options, isSnapshot, captured) {
491
704
  { cause: error }
492
705
  );
493
706
  }
707
+ let binding = options.type === import_core.UniverInstanceType.UNIVER_BOARD ? await (files || ole ? loadBoardFilesBinding() : loadBoardBinding()) : await loadNativeBinding(), resources = await collectExportResources(binding, input, nativeOptions, files, ole);
494
708
  result = {
495
- value: await (await loadNativeBinding()).exchangeExportSnapshot(input, nativeOptions, configBuffer(config)),
709
+ // Without resources the native call is the same as before this option existed.
710
+ value: resources === void 0 ? await binding.exchangeExportSnapshot(input, nativeOptions, configBuffer(config)) : await binding.exchangeExportSnapshot(input, nativeOptions, configBuffer(config), resources),
496
711
  diagnostics: []
497
712
  };
498
713
  }
499
714
  } catch (error) {
500
- throw structuredExchangeError(error);
715
+ throw error instanceof CallbackFailure ? error.failure : structuredExchangeError(error);
501
716
  }
502
717
  return await deliverDiagnostics(options, result.diagnostics), result.value;
503
718
  }