@betteroffice/xlsx 0.3.0 → 0.5.1

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,235 +1,151 @@
1
1
  # @betteroffice/xlsx
2
2
 
3
- Framework-free core for the BetterOffice XLSX editor — the Rust engine (parse,
4
- calc, render) compiled to WebAssembly, plus display-list, viewport, hit-test,
5
- and accessibility helpers.
3
+ Framework-free XLSX parsing, formula calculation, editing, and rendering through a Rust/WebAssembly
4
+ engine. Includes canvas painting, viewport, hit-testing, accessibility, and clipboard helpers.
5
+
6
+ ## Install
6
7
 
7
8
  ```bash
8
9
  bun add @betteroffice/xlsx
9
10
  ```
10
11
 
11
- Most apps want the turnkey React component in
12
- [`@betteroffice/xlsx-react`](https://www.npmjs.com/package/@betteroffice/xlsx-react).
13
- Reach for this package directly to render a spreadsheet onto your own canvas or
14
- to drive a workbook headlessly.
15
-
16
- ## Open, render, edit, save
12
+ No peer dependencies.
17
13
 
18
- ```ts
19
- import { initWasm, openWorkbook, paintDisplayList } from "@betteroffice/xlsx";
14
+ ## Usage
20
15
 
21
- await initWasm();
22
- const workbook = openWorkbook(new Uint8Array(await file.arrayBuffer()));
16
+ Sheet, row and column indices are zero-based, so `editCell(0, 9, 2, ...)` writes cell C10 on the
17
+ first sheet.
23
18
 
24
- const ctx = canvas.getContext("2d")!;
25
- const dpr = devicePixelRatio;
26
- canvas.width = 800 * dpr;
27
- canvas.height = 600 * dpr;
28
- const frame = workbook.displayList({ x: 0, y: 0, width: 800, height: 600 });
29
- paintDisplayList(ctx, frame, dpr);
30
-
31
- workbook.editCell(0, 9, 2, "=SUM(C1:C9)"); // recalcs dependents
32
- const bytes = workbook.save();
19
+ ```ts
20
+ import { initWasm, openWorkbook } from '@betteroffice/xlsx';
21
+
22
+ export async function updateWorkbook(bytes: Uint8Array): Promise<Uint8Array> {
23
+ await initWasm();
24
+ const workbook = openWorkbook(bytes);
25
+ try {
26
+ workbook.editCell(0, 9, 2, '=SUM(C1:C9)');
27
+ return workbook.save();
28
+ } finally {
29
+ workbook.dispose();
30
+ }
31
+ }
33
32
  ```
34
33
 
35
- `initWasm()` fetches the packaged wasm asset once in browsers; other runtimes
36
- pass wasm bytes or a precompiled `WebAssembly.Module`.
34
+ Cell input parses text, numbers, booleans, and formulas;
35
+ formulas start with `=`. Editing a cell recalculates its dependents.
37
36
 
38
- Around the handle, the package exports the helpers a custom grid needs:
39
- `cellAtPoint` / `cellRect` / `rangeRect` (hit-testing), the viewport math,
40
- `buildA11yGrid` (accessibility tree), and `toTsv` / `fromTsv` (clipboard). The
41
- handle itself covers styling (`patchRangeStyle`, `setNumberFormat`), undo/redo,
42
- and PNG export (`renderPng` / `renderRangePng`; guard with
43
- `isPngExportAvailable`).
37
+ ## Entry points
44
38
 
45
- ## Print a range
39
+ These entry points are exported from `@betteroffice/xlsx`:
46
40
 
47
- `workbook.printDisplayList(sheet, range, metrics, gridlines)` renders a range
48
- without changing workbook data, the active sheet, or screen geometry. Pass
49
- `PrintMetrics` measured from the workbook's normal font: `dpi`, `maxDigitWidth`,
50
- `fontAscent`, and `fontDescent` use the layout device's pixels; `fontSizePt` and
51
- `defaultRowHeightPt` use points. `fontFamily` supplies the default face, and
52
- optional `defaultColumnWidth` uses the stored OOXML character width.
41
+ | entry point | description |
42
+ | --- | --- |
43
+ | `initWasm(input?)` | Initialize the engine; concurrent calls share initialization. |
44
+ | `openWorkbook(bytes, options?)` | Open XLSX bytes as a synchronous `WorkbookHandle` after initialization. |
45
+ | `openWorkbookSession(bytes, options?)` | Open a workbook in a dedicated worker with asynchronous access. |
46
+ | `paintDisplayList(ctx, frame, dpr, origin?)` | Paint a display list onto a canvas 2D context. |
47
+ | `isPngExportAvailable()` | Check whether the initialized engine supports PNG export. |
48
+ | `isProposalsAvailable()` | Check whether the initialized engine supports edit proposals. |
49
+ | `exportXlsxStructured(bytes, options?)` | Asynchronously export stored workbook content from bytes. |
50
+ | `exportXlsxMarkdown(bytes, options?, markdownOptions?)` | Asynchronously export Markdown from bytes. |
53
51
 
54
- The result uses 96-DPI logical coordinates. Paint it with `paintDisplayList(ctx,
55
- frame, scale, { x, y })`; the optional origin uses backing-store pixels, so page
56
- margins need no intermediate image. Cell ranges, paper size, and pagination are
57
- chosen by the caller. See the [Office comparison harness](../../scripts/office-quality).
52
+ `initWasm()` loads the packaged WASM asset by default. Pass WASM bytes or a compiled
53
+ `WebAssembly.Module` in runtimes that cannot fetch that URL. Dispose workbook handles when finished.
58
54
 
59
- ## AI agents / human-in-the-loop
55
+ ## Canvas rendering and grid helpers
60
56
 
61
- An agent stages edits as a proposal instead of applying them; a human reviews
62
- per-cell before/after previews and accepts or rejects. Accepting applies the
63
- proposal as one undo step and recalcs dependents, and throws
64
- `StaleProposalError` if the workbook drifted under the proposal since it was
65
- staged.
57
+ `WorkbookHandle.displayList(viewport)` returns the active sheet's display list. Size the backing store
58
+ for the device pixel ratio and give the canvas its logical CSS dimensions:
66
59
 
67
60
  ```ts
68
- import { isProposalsAvailable } from "@betteroffice/xlsx";
69
-
70
- if (isProposalsAvailable()) {
71
- const proposal = workbook.propose("copilot", "add totals", [
72
- { sheet: 0, row: 9, col: 2, input: "=SUM(C1:C9)" },
73
- ]);
74
- workbook.listProposals(); // pending proposals, oldest first
75
- workbook.acceptProposal(proposal.id); // or workbook.rejectProposal(proposal.id)
61
+ import { paintDisplayList, type WorkbookHandle } from '@betteroffice/xlsx';
62
+
63
+ export function drawWorkbook(workbook: WorkbookHandle, canvas: HTMLCanvasElement) {
64
+ const dpr = window.devicePixelRatio || 1;
65
+ canvas.width = 800 * dpr;
66
+ canvas.height = 600 * dpr;
67
+ canvas.style.width = '800px';
68
+ canvas.style.height = '600px';
69
+ const ctx = canvas.getContext('2d');
70
+ if (!ctx) throw new Error('Canvas 2D is unavailable');
71
+ const frame = workbook.displayList({ x: 0, y: 0, width: 800, height: 600 });
72
+ paintDisplayList(ctx, frame, dpr);
76
73
  }
77
74
  ```
78
75
 
79
- The React editor paints pending proposals as in-cell tracked-change ghosts with
80
- an accept/reject panel. `isProposalsAvailable()` reports proposal availability.
81
- `StaleProposalError.targets` names each drifted cell's sheet beside `cells`.
76
+ For a custom grid, use `cellAtPoint`, `cellRect`, and `rangeRect` for hit-testing and geometry,
77
+ `buildA11yGrid` for accessibility data, and `toTsv` / `fromTsv` for clipboard text.
78
+ The `@betteroffice/xlsx/headless` entry exports pure grid helpers and types without the canvas painter
79
+ or WASM loader.
82
80
 
83
- ## Version-checked edit batches
81
+ ## Range moves
84
82
 
85
- Read cells with the version they were read at, then apply a batch against it.
86
- Every step commits as one recalculated change and one undo step, or the batch
87
- returns a typed refusal and nothing changes:
83
+ `workbook.moveRange(sheet, source, destination)` moves an A1 range within a sheet and rewrites
84
+ references in one undo step; the destination is the new top-left cell. Surface errors when a move is
85
+ refused rather than discarding the source workbook.
88
86
 
89
- ```ts
90
- const read = workbook.readCells({
91
- ranges: [{ sheetId: "sheet:0", range: { kind: "a1", a1: "B3" } }],
92
- });
93
- if (!read.ok) throw new Error(read.failure.message);
94
-
95
- const result = workbook.applyEdits({
96
- expectVersion: read.version,
97
- steps: [
98
- {
99
- op: "setCellInputs",
100
- target: { sheetId: "sheet:0", range: { kind: "a1", a1: "B3" } },
101
- inputs: [["120"]],
102
- expect: { cells: [[{ value: read.ranges[0].cells[0][0].value }]] },
103
- },
104
- { op: "setNumberFormat", target: { sheetId: "sheet:0", range: { kind: "a1", a1: "B3" } }, format: "currency" },
105
- ],
106
- });
107
- if (!result.ok) console.warn(result.failure.code); // e.g. "stale-version"
108
- ```
87
+ ## Printing and PNG export
109
88
 
110
- - Steps: `setCellInputs` (parsed like typing, against each cell's current
111
- number format), `setFormulas` (source without `=`, stored as formulas whatever
112
- the format), `setNumberFormat` and `patchStyle`. Content and formatting may
113
- combine on the same cells; writing one property twice refuses with
114
- `overlapping-steps`.
115
- - Targets name a sheet id from the current catalog (`sheet:{index}` standalone,
116
- the replica's sheet keys in collaboration) and an A1 range or zero-based
117
- corners. Matrices and guards match the target's shape exactly. Guards compare
118
- a cell's value, formula (`null` for none) or display text before the batch.
119
- - `validateEdits` stages a batch without changing anything; `findText` searches
120
- display text exactly and case-sensitively. Update listeners run once, before
121
- `applyEdits` returns, and see the recalculated state and its new version.
122
- `changedSheets` names every sheet the batch or its recalculation changed.
123
- - Requests over 16 MiB and results over 64 MiB refuse with `limit-exceeded`;
124
- calculation diagnostics stop at 10,000 cells per list and set `truncated`.
125
- - `history: "none"` keeps a batch out of undo; standalone undo still replays
126
- older steps over its cells. `source` records provenance only. Volatile
127
- functions see only `calculation.nowSerial`.
128
- - Versions and sheet ids are session-scoped; standalone sheet ids are
129
- positional, so each is valid only for the version it was read at.
89
+ `workbook.printDisplayList(sheet, range, metrics, gridlines)` renders an A1 range using `PrintMetrics`
90
+ measured from the workbook's normal font. The caller chooses paper size, margins, and pagination;
91
+ `paintDisplayList` accepts an optional origin in backing-store pixels for positioning the result.
130
92
 
131
- ## Structured export
93
+ `workbook.renderPng(viewport)` exports the active sheet's viewport. `workbook.renderRangePng()` exports
94
+ its used range, or accepts `{ range, scale }` to select an A1 range and raster scale. Both return PNG
95
+ bytes synchronously; check `isPngExportAvailable()` before calling them.
132
96
 
133
- XLSX exports bounded sparse worksheet content and Markdown with positional
134
- anchors, formulas, stored values, formatted text, explicit hidden-content
135
- options, and omission diagnostics. Export reads stored values:
97
+ ## Worker sessions
136
98
 
137
- ```ts
138
- import { exportXlsxStructured } from "@betteroffice/xlsx";
99
+ The low-level `openWorkbookSession` API (also exported from `@betteroffice/xlsx/worker`) is
100
+ experimental. It returns a `WorkbookSession` with
101
+ promise-returning operations through `session.call`, plus asynchronous `session.save()` and
102
+ `session.dispose()` methods.
139
103
 
140
- const read = workbook.exportStructured({ scope: [{ sheet: 0, range: "A1:D20" }] });
141
- if (read.ok) console.log(read.content.sheets[0].cells);
104
+ The React editor uses a worker by default and exposes its own asynchronous API. Use
105
+ [`@betteroffice/xlsx-react`](https://www.npmjs.com/package/@betteroffice/xlsx-react) for the editor UI.
142
106
 
143
- const markdown = workbook.exportMarkdown({}, { maxRows: 100 });
144
- const fromBytes = await exportXlsxStructured(bytes); // no session, no clock
145
- ```
107
+ ## Edit proposals
146
108
 
147
- - Each sheet lists its stored cells in row-major order (formula cells and
148
- styled empty cells included, empty positions skipped) with value, formula,
149
- display text, number format and merge membership, plus merges, tables,
150
- hyperlinks, hidden row and column spans, and charts, pictures and shapes as
151
- placeholders with alt text. Defined names are listed read-only.
152
- - Anchors are `{ sheet: { sheetId, index, name }, a1 }` positions in the
153
- exported version (`anchorScope: "session"`) or bytes snapshot (`"snapshot"`);
154
- neither follows later row, column or sheet edits. `sheetId` is the id edit
155
- batches take in that session (`sheet:{index}` for bytes), so a cell or range
156
- anchor's `{ sheetId: anchor.sheet.sheetId, range: { kind: "a1", a1: anchor.a1 } }`
157
- is its batch target at the exported version. Retained drawings carry a `sourcePart`
158
- provenance with the part's SHA-256.
159
- - Formula results are the stored values (`calculation.policy: "asStored"`,
160
- `freshness: "unverified"`); cells mark results the file did not store as
161
- `missing` (`uncertain` once anything has calculated, or where it cannot be
162
- traced) and the last calculation's `cycle` and `limited` cells. Live exports
163
- reflect whatever calculation already ran, and the same version and options
164
- always export the same content; `exportXlsxStructured` reads bytes without
165
- recalculating.
166
- - Hidden sheets, rows, columns and names are excluded unless requested
167
- (`includeHiddenSheets`, `includeHiddenRows`, `includeHiddenColumns`,
168
- `includeHiddenNames`), with a `hidden-content-excluded` diagnostic. A sheet
169
- whose visibility is unknown, such as one from a model handed in without its
170
- package, counts as hidden.
171
- - `maxCells` (default 100,000) and `maxBytes` (default 8 MiB) stop at a complete
172
- record with `truncated: true` and a `truncated` diagnostic; an absent cell is
173
- empty only before that point. Scope refusals (`invalid-scope`,
174
- `invalid-options`, `limit-exceeded`) return `{ ok: false, version, failure }`.
175
- - Markdown renders one grid per sheet labelled with its A1 columns and row
176
- numbers (200 rows, 50 columns and 10,000 positions by default), using an
177
- escaped HTML table where merges need spans, and `<!-- xlsx-export:N -->`
178
- markers whose anchors come back in `anchors`. Document text is escaped and
179
- kept on one line, and hyperlinks become Markdown links only for `http`,
180
- `https` and `mailto` destinations. `renderXlsxMarkdown` renders content you
181
- already hold, refusing content that does not validate.
109
+ `workbook.propose(agentId, note, edits)` stages cell edits for review without applying them.
110
+ `listProposals`, `acceptProposal`, and `rejectProposal` manage that queue; acceptance applies the
111
+ proposal as one undo step and recalculates dependents. Check `isProposalsAvailable()` first;
112
+ acceptance throws `StaleProposalError` if targeted cells have changed since staging.
182
113
 
183
- ## Collaboration
114
+ ## Version-checked edit batches
184
115
 
185
- Open a collaborative replica, then connect it to any reliable binary transport:
116
+ `readCells` returns cells with their version; `validateEdits` checks a batch without committing it,
117
+ and `applyEdits` applies all steps or returns a typed refusal without changing the workbook.
118
+ See [Edit XLSX in version-checked batches](https://docs.betteroffice.dev/docs/javascript#edit-xlsx-in-version-checked-batches)
119
+ for targets, guards, supported steps, and limits.
186
120
 
187
- ```ts
188
- import { initWasm, openWorkbook } from "@betteroffice/xlsx";
189
- import {
190
- CollaborationProvider,
191
- type CollaborationTransport,
192
- } from "@betteroffice/xlsx/collaboration";
193
-
194
- await initWasm();
195
- const workbook = openWorkbook(bytes, { collaborative: true });
196
- const transport: CollaborationTransport = createTransport();
197
- const provider = new CollaborationProvider(workbook, transport, {
198
- user: { name: "Ada" }, // identity for this peer's selection flag
199
- });
200
- provider.connect();
201
-
202
- function dispose() {
203
- provider.destroy();
204
- workbook.dispose();
205
- }
206
- ```
121
+ ## Structured export
207
122
 
208
- The provider handles Yjs sync-v1 and awareness. Room routing, authentication,
209
- WebRTC signaling, and reconnection remain transport concerns; document updates
210
- flow directly into the Rust/WASM Yrs replica.
211
- After a close, the transport may reopen itself or the caller may invoke
212
- `provider.connect()` for another connection attempt.
213
- Call `provider.destroy()` before discarding its transport or workbook.
123
+ `exportStructured` and `exportMarkdown` read committed content with positional anchors and diagnostics
124
+ without recalculating formulas. See
125
+ [Export XLSX content with anchors](https://docs.betteroffice.dev/docs/javascript#export-xlsx-content-with-anchors)
126
+ for scopes, hidden content, limits, and byte-based exports.
127
+
128
+ ## Collaboration
214
129
 
215
- Collaborative sessions synchronize cell content, formulas, styles, column widths,
216
- and row heights, with Yrs-backed undo and redo. Structural operations throw.
130
+ The `@betteroffice/xlsx/collaboration` entry exports `CollaborationProvider` for connecting replicas
131
+ to a binary transport. See the [collaboration guide](https://docs.betteroffice.dev/docs/collaboration)
132
+ for provider lifecycle, transport setup, and shared starting state.
217
133
 
218
- ## Development
134
+ Open the workbook with `openWorkbook(bytes, { collaborative: true })`. Collaborative workbooks
135
+ synchronize cell content, formulas, styles, column widths and row heights, with local undo and
136
+ redo whose effects synchronize.
137
+ Structural edits throw: inserting or deleting rows and columns, adding, removing, moving or renaming
138
+ sheets, and changing charts or defined names.
219
139
 
220
- The generated `.wasm` binary is intentionally not committed. From the repository
221
- root, install `wasm-pack` 0.15.0 and `binaryen`, then run
222
- `bun run build:xlsx-wasm`. Package builds, tests, demo startup, and CI run this
223
- step automatically.
140
+ ## Operation profiles
224
141
 
225
- [JavaScript guide](https://docs.betteroffice.dev/docs/javascript) ·
226
- [Changelog](https://github.com/openooxml/betteroffice/blob/main/packages/xlsx/CHANGELOG.md) · Apache-2.0.
142
+ `editCellProfiled`, `applyOpsProfiled`, and `displayListProfiled` return engine stage durations in
143
+ milliseconds alongside their results. See
144
+ [Operation profiles](https://docs.betteroffice.dev/docs/javascript#operation-profiles).
227
145
 
228
- ### Operation profiles
146
+ ## Documentation
229
147
 
230
- `editCellProfiled`, `applyOpsProfiled`, and `displayListProfiled` perform the same
231
- operations as their unprofiled counterparts and return engine stage durations
232
- in milliseconds. Edit results include `profile` (validate, apply, recalc, result);
233
- display results contain `{ displayList, profile }` (build, encode). The normal
234
- entry points do not read profiling clocks. See the
235
- [corpus and browser tests](../../e2e/README.md) for usage and timing limits.
148
+ - [JavaScript guide](https://docs.betteroffice.dev/docs/javascript)
149
+ - [Package guide](https://docs.betteroffice.dev/docs/packages)
150
+ - [React editor on npm](https://www.npmjs.com/package/@betteroffice/xlsx-react)
151
+ - [Repository](https://github.com/openooxml/betteroffice)
@@ -0,0 +1,253 @@
1
+ /**
2
+ * Wire format between a main-thread collaboration facade and the provider its document worker runs.
3
+ * Main owns the host transport's lifecycle and forwards its bytes untouched; the worker runs the protocol and
4
+ * answers with frames to send, state and the transport calls its own failures need.
5
+ */
6
+ type PipeErrorCode = 'backpressure' | 'protocol' | 'replica' | 'transport';
7
+ interface PipeError {
8
+ code: PipeErrorCode;
9
+ message: string;
10
+ }
11
+ interface PipeUser {
12
+ name: string;
13
+ color?: string;
14
+ }
15
+ interface PipeProviderOptions {
16
+ maxFrameBytes?: number;
17
+ maxMessagesPerFrame?: number;
18
+ syncChunkBytes?: number;
19
+ maxSyncBytes?: number;
20
+ user?: PipeUser;
21
+ }
22
+ /** The docx cursor; the default cursor type `C` of the pipe types. */
23
+ interface PipeCursor {
24
+ story: string;
25
+ anchor: Uint8Array;
26
+ head: Uint8Array;
27
+ }
28
+ type PipeTransportEvent = {
29
+ type: 'open';
30
+ } | {
31
+ type: 'message';
32
+ data: ArrayBuffer;
33
+ } | {
34
+ type: 'close';
35
+ reason?: string;
36
+ };
37
+ /**
38
+ * Main to worker, in order; `seq` increases. `connect`, `disconnect`, `destroy` and `fail` replay what main already
39
+ * did to the host transport, so the worker sends nothing and asks for no transport call while it runs them.
40
+ */
41
+ type PipeOp<C = PipeCursor> = {
42
+ op: 'create';
43
+ seq: number;
44
+ options: PipeProviderOptions;
45
+ } | {
46
+ op: 'connect';
47
+ seq: number;
48
+ } | {
49
+ op: 'disconnect';
50
+ seq: number;
51
+ } | {
52
+ op: 'destroy';
53
+ seq: number;
54
+ } | {
55
+ op: 'fail';
56
+ seq: number;
57
+ error: PipeError;
58
+ } | {
59
+ op: 'cursor';
60
+ seq: number;
61
+ cursor: C | null;
62
+ broadcast: boolean;
63
+ } | {
64
+ op: 'event';
65
+ seq: number;
66
+ event: PipeTransportEvent;
67
+ };
68
+ /** The docx peer; the default peer type `P` of the pipe types. */
69
+ interface PipePeer {
70
+ clientId: number;
71
+ clock: number;
72
+ user: {
73
+ name: string;
74
+ color: string;
75
+ };
76
+ cursor: PipeCursor | null;
77
+ lastSeenAt: number;
78
+ cursorMovedAt: number;
79
+ inferredCursor: {
80
+ clientId: number;
81
+ story: string;
82
+ paraId: string;
83
+ endOffset: number;
84
+ } | null;
85
+ }
86
+ /**
87
+ * Worker to main, in order. `through` is the last op the worker had run; main drops output older than its own
88
+ * latest lifecycle call.
89
+ */
90
+ type PipeOutput<P = PipePeer> = {
91
+ do: 'unsubscribe';
92
+ through: number;
93
+ } | {
94
+ do: 'disconnect';
95
+ through: number;
96
+ } | {
97
+ do: 'send';
98
+ data: ArrayBuffer;
99
+ through: number;
100
+ }
101
+ /** The awareness leave main sends when the host disconnects first; null while there is none to send. */
102
+ | {
103
+ do: 'leave';
104
+ data: ArrayBuffer | null;
105
+ through: number;
106
+ } | {
107
+ do: 'status';
108
+ status: 'disconnected' | 'connecting' | 'connected' | 'destroyed';
109
+ synced: boolean;
110
+ through: number;
111
+ } | {
112
+ do: 'peers';
113
+ peers: P[];
114
+ timeOrigin: number;
115
+ through: number;
116
+ } | {
117
+ do: 'error';
118
+ error: PipeError;
119
+ through: number;
120
+ }
121
+ /** The worker has no provider under this id. */
122
+ | {
123
+ do: 'lost';
124
+ };
125
+ interface PipeCommandPayload<C = PipeCursor> {
126
+ provider: number;
127
+ ops: PipeOp<C>[];
128
+ }
129
+
130
+ type CollaborationUpdateOrigin = 'local' | 'remote';
131
+ interface CollaborationReplica {
132
+ readonly clientId: number;
133
+ encodeStateVector(): Uint8Array;
134
+ encodeStateAsUpdate(remoteStateVector?: Uint8Array): Uint8Array;
135
+ applyUpdate(update: Uint8Array): unknown;
136
+ onUpdate(listener: (update: Uint8Array, origin: CollaborationUpdateOrigin) => void): () => void;
137
+ }
138
+ type CollaborationTransportEvent = {
139
+ type: 'open';
140
+ } | {
141
+ type: 'message';
142
+ data: Uint8Array;
143
+ } | {
144
+ type: 'close';
145
+ reason?: string;
146
+ } | {
147
+ type: 'error';
148
+ error: unknown;
149
+ } | {
150
+ type: 'drain';
151
+ };
152
+ interface CollaborationTransport {
153
+ /** Starts one attempt; after close, reopen internally or require another provider.connect(). */
154
+ connect(): void | Promise<void>;
155
+ disconnect(): void | Promise<void>;
156
+ /** Returns true only when the owned frame was accepted; false requires a later drain event. */
157
+ send(data: Uint8Array): boolean;
158
+ onEvent(listener: (event: CollaborationTransportEvent) => void): () => void;
159
+ }
160
+ type CollaborationStatus = 'disconnected' | 'connecting' | 'connected' | 'destroyed';
161
+ interface CollaborationStatusChange {
162
+ status: CollaborationStatus;
163
+ synced: boolean;
164
+ }
165
+ interface CollaborationUser {
166
+ name: string;
167
+ color: string;
168
+ }
169
+ interface CollaborationUserOptions {
170
+ name: string;
171
+ color?: string;
172
+ }
173
+ interface AwarenessCell {
174
+ row: number;
175
+ col: number;
176
+ }
177
+ interface AwarenessCursor {
178
+ sheet: string;
179
+ anchor: AwarenessCell;
180
+ head: AwarenessCell;
181
+ }
182
+ interface AwarenessPayload {
183
+ user: CollaborationUser;
184
+ cursor: AwarenessCursor | null;
185
+ }
186
+ interface AwarenessState extends AwarenessPayload {
187
+ clientId: number;
188
+ clock: number;
189
+ }
190
+ interface AwarenessUpdate {
191
+ clientId: number;
192
+ clock: number;
193
+ state: AwarenessPayload | null;
194
+ }
195
+ interface AwarenessPeer extends AwarenessState {
196
+ lastSeen: number;
197
+ cursorMovedAt: number;
198
+ }
199
+ interface CollaborationAwareness {
200
+ readonly peers: readonly AwarenessPeer[];
201
+ setCursor(cursor: AwarenessCursor | null): void;
202
+ onAwareness(listener: AwarenessListener): () => void;
203
+ }
204
+ type CollaborationErrorCode = 'backpressure' | 'protocol' | 'replica' | 'transport';
205
+ declare class CollaborationError extends Error {
206
+ readonly code: CollaborationErrorCode;
207
+ readonly cause: unknown;
208
+ constructor(code: CollaborationErrorCode, message: string, cause?: unknown);
209
+ }
210
+ interface CollaborationProviderOptions {
211
+ maxFrameBytes?: number;
212
+ maxMessagesPerFrame?: number;
213
+ maxPendingBytes?: number;
214
+ user?: CollaborationUserOptions;
215
+ }
216
+ type CollaborationStatusListener = (change: CollaborationStatusChange) => void;
217
+ type CollaborationErrorListener = (error: CollaborationError) => void;
218
+ type AwarenessListener = (peers: readonly AwarenessPeer[]) => void;
219
+
220
+ /** One provider's line to the worker that runs it. */
221
+ interface CollaborationPipeEndpoint<C = PipeCursor> {
222
+ /** Runs `ops` in the worker, in order after earlier posts; settles once the worker has run them. */
223
+ post(ops: PipeOp<C>[], transfer: ArrayBuffer[]): Promise<unknown>;
224
+ close(): void;
225
+ }
226
+ /** What a worker replica offers a provider that can run in its worker. */
227
+ interface CollaborationPipeChannel<C = PipeCursor, P = PipePeer> {
228
+ /** `receive` takes the worker's output for this provider; `lost` reports the worker is gone for it. */
229
+ open(receive: (out: readonly PipeOutput<P>[]) => void, lost: (reason: string) => void): CollaborationPipeEndpoint<C>;
230
+ }
231
+
232
+ /** @experimental */
233
+ interface AsyncCollaborationReplica {
234
+ readonly clientId: number;
235
+ encodeStateVector(): Promise<Uint8Array>;
236
+ encodeStateAsUpdate(remoteStateVector?: Uint8Array): Promise<Uint8Array>;
237
+ applyUpdate(update: Uint8Array): Promise<unknown>;
238
+ /** Applies updates in order as one merge; rejects at the first refused update, keeping the ones before it. */
239
+ applyUpdateChunks?(updates: readonly Uint8Array[]): Promise<unknown>;
240
+ onUpdate(listener: (update: Uint8Array, origin: CollaborationUpdateOrigin) => void): () => void;
241
+ }
242
+ /** @experimental */
243
+ interface AsyncReplicaAdapter extends CollaborationReplica {
244
+ readonly async: AsyncCollaborationReplica;
245
+ }
246
+ /** @internal */
247
+ declare function attachCollaborationPipe(adapter: AsyncReplicaAdapter, channel: CollaborationPipeChannel<AwarenessCursor, AwarenessPeer> | undefined): void;
248
+ /** @internal */
249
+ declare function collaborationPipeFor(replica: CollaborationReplica): CollaborationPipeChannel<AwarenessCursor, AwarenessPeer> | undefined;
250
+ /** @experimental */
251
+ declare function createAsyncCollaborationReplica(replica: AsyncCollaborationReplica): AsyncReplicaAdapter;
252
+
253
+ export { type AwarenessPeer as A, type CollaborationReplica as C, type PipeCommandPayload as P, type CollaborationTransport as a, type CollaborationProviderOptions as b, type CollaborationStatus as c, type CollaborationStatusListener as d, type CollaborationErrorListener as e, type AwarenessListener as f, type AwarenessCursor as g, type AwarenessPayload as h, type AwarenessUpdate as i, type CollaborationUserOptions as j, type CollaborationUser as k, type AsyncCollaborationReplica as l, type AsyncReplicaAdapter as m, type AwarenessCell as n, type AwarenessState as o, type CollaborationAwareness as p, CollaborationError as q, type CollaborationErrorCode as r, type CollaborationStatusChange as s, type CollaborationTransportEvent as t, type CollaborationUpdateOrigin as u, attachCollaborationPipe as v, collaborationPipeFor as w, createAsyncCollaborationReplica as x };