ducjs 3.5.1 → 4.0.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.
Binary file
@@ -1,8 +1,43 @@
1
1
  /* tslint:disable */
2
2
  /* eslint-disable */
3
3
  export const memory: WebAssembly.Memory;
4
+ export const __wbg_ducopfsdocument_free: (a: number, b: number) => void;
5
+ export const __wbg_ducopfsimporter_free: (a: number, b: number) => void;
4
6
  export const applyDeltaChangeset: (a: number, b: number, c: number, d: number) => [number, number, number, number];
5
7
  export const createDeltaChangeset: (a: number, b: number, c: number, d: number) => [number, number, number, number];
8
+ export const ducopfsdocument_checkpointWal: (a: number) => [number, number];
9
+ export const ducopfsdocument_clearCheckpointDataChunks: (a: number, b: number, c: number) => [number, number];
10
+ export const ducopfsdocument_clearDeltaChangesetChunks: (a: number, b: number, c: number) => [number, number];
11
+ export const ducopfsdocument_clearExternalFileRevisionChunks: (a: number, b: number, c: number) => [number, number];
12
+ export const ducopfsdocument_deleteOpfsDatabase: (a: number, b: number) => any;
13
+ export const ducopfsdocument_deleteOpfsDatabaseInPool: (a: number, b: number, c: number, d: number) => any;
14
+ export const ducopfsdocument_executeBatch: (a: number, b: number, c: number) => [number, number];
15
+ export const ducopfsdocument_exportDbChunk: (a: number, b: number, c: number) => any;
16
+ export const ducopfsdocument_getDbSizeBytes: (a: number) => [number, number, number];
17
+ export const ducopfsdocument_getFilename: (a: number) => [number, number];
18
+ export const ducopfsdocument_listExternalFiles: (a: number) => [number, number, number];
19
+ export const ducopfsdocument_listOpfsDatabases: () => any;
20
+ export const ducopfsdocument_listOpfsDatabasesInPool: (a: number, b: number) => any;
21
+ export const ducopfsdocument_listVersions: (a: number) => [number, number, number];
22
+ export const ducopfsdocument_open: (a: number, b: number) => any;
23
+ export const ducopfsdocument_openInPool: (a: number, b: number, c: number, d: number) => any;
24
+ export const ducopfsdocument_readCheckpointDataChunk: (a: number, b: number, c: number, d: number) => [number, number, number];
25
+ export const ducopfsdocument_readDeltaChangesetChunk: (a: number, b: number, c: number, d: number) => [number, number, number];
26
+ export const ducopfsdocument_readDocumentState: (a: number) => [number, number, number];
27
+ export const ducopfsdocument_readExternalFileRevisionChunk: (a: number, b: number, c: number, d: number) => [number, number, number];
28
+ export const ducopfsdocument_readExternalFileRevisionChunks: (a: number, b: number, c: number, d: number, e: number) => [number, number, number];
29
+ export const ducopfsdocument_readExternalFileRevisionRange: (a: number, b: number, c: number, d: number, e: number) => [number, number, number];
30
+ export const ducopfsdocument_readVersionGraph: (a: number) => [number, number, number];
31
+ export const ducopfsdocument_writeCheckpointDataChunk: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => [number, number];
32
+ export const ducopfsdocument_writeDeltaChangesetChunk: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => [number, number];
33
+ export const ducopfsdocument_writeDocumentState: (a: number, b: any) => [number, number];
34
+ export const ducopfsdocument_writeExternalFileRevisionChunk: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => [number, number];
35
+ export const ducopfsimporter_abort: (a: number) => [number, number, number];
36
+ export const ducopfsimporter_begin: (a: number, b: number) => any;
37
+ export const ducopfsimporter_beginInPool: (a: number, b: number, c: number, d: number) => any;
38
+ export const ducopfsimporter_finish: (a: number) => [number, number, number];
39
+ export const ducopfsimporter_getBytesWritten: (a: number) => number;
40
+ export const ducopfsimporter_writeChunk: (a: number, b: number, c: number) => [number, number];
6
41
  export const getCurrentSchemaVersion: () => number;
