@univerjs-pro/exchange-node 1.2.0 → 1.3.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/README.md +151 -3
- package/lib/cjs/index.cjs +156 -29
- package/lib/cjs/pdf.cjs +190 -0
- package/lib/es/index.js +1 -391
- package/lib/es/pdf.js +1 -0
- package/lib/shared/runtime.cjs +93 -0
- package/lib/types/index.d.ts +14 -249
- package/lib/types/pdf.d.ts +23 -0
- package/lib/types/types.d.ts +299 -0
- package/package.json +26 -6
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @univerjs-pro/exchange-node
|
|
2
2
|
|
|
3
|
-
Node.js SDK for converting between Office formats, Univer unit data, and complete Univer snapshots.
|
|
3
|
+
Node.js SDK for converting between Office/PDF formats, Univer unit data, and complete Univer snapshots.
|
|
4
4
|
|
|
5
5
|
The package exposes two API families:
|
|
6
6
|
|
|
@@ -9,12 +9,14 @@ The package exposes two API families:
|
|
|
9
9
|
|
|
10
10
|
## Install
|
|
11
11
|
|
|
12
|
-
Keep this package and its Univer SDK dependencies on the same SDK version:
|
|
12
|
+
Keep this package and its Univer SDK dependencies on the same SDK version for non-dev releases:
|
|
13
13
|
|
|
14
14
|
```sh
|
|
15
15
|
pnpm add @univerjs-pro/exchange-node
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
+
Dev releases declare `*` for their Univer SDK dependencies; this does not select the `insiders` dist-tag. Use your application's package-manager overrides to choose a compatible, exact SDK version combination. The native Binding remains pinned to the version paired with the Wrapper.
|
|
19
|
+
|
|
18
20
|
## Import
|
|
19
21
|
|
|
20
22
|
```ts
|
|
@@ -68,4 +70,150 @@ Snapshot APIs materialize the complete aggregate in memory. They do not call a S
|
|
|
68
70
|
|
|
69
71
|
The initial release supports Sheet and Base import from XLS, XLSX, CSV, and TSV; Doc import from DOC and DOCX; and Slide import from PPT and PPTX. Export supports XLSX, CSV, TSV, DOCX, and PPTX for their corresponding unit types.
|
|
70
72
|
|
|
71
|
-
|
|
73
|
+
Office native packages are published for Linux x64 GNU, Linux arm64 GNU, Windows x64 MSVC, and macOS arm64.
|
|
74
|
+
|
|
75
|
+
## License and monthly export quota
|
|
76
|
+
|
|
77
|
+
Set both `UNIVER_LICENSE` and `UNIVER_LICENSE_KEY` for automatic configuration. The first export or quota query reads them once; no `configureExchange` call is required. Without credentials, Free applies.
|
|
78
|
+
|
|
79
|
+
To configure credentials explicitly:
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { configureExchange, getExportQuota } from '@univerjs-pro/exchange-node';
|
|
83
|
+
|
|
84
|
+
await configureExchange({
|
|
85
|
+
license: '<license content>',
|
|
86
|
+
licenseKey: '<licenseKey content>',
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
const quota = await getExportQuota();
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
`license` and `licenseKey` are the complete credential contents, not file paths. Provide both together. Explicit configuration completely ignores the environment. `configureExchange({})` explicitly selects Free; an incomplete pair returns `INVALID_ARGUMENT` without mixing sources. The first complete environment configuration is fixed even if a later native operation fails. An incomplete environment pair rejects without committing configuration and a new call may try again. The environment is not reread after initialization; use an explicit call to replace credentials, and await it before starting exports that should use the new configuration.
|
|
93
|
+
|
|
94
|
+
Exports and quota queries also accept a complete `license` / `licenseKey` pair in their options. This overrides defaults for that operation only:
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
const quota = await getExportQuota({ license, licenseKey });
|
|
98
|
+
const output = await exportToBuffer(workbook, {
|
|
99
|
+
type: UniverInstanceType.UNIVER_SHEET,
|
|
100
|
+
format: ExchangeFormat.XLSX,
|
|
101
|
+
license,
|
|
102
|
+
licenseKey,
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Omitting both fields uses the default configuration. A partial pair returns `INVALID_ARGUMENT`; credentials are never combined across sources. An explicitly supplied pair is used as supplied, including empty strings, and never retried with the default credentials. Per-operation credentials do not initialize or modify defaults. Successful commercial exports are tracked separately for each License ID; returning to the same ID resumes its usage. Free usage remains shared within the installation.
|
|
107
|
+
|
|
108
|
+
`getExportQuota({ license, licenseKey })` queries shared Office/PDF quota. Omit credentials to query the default configuration. It accepts no Unit type and does not check the SDK version, activation time, or type entitlement; actual exports perform those checks. Importing `/pdf` selects the PDF query backend, so PDF-only consumers do not load Office binding. No alternate backend is tried on failure.
|
|
109
|
+
|
|
110
|
+
The response has nine fields:
|
|
111
|
+
|
|
112
|
+
- `licenseStatus`: `not_configured`, `expired`, or `valid` (not expired); this status does not grant permission to export. Invalid credentials reject the Promise.
|
|
113
|
+
- `expiresAt`: UTC ISO export subscription expiry, or `null` if absent.
|
|
114
|
+
- `observedAt`: UTC ISO snapshot time.
|
|
115
|
+
- `limit`, `used`, `reserved`, `remaining`: monthly limit, successful uses, in-flight uses and available balance; all `null` when unlimited.
|
|
116
|
+
- `periodStart`, `periodEnd`: UTC ISO monthly quota bounds, inclusive start and exclusive end; `null` when unlimited.
|
|
117
|
+
|
|
118
|
+
Queries neither reserve nor consume quota. Before activation, limited quota describes the first authorization month with a future `periodStart`. Zero remaining is a successful query. The snapshot does not guarantee admission of the next export. `periodEnd` is the next monthly quota boundary, while `expiresAt` ends the subscription. A valid subscription always uses commercial quota: exhaustion or unavailable type entitlement cannot select Free. Subscription expiry selects the installation's existing remaining Free quota without resetting it.
|
|
119
|
+
|
|
120
|
+
Free allows 10 successful exports per authorization month. Purchased licenses determine commercial quota, concurrency and version entitlements. Neither Free nor commercial licenses impose file-size or cell-count limits. Use the query response for the applicable period and balance. Unused monthly quota does not carry over. Office and PDF exports in the same deployment share quota. Imports do not require export authorization and do not consume export quota.
|
|
121
|
+
|
|
122
|
+
A successful Buffer conversion counts once. File APIs then write that Buffer: a subsequent file-write failure is `IO_ERROR` and does not refund the conversion. Upload or download failures after successful conversion do not refund usage either. Each successful repeated conversion counts again. When quota is exhausted, wait for the next authorization period or update the license.
|
|
123
|
+
|
|
124
|
+
Errors use `ExchangeError` with a stable `code`, a diagnostic `message` containing the concrete failure reason, and `cause` where available. Handle `code` rather than parsing message text. Applications decide how to log errors and what to display to their end users.
|
|
125
|
+
|
|
126
|
+
The following table compares quota queries and actual exports. Both APIs return Promises; use `await` and `try/catch` to handle failures.
|
|
127
|
+
|
|
128
|
+
| Code | Operation | Meaning and action |
|
|
129
|
+
| --- | --- | --- |
|
|
130
|
+
| `LICENSE_EXPORT_QUOTA_EXCEEDED` | Export only | Insufficient export quota for the current period. Query quota or contact sales to adjust the license. |
|
|
131
|
+
| `LICENSE_INVALID` | Query, export | The license is invalid. Check the complete credentials or contact the license provider for an update. |
|
|
132
|
+
| `LICENSE_POLICY_INVALID` | Query, export | The authorization configuration does not meet SDK requirements. Contact the license provider for an update. |
|
|
133
|
+
| `LICENSE_UNIT_TYPE_REJECTED` | Export only | This export type is not licensed or its type entitlement has expired. Provide a valid license covering the type. |
|
|
134
|
+
| `LICENSE_NOT_YET_EFFECTIVE` | Export only | Authorization has not started yet. Use it after its effective date. |
|
|
135
|
+
| `LICENSE_VERSION_NOT_ALLOWED` | Export only | The current SDK version is outside the licensed range. Use a matching version or update the license. |
|
|
136
|
+
| `LICENSE_CONCURRENCY_TIMEOUT` | Export only | Waiting for available export concurrency timed out. Reduce concurrent exports before submitting again. |
|
|
137
|
+
| `LICENSE_USAGE_STATE_INVALID` | Query, export | License usage status cannot be verified. Preserve the error and contact technical support. |
|
|
138
|
+
| `LICENSE_USAGE_STORAGE_ERROR` | Query, export | License usage processing failed. Preserve the error, contact technical support, and avoid automatic resubmission. |
|
|
139
|
+
| `INVALID_ARGUMENT` | Query, export | Incomplete arguments or credentials. Check the configuration. |
|
|
140
|
+
| `NATIVE_LOAD_FAILED` | Query, export | A native SDK component could not load. Check package and runtime compatibility. |
|
|
141
|
+
| `IO_ERROR` | Export only | File input/output failed. An output-write failure after successful conversion has already consumed an export. |
|
|
142
|
+
| `UNSUPPORTED_FORMAT` | Export only | The format is unsupported or incompatible with the Unit type. Check export options. |
|
|
143
|
+
| `INVALID_FILE` | Export only | The conversion input is invalid. Check its contents. |
|
|
144
|
+
| `INCOMPLETE_SNAPSHOT` | Export only | Export data is incomplete. Provide complete data or a complete Snapshot. |
|
|
145
|
+
| `CONVERSION_FAILED` | Export only | Conversion failed. Retain the error and check the input contents. |
|
|
146
|
+
|
|
147
|
+
Applications may derive expiry reminders from `licenseStatus` and `expiresAt`. No separate notice list or automatic logging is emitted. Supplied invalid credentials reject configuration, queries and exports with `LICENSE_INVALID`. If usage processing fails, do not infer whether a count was consumed from the error alone; preserve the complete error for support.
|
|
148
|
+
ESM and CommonJS share configuration within the same JavaScript context. Each `worker_threads` Worker must configure itself or initialize from its environment; Workers share the export quota, not their configuration. Each backend used in a Worker opens its own authorization service on first use. Exports capture configuration when the public method is called; a later configuration change applies to subsequently started exports. A failed explicit configuration leaves the previous configuration in effect.
|
|
149
|
+
|
|
150
|
+
## Optional PDF support
|
|
151
|
+
|
|
152
|
+
Install the optional backend with the SDK, then execute the PDF side-effect import before converting:
|
|
153
|
+
|
|
154
|
+
```sh
|
|
155
|
+
pnpm add @univerjs-pro/exchange-node @univerjs-pro/exchange-pdf-node-binding
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
import '@univerjs-pro/exchange-node/pdf';
|
|
160
|
+
import { UniverInstanceType } from '@univerjs/core';
|
|
161
|
+
import { ExchangeFormat, importBuffer, exportToBuffer } from '@univerjs-pro/exchange-node';
|
|
162
|
+
|
|
163
|
+
const pdf = await importBuffer(pdfBuffer, {
|
|
164
|
+
type: UniverInstanceType.UNIVER_PDF,
|
|
165
|
+
format: ExchangeFormat.PDF,
|
|
166
|
+
fileName: 'input.pdf',
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
const output = await exportToBuffer(pdf, {
|
|
170
|
+
type: UniverInstanceType.UNIVER_PDF,
|
|
171
|
+
format: ExchangeFormat.PDF,
|
|
172
|
+
onDiagnostics: async (items) => {
|
|
173
|
+
// The application decides whether to display or record these messages.
|
|
174
|
+
for (const item of items) console.warn(item.code, item.message, item.details);
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
The same eight Buffer/File and Unit/Snapshot methods support PDF. PDF conversion operates between PDF files and PDF Unit/Snapshot data; it does not convert Office units to PDF. The optional backend loads when a PDF conversion, PDF quota query, or configuration after registration is requested. Import `/pdf` before calling `configureExchange` in PDF-only applications so configuration uses the PDF backend without loading the Office native library. The side-effect import itself does not load native code. Office-only applications do not need it. Without the runtime side-effect import, PDF conversion rejects with `UNSUPPORTED_FORMAT`. TypeScript augmentation applies to the compilation program; importing only its types does not initialize the runtime.
|
|
180
|
+
|
|
181
|
+
PDF native packages support Linux x64/arm64 with glibc, macOS x64/arm64, and Windows x64. Linux musl and Windows arm64 are unsupported. Each platform package contains a single `.node` file; applications do not need a separate Go executable or project dynamic library.
|
|
182
|
+
|
|
183
|
+
For services that require process-level fault isolation, run PDF conversion in a dedicated Node process or conversion worker service. The addon runs native code in its host process; `worker_threads` and asynchronous APIs do not isolate fatal native crashes. Limit in-flight conversions based on document size and measured process memory, and report abnormal worker exits as task failures.
|
|
184
|
+
|
|
185
|
+
Imported PDF units contain their document resources. Preserve `document`, its asset streams, `metadata`, and `editState` when saving them. Snapshot APIs use the existing complete aggregate representation; server resource IDs alone do not provide the bytes required for offline export, and the SDK does not fetch external resources automatically. The SDK performs the Unit/Snapshot transforms without creating a Univer runtime or applying edits a second time.
|
|
186
|
+
|
|
187
|
+
Export fails by default if a required image is missing or undecodable. Set `strictResources: false` only when the application accepts omission of those images. It does not ignore file IO, engine, or unrelated conversion failures. Use `onDiagnostics` to receive the resulting messages and their asset/page identifiers.
|
|
188
|
+
|
|
189
|
+
`onDiagnostics` is optional on import and export. It receives one nonempty batch per successful conversion and is awaited before the method returns or writes the destination file. An empty batch does not invoke it; the SDK does not log or retain a global history. Conversion failures reject the Promise instead of reporting a successful diagnostic batch. Exceptions thrown or rejected by the application's callback propagate unchanged. A destination write failure uses `IO_ERROR`; it does not trigger another conversion.
|
|
190
|
+
|
|
191
|
+
Handle conversion failures through the existing `ExchangeError` and its `code`. `NATIVE_LOAD_FAILED` means that the optional platform package could not initialize; `CONVERSION_FAILED` means the conversion failed. For PDF resource failures, the message includes the applicable asset, page and entry identifiers; the native error remains available as `error.cause`. These failures do not invoke `onDiagnostics`.
|
|
192
|
+
|
|
193
|
+
## Building from source
|
|
194
|
+
|
|
195
|
+
From a clean checkout with the repository's submodules initialized:
|
|
196
|
+
|
|
197
|
+
```sh
|
|
198
|
+
pnpm install --frozen-lockfile --ignore-scripts --filter @univerjs-pro/exchange-node...
|
|
199
|
+
pnpm --filter @univerjs-pro/exchange-node build
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
This builds the JavaScript wrapper and declarations. The optional PDF native package is built separately using the verified inputs and platform toolchain described in `packages/exchange-pdf-node-binding/README.md`.
|
|
203
|
+
|
|
204
|
+
The manual `Exchange PDF Binding Release` workflow accepts an independent dev `binding_version` and an optional `native_ref`. When omitted, `native_ref` resolves univer-exchange `main` once to a full commit shared by all five platform builds. Each platform builds or reuses an exactly matching verified native cache, then runs installed-Binding smoke tests and dependency inspection before publication to insider-npm. This workflow neither builds nor publishes the Exchange Wrapper. Automatic source and packaging checks run separately in `Exchange PDF Checks`; full SDK integration tests use the explicit script documented in `packages/exchange-pdf-node-binding/README.md`.
|
|
205
|
+
|
|
206
|
+
The PDF backend uses private per-conversion temporary files and requires writable OS temporary storage. Embedded resources are materialized there and removed before returning. Existing system/configured font lookup still applies; this package does not promise identical font appearance across hosts.
|
|
207
|
+
|
|
208
|
+
## Test scopes
|
|
209
|
+
|
|
210
|
+
`pnpm --filter @univerjs-pro/exchange-node test` runs Office and shared wrapper checks, excluding the optional PDF contract suite. The repository's root `test`, `test:ts` and `test:rust` commands retain their existing scopes. PDF checks are explicit:
|
|
211
|
+
|
|
212
|
+
```sh
|
|
213
|
+
pnpm --filter @univerjs-pro/exchange-node test:pdf
|
|
214
|
+
# After building the wrapper:
|
|
215
|
+
pnpm --filter @univerjs-pro/exchange-node test:pdf:types
|
|
216
|
+
pnpm --filter @univerjs-pro/exchange-node test:pdf:package
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
The PDF binding package has explicit `test:unit` and `test:bridge` commands instead of a default `test`, so recursive workspace tests do not compile its native bridge. In CI, full native PDF builds run only in the manual release workflow; full SDK integration tests are invoked separately. PDF workflow quick checks follow PDF/shared adapter changes, rather than unrelated Office tests, documentation or lockfile-only changes.
|
package/lib/cjs/index.cjs
CHANGED
|
@@ -42,23 +42,25 @@ __export(index_exports, {
|
|
|
42
42
|
ExchangeErrorCode: () => ExchangeErrorCode,
|
|
43
43
|
ExchangeFormat: () => ExchangeFormat,
|
|
44
44
|
FormulaCalculationMode: () => FormulaCalculationMode,
|
|
45
|
+
configureExchange: () => configureExchange,
|
|
45
46
|
exportSnapshotToBuffer: () => exportSnapshotToBuffer,
|
|
46
47
|
exportSnapshotToFile: () => exportSnapshotToFile,
|
|
47
48
|
exportToBuffer: () => exportToBuffer,
|
|
48
49
|
exportToFile: () => exportToFile,
|
|
50
|
+
getExportQuota: () => getExportQuota,
|
|
49
51
|
importBuffer: () => importBuffer,
|
|
50
52
|
importBufferToSnapshot: () => importBufferToSnapshot,
|
|
51
53
|
importFile: () => importFile,
|
|
52
54
|
importFileToSnapshot: () => importFileToSnapshot
|
|
53
55
|
});
|
|
54
56
|
module.exports = __toCommonJS(index_exports);
|
|
55
|
-
var import_collaboration = require("@univerjs-pro/collaboration"), import_core = require("@univerjs/core"), import_node_path = require("node:path"), import_promises = require("node:fs/promises");
|
|
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");
|
|
56
58
|
|
|
57
59
|
// src/binding.ts
|
|
58
60
|
var import_node_module = require("node:module"), import_node_process = __toESM(require("node:process"), 1);
|
|
59
61
|
|
|
60
62
|
// src/types.ts
|
|
61
|
-
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))(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))(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))(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 {
|
|
62
64
|
constructor(code, message, options) {
|
|
63
65
|
super(message, options);
|
|
64
66
|
this.code = code;
|
|
@@ -72,12 +74,21 @@ var nativeBinding = null, nativeBindingSource = null, nodeRequire = (0, import_n
|
|
|
72
74
|
function errorMessage(error) {
|
|
73
75
|
return error instanceof Error ? error.message : String(error);
|
|
74
76
|
}
|
|
77
|
+
function validateBinding(binding) {
|
|
78
|
+
try {
|
|
79
|
+
if (!binding || typeof binding.__internalExchangeConfigProtocolVersion != "function" || binding.__internalExchangeConfigProtocolVersion() !== 1 || typeof binding.__internalExchangeConfigure != "function" || typeof binding.__internalExchangeGetExportQuota != "function" || typeof binding.exchangeExportSnapshot != "function")
|
|
80
|
+
throw new ExchangeError("NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */, "Incompatible native exchange configuration protocol.");
|
|
81
|
+
return binding;
|
|
82
|
+
} catch (error) {
|
|
83
|
+
throw error instanceof ExchangeError ? error : new ExchangeError("NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */, "Incompatible native exchange configuration protocol.");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
75
86
|
async function loadNativeBinding() {
|
|
76
87
|
if (nativeBinding)
|
|
77
88
|
return nativeBinding;
|
|
78
89
|
let errors = [];
|
|
79
90
|
try {
|
|
80
|
-
return nativeBinding = nodeRequire("@univerjs-pro/exchange-node-binding"), nativeBindingSource = "@univerjs-pro/exchange-node-binding", nativeBinding;
|
|
91
|
+
return nativeBinding = validateBinding(nodeRequire("@univerjs-pro/exchange-node-binding")), nativeBindingSource = "@univerjs-pro/exchange-node-binding", nativeBinding;
|
|
81
92
|
} catch (error) {
|
|
82
93
|
errors.push(`@univerjs-pro/exchange-node-binding: ${errorMessage(error)}`);
|
|
83
94
|
}
|
|
@@ -95,6 +106,13 @@ async function loadNativeBinding() {
|
|
|
95
106
|
);
|
|
96
107
|
}
|
|
97
108
|
|
|
109
|
+
// src/errors.ts
|
|
110
|
+
function structuredExchangeError(error, ErrorClass = ExchangeError) {
|
|
111
|
+
return error instanceof ErrorClass ? error : error !== null && typeof error == "object" && "code" in error && "message" in error && typeof error.code == "string" && typeof error.message == "string" && Object.values(ExchangeErrorCode).includes(error.code) ? new ErrorClass(error.code, error.message, {
|
|
112
|
+
cause: error
|
|
113
|
+
}) : new ErrorClass("NATIVE_LOAD_FAILED" /* NATIVE_LOAD_FAILED */, "Invalid native exchange error protocol.");
|
|
114
|
+
}
|
|
115
|
+
|
|
98
116
|
// src/snapshot-collector.ts
|
|
99
117
|
var import_protocol = require("@univerjs/protocol");
|
|
100
118
|
function createSnapshotCollector() {
|
|
@@ -192,6 +210,14 @@ function fromNativeSnapshot(value) {
|
|
|
192
210
|
};
|
|
193
211
|
}
|
|
194
212
|
|
|
213
|
+
// src/index.ts
|
|
214
|
+
var import_runtime = __toESM(require("../shared/runtime.cjs"), 1);
|
|
215
|
+
|
|
216
|
+
// src/diagnostics.ts
|
|
217
|
+
async function deliverDiagnostics(options, diagnostics) {
|
|
218
|
+
diagnostics.length !== 0 && options.onDiagnostics && await options.onDiagnostics(diagnostics);
|
|
219
|
+
}
|
|
220
|
+
|
|
195
221
|
// src/index.ts
|
|
196
222
|
var FORMAT_BY_EXTENSION = {
|
|
197
223
|
".xls": "xls" /* XLS */,
|
|
@@ -201,8 +227,25 @@ var FORMAT_BY_EXTENSION = {
|
|
|
201
227
|
".doc": "doc" /* DOC */,
|
|
202
228
|
".docx": "docx" /* DOCX */,
|
|
203
229
|
".ppt": "ppt" /* PPT */,
|
|
204
|
-
".pptx": "pptx" /* PPTX
|
|
230
|
+
".pptx": "pptx" /* PPTX */,
|
|
231
|
+
".pdf": "pdf" /* PDF */
|
|
205
232
|
};
|
|
233
|
+
function pdfAdapter(type, format) {
|
|
234
|
+
if (type !== import_core.UniverInstanceType.UNIVER_PDF && format !== "pdf" /* PDF */)
|
|
235
|
+
return;
|
|
236
|
+
if (type !== import_core.UniverInstanceType.UNIVER_PDF || format !== "pdf" /* PDF */)
|
|
237
|
+
throw new ExchangeError(
|
|
238
|
+
"UNSUPPORTED_FORMAT" /* UNSUPPORTED_FORMAT */,
|
|
239
|
+
"PDF conversion requires PDF unit type and PDF format"
|
|
240
|
+
);
|
|
241
|
+
let adapter = import_runtime.default.getPdf();
|
|
242
|
+
if (!adapter)
|
|
243
|
+
throw new ExchangeError(
|
|
244
|
+
"UNSUPPORTED_FORMAT" /* UNSUPPORTED_FORMAT */,
|
|
245
|
+
"Enable PDF conversion by importing '@univerjs-pro/exchange-node/pdf' first"
|
|
246
|
+
);
|
|
247
|
+
return adapter;
|
|
248
|
+
}
|
|
206
249
|
function normalizeWorkbookSheetOrder(data) {
|
|
207
250
|
let existingOrder = Array.isArray(data.sheetOrder) ? data.sheetOrder.filter((sheetId) => typeof sheetId == "string") : [], ordered = new Set(existingOrder), missingSheetIds = Object.keys(data.sheets).filter((sheetId) => !ordered.has(sheetId));
|
|
208
251
|
return missingSheetIds.length === 0 ? data : { ...data, sheetOrder: [...existingOrder, ...missingSheetIds] };
|
|
@@ -215,6 +258,31 @@ function exchangeError(error, fallback) {
|
|
|
215
258
|
cause: error
|
|
216
259
|
}) : error instanceof TypeError ? new ExchangeError("INVALID_ARGUMENT" /* INVALID_ARGUMENT */, message, { cause: error }) : new ExchangeError(fallback, message, { cause: error });
|
|
217
260
|
}
|
|
261
|
+
async function configureExchange(config) {
|
|
262
|
+
try {
|
|
263
|
+
let adapter = import_runtime.default.getPdf();
|
|
264
|
+
await import_runtime.default.configure(config, async (snapshot) => {
|
|
265
|
+
adapter ? await adapter.configure(snapshot) : await (await loadNativeBinding()).__internalExchangeConfigure(configBuffer(snapshot));
|
|
266
|
+
});
|
|
267
|
+
} catch (error) {
|
|
268
|
+
throw structuredExchangeError(error);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
function configBuffer(snapshot) {
|
|
272
|
+
return import_node_buffer2.Buffer.from(JSON.stringify(snapshot));
|
|
273
|
+
}
|
|
274
|
+
async function getExportQuota(options = {}) {
|
|
275
|
+
try {
|
|
276
|
+
if (options === null || typeof options != "object" || Array.isArray(options) || Reflect.ownKeys(options).some((key) => key !== "license" && key !== "licenseKey"))
|
|
277
|
+
throw new ExchangeError("INVALID_ARGUMENT" /* INVALID_ARGUMENT */, "Invalid argument: options.");
|
|
278
|
+
let snapshot = await import_runtime.default.capture(options), adapter = import_runtime.default.getPdf();
|
|
279
|
+
if (adapter) return await adapter.quota(snapshot);
|
|
280
|
+
let binding = await loadNativeBinding();
|
|
281
|
+
return JSON.parse(await binding.__internalExchangeGetExportQuota(configBuffer(snapshot)));
|
|
282
|
+
} catch (error) {
|
|
283
|
+
throw structuredExchangeError(error);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
218
286
|
function resolveFormat(fileName, format) {
|
|
219
287
|
if (format)
|
|
220
288
|
return format;
|
|
@@ -358,49 +426,106 @@ async function memoryToSnapshot(data, options) {
|
|
|
358
426
|
throw exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
|
|
359
427
|
}
|
|
360
428
|
}
|
|
429
|
+
async function readInput(path) {
|
|
430
|
+
try {
|
|
431
|
+
return await (0, import_promises.readFile)(path);
|
|
432
|
+
} catch (error) {
|
|
433
|
+
throw exchangeError(error, "IO_ERROR" /* IO_ERROR */);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
async function importResult(input, options, fileName, asSnapshot) {
|
|
437
|
+
let result;
|
|
438
|
+
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 });
|
|
442
|
+
result = {
|
|
443
|
+
value: asSnapshot ? await adapter.toSnapshot(converted.value) : converted.value,
|
|
444
|
+
diagnostics: converted.diagnostics
|
|
445
|
+
};
|
|
446
|
+
} else {
|
|
447
|
+
let snapshot = await importSnapshot(input, options, fileName);
|
|
448
|
+
result = { value: asSnapshot ? snapshot : await snapshotToMemory(snapshot, options.type), diagnostics: [] };
|
|
449
|
+
}
|
|
450
|
+
} catch (error) {
|
|
451
|
+
throw exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
|
|
452
|
+
}
|
|
453
|
+
return await deliverDiagnostics(options, result.diagnostics), result.value;
|
|
454
|
+
}
|
|
361
455
|
async function importFile(path, options) {
|
|
362
|
-
|
|
363
|
-
return snapshotToMemory(snapshot, options.type);
|
|
456
|
+
return importResult(await readInput(path), options, options.fileName ?? (0, import_node_path.basename)(path), !1);
|
|
364
457
|
}
|
|
365
458
|
async function importBuffer(input, options) {
|
|
366
|
-
|
|
367
|
-
return snapshotToMemory(snapshot, options.type);
|
|
459
|
+
return importResult(input, options, options.fileName, !1);
|
|
368
460
|
}
|
|
369
461
|
async function importFileToSnapshot(path, options) {
|
|
370
|
-
|
|
462
|
+
return importResult(
|
|
463
|
+
await readInput(path),
|
|
464
|
+
options,
|
|
465
|
+
options.fileName ?? (0, import_node_path.basename)(path),
|
|
466
|
+
!0
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
async function importBufferToSnapshot(input, options) {
|
|
470
|
+
return importResult(input, options, options.fileName, !0);
|
|
471
|
+
}
|
|
472
|
+
async function exportResult(data, options, isSnapshot, captured) {
|
|
473
|
+
let result;
|
|
371
474
|
try {
|
|
372
|
-
|
|
475
|
+
let config = await captured, adapter = pdfAdapter(options.type, options.format);
|
|
476
|
+
if (adapter) {
|
|
477
|
+
let unit = isSnapshot ? adapter.fromSnapshot(data) : data;
|
|
478
|
+
result = await adapter.export(
|
|
479
|
+
unit,
|
|
480
|
+
{ strictResources: "strictResources" in options ? options.strictResources : void 0 },
|
|
481
|
+
config
|
|
482
|
+
);
|
|
483
|
+
} else {
|
|
484
|
+
let snapshot = isSnapshot ? data : await memoryToSnapshot(data, options), input, nativeOptions;
|
|
485
|
+
try {
|
|
486
|
+
input = toNativeSnapshot(snapshot), nativeOptions = JSON.stringify(nativeExportOptions(options));
|
|
487
|
+
} catch (error) {
|
|
488
|
+
throw error instanceof ExchangeError ? error : new ExchangeError(
|
|
489
|
+
"INVALID_ARGUMENT" /* INVALID_ARGUMENT */,
|
|
490
|
+
`Invalid export arguments: ${error instanceof Error ? error.message : String(error)}`,
|
|
491
|
+
{ cause: error }
|
|
492
|
+
);
|
|
493
|
+
}
|
|
494
|
+
result = {
|
|
495
|
+
value: await (await loadNativeBinding()).exchangeExportSnapshot(input, nativeOptions, configBuffer(config)),
|
|
496
|
+
diagnostics: []
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
} catch (error) {
|
|
500
|
+
throw structuredExchangeError(error);
|
|
501
|
+
}
|
|
502
|
+
return await deliverDiagnostics(options, result.diagnostics), result.value;
|
|
503
|
+
}
|
|
504
|
+
async function writeOutput(path, output) {
|
|
505
|
+
try {
|
|
506
|
+
await (0, import_promises.writeFile)(path, output);
|
|
373
507
|
} catch (error) {
|
|
374
508
|
throw exchangeError(error, "IO_ERROR" /* IO_ERROR */);
|
|
375
509
|
}
|
|
376
|
-
return importSnapshot(input, options, fileName);
|
|
377
510
|
}
|
|
378
|
-
|
|
379
|
-
|
|
511
|
+
function captureExportConfig(options) {
|
|
512
|
+
try {
|
|
513
|
+
return import_runtime.default.capture(options);
|
|
514
|
+
} catch (error) {
|
|
515
|
+
return Promise.reject(structuredExchangeError(error));
|
|
516
|
+
}
|
|
380
517
|
}
|
|
381
518
|
async function exportToBuffer(data, options) {
|
|
382
|
-
return
|
|
519
|
+
return exportResult(data, options, !1, captureExportConfig(options));
|
|
383
520
|
}
|
|
384
521
|
async function exportToFile(data, path, options) {
|
|
385
|
-
await
|
|
522
|
+
await writeOutput(path, await exportResult(data, options, !1, captureExportConfig(options)));
|
|
386
523
|
}
|
|
387
524
|
async function exportSnapshotToBuffer(snapshot, options) {
|
|
388
|
-
|
|
389
|
-
return await (await loadNativeBinding()).exchangeExportSnapshot(
|
|
390
|
-
toNativeSnapshot(snapshot),
|
|
391
|
-
JSON.stringify(nativeExportOptions(options))
|
|
392
|
-
);
|
|
393
|
-
} catch (error) {
|
|
394
|
-
throw exchangeError(error, "CONVERSION_FAILED" /* CONVERSION_FAILED */);
|
|
395
|
-
}
|
|
525
|
+
return exportResult(snapshot, options, !0, captureExportConfig(options));
|
|
396
526
|
}
|
|
397
527
|
async function exportSnapshotToFile(snapshot, path, options) {
|
|
398
|
-
|
|
399
|
-
try {
|
|
400
|
-
await (0, import_promises.writeFile)(path, output);
|
|
401
|
-
} catch (error) {
|
|
402
|
-
throw exchangeError(error, "IO_ERROR" /* IO_ERROR */);
|
|
403
|
-
}
|
|
528
|
+
await writeOutput(path, await exportResult(snapshot, options, !0, captureExportConfig(options)));
|
|
404
529
|
}
|
|
405
530
|
// Annotate the CommonJS export names for ESM import in node:
|
|
406
531
|
0 && (module.exports = {
|
|
@@ -421,10 +546,12 @@ async function exportSnapshotToFile(snapshot, path, options) {
|
|
|
421
546
|
ExchangeErrorCode,
|
|
422
547
|
ExchangeFormat,
|
|
423
548
|
FormulaCalculationMode,
|
|
549
|
+
configureExchange,
|
|
424
550
|
exportSnapshotToBuffer,
|
|
425
551
|
exportSnapshotToFile,
|
|
426
552
|
exportToBuffer,
|
|
427
553
|
exportToFile,
|
|
554
|
+
getExportQuota,
|
|
428
555
|
importBuffer,
|
|
429
556
|
importBufferToSnapshot,
|
|
430
557
|
importFile,
|