@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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @univerjs-pro/exchange-node
2
2
 
3
- Node.js SDK for converting between Office/PDF formats, Univer unit data, and complete Univer snapshots.
3
+ Node.js SDK for converting between Office/PDF formats, Mermaid diagrams, Univer unit data, and complete Univer snapshots.
4
4
 
5
5
  The package exposes two API families:
6
6
 
@@ -15,7 +15,7 @@ Keep this package and its Univer SDK dependencies on the same SDK version for no
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.
18
+ Native Binding dependencies allow same-minor patches from the version paired with the SDK; the application lock controls the installed patch.
19
19
 
20
20
  ## Import
21
21
 
@@ -32,6 +32,14 @@ const workbook = await importBuffer(xlsxBuffer, {
32
32
 
33
33
  `importBuffer` requires `fileName`. File imports use the path basename by default and allow `fileName` to override format inference. An explicit `format` always takes precedence.
34
34
 
35
+ ### XLSX legacy note sizes
36
+
37
+ XLSX imports convert legacy note dimensions from VML to pixels, then store `max(convertedWidth, 160)` and `max(convertedHeight, 72)` in the note resource. Each dimension is clamped independently to accommodate Univer's note styling. Missing, zero or unreadable dimensions, including an absent or unmatched VML shape, use the same minimum. Previously, small dimensions and zero-size fallbacks were imported directly.
38
+
39
+ This changes imported note geometry: larger dimensions are retained, while smaller boxes grow. Exporting the imported workbook writes those resulting sizes, so a round trip can enlarge notes in Excel too. The resource structure and API signatures are unchanged; existing snapshots are not resized automatically. Re-import the original XLSX to apply the new minimum, and update snapshot size assertions that expect smaller values. This fixed import minimum does not read the UI's `defaultNoteSize` configuration or prevent users from resizing notes afterward. Threaded comments are outside this change.
40
+
41
+ The behavior requires Office native artifacts containing this import correction; updating only the JavaScript wrapper does not change an older native importer. Source-level XLSX tests cover conversion, independent size limits, missing shapes and existing note metadata. Published package combinations and the screenshot's original workbook have not been verified.
42
+
35
43
  ## Export
36
44
 
37
45
  ```ts
@@ -51,6 +59,36 @@ const xlsxBuffer = await exportToBuffer(workbook, {
51
59
 
52
60
  Sheet export defaults to `FormulaCalculationMode.WHEN_EMPTY`: missing cached formula values are calculated, while existing cached values are preserved. Pass `FormulaCalculationMode.NO` to disable calculation.
53
61
 
62
+ ### XLSX worksheet default styles
63
+
64
+ XLSX has no worksheet-level equivalent of Univer's `sheet.defaultStyle`. The Office native exporter passes the complete default-style object, or the object resolved from its workbook style ID, through the same style conversion used for cells. Column defaults and the necessary composed row/cell styles preserve supported font properties, RGB text and fill colors, borders, number formats, alignment, wrapping, shrink-to-fit, rotation, text direction and left indent. The projection does not filter the input to a list of font fields. Unspecified attributes retain the existing workbook export base; column, row and cell attributes override the default by property, including explicit `0` and `null` clearing values. This also applies to `FWorksheet.setDefaultStyle()` followed by `workbook.save()` and to complete snapshot exports. The workbook's existing Normal style is retained.
65
+
66
+ Previously, worksheet defaults such as a changed font or a default fill could be silently lost on export. The corrected native binding preserves the supported effective styles, including blank cells within the worksheet's `columnCount`. Existing cells and explicit column metadata beyond that count are also covered, up to XLSX limits. Columns outside that range and subsequently inserted columns follow Excel's formatting rules; there is no persistent sheet-default inheritance rule in XLSX. Export does not mutate the supplied data. Re-import can represent the defaults using column/cell styles, so `getDefaultStyle()` and snapshot style IDs need not equal their pre-export values. Explicit false bold/italic flags are retained on import, General horizontal alignment can appear as `ht: null` to clear inherited alignment, and font superscript/subscript is read back. These shared conversion corrections also apply to ordinary cell/row/column styles. Applications asserting identical snapshot structure should compare effective styles instead. Default-style colors now use the same validation as cell styles; an invalid CSS color fails export instead of being silently discarded.
67
+
68
+ Explicit `ff/va/vt/td: null` clears inherited formatting instead of silently re-inheriting it. XLSX stores equivalent concrete values: the core font fallback (Arial), baseline text, bottom alignment and automatic reading order (`td: 0`). `vt: 0` also maps to bottom alignment. These values can replace the original `null` in the re-imported snapshot. The same handling applies to ordinary row/column/cell styles and rich-text cell font-family inheritance; when an imported cell XF omits these properties, the importer supplies clearing values where its row/column parent sets them. This changes previously inherited appearance for those inputs, so applications that relied on it should specify the desired formatting explicitly.
69
+
70
+ All default-style fields reach the existing cell-style encoder; this does not make every Univer property losslessly representable in XLSX. Default fill and border theme colors are resolved against the workbook's current palette before encoding, including theme zero; their theme-token identity is not guaranteed after the round trip. Existing conversion limits still apply: for example, there is no independent cell-font overline or per-script East Asian font-family mapping, bottom text-decoration lines are not converted to cell-edge borders, only Excel's supported border directions are written, and padding is mapped to left indent rather than arbitrary four-sided pixel padding. Decoration-specific colors/patterns and wrapping modes follow the existing Excel mapping. Explicit false font flags in table themes and conditional formats are also retained as `0`, since they use the same font reader.
71
+
72
+ The generated column records carry the worksheet's column widths as well as their styles, because Excel can treat a style-bearing column with no width as zero-width. Export may add style-only cells where row and column formatting must be combined; highly intersecting row/column styles can increase memory use, processing time and output size. This change does not add a style-count limit check or an automatic fallback: it does not intentionally reject export because of that count. The generated workbook can exceed Excel's supported format limits, and successful loading or automatic repair by Excel is not guaranteed. This fix also does not adjust the existing Table formatting logic. In the tested imported Table case, projecting a worksheet default fill into direct cell formats masked Table theme fills after export; preserving Table theme appearance in that combination remains outside this fix's verified guarantees.
73
+
74
+ Existing diagnostics and native protocol signatures are unchanged. The fix requires Office native artifacts containing the default-style projection and corresponding explicit-override import corrections; updating only the JavaScript wrapper cannot update an older native implementation. XLSX files remain standard Office files, but an older native importer can still lose clearing or baseline-offset information. Published old/new package combinations must be validated before promotion; the package version string alone does not establish this behavior.
75
+
76
+ Row and column styles are independent of `sheet.defaultStyle`. The exporter now materializes them on cells whenever `rowData` or `columnData` carries a style, including worksheets without a default style and worksheets whose default only restates the workbook Normal font. A cell that would otherwise show the column style only through `<col style>` therefore receives an explicit cell style, so readers that ignore column formatting (for example, openpyxl) resolve the same font as Univer. Existing cells at row/column intersections receive the composed style as well, because an XLSX row format shadows a column format instead of merging it by property; blank intersections are not filled in, so this fix does not grow the used range, `columnCount`/`rowCount`, or the `<dimension ref>` of a worksheet. Explicit cell styles keep winning per property; only properties the cell leaves unset are inherited. Unaffected cells stay on the workbook default, so output grows only where dimension styles apply, and additional `cellXfs` entries can appear for cells that combine their own style with a row/column style. The same projection applies to the streaming snapshot-bundle export (`prepare_snapshot_bundle_export` plus `export_prepared_snapshot_bundle_to_file`): block cells are composed as they are written. Filling blank intersections remains limited to worksheets whose own `defaultStyle` takes part in the projection, as before this change.
77
+
78
+ ### XLSX Table differential formats
79
+
80
+ Tables with direct differential formats keep their complete table theme when rows or columns are inserted, deleted or moved. Direct formats are evaluated from table metadata by the matching Univer runtime instead of being materialized into direct cell styles. This requires matching Sheets Table, Sheets, Sheets Numfmt and Office native implementations; the JavaScript wrapper alone cannot update an older runtime or binding. Release identities must be selected and the full consumer combination validated before promotion.
81
+
82
+ The six table-level formats live in `ITableJson.meta._xlsx.options`: `dataDxfStyle`, `headerRowDxfStyle`, `totalsRowDxfStyle`, `tableBorderDxfStyle`, `headerRowBorderDxfStyle` and `totalsRowBorderDxfStyle`. The three column-level formats live in `ITableColumnJson.meta._xlsx`: `dataDxfStyle`, `headerRowDxfStyle` and `totalsRowDxfStyle`. No resource version field is added; `TableColumn.style` is not used for these formats.
83
+
84
+ The frontend only preserves and renders imported dxf; it does not provide a UI, Facade setter or dedicated dxf editing command. Theme and number-format integration is conditional on a matching dxf, and structural preservation changes are conditional on the table having dxf metadata. Tables without dxf keep the previous frontend processing paths.
85
+
86
+ When the metadata container exists, its fields are authoritative. Removing a format key removes that direct format on export; stale top-level fields and the original table XML do not restore it. Top-level legacy formats remain readable when the corresponding metadata container is absent. A table originally without a theme but with direct formats stays unthemed until a theme is explicitly chosen. Theme selection and direct formats remain independent.
87
+
88
+ Previously, a structural edit could leave an empty `rust-direct-dxf-*` custom theme. Existing placeholder snapshots use the table's retained source reference to recover the source theme where available; missing source metadata or already-lost definitions cannot be recovered reliably. Re-importing the original XLSX is recommended for historical snapshots containing materialized cell styles. An old frontend can preserve metadata without rendering it, and an old binding can ignore metadata edits or clears; do not mix these implementations without consumer validation.
89
+
90
+ Raw dxf XML matching the current supported properties is retained. Regenerated Table dxf records also write supported alignment and wrapping properties. Editing a supported property regenerates that dxf using the existing encoder, so unsupported extensions are not guaranteed to survive that edit. OOXML inside-horizontal/inside-vertical border definitions not supported by the frontend border model are retained for unedited export but are not rendered as such. Source tests do not establish Excel rendering fidelity or compatibility of published package combinations. The native call signatures and existing diagnostics behavior are unchanged; in particular, this does not add an XLSX `onDiagnostics` channel.
91
+
54
92
  ## Complete snapshots
55
93
 
56
94
  Snapshot APIs use `ISnapshotWithBlocks`:
@@ -62,19 +100,147 @@ interface ISnapshotWithBlocks {
62
100
  }
63
101
  ```
64
102
 
65
- Sheet and Base snapshots must include every referenced sheet block. Doc and Slide snapshots normally use an empty `sheetBlocks` array.
103
+ Sheet and Base snapshots must include every referenced sheet block. Doc, Slide and Board snapshots normally use an empty `sheetBlocks` array.
66
104
 
67
105
  Snapshot APIs materialize the complete aggregate in memory. They do not call a Snapshot Server or stream blocks to storage.
68
106
 
107
+ ## Board export
108
+
109
+ Use the existing export methods with `UNIVER_BOARD` and `PPTX`:
110
+
111
+ ```ts
112
+ import { UniverInstanceType } from '@univerjs/core';
113
+ import { ExchangeFormat, exportToBuffer } from '@univerjs-pro/exchange-node';
114
+
115
+ const pptx = await exportToBuffer(board, {
116
+ type: UniverInstanceType.UNIVER_BOARD,
117
+ format: ExchangeFormat.PPTX,
118
+ });
119
+ ```
120
+
121
+ `exportToFile`, `exportSnapshotToBuffer` and `exportSnapshotToFile` support the same pair. Data exports accept `IBoardData`; snapshot exports accept the complete Board snapshot, including its binary `board.originalMeta` and resources. The active Board page becomes one editable PPTX slide. If `activePageId` is omitted, the first page in `pageOrder` is used. Missing or empty pages fail explicitly. This uses the CLI's existing Rust Board-to-Slide conversion; export fidelity follows that converter, rather than the browser renderer.
122
+
123
+ Board export needs no optional entry. It uses the existing Slide export authorization and shared export quota. The existing `files` and `ole` options can be passed for Board exports. `files.load` resolves required picture references on the exported page; no callback runs when there is no matching resource. Boards currently have no OLE attachment elements, so `ole.loadOnlineUnit` is not called. Accepting these options does not add Board attachment support.
124
+
125
+ ## Optional Mermaid import
126
+
127
+ Enable the `/mermaid` entry only when importing Mermaid. The existing import methods then return a complete Board or snapshot:
128
+
129
+ ```ts
130
+ import '@univerjs-pro/exchange-node/mermaid';
131
+ import { UniverInstanceType } from '@univerjs/core';
132
+ import { ExchangeFormat, importBuffer } from '@univerjs-pro/exchange-node';
133
+
134
+ const board = await importBuffer(Buffer.from('flowchart LR\nA -->|Approved| B'), {
135
+ type: UniverInstanceType.UNIVER_BOARD,
136
+ format: ExchangeFormat.MERMAID,
137
+ fileName: 'approval.mmd',
138
+ unitId: 'your-document-id', // Optional: omit to generate an ID, or use your system's document ID.
139
+ });
140
+ ```
141
+
142
+ `importFile`, `importFileToSnapshot` and `importBufferToSnapshot` support the same pair. File imports infer Mermaid from `.mmd` or `.mermaid`; other extensions need an explicit `format`. Buffer imports require `fileName` even with an explicit format. Its basename supplies the Board name, and its extension supplies the format when omitted.
143
+
144
+ The SDK compiles with the same Rust defaults as the CLI, materializes a Board page with the public Boards helpers, normalizes connector labels, and retains chart/table resources. It runs in pure Node. Supported diagram syntax and limits follow the [Rust Mermaid diagram inventory](../../crates/univer-exchange-rust/mermaid/src/inventory.rs). Compilation and imports do not consume export quota.
145
+
146
+ ### Advanced compilation
147
+
148
+ Use the named import when your application needs the intermediate conversion data, for example to insert a diagram into an existing Board:
149
+
150
+ ```ts
151
+ import { compileMermaid } from '@univerjs-pro/exchange-node/mermaid';
152
+
153
+ const draft = await compileMermaid('flowchart LR\nA --> B');
154
+ // draft: IBoardImportDraft from @univerjs-pro/boards.
155
+ ```
156
+
157
+ This import also enables the ordinary Mermaid import methods; no additional side-effect import is needed. The return type is the existing `IBoardImportDraft` owned by `@univerjs-pro/boards`, using its element, bounds and diagnostic types. It is neither `IBoardData` nor a snapshot. It uses the same Rust implementation and defaults as the CLI, preserving its JSON output without adding a Node-specific normalization step.
158
+
159
+ `compileMermaid` only converts data. Your application owns placement, insertion and persistence. This Node API does not provide resource merging or insertion into an existing Board; those capabilities depend on the receiving Web SDK and application. Use the complete import methods above to preserve those resources in a new Board or snapshot. For example, this matters for pie charts and the tables generated from class/ER diagrams.
160
+
161
+ Rust-only fields, including resource payloads and source metadata, may remain on the runtime object for internal conversion. They are not declared or guaranteed by this public API; consumers must use the Boards contract rather than depend on the native wire schema. Compilation does not accept target document/page IDs, positions or an import mode. There is no separate public Rust V2 DTO. Native diagnostic positions, when present, retain the CLI's byte offsets in normalized UTF-8 source.
162
+
163
+ Both APIs accept the CLI's resource manifest as **JSON content**, not a path:
164
+
165
+ ```ts
166
+ const draft = await compileMermaid(source, { resourceManifest: manifestJson });
167
+ const board = await importBuffer(sourceBuffer, {
168
+ type: UniverInstanceType.UNIVER_BOARD,
169
+ fileName: 'diagram.mmd',
170
+ mermaid: { resourceManifest: manifestJson },
171
+ });
172
+ ```
173
+
174
+ `source` and `resourceManifest` each accept a string or Buffer. Complete imports preserve resolved image sources; the compiler does not fetch remote image URLs. `/pdf` and `/mermaid` may be enabled together, in either order, with ESM or CommonJS.
175
+
176
+ Use the native binding selected by the SDK's declared dependencies. Board/Mermaid and its resource callbacks require the corresponding native capabilities; an incompatible externally supplied binding produces an explicit upgrade error. The new `MERMAID` enum and Board entries expand the existing type unions; consumers with exhaustive switches should add the new cases.
177
+
178
+ ## Application-owned file storage
179
+
180
+ Imported images and attachments stay inline in the snapshot unless the application takes them. Pass `files` to import and export to decide per file where bytes live. The converter decides which bytes are files, deduplicates identical content and writes references; the application stores and reads them.
181
+
182
+ Import offers each distinct file once, in order, through `files.store`:
183
+
184
+ ```ts
185
+ const imported = await importBufferToSnapshot(bytes, {
186
+ type: UniverInstanceType.UNIVER_SHEET,
187
+ fileName: 'host.xlsx',
188
+ files: {
189
+ store: async (file) => {
190
+ // file: { name, mimeType, size, bytes }
191
+ const stored = await storage.save(file.bytes, { name: file.name, contentType: file.mimeType });
192
+ return { mode: 'reference', source: stored.fileID };
193
+ },
194
+ },
195
+ });
196
+ ```
197
+
198
+ `inline` keeps the bytes in the snapshot; `reference` replaces them with a `UUID` reference to `source`. A rejected `store` fails the import with the application's error; every earlier call has completed by then. Thresholds and fallbacks are the application's decisions. Mermaid/Board imports accept the same `files.store` option: embedded pictures are offered once per distinct byte sequence, while inputs with no files call it zero times. Image URLs are preserved without being downloaded. PDF imports use the same file callbacks described below. `files` is not supported for Base imports.
199
+
200
+ Export asks `files.load` for every reference it needs and verifies stored attachments against the identity recorded in the snapshot:
201
+
202
+ ```ts
203
+ const bytes = await exportSnapshotToBuffer(host, {
204
+ type: UniverInstanceType.UNIVER_SHEET,
205
+ format: ExchangeFormat.XLSX,
206
+ files: {
207
+ load: async (ref) => {
208
+ // ref: { sourceType: 'UUID' | 'URL', source, unitId }
209
+ await authorize(ref.unitId, ref.source);
210
+ return { bytes: await storage.read(ref.source) };
211
+ },
212
+ },
213
+ });
214
+ ```
215
+
216
+ `load` must return bytes; an application that wants a placeholder returns the placeholder's bytes. `ref.unitId` names the snapshot the reference belongs to: the host, or one of its online child Units. `files` is accepted for Sheet/XLSX, Doc/DOCX, Slide/PPTX and PDF exports. Without `files`, including in online attachment exports, `UUID` and `URL` pictures keep each format's existing handling and a stored attachment is an explicit error.
217
+
218
+ Files are OLE attachments with their parts and pictures: floating and cell images in sheets, pictures and the page background in the document body, pictures, picture fills and page backgrounds in slides, layouts and masters, including inside groups. Shapes the importers render themselves and the import placeholder are converter output, not files, and stay inline; so do pictures in document headers and footers, which the exporters write back verbatim. Workbooks imported from XLSX also keep a verbatim copy of each worksheet's drawing parts, pictures included, for byte-exact export; storing such a picture removes the drawing's inline copy but not that retained part, and export writes the retained part.
219
+
220
+ ### Embedded OLE attachments
221
+
222
+ XLSX, DOCX and PPTX imports retain supported OLE occurrences with their original bytes. Ordinary export writes those originals back, including for occurrences that reference a converted online Unit. To embed the converted Units instead, add `ole` to the export options:
223
+
224
+ ```ts
225
+ ole: {
226
+ attachmentSource: 'online',
227
+ loadOnlineUnit: (ref) => readConfirmedSnapshot(ref.unitId, ref.type),
228
+ },
229
+ ```
230
+
231
+ The converter finds converted attachments on the canvas, calls `loadOnlineUnit` once per referenced Unit, exports each child through the same pipeline and embeds the result; children may reference further online Units. Recursion is bounded to 8 levels, 64 Units and 50 MiB; cycles, type mismatches, missing Units and `loadOnlineUnit` failures fail the export, which never falls back to stale originals. The whole task counts as one export against the license quota.
232
+
233
+ See [Embedded Office attachments](../../docs/ole-attachments.md) for supported placements, formats and limitations.
234
+
69
235
  ## Formats and platforms
70
236
 
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.
237
+ Office conversion 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. Board exports PPTX from the root entry; Mermaid imports Board through `/mermaid`. PDF import/export uses the optional `/pdf` entry described below.
72
238
 
73
- Office native packages are published for Linux x64 GNU, Linux arm64 GNU, Windows x64 MSVC, and macOS arm64.
239
+ Office native packages are published for Linux x64 GNU, Linux arm64 GNU, Windows x64 MSVC, and macOS x64/arm64.
74
240
 
75
241
  ## License and monthly export quota
76
242
 
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.
243
+ 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. Unset, empty or whitespace-only environment values count as absent; when both are absent, Free applies. A single nonblank value is an incomplete pair. Nonblank contents are passed unchanged. This normalization applies only to environment fallbacks; explicit configuration and per-operation values remain unchanged and are strictly validated.
78
244
 
79
245
  To configure credentials explicitly:
80
246
 
@@ -103,7 +269,7 @@ const output = await exportToBuffer(workbook, {
103
269
  });
104
270
  ```
105
271
 
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.
272
+ Omitting both fields uses the default configuration. A partial pair returns `INVALID_ARGUMENT`; credentials are never combined across sources. Explicit values, including empty strings, are strictly validated as supplied; they are not treated as absent or 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 uses the shared Office/PDF quota.
107
273
 
108
274
  `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
275
 
@@ -115,9 +281,11 @@ The response has nine fields:
115
281
  - `limit`, `used`, `reserved`, `remaining`: monthly limit, successful uses, in-flight uses and available balance; all `null` when unlimited.
116
282
  - `periodStart`, `periodEnd`: UTC ISO monthly quota bounds, inclusive start and exclusive end; `null` when unlimited.
117
283
 
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.
284
+ 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 existing remaining Free quota without resetting it.
285
+
286
+ 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 share quota. Imports do not require export authorization and do not consume export quota.
119
287
 
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.
288
+ Ordinary-user installation and export do not require sudo. The process needs writable local persistent storage for export usage. If that storage cannot be used, the SDK returns `LICENSE_USAGE_STORAGE_ERROR`; preserve the complete error and contact technical support.
121
289
 
122
290
  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
291
 
@@ -145,7 +313,13 @@ The following table compares quota queries and actual exports. Both APIs return
145
313
  | `CONVERSION_FAILED` | Export only | Conversion failed. Retain the error and check the input contents. |
146
314
 
147
315
  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.
316
+ 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. 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.
317
+
318
+ ## Advanced packaging
319
+
320
+ Standard npm installation is recommended. `UNIVER_NODE_SDK_RUNTIME_DIR_OVERRIDE` is an escape hatch for external packagers; our own build and runtime flows do not set it.
321
+ For example, a packaging script can collect the complete SDK runtime resource directory into `./sdk-runtime`, then set this variable to the directory's absolute runtime path before first SDK use.
322
+ Preserve the directory layout and use resources matching the SDK and target platform. Do not hard-code filenames, file counts or binding package names in the script; these can change between SDK releases.
149
323
 
150
324
  ## Optional PDF support
151
325
 
@@ -178,42 +352,22 @@ const output = await exportToBuffer(pdf, {
178
352
 
179
353
  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
354
 
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.
355
+ PDF 待发布的目标覆盖 Linux x64/ARM64(以 glibc 2.28 或 Alpine 3.20 musl 为最低验收环境)、macOS x64/ARM64 及 Windows x64。Windows ARM64 暂不支持。GNU 的最低 libc 基线与 Office/Formula 一致;Alpine 用户需配套包含 musl 平台包的新 PDF 加载器,既有版本尚无此支持。现有 glibc 用户可沿兼容依赖范围升级,无须修改应用 API、snapshot 或文件存取方式。每个平台包只包含一个 `.node` 文件,不需要额外 Go 可执行程序或项目动态库。新增目标的支持范围需经完整包组合验收后确认。
182
356
 
183
357
  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
358
 
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.
359
+ Imported PDF units follow the existing JS SDK snapshot contract. Preserve `document`, `sourceDocumentRef`, resource bindings, metadata, and `editState` when saving them. The source PDF is a managed file resource, resolved through `files.load`; applications do not need to keep a separate upload or supply another export input. Snapshot APIs retain the existing complete aggregate input requirement. File loading does not expand page fragments or generate edit instructions; existing requirements for saved semantic edit instructions remain in effect.
188
360
 
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.
361
+ PDF imports use the same `files.store` contract as Office: each distinct binary payload is offered once, including the source PDF, font programs, images, page rasters, native streams and embedded attachments. Returning `reference` replaces inline bytes with existing `resourceBindings` and stream references. Attachment names and document/page/associated-file relationships remain in the existing attachment assets; sharing bytes does not merge those relationships. Resource identities are scoped to their imported source, independently of the storage keys used to reuse identical bytes. Without a storage callback, resources remain inline.
190
362
 
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`.
363
+ PDF exports resolve required references through `files.load`, once per distinct reference in the Unit, and use the existing source-PDF edit exporter. If the exporter can reconstruct edits without a saved instruction file, failure to load that optional file preserves its existing fallback; required file failures still propagate. Loading prepares a copy and leaves the supplied Unit unchanged. Use a compatible PDF binding declared by the SDK's optional peer dependency. If you supply a native runtime directory, keep its PDF binary paired with the SDK. Edited exports reserialize PDF content and do not preserve original signature validity. PDF accepts valid `ole` options without requesting Office child Units.
192
364
 
193
- ## Building from source
365
+ File callbacks carry file metadata and bytes/references, not embedding classifications. Use the document's existing attachment and drawing metadata to distinguish ordinary files from OLE objects. Existing OLE SDK preview, online conversion and binding behavior continues to own those actions.
194
366
 
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
- ```
367
+ 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.
201
368
 
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`.
369
+ `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.
203
370
 
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`.
371
+ 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`.
205
372
 
206
373
  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.