7
42
  export const getExternalFile: (a: number, b: number, c: number, d: number) => [number, number, number];
8
43
  export const listExternalFiles: (a: number, b: number) => [number, number, number];
@@ -29,6 +64,9 @@ export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) =>
29
64
  export const __wbindgen_exn_store: (a: number) => void;
30
65
  export const __externref_table_alloc: () => number;
31
66
  export const __wbindgen_export_4: WebAssembly.Table;
32
- export const __externref_table_dealloc: (a: number) => void;
67
+ export const __wbindgen_export_5: WebAssembly.Table;
33
68
  export const __wbindgen_free: (a: number, b: number, c: number) => void;
69
+ export const __externref_table_dealloc: (a: number) => void;
70
+ export const closure99_externref_shim: (a: number, b: number, c: any) => void;
71
+ export const closure80_externref_shim: (a: number, b: number, c: any, d: any) => void;
34
72
  export const __wbindgen_start: () => void;
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  export * from "./enums";
2
2
  export * from "./lazy-files";
3
- export * from "./parse";
3
+ export * from "./opfs";
4
+ export * from "./opfs-import";
4
5
  export * from "./restore";
5
- export * from "./serialize";
6
6
  export * from "./technical";
7
7
  export * from "./transform";
8
8
  export * from "./types";
9
9
  export * from "./utils";
10
10
  export * as vc from "./version-control";
11
- export { ensureWasm, getWasmBinary } from "./wasm";
11
+ export { DucOpfsDocument, ensureWasm, getWasmBinary } from "./wasm";
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  export * from "./enums";
2
2
  export * from "./lazy-files";
3
- export * from "./parse";
3
+ export * from "./opfs";
4
+ export * from "./opfs-import";
4
5
  export * from "./restore";
5
- export * from "./serialize";
6
6
  export * from "./technical";
7
7
  export * from "./transform";
8
8
  export * from "./types";
9
9
  export * from "./utils";
10
10
  export * as vc from "./version-control";
11
- export { ensureWasm, getWasmBinary } from "./wasm";
11
+ export { DucOpfsDocument, ensureWasm, getWasmBinary } from "./wasm";
@@ -17,6 +17,7 @@ export declare class LazyExternalFileStore {
17
17
  private buffer;
18
18
  private metadataCache;
19
19
  private runtimeFiles;
20
+ private released;
20
21
  constructor(buffer: Uint8Array);
21
22
  get isReleased(): boolean;
22
23
  get size(): number;
@@ -21,10 +21,11 @@ export class LazyExternalFileStore {
21
21
  constructor(buffer) {
22
22
  this.metadataCache = null;
23
23
  this.runtimeFiles = new Map();
24
- this.buffer = buffer;
24
+ this.released = false;
25
+ this.buffer = buffer.byteLength > 0 ? buffer : null;
25
26
  }
26
27
  get isReleased() {
27
- return this.buffer === null;
28
+ return this.released;
28
29
  }
29
30
  get size() {
30
31
  return this.getMetadataMap().size + this.runtimeFiles.size;
@@ -213,6 +214,7 @@ export class LazyExternalFileStore {
213
214
  release() {
214
215
  this.buffer = null;
215
216
  this.metadataCache = null;
217
+ this.released = true;
216
218
  }
217
219
  getMetadataMap() {
218
220
  if (!this.metadataCache) {
@@ -0,0 +1,12 @@
1
+ export type OpfsChunkImporter = {
2
+ writeChunk(data: Uint8Array): void;
3
+ };
4
+ export type DucStreamImportOptions = {
5
+ compressedChunkSize?: number;
6
+ writeBufferSize?: number;
7
+ };
8
+ /**
9
+ * Incrementally copy raw SQLite or decompress a compressed DUC stream into an
10
+ * OPFS importer. Neither input nor SQLite payload is materialized as one JS buffer.
11
+ */
12
+ export declare function importDucStreamToOpfs(stream: ReadableStream<Uint8Array>, importer: OpfsChunkImporter, options?: DucStreamImportOptions): Promise<number>;
@@ -0,0 +1,113 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { Decompress } from "fflate";
11
+ const DEFAULT_COMPRESSED_CHUNK_SIZE = 64 * 1024;
12
+ const DEFAULT_WRITE_BUFFER_SIZE = 1024 * 1024;
13
+ const SQLITE_HEADER = new TextEncoder().encode("SQLite format 3\0");
14
+ class BufferedImporterWriter {
15
+ constructor(importer, bufferSize) {
16
+ this.importer = importer;
17
+ this.offset = 0;
18
+ this.totalBytes = 0;
19
+ if (!Number.isSafeInteger(bufferSize) || bufferSize <= 0) {
20
+ throw new RangeError("writeBufferSize must be a positive safe integer");
21
+ }
22
+ this.buffer = new Uint8Array(bufferSize);
23
+ }
24
+ write(chunk) {
25
+ let sourceOffset = 0;
26
+ while (sourceOffset < chunk.byteLength) {
27
+ const writable = Math.min(this.buffer.byteLength - this.offset, chunk.byteLength - sourceOffset);
28
+ this.buffer.set(chunk.subarray(sourceOffset, sourceOffset + writable), this.offset);
29
+ this.offset += writable;
30
+ sourceOffset += writable;
31
+ if (this.offset === this.buffer.byteLength) {
32
+ this.flush();
33
+ }
34
+ }
35
+ }
36
+ finish() {
37
+ this.flush();
38
+ return this.totalBytes;
39
+ }
40
+ flush() {
41
+ if (this.offset === 0)
42
+ return;
43
+ this.importer.writeChunk(this.buffer.subarray(0, this.offset));
44
+ this.totalBytes += this.offset;
45
+ this.offset = 0;
46
+ }
47
+ }
48
+ /**
49
+ * Incrementally copy raw SQLite or decompress a compressed DUC stream into an
50
+ * OPFS importer. Neither input nor SQLite payload is materialized as one JS buffer.
51
+ */
52
+ export function importDucStreamToOpfs(stream_1, importer_1) {
53
+ return __awaiter(this, arguments, void 0, function* (stream, importer, options = {}) {
54
+ var _a, _b;
55
+ const compressedChunkSize = (_a = options.compressedChunkSize) !== null && _a !== void 0 ? _a : DEFAULT_COMPRESSED_CHUNK_SIZE;
56
+ if (!Number.isSafeInteger(compressedChunkSize) || compressedChunkSize <= 0) {
57
+ throw new RangeError("compressedChunkSize must be a positive safe integer");
58
+ }
59
+ const writer = new BufferedImporterWriter(importer, (_b = options.writeBufferSize) !== null && _b !== void 0 ? _b : DEFAULT_WRITE_BUFFER_SIZE);
60
+ const decompressor = new Decompress((chunk) => writer.write(chunk));
61
+ const reader = stream.getReader();
62
+ const header = new Uint8Array(SQLITE_HEADER.byteLength);
63
+ let headerLength = 0;
64
+ let isRawSqlite = null;
65
+ const writeCompressed = (chunk) => {
66
+ for (let offset = 0; offset < chunk.byteLength; offset += compressedChunkSize) {
67
+ decompressor.push(chunk.subarray(offset, Math.min(chunk.byteLength, offset + compressedChunkSize)), false);
68
+ }
69
+ };
70
+ const writeDetected = (chunk) => {
71
+ if (isRawSqlite) {
72
+ writer.write(chunk);
73
+ }
74
+ else {
75
+ writeCompressed(chunk);
76
+ }
77
+ };
78
+ try {
79
+ while (true) {
80
+ const { done, value } = yield reader.read();
81
+ if (done)
82
+ break;
83
+ if (!(value === null || value === void 0 ? void 0 : value.byteLength))
84
+ continue;
85
+ let valueOffset = 0;
86
+ if (isRawSqlite === null) {
87
+ const headerBytes = Math.min(header.byteLength - headerLength, value.byteLength);
88
+ header.set(value.subarray(0, headerBytes), headerLength);
89
+ headerLength += headerBytes;
90
+ valueOffset = headerBytes;
91
+ if (headerLength === header.byteLength) {
92
+ isRawSqlite = header.every((byte, index) => byte === SQLITE_HEADER[index]);
93
+ writeDetected(header);
94
+ }
95
+ }
96
+ if (isRawSqlite !== null && valueOffset < value.byteLength) {
97
+ writeDetected(value.subarray(valueOffset));
98
+ }
99
+ }
100
+ if (isRawSqlite === null) {
101
+ isRawSqlite = false;
102
+ writeCompressed(header.subarray(0, headerLength));
103
+ }
104
+ if (!isRawSqlite) {
105
+ decompressor.push(new Uint8Array(), true);
106
+ }
107
+ return writer.finish();
108
+ }
109
+ finally {
110
+ reader.releaseLock();
111
+ }
112
+ });
113
+ }
package/dist/opfs.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { type DucStreamImportOptions } from "./opfs-import";
2
+ import { type ElementsConfig, type RestoreConfig, type RestoredDataState } from "./restore";
3
+ import type { ExportedDataState } from "./types";
4
+ export type BrowserDucDocumentOptions = {
5
+ name?: string;
6
+ /** Isolates OPFS SyncAccessHandles owned by independent workers. */
7
+ poolName?: string;
8
+ wasmUrl?: string | URL | BufferSource;
9
+ chunkSize?: number;
10
+ };
11
+ export declare class BrowserDucDocument {
12
+ private readonly document;
13
+ private readonly chunkSize;
14
+ private closed;
15
+ private constructor();
16
+ static create(options?: BrowserDucDocumentOptions): Promise<BrowserDucDocument>;
17
+ static openDucStream(stream: ReadableStream<Uint8Array>, options?: BrowserDucDocumentOptions & DucStreamImportOptions): Promise<BrowserDucDocument>;
18
+ static listDatabases(wasmUrl?: string | URL | BufferSource, poolName?: string): Promise<string[]>;
19
+ static deleteDatabase(name: string, wasmUrl?: string | URL | BufferSource, poolName?: string): Promise<boolean>;
20
+ getFilename(): string;
21
+ readState(): ExportedDataState;
22
+ readRestoredState(elementsConfig?: ElementsConfig, restoreConfig?: RestoreConfig): RestoredDataState;
23
+ writeState(data: Partial<ExportedDataState>): void;
24
+ listExternalFiles(): unknown;
25
+ clearExternalFileRevisionChunks(revisionId: string): void;
26
+ writeExternalFileRevisionChunk(revisionId: string, chunkIndex: number, offsetBytes: number, data: Uint8Array): void;
27
+ readExternalFileRevisionChunk(revisionId: string, chunkIndex: number): Uint8Array | undefined;
28
+ readExternalFileRevisionChunks(revisionId: string, startChunkIndex?: number, maxChunks?: number): Uint8Array[];
29
+ readExternalFileRevisionRange(revisionId: string, offsetBytes: number, lengthBytes: number): Uint8Array | undefined;
30
+ createDucStream(): Promise<ReadableStream<Uint8Array>>;
31
+ exportDucBlob(): Promise<Blob>;
32
+ exportDucBytes(): Promise<Uint8Array>;
33
+ close(): void;
34
+ }
35
+ export declare function serializeDucToStream(data: Partial<ExportedDataState>, options?: BrowserDucDocumentOptions): Promise<ReadableStream<Uint8Array>>;
36
+ export declare function serializeDucToBlob(data: Partial<ExportedDataState>, options?: BrowserDucDocumentOptions): Promise<Blob>;
package/dist/opfs.js ADDED
@@ -0,0 +1,218 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { AsyncGzip } from "fflate";
11
+ import { importDucStreamToOpfs, } from "./opfs-import";
12
+ import { restoreParsedData } from "./restore-parsed";
13
+ import { prepareStateForSerialization } from "./serialize";
14
+ import { transformFromRust } from "./transform";
15
+ import { DucOpfsDocument, DucOpfsImporter, ensureWasm } from "./wasm";
16
+ const DEFAULT_CHUNK_SIZE = 1024 * 1024;
17
+ const MAX_EXTERNAL_CHUNK_BATCH = 4;
18
+ const MAX_EXTERNAL_RANGE_SIZE = 8 * 1024 * 1024;
19
+ const openOpfsDocument = (name, poolName) => (poolName
20
+ ? DucOpfsDocument.openInPool(name, poolName)
21
+ : DucOpfsDocument.open(name));
22
+ const beginOpfsImport = (name, poolName) => (poolName
23
+ ? DucOpfsImporter.beginInPool(name, poolName)
24
+ : DucOpfsImporter.begin(name));
25
+ export class BrowserDucDocument {
26
+ constructor(document, chunkSize) {
27
+ this.document = document;
28
+ this.chunkSize = chunkSize;
29
+ this.closed = false;
30
+ }
31
+ static create() {
32
+ return __awaiter(this, arguments, void 0, function* (options = {}) {
33
+ var _a, _b;
34
+ yield ensureWasm(options.wasmUrl);
35
+ const name = (_a = options.name) !== null && _a !== void 0 ? _a : `duc-${crypto.randomUUID()}.sqlite`;
36
+ const document = yield openOpfsDocument(name, options.poolName);
37
+ return new BrowserDucDocument(document, (_b = options.chunkSize) !== null && _b !== void 0 ? _b : DEFAULT_CHUNK_SIZE);
38
+ });
39
+ }
40
+ static openDucStream(stream_1) {
41
+ return __awaiter(this, arguments, void 0, function* (stream, options = {}) {
42
+ var _a, _b;
43
+ yield ensureWasm(options.wasmUrl);
44
+ const name = (_a = options.name) !== null && _a !== void 0 ? _a : `duc-import-${crypto.randomUUID()}.sqlite`;
45
+ const importer = yield beginOpfsImport(name, options.poolName);
46
+ let finished = false;
47
+ let importerReleased = false;
48
+ try {
49
+ const importedBytes = yield importDucStreamToOpfs(stream, importer, options);
50
+ const committedBytes = importer.finish();
51
+ if (committedBytes !== importedBytes) {
52
+ throw new Error(`OPFS importer wrote ${committedBytes} bytes, expected ${importedBytes}`);
53
+ }
54
+ finished = true;
55
+ importer.free();
56
+ importerReleased = true;
57
+ const document = yield openOpfsDocument(name, options.poolName);
58
+ return new BrowserDucDocument(document, (_b = options.chunkSize) !== null && _b !== void 0 ? _b : DEFAULT_CHUNK_SIZE);
59
+ }
60
+ catch (error) {
61
+ if (!finished) {
62
+ try {
63
+ importer.abort();
64
+ }
65
+ catch (_c) {
66
+ // Preserve the original stream/import error.
67
+ }
68
+ }
69
+ throw error;
70
+ }
71
+ finally {
72
+ if (!importerReleased) {
73
+ importer.free();
74
+ }
75
+ }
76
+ });
77
+ }
78
+ static listDatabases(wasmUrl, poolName) {
79
+ return __awaiter(this, void 0, void 0, function* () {
80
+ yield ensureWasm(wasmUrl);
81
+ if (poolName) {
82
+ return yield DucOpfsDocument
83
+ .listOpfsDatabasesInPool(poolName);
84
+ }
85
+ return yield DucOpfsDocument.listOpfsDatabases();
86
+ });
87
+ }
88
+ static deleteDatabase(name, wasmUrl, poolName) {
89
+ return __awaiter(this, void 0, void 0, function* () {
90
+ yield ensureWasm(wasmUrl);
91
+ if (poolName) {
92
+ return yield DucOpfsDocument
93
+ .deleteOpfsDatabaseInPool(name, poolName);
94
+ }
95
+ return yield DucOpfsDocument.deleteOpfsDatabase(name);
96
+ });
97
+ }
98
+ getFilename() {
99
+ return this.document.getFilename();
100
+ }
101
+ readState() {
102
+ return transformFromRust(this.document.readDocumentState());
103
+ }
104
+ readRestoredState(elementsConfig, restoreConfig) {
105
+ const raw = this.document.readDocumentState();
106
+ return restoreParsedData(raw, elementsConfig, restoreConfig);
107
+ }
108
+ writeState(data) {
109
+ this.document.writeDocumentState(prepareStateForSerialization(data));
110
+ }
111
+ listExternalFiles() {
112
+ return this.document.listExternalFiles();
113
+ }
114
+ clearExternalFileRevisionChunks(revisionId) {
115
+ this.document.clearExternalFileRevisionChunks(revisionId);
116
+ }
117
+ writeExternalFileRevisionChunk(revisionId, chunkIndex, offsetBytes, data) {
118
+ this.document.writeExternalFileRevisionChunk(revisionId, chunkIndex, offsetBytes, data);
119
+ }
120
+ readExternalFileRevisionChunk(revisionId, chunkIndex) {
121
+ return this.document.readExternalFileRevisionChunk(revisionId, chunkIndex);
122
+ }
123
+ readExternalFileRevisionChunks(revisionId, startChunkIndex = 0, maxChunks = MAX_EXTERNAL_CHUNK_BATCH) {
124
+ if (!Number.isSafeInteger(startChunkIndex) || startChunkIndex < 0) {
125
+ throw new RangeError("startChunkIndex must be a non-negative safe integer");
126
+ }
127
+ if (!Number.isSafeInteger(maxChunks)
128
+ || maxChunks < 1
129
+ || maxChunks > MAX_EXTERNAL_CHUNK_BATCH) {
130
+ throw new RangeError(`maxChunks must be between 1 and ${MAX_EXTERNAL_CHUNK_BATCH}`);
131
+ }
132
+ return this.document.readExternalFileRevisionChunks(revisionId, startChunkIndex, maxChunks);
133
+ }
134
+ readExternalFileRevisionRange(revisionId, offsetBytes, lengthBytes) {
135
+ if (!Number.isSafeInteger(offsetBytes) || offsetBytes < 0) {
136
+ throw new RangeError("offsetBytes must be a non-negative safe integer");
137
+ }
138
+ if (!Number.isSafeInteger(lengthBytes)
139
+ || lengthBytes < 1
140
+ || lengthBytes > MAX_EXTERNAL_RANGE_SIZE) {
141
+ throw new RangeError(`lengthBytes must be between 1 and ${MAX_EXTERNAL_RANGE_SIZE}`);
142
+ }
143
+ return this.document.readExternalFileRevisionRange(revisionId, offsetBytes, lengthBytes);
144
+ }
145
+ createDucStream() {
146
+ return __awaiter(this, void 0, void 0, function* () {
147
+ this.document.checkpointWal();
148
+ const dbSize = this.document.getDbSizeBytes();
149
+ const chunkSize = this.chunkSize;
150
+ const document = this.document;
151
+ return new ReadableStream({
152
+ start(controller) {
153
+ return __awaiter(this, void 0, void 0, function* () {
154
+ const gzip = new AsyncGzip((error, chunk, final) => {
155
+ if (error) {
156
+ controller.error(error);
157
+ return;
158
+ }
159
+ controller.enqueue(chunk);
160
+ if (final) {
161
+ controller.close();
162
+ }
163
+ });
164
+ try {
165
+ for (let offset = 0; offset < dbSize; offset += chunkSize) {
166
+ const length = Math.min(chunkSize, dbSize - offset);
167
+ const chunk = yield document.exportDbChunk(offset, length);
168
+ gzip.push(chunk, offset + length >= dbSize);
169
+ }
170
+ if (dbSize === 0) {
171
+ gzip.push(new Uint8Array(), true);
172
+ }
173
+ }
174
+ catch (error) {
175
+ controller.error(error);
176
+ }
177
+ });
178
+ },
179
+ });
180
+ });
181
+ }
182
+ exportDucBlob() {
183
+ return __awaiter(this, void 0, void 0, function* () {
184
+ const stream = yield this.createDucStream();
185
+ return new Response(stream, {
186
+ headers: { "Content-Type": "application/octet-stream" },
187
+ }).blob();
188
+ });
189
+ }
190
+ exportDucBytes() {
191
+ return __awaiter(this, void 0, void 0, function* () {
192
+ const buffer = yield (yield this.exportDucBlob()).arrayBuffer();
193
+ return new Uint8Array(buffer);
194
+ });
195
+ }
196
+ close() {
197
+ var _a, _b;
198
+ if (this.closed)
199
+ return;
200
+ this.closed = true;
201
+ (_b = (_a = this.document).free) === null || _b === void 0 ? void 0 : _b.call(_a);
202
+ }
203
+ }
204
+ export function serializeDucToStream(data_1) {
205
+ return __awaiter(this, arguments, void 0, function* (data, options = {}) {
206
+ const document = yield BrowserDucDocument.create(options);
207
+ document.writeState(data);
208
+ return document.createDucStream();
209
+ });
210
+ }
211
+ export function serializeDucToBlob(data_1) {
212
+ return __awaiter(this, arguments, void 0, function* (data, options = {}) {
213
+ const stream = yield serializeDucToStream(data, options);
214
+ return new Response(stream, {
215
+ headers: { "Content-Type": "application/octet-stream" },
216
+ }).blob();
217
+ });
218
+ }
package/dist/parse.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type ElementsConfig, type RestoreConfig, type RestoredDataState } from "./restore";
1
+ import type { ElementsConfig, RestoreConfig, RestoredDataState } from "./restore";
2
2
  export type { RestoredDataState };
3
3
  export type LazyRestoredDataState = RestoredDataState & {
4
4
  lazyFileStore: LazyExternalFileStore;
package/dist/parse.js CHANGED
@@ -7,8 +7,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import { restore } from "./restore";
11
- import { transformFromRust } from "./transform";
10
+ import { restoreParsedData } from "./restore-parsed";
12
11
  import { ensureWasm, wasmParseDuc, wasmParseDucLazy } from "./wasm";
13
12
  // Re-export from lazy-files for backwards compatibility
14
13
  import { LazyExternalFileStore } from "./lazy-files";
@@ -39,27 +38,7 @@ export function parseDuc(blob, _fileHandle, elementsConfig, restoreConfig) {
39
38
  .join(" ");
40
39
  throw new Error(`[parseDuc] wasm parse failed (size=${buffer.byteLength}, header="${header}", prefix=${prefixHex}): ${error instanceof Error ? error.message : String(error)}`);
41
40
  }
42
- const data = transformFromRust(raw);
43
- // Preserve the original version graph from Rust before restore() can
44
- // filter out entries through restoreCheckpoint/restoreDelta validation.
45
- // The VG data is already validated by the Rust parser.
46
- const originalVG = data.versionGraph;
47
- const restored = restore(Object.assign(Object.assign({}, data), {
48
- // Preserve versionGraph from Rust separately; do not run it through restore()
49
- versionGraph: undefined }), elementsConfig !== null && elementsConfig !== void 0 ? elementsConfig : { syncInvalidIndices: (els) => els }, restoreConfig);
50
- // Use the original version graph from Rust, bypassing restore's lossy filtering
51
- if (originalVG) {
52
- restored.versionGraph = originalVG;
53
- }
54
- // Keep charter and issues in the parsed output even though restore() does not
55
- // currently populate them itself.
56
- if (data.charter) {
57
- restored.charter = data.charter;
58
- }
59
- if (data.issues) {
60
- restored.issues = data.issues;
61
- }
62
- return restored;
41
+ return restoreParsedData(raw, elementsConfig, restoreConfig);
63
42
  });
64
43
  }
65
44
  /**
@@ -83,29 +62,11 @@ export function parseDucLazy(buffer, elementsConfig, restoreConfig) {
83
62
  .join(" ");
84
63
  throw new Error(`[parseDucLazy] wasm parse failed (size=${buffer.byteLength}, header="${header}", prefix=${prefixHex}): ${error instanceof Error ? error.message : String(error)}`);
85
64
  }
86
- const data = transformFromRust(raw);
87
- // Preserve the original version graph from Rust before restore() filters
88
- const originalVG = data.versionGraph;
89
65
  const lazyFileStore = new LazyExternalFileStore(buffer);
90
66
  const files = {};
91
67
  const filesData = {};
92
- const restored = restore(Object.assign(Object.assign({}, data), { files,
93
- filesData,
94
- // Preserve versionGraph from Rust separately; do not run it through restore()
95
- versionGraph: undefined }), elementsConfig !== null && elementsConfig !== void 0 ? elementsConfig : { syncInvalidIndices: (els) => els }, restoreConfig);
68
+ const restored = restoreParsedData(raw, elementsConfig, restoreConfig, { files, filesData });
96
69
  restored.lazyFileStore = lazyFileStore;
97
- // Use the original version graph from Rust, bypassing restore's lossy filtering
98
- if (originalVG) {
99
- restored.versionGraph = originalVG;
100
- }
101
- // Keep charter and issues in the parsed output even though restore() does not
102
- // currently populate them itself.
103
- if (data.charter) {
104
- restored.charter = data.charter;
105
- }
106
- if (data.issues) {
107
- restored.issues = data.issues;
108
- }
109
70
  return restored;
110
71
  });
111
72
  }
@@ -0,0 +1,7 @@
1
+ import { type ElementsConfig, type RestoreConfig, type RestoredDataState } from "./restore";
2
+ import type { ExportedDataState } from "./types";
3
+ /**
4
+ * Normalize the Rust representation and apply the same restore semantics for
5
+ * byte-buffer and OPFS-backed parsing.
6
+ */
7
+ export declare function restoreParsedData(raw: ExportedDataState, elementsConfig?: ElementsConfig, restoreConfig?: RestoreConfig, overrides?: Partial<ExportedDataState>): RestoredDataState;
@@ -0,0 +1,23 @@
1
+ import { restore, } from "./restore";
2
+ import { transformFromRust } from "./transform";
3
+ /**
4
+ * Normalize the Rust representation and apply the same restore semantics for
5
+ * byte-buffer and OPFS-backed parsing.
6
+ */
7
+ export function restoreParsedData(raw, elementsConfig, restoreConfig, overrides) {
8
+ const data = transformFromRust(raw);
9
+ const originalVersionGraph = data.versionGraph;
10
+ const restored = restore(Object.assign(Object.assign(Object.assign({}, data), overrides), {
11
+ // Rust already validated the graph. Avoid restore filtering entries.
12
+ versionGraph: undefined }), elementsConfig !== null && elementsConfig !== void 0 ? elementsConfig : { syncInvalidIndices: (elements) => elements }, restoreConfig);
13
+ if (originalVersionGraph) {
14
+ restored.versionGraph = originalVersionGraph;
15
+ }
16
+ if (data.charter) {
17
+ restored.charter = data.charter;
18
+ }
19
+ if (data.issues) {
20
+ restored.issues = data.issues;
21
+ }
22
+ return restored;
23
+ }
@@ -1,6 +1,7 @@
1
1
  import { type ElementsConfig, type RestoreConfig } from "./restore";
2
2
  import type { ExportedDataState } from "./types";
3
3
  export declare const DUC_SCHEMA_VERSION: string | undefined;
4
+ export declare function prepareStateForSerialization(data: Partial<ExportedDataState>, elementsConfig?: ElementsConfig, restoreConfig?: RestoreConfig): unknown;
4
5
  /**
5
6
  * Serialize an ExportedDataState into `.duc` bytes (Uint8Array).
6
7
  *