ducjs 3.1.1 → 3.2.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
@@ -2,7 +2,7 @@
2
2
 
3
3
  <p align="center">
4
4
  <br/>
5
- <a href="https://duc.ducflair.com" target="_blank"><img width="256px" src="https://raw.githubusercontent.com/ducflair/assets/refs/heads/main/src/duc/duc-extended.png" /></a>
5
+ <a href="https://duc.ducflair.com" target="_blank"><img width="256px" src="https://cdn.jsdelivr.net/gh/ducflair/assets@main/src/duc/duc-extended.png" /></a>
6
6
  <p align="center">2D CAD File Format</p>
7
7
  <p align="center" style="align: center;">
8
8
  <a href="https://www.npmjs.com/package/ducjs"><img src="https://shields.io/badge/NPM-cc3534?logo=Npm&logoColor=white&style=round-square" alt="NPM" /></a>
@@ -1,23 +1,21 @@
1
1
  /* tslint:disable */
2
2
  /* eslint-disable */
3
3
  /**
4
- * Fetch a single external file from a `.duc` buffer by file ID.
5
- *
6
- * Returns the file entry as a JS object, or `undefined` if not found.
7
- */
8
- export function getExternalFile(buf: Uint8Array, file_id: string): any;
9
- /**
10
- * Restore a specific checkpoint by its ID from a `.duc` file buffer.
4
+ * Parse a `.duc` file lazily returns everything EXCEPT external file data blobs.
11
5
  *
12
- * Returns a JS object `{ versionNumber, schemaVersion, data, fromCheckpoint }`.
6
+ * Use `getExternalFile()` or `listExternalFiles()` for on-demand access.
13
7
  */
14
- export function restoreCheckpoint(duc_buf: Uint8Array, checkpoint_id: string): any;
8
+ export function parseDucLazy(buf: Uint8Array): any;
15
9
  /**
16
10
  * List all versions (checkpoints + deltas) from a `.duc` file buffer.
17
11
  *
18
12
  * Returns a JS array of `VersionEntry` objects (no heavy data blobs).
19
13
  */
20
14
  export function listVersions(duc_buf: Uint8Array): any;
15
+ /**
16
+ * Parse a `.duc` file (Uint8Array) into a JS object (ExportedDataState).
17
+ */
18
+ export function parseDuc(buf: Uint8Array): any;
21
19
  /**
22
20
  * Read the full VersionGraph from a `.duc` file buffer.
23
21
  *
@@ -26,23 +24,26 @@ export function listVersions(duc_buf: Uint8Array): any;
26
24
  */
27
25
  export function readVersionGraph(duc_buf: Uint8Array): any;
28
26
  /**
29
- * Returns the current version-control schema version defined in Rust.
27
+ * Apply a changeset to reconstruct document state.
30
28
  *
31
- * TypeScript should use this as the source of truth instead of hardcoding
32
- * its own constant. When this value is bumped in Rust, the version control
33
- * system will automatically handle migration bookkeeping (closing old chains,
34
- * recording migrations) the next time a checkpoint or delta is created.
29
+ * `base_state` must be the exact checkpoint data used when the changeset
30
+ * was created. Returns the full document state as `Uint8Array`.
31
+ *
32
+ * Handles all changeset formats transparently:
33
+ * - v3 (bsdiff), v2 (XOR diff), v1 (zlib full snapshot)
35
34
  */
36
- export function getCurrentSchemaVersion(): number;
35
+ export function applyDeltaChangeset(base_state: Uint8Array, changeset: Uint8Array): Uint8Array;
37
36
  /**
38
- * Restore the document state at `version_number` from a `.duc` file buffer.
37
+ * Compute a checkpoint-relative binary diff changeset using bsdiff.
39
38
  *
40
- * The `.duc` file is a SQLite database this function opens it and queries
41
- * the `checkpoints` / `deltas` tables directly for version restoration.
39
+ * `base_state` is the checkpoint's full data blob.
40
+ * `current_state` is the full document state at the new version.
42
41
  *
43
- * Returns a JS object `{ versionNumber, schemaVersion, data, fromCheckpoint }`.
42
+ * Returns an encoded changeset (`Uint8Array`) ready for storage in a
43
+ * `Delta.payload`. bsdiff finds matching blocks even when they shift
44
+ * offsets, which is critical for SQLite databases.
44
45
  */
45
- export function restoreVersion(duc_buf: Uint8Array, version_number: number): any;
46
+ export function createDeltaChangeset(base_state: Uint8Array, current_state: Uint8Array): Uint8Array;
46
47
  /**
47
48
  * Revert the document to a specific version, removing all newer versions.
48
49
  *
@@ -50,15 +51,11 @@ export function restoreVersion(duc_buf: Uint8Array, version_number: number): any
50
51
  */
51
52
  export function revertToVersion(duc_buf: Uint8Array, target_version: number): any;
52
53
  /**
53
- * Apply a changeset to reconstruct document state.
54
- *
55
- * `base_state` must be the exact checkpoint data used when the changeset
56
- * was created. Returns the full document state as `Uint8Array`.
54
+ * Restore a specific checkpoint by its ID from a `.duc` file buffer.
57
55
  *
58
- * Handles all changeset formats transparently:
59
- * - v3 (bsdiff), v2 (XOR diff), v1 (zlib full snapshot)
56
+ * Returns a JS object `{ versionNumber, schemaVersion, data, fromCheckpoint }`.
60
57
  */
61
- export function applyDeltaChangeset(base_state: Uint8Array, changeset: Uint8Array): Uint8Array;
58
+ export function restoreCheckpoint(duc_buf: Uint8Array, checkpoint_id: string): any;
62
59
  /**
63
60
  * List metadata for all external files (without loading the heavy data blobs).
64
61
  */
@@ -68,26 +65,29 @@ export function listExternalFiles(buf: Uint8Array): any;
68
65
  */
69
66
  export function serializeDuc(data: any): Uint8Array;
70
67
  /**
71
- * Compute a checkpoint-relative binary diff changeset using bsdiff.
72
- *
73
- * `base_state` is the checkpoint's full data blob.
74
- * `current_state` is the full document state at the new version.
68
+ * Fetch a single external file from a `.duc` buffer by file ID.
75
69
  *
76
- * Returns an encoded changeset (`Uint8Array`) ready for storage in a
77
- * `Delta.payload`. bsdiff finds matching blocks even when they shift
78
- * offsets, which is critical for SQLite databases.
70
+ * Returns the file entry as a JS object, or `undefined` if not found.
79
71
  */
80
- export function createDeltaChangeset(base_state: Uint8Array, current_state: Uint8Array): Uint8Array;
72
+ export function getExternalFile(buf: Uint8Array, file_id: string): any;
81
73
  /**
82
- * Parse a `.duc` file (Uint8Array) into a JS object (ExportedDataState).
74
+ * Returns the current version-control schema version defined in Rust.
75
+ *
76
+ * TypeScript should use this as the source of truth instead of hardcoding
77
+ * its own constant. When this value is bumped in Rust, the version control
78
+ * system will automatically handle migration bookkeeping (closing old chains,
79
+ * recording migrations) the next time a checkpoint or delta is created.
83
80
  */
84
- export function parseDuc(buf: Uint8Array): any;
81
+ export function getCurrentSchemaVersion(): number;
85
82
  /**
86
- * Parse a `.duc` file lazily returns everything EXCEPT external file data blobs.
83
+ * Restore the document state at `version_number` from a `.duc` file buffer.
87
84
  *
88
- * Use `getExternalFile()` or `listExternalFiles()` for on-demand access.
85
+ * The `.duc` file is a SQLite database — this function opens it and queries
86
+ * the `checkpoints` / `deltas` tables directly for version restoration.
87
+ *
88
+ * Returns a JS object `{ versionNumber, schemaVersion, data, fromCheckpoint }`.
89
89
  */
90
- export function parseDucLazy(buf: Uint8Array): any;
90
+ export function restoreVersion(duc_buf: Uint8Array, version_number: number): any;
91
91
 
92
92
  export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
93
93
 
@@ -195,19 +195,16 @@ function takeFromExternrefTable0(idx) {
195
195
  return value;
196
196
  }
197
197
  /**
198
- * Fetch a single external file from a `.duc` buffer by file ID.
198
+ * Parse a `.duc` file lazily returns everything EXCEPT external file data blobs.
199
199
  *
200
- * Returns the file entry as a JS object, or `undefined` if not found.
200
+ * Use `getExternalFile()` or `listExternalFiles()` for on-demand access.
201
201
  * @param {Uint8Array} buf
202
- * @param {string} file_id
203
202
  * @returns {any}
204
203
  */
205
- export function getExternalFile(buf, file_id) {
204
+ export function parseDucLazy(buf) {
206
205
  const ptr0 = passArray8ToWasm0(buf, wasm.__wbindgen_malloc);
207
206
  const len0 = WASM_VECTOR_LEN;
208
- const ptr1 = passStringToWasm0(file_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
209
- const len1 = WASM_VECTOR_LEN;
210
- const ret = wasm.getExternalFile(ptr0, len0, ptr1, len1);
207
+ const ret = wasm.parseDucLazy(ptr0, len0);
211
208
  if (ret[2]) {
212
209
  throw takeFromExternrefTable0(ret[1]);
213
210
  }
@@ -215,19 +212,16 @@ export function getExternalFile(buf, file_id) {
215
212
  }
216
213
 
217
214
  /**
218
- * Restore a specific checkpoint by its ID from a `.duc` file buffer.
215
+ * List all versions (checkpoints + deltas) from a `.duc` file buffer.
219
216
  *
220
- * Returns a JS object `{ versionNumber, schemaVersion, data, fromCheckpoint }`.
217
+ * Returns a JS array of `VersionEntry` objects (no heavy data blobs).
221
218
  * @param {Uint8Array} duc_buf
222
- * @param {string} checkpoint_id
223
219
  * @returns {any}
224
220
  */
225
- export function restoreCheckpoint(duc_buf, checkpoint_id) {
221
+ export function listVersions(duc_buf) {
226
222
  const ptr0 = passArray8ToWasm0(duc_buf, wasm.__wbindgen_malloc);
227
223
  const len0 = WASM_VECTOR_LEN;
228
- const ptr1 = passStringToWasm0(checkpoint_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
229
- const len1 = WASM_VECTOR_LEN;
230
- const ret = wasm.restoreCheckpoint(ptr0, len0, ptr1, len1);
224
+ const ret = wasm.listVersions(ptr0, len0);
231
225
  if (ret[2]) {
232
226
  throw takeFromExternrefTable0(ret[1]);
233
227
  }
@@ -235,16 +229,14 @@ export function restoreCheckpoint(duc_buf, checkpoint_id) {
235
229
  }
236
230
 
237
231
  /**
238
- * List all versions (checkpoints + deltas) from a `.duc` file buffer.
239
- *
240
- * Returns a JS array of `VersionEntry` objects (no heavy data blobs).
241
- * @param {Uint8Array} duc_buf
232
+ * Parse a `.duc` file (Uint8Array) into a JS object (ExportedDataState).
233
+ * @param {Uint8Array} buf
242
234
  * @returns {any}
243
235
  */
244
- export function listVersions(duc_buf) {
245
- const ptr0 = passArray8ToWasm0(duc_buf, wasm.__wbindgen_malloc);
236
+ export function parseDuc(buf) {
237
+ const ptr0 = passArray8ToWasm0(buf, wasm.__wbindgen_malloc);
246
238
  const len0 = WASM_VECTOR_LEN;
247
- const ret = wasm.listVersions(ptr0, len0);
239
+ const ret = wasm.parseDuc(ptr0, len0);
248
240
  if (ret[2]) {
249
241
  throw takeFromExternrefTable0(ret[1]);
250
242
  }
@@ -270,37 +262,56 @@ export function readVersionGraph(duc_buf) {
270
262
  }
271
263
 
272
264
  /**
273
- * Returns the current version-control schema version defined in Rust.
265
+ * Apply a changeset to reconstruct document state.
274
266
  *
275
- * TypeScript should use this as the source of truth instead of hardcoding
276
- * its own constant. When this value is bumped in Rust, the version control
277
- * system will automatically handle migration bookkeeping (closing old chains,
278
- * recording migrations) the next time a checkpoint or delta is created.
279
- * @returns {number}
267
+ * `base_state` must be the exact checkpoint data used when the changeset
268
+ * was created. Returns the full document state as `Uint8Array`.
269
+ *
270
+ * Handles all changeset formats transparently:
271
+ * - v3 (bsdiff), v2 (XOR diff), v1 (zlib full snapshot)
272
+ * @param {Uint8Array} base_state
273
+ * @param {Uint8Array} changeset
274
+ * @returns {Uint8Array}
280
275
  */
281
- export function getCurrentSchemaVersion() {
282
- return 3000001;
276
+ export function applyDeltaChangeset(base_state, changeset) {
277
+ const ptr0 = passArray8ToWasm0(base_state, wasm.__wbindgen_malloc);
278
+ const len0 = WASM_VECTOR_LEN;
279
+ const ptr1 = passArray8ToWasm0(changeset, wasm.__wbindgen_malloc);
280
+ const len1 = WASM_VECTOR_LEN;
281
+ const ret = wasm.applyDeltaChangeset(ptr0, len0, ptr1, len1);
282
+ if (ret[3]) {
283
+ throw takeFromExternrefTable0(ret[2]);
284
+ }
285
+ var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
286
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
287
+ return v3;
283
288
  }
284
289
 
285
290
  /**
286
- * Restore the document state at `version_number` from a `.duc` file buffer.
291
+ * Compute a checkpoint-relative binary diff changeset using bsdiff.
287
292
  *
288
- * The `.duc` file is a SQLite database this function opens it and queries
289
- * the `checkpoints` / `deltas` tables directly for version restoration.
293
+ * `base_state` is the checkpoint's full data blob.
294
+ * `current_state` is the full document state at the new version.
290
295
  *
291
- * Returns a JS object `{ versionNumber, schemaVersion, data, fromCheckpoint }`.
292
- * @param {Uint8Array} duc_buf
293
- * @param {number} version_number
294
- * @returns {any}
296
+ * Returns an encoded changeset (`Uint8Array`) ready for storage in a
297
+ * `Delta.payload`. bsdiff finds matching blocks even when they shift
298
+ * offsets, which is critical for SQLite databases.
299
+ * @param {Uint8Array} base_state
300
+ * @param {Uint8Array} current_state
301
+ * @returns {Uint8Array}
295
302
  */
296
- export function restoreVersion(duc_buf, version_number) {
297
- const ptr0 = passArray8ToWasm0(duc_buf, wasm.__wbindgen_malloc);
303
+ export function createDeltaChangeset(base_state, current_state) {
304
+ const ptr0 = passArray8ToWasm0(base_state, wasm.__wbindgen_malloc);
298
305
  const len0 = WASM_VECTOR_LEN;
299
- const ret = wasm.restoreVersion(ptr0, len0, version_number);
300
- if (ret[2]) {
301
- throw takeFromExternrefTable0(ret[1]);
306
+ const ptr1 = passArray8ToWasm0(current_state, wasm.__wbindgen_malloc);
307
+ const len1 = WASM_VECTOR_LEN;
308
+ const ret = wasm.createDeltaChangeset(ptr0, len0, ptr1, len1);
309
+ if (ret[3]) {
310
+ throw takeFromExternrefTable0(ret[2]);
302
311
  }
303
- return takeFromExternrefTable0(ret[0]);
312
+ var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
313
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
314
+ return v3;
304
315
  }
305
316
 
306
317
  /**
@@ -322,29 +333,23 @@ export function revertToVersion(duc_buf, target_version) {
322
333
  }
323
334
 
324
335
  /**
325
- * Apply a changeset to reconstruct document state.
326
- *
327
- * `base_state` must be the exact checkpoint data used when the changeset
328
- * was created. Returns the full document state as `Uint8Array`.
336
+ * Restore a specific checkpoint by its ID from a `.duc` file buffer.
329
337
  *
330
- * Handles all changeset formats transparently:
331
- * - v3 (bsdiff), v2 (XOR diff), v1 (zlib full snapshot)
332
- * @param {Uint8Array} base_state
333
- * @param {Uint8Array} changeset
334
- * @returns {Uint8Array}
338
+ * Returns a JS object `{ versionNumber, schemaVersion, data, fromCheckpoint }`.
339
+ * @param {Uint8Array} duc_buf
340
+ * @param {string} checkpoint_id
341
+ * @returns {any}
335
342
  */
336
- export function applyDeltaChangeset(base_state, changeset) {
337
- const ptr0 = passArray8ToWasm0(base_state, wasm.__wbindgen_malloc);
343
+ export function restoreCheckpoint(duc_buf, checkpoint_id) {
344
+ const ptr0 = passArray8ToWasm0(duc_buf, wasm.__wbindgen_malloc);
338
345
  const len0 = WASM_VECTOR_LEN;
339
- const ptr1 = passArray8ToWasm0(changeset, wasm.__wbindgen_malloc);
346
+ const ptr1 = passStringToWasm0(checkpoint_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
340
347
  const len1 = WASM_VECTOR_LEN;
341
- const ret = wasm.applyDeltaChangeset(ptr0, len0, ptr1, len1);
342
- if (ret[3]) {
343
- throw takeFromExternrefTable0(ret[2]);
348
+ const ret = wasm.restoreCheckpoint(ptr0, len0, ptr1, len1);
349
+ if (ret[2]) {
350
+ throw takeFromExternrefTable0(ret[1]);
344
351
  }
345
- var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
346
- wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
347
- return v3;
352
+ return takeFromExternrefTable0(ret[0]);
348
353
  }
349
354
 
350
355
  /**
@@ -378,41 +383,19 @@ export function serializeDuc(data) {
378
383
  }
379
384
 
380
385
  /**
381
- * Compute a checkpoint-relative binary diff changeset using bsdiff.
382
- *
383
- * `base_state` is the checkpoint's full data blob.
384
- * `current_state` is the full document state at the new version.
386
+ * Fetch a single external file from a `.duc` buffer by file ID.
385
387
  *
386
- * Returns an encoded changeset (`Uint8Array`) ready for storage in a
387
- * `Delta.payload`. bsdiff finds matching blocks even when they shift
388
- * offsets, which is critical for SQLite databases.
389
- * @param {Uint8Array} base_state
390
- * @param {Uint8Array} current_state
391
- * @returns {Uint8Array}
392
- */
393
- export function createDeltaChangeset(base_state, current_state) {
394
- const ptr0 = passArray8ToWasm0(base_state, wasm.__wbindgen_malloc);
395
- const len0 = WASM_VECTOR_LEN;
396
- const ptr1 = passArray8ToWasm0(current_state, wasm.__wbindgen_malloc);
397
- const len1 = WASM_VECTOR_LEN;
398
- const ret = wasm.createDeltaChangeset(ptr0, len0, ptr1, len1);
399
- if (ret[3]) {
400
- throw takeFromExternrefTable0(ret[2]);
401
- }
402
- var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
403
- wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
404
- return v3;
405
- }
406
-
407
- /**
408
- * Parse a `.duc` file (Uint8Array) into a JS object (ExportedDataState).
388
+ * Returns the file entry as a JS object, or `undefined` if not found.
409
389
  * @param {Uint8Array} buf
390
+ * @param {string} file_id
410
391
  * @returns {any}
411
392
  */
412
- export function parseDuc(buf) {
393
+ export function getExternalFile(buf, file_id) {
413
394
  const ptr0 = passArray8ToWasm0(buf, wasm.__wbindgen_malloc);
414
395
  const len0 = WASM_VECTOR_LEN;
415
- const ret = wasm.parseDuc(ptr0, len0);
396
+ const ptr1 = passStringToWasm0(file_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
397
+ const len1 = WASM_VECTOR_LEN;
398
+ const ret = wasm.getExternalFile(ptr0, len0, ptr1, len1);
416
399
  if (ret[2]) {
417
400
  throw takeFromExternrefTable0(ret[1]);
418
401
  }
@@ -420,16 +403,33 @@ export function parseDuc(buf) {
420
403
  }
421
404
 
422
405
  /**
423
- * Parse a `.duc` file lazily returns everything EXCEPT external file data blobs.
406
+ * Returns the current version-control schema version defined in Rust.
424
407
  *
425
- * Use `getExternalFile()` or `listExternalFiles()` for on-demand access.
426
- * @param {Uint8Array} buf
408
+ * TypeScript should use this as the source of truth instead of hardcoding
409
+ * its own constant. When this value is bumped in Rust, the version control
410
+ * system will automatically handle migration bookkeeping (closing old chains,
411
+ * recording migrations) the next time a checkpoint or delta is created.
412
+ * @returns {number}
413
+ */
414
+ export function getCurrentSchemaVersion() {
415
+ return 3000003;
416
+ }
417
+
418
+ /**
419
+ * Restore the document state at `version_number` from a `.duc` file buffer.
420
+ *
421
+ * The `.duc` file is a SQLite database — this function opens it and queries
422
+ * the `checkpoints` / `deltas` tables directly for version restoration.
423
+ *
424
+ * Returns a JS object `{ versionNumber, schemaVersion, data, fromCheckpoint }`.
425
+ * @param {Uint8Array} duc_buf
426
+ * @param {number} version_number
427
427
  * @returns {any}
428
428
  */
429
- export function parseDucLazy(buf) {
430
- const ptr0 = passArray8ToWasm0(buf, wasm.__wbindgen_malloc);
429
+ export function restoreVersion(duc_buf, version_number) {
430
+ const ptr0 = passArray8ToWasm0(duc_buf, wasm.__wbindgen_malloc);
431
431
  const len0 = WASM_VECTOR_LEN;
432
- const ret = wasm.parseDucLazy(ptr0, len0);
432
+ const ret = wasm.restoreVersion(ptr0, len0, version_number);
433
433
  if (ret[2]) {
434
434
  throw takeFromExternrefTable0(ret[1]);
435
435
  }
Binary file
package/dist/enums.d.ts CHANGED
@@ -95,11 +95,6 @@ export declare enum IMAGE_STATUS {
95
95
  SAVED = 11,
96
96
  ERROR = 12
97
97
  }
98
- export declare enum PRUNING_LEVEL {
99
- CONSERVATIVE = 10,
100
- BALANCED = 20,
101
- AGGRESSIVE = 30
102
- }
103
98
  export declare enum BOOLEAN_OPERATION {
104
99
  UNION = 10,
105
100
  SUBTRACT = 11,
package/dist/enums.js CHANGED
@@ -109,12 +109,6 @@ export var IMAGE_STATUS;
109
109
  IMAGE_STATUS[IMAGE_STATUS["SAVED"] = 11] = "SAVED";
110
110
  IMAGE_STATUS[IMAGE_STATUS["ERROR"] = 12] = "ERROR";
111
111
  })(IMAGE_STATUS || (IMAGE_STATUS = {}));
112
- export var PRUNING_LEVEL;
113
- (function (PRUNING_LEVEL) {
114
- PRUNING_LEVEL[PRUNING_LEVEL["CONSERVATIVE"] = 10] = "CONSERVATIVE";
115
- PRUNING_LEVEL[PRUNING_LEVEL["BALANCED"] = 20] = "BALANCED";
116
- PRUNING_LEVEL[PRUNING_LEVEL["AGGRESSIVE"] = 30] = "AGGRESSIVE";
117
- })(PRUNING_LEVEL || (PRUNING_LEVEL = {}));
118
112
  export var BOOLEAN_OPERATION;
119
113
  (function (BOOLEAN_OPERATION) {
120
114
  BOOLEAN_OPERATION[BOOLEAN_OPERATION["UNION"] = 10] = "UNION";
@@ -1,4 +1,4 @@
1
- import type { DucExternalFile, DucExternalFiles, ExternalFileRevision } from "./types";
1
+ import type { DucExternalFile, DucExternalFiles, ExternalFileLoaded, ResolvedFileData, ExternalFilesData } from "./types";
2
2
  export type LazyFileMetadata = {
3
3
  id: string;
4
4
  mimeType: string;
@@ -27,19 +27,21 @@ export declare class LazyExternalFileStore {
27
27
  /** Get metadata for all files. */
28
28
  getAllMetadata(): LazyFileMetadata[];
29
29
  /** Fetch the full file (including data blobs for all revisions) for a specific file. */
30
- getFile(fileId: string): DucExternalFile | null;
30
+ getFile(fileId: string): ExternalFileLoaded | null;
31
31
  /** Get the active revision data for a specific file. */
32
- getFileData(fileId: string): ExternalFileRevision | null;
32
+ getFileData(fileId: string): ResolvedFileData | null;
33
33
  /** Fetch active revision data and return a copy of the data buffer (safe for transfer). */
34
- getFileDataCopy(fileId: string): ExternalFileRevision | null;
34
+ getFileDataCopy(fileId: string): ResolvedFileData | null;
35
35
  /** Add a file at runtime (not persisted in .duc until next serialize). */
36
- addRuntimeFile(fileId: string, file: DucExternalFile): void;
36
+ addRuntimeFile(fileId: string, file: DucExternalFile, data: Record<string, Uint8Array>): void;
37
37
  /** Remove a runtime file. */
38
38
  removeRuntimeFile(fileId: string): boolean;
39
- /** Export all files eagerly as a DucExternalFiles record. */
39
+ /** Export all files metadata as a DucExternalFiles record. */
40
40
  toExternalFiles(): DucExternalFiles;
41
+ /** Export all revision data blobs as an ExternalFilesData record. */
42
+ toExternalFilesData(): ExternalFilesData;
41
43
  /** Merge files from another source. Adds missing files and merges new revisions into existing ones. */
42
- mergeFiles(files: DucExternalFiles): void;
44
+ mergeFiles(files: DucExternalFiles, filesData?: ExternalFilesData): void;
43
45
  /** Release the underlying buffer to free memory. */
44
46
  release(): void;
45
47
  private getMetadataMap;
@@ -1,3 +1,14 @@
1
+ var __rest = (this && this.__rest) || function (s, e) {
2
+ var t = {};
3
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
+ t[p] = s[p];
5
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
+ t[p[i]] = s[p[i]];
9
+ }
10
+ return t;
11
+ };
1
12
  import { wasmGetExternalFile, wasmListExternalFiles } from "./wasm";
2
13
  /**
3
14
  * Provides lazy access to external files embedded inside a `.duc` buffer.
@@ -76,11 +87,16 @@ export class LazyExternalFileStore {
76
87
  }
77
88
  /** Get the active revision data for a specific file. */
78
89
  getFileData(fileId) {
79
- var _a;
80
- const file = this.getFile(fileId);
81
- if (!file)
90
+ const loaded = this.getFile(fileId);
91
+ if (!loaded)
92
+ return null;
93
+ const meta = loaded.revisions[loaded.activeRevisionId];
94
+ if (!meta)
82
95
  return null;
83
- return (_a = file.revisions[file.activeRevisionId]) !== null && _a !== void 0 ? _a : null;
96
+ const dataBlob = loaded.data[loaded.activeRevisionId];
97
+ if (!dataBlob)
98
+ return null;
99
+ return { data: dataBlob, mimeType: meta.mimeType };
84
100
  }
85
101
  /** Fetch active revision data and return a copy of the data buffer (safe for transfer). */
86
102
  getFileDataCopy(fileId) {
@@ -90,53 +106,97 @@ export class LazyExternalFileStore {
90
106
  return Object.assign(Object.assign({}, data), { data: new Uint8Array(data.data) });
91
107
  }
92
108
  /** Add a file at runtime (not persisted in .duc until next serialize). */
93
- addRuntimeFile(fileId, file) {
94
- this.runtimeFiles.set(fileId, file);
109
+ addRuntimeFile(fileId, file, data) {
110
+ this.runtimeFiles.set(fileId, Object.assign(Object.assign({}, file), { data }));
95
111
  }
96
112
  /** Remove a runtime file. */
97
113
  removeRuntimeFile(fileId) {
98
114
  return this.runtimeFiles.delete(fileId);
99
115
  }
100
- /** Export all files eagerly as a DucExternalFiles record. */
116
+ /** Export all files metadata as a DucExternalFiles record. */
101
117
  toExternalFiles() {
102
118
  const result = {};
103
119
  if (this.buffer) {
104
120
  for (const [id] of this.getMetadataMap()) {
105
- const file = this.getFile(id);
106
- if (file) {
121
+ const loaded = this.getFile(id);
122
+ if (loaded) {
123
+ const { data: _ } = loaded, file = __rest(loaded, ["data"]);
107
124
  result[id] = file;
108
125
  }
109
126
  }
110
127
  }
111
- for (const [id, file] of this.runtimeFiles) {
128
+ for (const [id, loaded] of this.runtimeFiles) {
129
+ const { data: _ } = loaded, file = __rest(loaded, ["data"]);
112
130
  result[id] = file;
113
131
  }
114
132
  return result;
115
133
  }
134
+ /** Export all revision data blobs as an ExternalFilesData record. */
135
+ toExternalFilesData() {
136
+ const result = {};
137
+ if (this.buffer) {
138
+ for (const [id] of this.getMetadataMap()) {
139
+ const loaded = this.getFile(id);
140
+ if (loaded) {
141
+ for (const [revId, blob] of Object.entries(loaded.data)) {
142
+ result[revId] = blob;
143
+ }
144
+ }
145
+ }
146
+ }
147
+ for (const [, loaded] of this.runtimeFiles) {
148
+ for (const [revId, blob] of Object.entries(loaded.data)) {
149
+ result[revId] = blob;
150
+ }
151
+ }
152
+ return result;
153
+ }
116
154
  /** Merge files from another source. Adds missing files and merges new revisions into existing ones. */
117
- mergeFiles(files) {
155
+ mergeFiles(files, filesData) {
118
156
  var _a, _b, _c;
119
157
  for (const [id, file] of Object.entries(files)) {
120
- if (!this.has(id)) {
121
- this.runtimeFiles.set(id, file);
122
- continue;
123
- }
124
158
  const existing = (_a = this.runtimeFiles.get(id)) !== null && _a !== void 0 ? _a : this.getFile(id);
125
159
  if (!existing) {
126
- this.runtimeFiles.set(id, file);
160
+ const dataMap = {};
161
+ if (filesData) {
162
+ for (const revId of Object.keys(file.revisions)) {
163
+ if (filesData[revId]) {
164
+ dataMap[revId] = filesData[revId];
165
+ }
166
+ }
167
+ }
168
+ this.runtimeFiles.set(id, Object.assign(Object.assign({}, file), { data: dataMap }));
127
169
  continue;
128
170
  }
129
- // Merge: add any new revisions that don't exist yet, and update metadata
130
171
  let merged = false;
131
172
  const mergedRevisions = Object.assign({}, existing.revisions);
173
+ const mergedData = Object.assign({}, existing.data);
132
174
  for (const [revId, rev] of Object.entries(file.revisions)) {
133
175
  if (!mergedRevisions[revId]) {
176
+ mergedRevisions[revId] = rev;
177
+ if (filesData === null || filesData === void 0 ? void 0 : filesData[revId]) {
178
+ mergedData[revId] = filesData[revId];
179
+ }
180
+ merged = true;
181
+ continue;
182
+ }
183
+ if ((filesData === null || filesData === void 0 ? void 0 : filesData[revId]) && mergedData[revId] !== filesData[revId]) {
184
+ mergedData[revId] = filesData[revId];
185
+ merged = true;
186
+ }
187
+ if (rev.sizeBytes !== mergedRevisions[revId].sizeBytes ||
188
+ rev.lastRetrieved !== mergedRevisions[revId].lastRetrieved ||
189
+ rev.created !== mergedRevisions[revId].created ||
190
+ rev.mimeType !== mergedRevisions[revId].mimeType ||
191
+ rev.sourceName !== mergedRevisions[revId].sourceName ||
192
+ rev.message !== mergedRevisions[revId].message) {
134
193
  mergedRevisions[revId] = rev;
135
194
  merged = true;
136
195
  }
137
196
  }
138
- if (merged || file.updated > existing.updated) {
139
- this.runtimeFiles.set(id, Object.assign(Object.assign({}, existing), { activeRevisionId: file.activeRevisionId, updated: Math.max(file.updated, existing.updated), version: Math.max((_b = file.version) !== null && _b !== void 0 ? _b : 0, (_c = existing.version) !== null && _c !== void 0 ? _c : 0), revisions: mergedRevisions }));
197
+ const activeRevisionChanged = file.activeRevisionId !== existing.activeRevisionId;
198
+ if (merged || activeRevisionChanged || file.updated > existing.updated) {
199
+ this.runtimeFiles.set(id, Object.assign(Object.assign({}, existing), { activeRevisionId: file.activeRevisionId, updated: Math.max(file.updated, existing.updated), version: Math.max((_b = file.version) !== null && _b !== void 0 ? _b : 0, (_c = existing.version) !== null && _c !== void 0 ? _c : 0), revisions: mergedRevisions, data: mergedData }));
140
200
  }
141
201
  }
142
202
  }
package/dist/parse.js CHANGED
@@ -80,7 +80,9 @@ export function parseDucLazy(buffer, elementsConfig, restoreConfig) {
80
80
  const originalVG = data.versionGraph;
81
81
  const lazyFileStore = new LazyExternalFileStore(buffer);
82
82
  const files = {};
83
- const restored = restore(Object.assign(Object.assign({}, data), { files,
83
+ const filesData = {};
84
+ const restored = restore(Object.assign(Object.assign({}, data), { files,
85
+ filesData,
84
86
  // Preserve versionGraph from Rust separately; do not run it through restore()
85
87
  versionGraph: undefined }), elementsConfig !== null && elementsConfig !== void 0 ? elementsConfig : { syncInvalidIndices: (els) => els }, restoreConfig);
86
88
  restored.lazyFileStore = lazyFileStore;
@@ -1,5 +1,5 @@
1
1
  import { BLENDING } from "../enums";
2
- import type { Checkpoint, Delta, Dictionary, DucExternalFiles, DucGlobalState, ImportedDataState, LibraryItems, PrecisionValue, Scope, VersionGraph } from "../types";
2
+ import type { Checkpoint, Delta, Dictionary, DucExternalFiles, DucGlobalState, ExternalFilesData, ImportedDataState, LibraryItems, PrecisionValue, Scope, VersionGraph } from "../types";
3
3
  import { DucLocalState } from "../types";
4
4
  import type { _DucStackBase, BezierMirroring, DucBlock, DucBlockCollection, DucBlockInstance, DucElement, DucGroup, DucHead, DucLayer, DucRegion, ElementBackground, ElementContentBase, ElementStroke, ExternalFileId, FillStyle, ImageStatus, LineHead, OrderedDucElement, StrokeCap, StrokeJoin, StrokePreference, StrokeSidePreference, StrokeStyle, TextAlign, VerticalAlign } from "../types/elements";
5
5
  import { Percentage, Radian } from "../types/geometryTypes";
@@ -13,6 +13,7 @@ export type RestoredDataState = {
13
13
  localState: RestoredLocalState;
14
14
  globalState: DucGlobalState;
15
15
  files: DucExternalFiles;
16
+ filesData: ExternalFilesData;
16
17
  blocks: DucBlock[];
17
18
  blockInstances: DucBlockInstance[];
18
19
  blockCollections: DucBlockCollection[];
@@ -47,6 +48,11 @@ export type RestoreConfig = {
47
48
  };
48
49
  export declare const restore: (data: ImportedDataState | null, elementsConfig: ElementsConfig, restoreConfig?: RestoreConfig) => RestoredDataState;
49
50
  export declare const restoreFiles: (importedFiles: unknown) => DucExternalFiles;
51
+ /**
52
+ * Restore external file data blobs from the split `filesData` field.
53
+ * Also extracts data from legacy inline `revisions[].data` when present.
54
+ */
55
+ export declare const restoreFilesData: (importedFilesData: unknown, importedFiles: unknown) => ExternalFilesData;
50
56
  export declare const restoreDictionary: (importedDictionary: unknown) => Dictionary;
51
57
  /**
52
58
  * Restores the groups array from imported data, ensuring each item
@@ -1,6 +1,6 @@
1
1
  import { nanoid } from "nanoid";
2
2
  import tinycolor from "tinycolor2";
3
- import { BEZIER_MIRRORING, BLENDING, BOOLEAN_OPERATION, ELEMENT_CONTENT_PREFERENCE, IMAGE_STATUS, LINE_HEAD, PRUNING_LEVEL, STROKE_CAP, STROKE_JOIN, STROKE_PLACEMENT, STROKE_PREFERENCE, STROKE_SIDE_PREFERENCE, TEXT_ALIGN, VERTICAL_ALIGN, } from "../enums";
3
+ import { BEZIER_MIRRORING, BLENDING, BOOLEAN_OPERATION, ELEMENT_CONTENT_PREFERENCE, IMAGE_STATUS, LINE_HEAD, STROKE_CAP, STROKE_JOIN, STROKE_PLACEMENT, STROKE_PREFERENCE, STROKE_SIDE_PREFERENCE, TEXT_ALIGN, VERTICAL_ALIGN, } from "../enums";
4
4
  import { getPrecisionScope } from "../technical/measurements";
5
5
  import { getPrecisionValueFromRaw, getPrecisionValueFromScoped, NEUTRAL_SCOPE, ScaleFactors } from "../technical/scopes";
6
6
  import { base64ToUint8Array, getDefaultGlobalState, getDefaultLocalState, getZoom, isEncodedFunctionString, isFiniteNumber, reviveEncodedFunction, } from "../utils";
@@ -37,11 +37,11 @@ export const restore = (data, elementsConfig, restoreConfig = {}) => {
37
37
  localState: restoredLocalState,
38
38
  globalState: restoredGlobalState,
39
39
  files: restoreFiles(data === null || data === void 0 ? void 0 : data.files),
40
+ filesData: restoreFilesData(data === null || data === void 0 ? void 0 : data.filesData, data === null || data === void 0 ? void 0 : data.files),
40
41
  id: restoredId,
41
42
  };
42
43
  };
43
44
  export const restoreFiles = (importedFiles) => {
44
- var _a, _b;
45
45
  if (!importedFiles || typeof importedFiles !== "object") {
46
46
  return {};
47
47
  }
@@ -70,20 +70,17 @@ export const restoreFiles = (importedFiles) => {
70
70
  const r = rev;
71
71
  const revId = isValidString(r.id);
72
72
  const mimeType = isValidString(r.mimeType);
73
- const dataSource = (_a = r.data) !== null && _a !== void 0 ? _a : r.dataURL;
74
- const data = isValidUint8Array(dataSource);
75
- if (!revId || !mimeType || !data)
73
+ if (!revId || !mimeType)
76
74
  continue;
77
75
  restoredRevisions[revKey] = {
78
76
  id: revId,
79
- sizeBytes: isFiniteNumber(r.sizeBytes) ? r.sizeBytes : data.byteLength,
77
+ sizeBytes: isFiniteNumber(r.sizeBytes) ? r.sizeBytes : 0,
80
78
  checksum: isValidString(r.checksum) || undefined,
81
79
  sourceName: isValidString(r.sourceName) || undefined,
82
80
  mimeType,
83
81
  message: isValidString(r.message) || undefined,
84
82
  created: isFiniteNumber(r.created) ? r.created : Date.now(),
85
83
  lastRetrieved: isFiniteNumber(r.lastRetrieved) ? r.lastRetrieved : undefined,
86
- data,
87
84
  };
88
85
  }
89
86
  if (Object.keys(restoredRevisions).length === 0)
@@ -99,15 +96,12 @@ export const restoreFiles = (importedFiles) => {
99
96
  }
100
97
  // Legacy flat format: DucExternalFileData — wrap in a single-revision DucExternalFile.
101
98
  let legacyData = fd;
102
- // Handle the nested { key, value: { ... } } structure from old Rust serde output.
103
99
  if (fd.value && typeof fd.value === "object") {
104
100
  legacyData = fd.value;
105
101
  }
106
102
  const id = isValidExternalFileId(legacyData.id);
107
103
  const mimeType = isValidString(legacyData.mimeType);
108
- const dataSource = (_b = legacyData.data) !== null && _b !== void 0 ? _b : legacyData.dataURL;
109
- const data = isValidUint8Array(dataSource);
110
- if (!id || !mimeType || !data)
104
+ if (!id || !mimeType)
111
105
  continue;
112
106
  const revId = `${id}_rev1`;
113
107
  const created = isFiniteNumber(legacyData.created) ? legacyData.created : Date.now();
@@ -119,19 +113,87 @@ export const restoreFiles = (importedFiles) => {
119
113
  revisions: {
120
114
  [revId]: {
121
115
  id: revId,
122
- sizeBytes: data.byteLength,
116
+ sizeBytes: 0,
123
117
  mimeType,
124
118
  created,
125
119
  lastRetrieved: isFiniteNumber(legacyData.lastRetrieved)
126
120
  ? legacyData.lastRetrieved
127
121
  : undefined,
128
- data,
129
122
  },
130
123
  },
131
124
  };
132
125
  }
133
126
  return restoredFiles;
134
127
  };
128
+ /**
129
+ * Restore external file data blobs from the split `filesData` field.
130
+ * Also extracts data from legacy inline `revisions[].data` when present.
131
+ */
132
+ export const restoreFilesData = (importedFilesData, importedFiles) => {
133
+ var _a, _b;
134
+ const result = {};
135
+ // 1. Restore from the explicit filesData field (new format)
136
+ if (importedFilesData && typeof importedFilesData === "object") {
137
+ const fd = importedFilesData;
138
+ for (const revId in fd) {
139
+ if (!Object.prototype.hasOwnProperty.call(fd, revId))
140
+ continue;
141
+ const data = isValidUint8Array(fd[revId]);
142
+ if (data) {
143
+ result[revId] = data;
144
+ }
145
+ }
146
+ }
147
+ // 2. Extract data from legacy inline revisions (backward compatibility)
148
+ if (importedFiles && typeof importedFiles === "object") {
149
+ const files = importedFiles;
150
+ for (const key in files) {
151
+ if (!Object.prototype.hasOwnProperty.call(files, key))
152
+ continue;
153
+ const fileData = files[key];
154
+ if (!fileData || typeof fileData !== "object")
155
+ continue;
156
+ const fd = fileData;
157
+ if (fd.revisions && typeof fd.revisions === "object") {
158
+ const rawRevisions = fd.revisions;
159
+ for (const revKey in rawRevisions) {
160
+ if (!Object.prototype.hasOwnProperty.call(rawRevisions, revKey))
161
+ continue;
162
+ if (result[revKey])
163
+ continue; // filesData takes precedence
164
+ const rev = rawRevisions[revKey];
165
+ if (!rev || typeof rev !== "object")
166
+ continue;
167
+ const r = rev;
168
+ const dataSource = (_a = r.data) !== null && _a !== void 0 ? _a : r.dataURL;
169
+ const data = isValidUint8Array(dataSource);
170
+ if (data) {
171
+ result[revKey] = data;
172
+ }
173
+ }
174
+ }
175
+ else {
176
+ // Legacy flat format
177
+ let legacyData = fd;
178
+ if (fd.value && typeof fd.value === "object") {
179
+ legacyData = fd.value;
180
+ }
181
+ const id = isValidExternalFileId(legacyData.id);
182
+ if (!id)
183
+ continue;
184
+ const revId = `${id}_rev1`;
185
+ if (result[revId])
186
+ continue;
187
+ const dataSource = (_b = legacyData.data) !== null && _b !== void 0 ? _b : legacyData.dataURL;
188
+ const data = isValidUint8Array(dataSource);
189
+ if (data) {
190
+ result[revId] = data;
191
+ }
192
+ }
193
+ }
194
+ }
195
+ return result;
196
+ };
135
197
  export const restoreDictionary = (importedDictionary) => {
136
198
  if (!importedDictionary || typeof importedDictionary !== "object") {
137
199
  return {};
@@ -377,10 +439,7 @@ const restoreBlockMetadata = (metadata) => {
377
439
  export const restoreGlobalState = (importedState = {}) => {
378
440
  var _a, _b, _c;
379
441
  const defaults = getDefaultGlobalState();
380
- return Object.assign(Object.assign({}, defaults), { name: (_a = importedState === null || importedState === void 0 ? void 0 : importedState.name) !== null && _a !== void 0 ? _a : defaults.name, viewBackgroundColor: (_b = importedState === null || importedState === void 0 ? void 0 : importedState.viewBackgroundColor) !== null && _b !== void 0 ? _b : defaults.viewBackgroundColor, mainScope: (_c = isValidAppStateScopeValue(importedState === null || importedState === void 0 ? void 0 : importedState.mainScope)) !== null && _c !== void 0 ? _c : defaults.mainScope, scopeExponentThreshold: isValidAppStateScopeExponentThresholdValue(importedState === null || importedState === void 0 ? void 0 : importedState.scopeExponentThreshold, defaults.scopeExponentThreshold), pruningLevel: (importedState === null || importedState === void 0 ? void 0 : importedState.pruningLevel) &&
381
- Object.values(PRUNING_LEVEL).includes(importedState.pruningLevel)
382
- ? importedState.pruningLevel
383
- : PRUNING_LEVEL.BALANCED });
442
+ return Object.assign(Object.assign({}, defaults), { name: (_a = importedState === null || importedState === void 0 ? void 0 : importedState.name) !== null && _a !== void 0 ? _a : defaults.name, viewBackgroundColor: (_b = importedState === null || importedState === void 0 ? void 0 : importedState.viewBackgroundColor) !== null && _b !== void 0 ? _b : defaults.viewBackgroundColor, mainScope: (_c = isValidAppStateScopeValue(importedState === null || importedState === void 0 ? void 0 : importedState.mainScope)) !== null && _c !== void 0 ? _c : defaults.mainScope, scopeExponentThreshold: isValidAppStateScopeExponentThresholdValue(importedState === null || importedState === void 0 ? void 0 : importedState.scopeExponentThreshold, defaults.scopeExponentThreshold) });
384
443
  };
385
444
  /**
386
445
  * Restores the user's local session state from imported data.
@@ -447,9 +506,6 @@ export const restoreVersionGraph = (importedGraph) => {
447
506
  chainCount: isFiniteNumber(importedMetadata === null || importedMetadata === void 0 ? void 0 : importedMetadata.chainCount) && importedMetadata.chainCount >= 1
448
507
  ? importedMetadata.chainCount
449
508
  : 1,
450
- lastPruned: isFiniteNumber(importedMetadata === null || importedMetadata === void 0 ? void 0 : importedMetadata.lastPruned)
451
- ? importedMetadata.lastPruned
452
- : 0,
453
509
  totalSize: isFiniteNumber(importedMetadata === null || importedMetadata === void 0 ? void 0 : importedMetadata.totalSize) &&
454
510
  importedMetadata.totalSize >= 0
455
511
  ? importedMetadata.totalSize
@@ -240,7 +240,11 @@ const restoreElement = (element, currentScope, restoredBlocks, localState, globa
240
240
  ? repairBinding(element, endBinding, currentScope, restoredBlocks)
241
241
  : null;
242
242
  // Create the base restored element
243
+ // Skip sizeFromPoints override for block instance elements: their stored
244
+ // width/height represents the total duplication grid, not single-cell dims.
245
+ const isBlockInstanceElement = !!element.instanceId;
243
246
  const sizeFromPoints = !hasBindings &&
247
+ !isBlockInstanceElement &&
244
248
  getSizeFromPoints(finalPoints.map(getScopedBezierPointFromDucPoint));
245
249
  let restoredElement = restoreElementWithProperties(element, Object.assign({ points: finalPoints, lines, lastCommittedPoint: element.lastCommittedPoint
246
250
  ? restorePoint(element.lastCommittedPoint, element.scope, currentScope)
@@ -329,7 +333,7 @@ const restoreElement = (element, currentScope, restoredBlocks, localState, globa
329
333
  modelType: isValidString(modelElement.modelType) || null,
330
334
  code: isValidString(modelElement.code) || null,
331
335
  fileIds: modelElement.fileIds || [],
332
- svgPath: modelElement.svgPath || null,
336
+ thumbnail: modelElement.thumbnail instanceof Uint8Array ? modelElement.thumbnail : null,
333
337
  viewerState: (modelElement.viewerState || null),
334
338
  }, localState, globalState);
335
339
  }
package/dist/transform.js CHANGED
@@ -284,14 +284,95 @@ function fixElementFromRust(el) {
284
284
  return el;
285
285
  return Object.assign(Object.assign({}, rest), { isCollapsed: (_c = stackBase.isCollapsed) !== null && _c !== void 0 ? _c : false });
286
286
  }
287
+ function normalizeViewer3DStateForRust(vs) {
288
+ var _a, _b, _c, _d, _e, _f, _g;
289
+ if (!vs || typeof vs !== "object")
290
+ return vs;
291
+ const n = (v, fallback) => typeof v === "number" && Number.isFinite(v) ? v : fallback;
292
+ const b = (v, fallback) => typeof v === "boolean" ? v : fallback;
293
+ const s = (v, fallback) => typeof v === "string" ? v : fallback;
294
+ const arr3 = (v, fallback) => Array.isArray(v) && v.length === 3 && v.every((x) => typeof x === "number")
295
+ ? v
296
+ : fallback;
297
+ const arr4 = (v, fallback) => Array.isArray(v) && v.length === 4 && v.every((x) => typeof x === "number")
298
+ ? v
299
+ : fallback;
300
+ const cam = (_a = vs.camera) !== null && _a !== void 0 ? _a : {};
301
+ const dsp = (_b = vs.display) !== null && _b !== void 0 ? _b : {};
302
+ const mat = (_c = vs.material) !== null && _c !== void 0 ? _c : {};
303
+ const clip = (_d = vs.clipping) !== null && _d !== void 0 ? _d : {};
304
+ const expl = (_e = vs.explode) !== null && _e !== void 0 ? _e : {};
305
+ const zeb = (_f = vs.zebra) !== null && _f !== void 0 ? _f : {};
306
+ const normalizeClipPlane = (cp) => ({
307
+ enabled: b(cp === null || cp === void 0 ? void 0 : cp.enabled, false),
308
+ value: n(cp === null || cp === void 0 ? void 0 : cp.value, 0),
309
+ normal: (cp === null || cp === void 0 ? void 0 : cp.normal) != null ? arr3(cp.normal, [0, 0, 0]) : null,
310
+ });
311
+ return {
312
+ camera: {
313
+ control: s(cam.control, "orbit"),
314
+ ortho: b(cam.ortho, true),
315
+ up: s(cam.up, "Z"),
316
+ position: arr3(cam.position, [0, 0, 0]),
317
+ quaternion: arr4(cam.quaternion, [0, 0, 0, 1]),
318
+ target: arr3(cam.target, [0, 0, 0]),
319
+ zoom: n(cam.zoom, 1),
320
+ panSpeed: n(cam.panSpeed, 1),
321
+ rotateSpeed: n(cam.rotateSpeed, 1),
322
+ zoomSpeed: n(cam.zoomSpeed, 1),
323
+ holroyd: b(cam.holroyd, false),
324
+ },
325
+ display: {
326
+ wireframe: b(dsp.wireframe, false),
327
+ transparent: b(dsp.transparent, false),
328
+ blackEdges: b(dsp.blackEdges, true),
329
+ grid: (_g = dsp.grid) !== null && _g !== void 0 ? _g : { type: "uniform", value: false },
330
+ axesVisible: b(dsp.axesVisible, false),
331
+ axesAtOrigin: b(dsp.axesAtOrigin, true),
332
+ },
333
+ material: {
334
+ metalness: n(mat.metalness, 0.3),
335
+ roughness: n(mat.roughness, 0.65),
336
+ defaultOpacity: n(mat.defaultOpacity, 0.5),
337
+ edgeColor: n(mat.edgeColor, 0x707070),
338
+ ambientIntensity: n(mat.ambientIntensity, 1.0),
339
+ directIntensity: n(mat.directIntensity, 1.1),
340
+ },
341
+ clipping: {
342
+ x: normalizeClipPlane(clip.x),
343
+ y: normalizeClipPlane(clip.y),
344
+ z: normalizeClipPlane(clip.z),
345
+ intersection: b(clip.intersection, false),
346
+ showPlanes: b(clip.showPlanes, false),
347
+ objectColorCaps: b(clip.objectColorCaps, false),
348
+ },
349
+ explode: {
350
+ active: b(expl.active, false),
351
+ value: n(expl.value, 0),
352
+ },
353
+ zebra: {
354
+ active: b(zeb.active, false),
355
+ stripeCount: toInteger(zeb.stripeCount, 6),
356
+ stripeDirection: n(zeb.stripeDirection, 0),
357
+ colorScheme: s(zeb.colorScheme, "blackwhite"),
358
+ opacity: n(zeb.opacity, 1),
359
+ mappingMode: s(zeb.mappingMode, "reflection"),
360
+ },
361
+ };
362
+ }
287
363
  function fixElementToRust(el) {
288
364
  var _a, _b, _c, _d, _e, _f, _g, _h;
289
365
  if (!el)
290
366
  return el;
291
367
  fixStylesHatch(el, false);
292
368
  fixCustomDataToRust(el);
293
- if (el.type === "model" && ((_b = (_a = el.viewerState) === null || _a === void 0 ? void 0 : _a.display) === null || _b === void 0 ? void 0 : _b.grid)) {
294
- el.viewerState = Object.assign(Object.assign({}, el.viewerState), { display: Object.assign(Object.assign({}, el.viewerState.display), { grid: fixViewer3DGridToRust(el.viewerState.display.grid) }) });
369
+ if (el.type === "model") {
370
+ if (el.viewerState) {
371
+ el.viewerState = normalizeViewer3DStateForRust(el.viewerState);
372
+ }
373
+ if ((_b = (_a = el.viewerState) === null || _a === void 0 ? void 0 : _a.display) === null || _b === void 0 ? void 0 : _b.grid) {
374
+ el.viewerState = Object.assign(Object.assign({}, el.viewerState), { display: Object.assign(Object.assign({}, el.viewerState.display), { grid: fixViewer3DGridToRust(el.viewerState.display.grid) }) });
375
+ }
295
376
  }
296
377
  // Convert TypeScript DucLine tuples [start, end] → Rust structs { start, end }
297
378
  if (LINEAR_ELEMENT_TYPES.has(el.type) && Array.isArray(el.lines)) {
@@ -349,6 +430,9 @@ function flattenPrecisionValues(obj) {
349
430
  return obj.value;
350
431
  if (Array.isArray(obj))
351
432
  return obj.map(flattenPrecisionValues);
433
+ if (ArrayBuffer.isView(obj) || obj instanceof ArrayBuffer) {
434
+ return obj;
435
+ }
352
436
  if (typeof obj === "object") {
353
437
  const out = {};
354
438
  for (const key in obj) {
@@ -395,7 +479,7 @@ function normalizeLocalStateForRust(localState) {
395
479
  function normalizeGlobalStateForRust(globalState) {
396
480
  if (!globalState || typeof globalState !== "object")
397
481
  return globalState;
398
- return Object.assign(Object.assign({}, globalState), { scopeExponentThreshold: toInteger(globalState.scopeExponentThreshold, 4), pruningLevel: toInteger(globalState.pruningLevel, 20) });
482
+ return Object.assign(Object.assign({}, globalState), { scopeExponentThreshold: toInteger(globalState.scopeExponentThreshold, 4) });
399
483
  }
400
484
  function easingFnToName(fn) {
401
485
  var _a;
@@ -846,8 +846,8 @@ export type DucModelElement = _DucElementBase & {
846
846
  modelType: string | null;
847
847
  /** Defines the source code of the model using build123d python code */
848
848
  code: string | null;
849
- /** The last known SVG path representation of the 3D model for quick rendering on the canvas */
850
- svgPath: string | null;
849
+ /** The last known image thumbnail of the 3D model for quick rendering on the canvas */
850
+ thumbnail: Uint8Array | null;
851
851
  /** Possibly connected external files, such as STEP, STL, DXF, etc. */
852
852
  fileIds: ExternalFileId[];
853
853
  /** The last known 3D viewer state for the model */
@@ -2,11 +2,10 @@ export * from "./elements";
2
2
  export * from "./geometryTypes";
3
3
  export * from "./typeChecks";
4
4
  export * from "./utility-types";
5
- import { PRUNING_LEVEL } from "../enums";
6
5
  import { SupportedMeasures } from "../technical/scopes";
7
- import { DucBindableElement, DucBlock, DucBlockCollection, DucBlockInstance, DucElement, DucElementType, DucGroup, DucIframeLikeElement, DucLayer, DucLinearElement, DucPoint, DucRegion, DucTextElement, ElementBackground, ElementStroke, ExternalFileId, FontFamilyValues, LineHead, NonDeleted, TextAlign } from "./elements";
8
- import { GeometricPoint, Percentage, Radian } from "./geometryTypes";
9
- import { MarkOptional, MaybePromise, ValueOf } from "./utility-types";
6
+ import { DucBindableElement, DucBlock, DucBlockCollection, DucBlockInstance, DucElement, DucElementType, DucGroup, DucIframeLikeElement, DucLayer, DucLinearElement, DucRegion, DucTextElement, ElementBackground, ElementStroke, ExternalFileId, FontFamilyValues, LineHead, NonDeleted, TextAlign } from "./elements";
7
+ import { Percentage } from "./geometryTypes";
8
+ import { MarkOptional, MaybePromise } from "./utility-types";
10
9
  /**
11
10
  * Root data structure for the stored data state
12
11
  */
@@ -28,6 +27,8 @@ export interface ExportedDataState {
28
27
  regions: readonly DucRegion[];
29
28
  layers: readonly DucLayer[];
30
29
  files: DucExternalFiles | undefined;
30
+ /** Revision data blobs keyed by revision id. Separated from metadata for lazy loading. */
31
+ filesData: ExternalFilesData | undefined;
31
32
  /** In case it is needed to embed the version control into the file format */
32
33
  versionGraph: VersionGraph | undefined;
33
34
  /** Actual file id */
@@ -51,35 +52,8 @@ export type Identifier = {
51
52
  export type Dictionary = {
52
53
  [key: string]: string;
53
54
  };
54
- export type DucView = {
55
- scrollX: PrecisionValue;
56
- scrollY: PrecisionValue;
57
- zoom: Zoom;
58
- twistAngle: Radian;
59
- /** The specific spot on that plane that you want to be in the middle of your screen when this view is active */
60
- centerPoint: DucPoint;
61
- scope: Scope;
62
- };
63
- /**
64
- * Defines a 2D User Coordinate System (UCS), a movable coordinate system
65
- * that establishes a local origin and rotation for drawing. All coordinates
66
- * within this UCS are relative to its origin and angle.
67
- */
68
- export type DucUcs = {
69
- /**
70
- * The origin point of the UCS in World Coordinate System (WCS) coordinates.
71
- * This defines the (0,0) point of the new local system.
72
- */
73
- origin: GeometricPoint;
74
- /**
75
- * The rotation angle of the UCS's X-axis, measured in radians,
76
- * relative to the World Coordinate System's X-axis.
77
- * An angle of 0 means the UCS is aligned with the WCS.
78
- */
79
- angle: Radian;
80
- };
81
55
  export type Scope = SupportedMeasures;
82
- export type ExternalFileRevision = {
56
+ export type ExternalFileRevisionMeta = {
83
57
  id: string;
84
58
  sizeBytes: number;
85
59
  /** Content hash for integrity checks and optional deduplication. */
@@ -96,26 +70,38 @@ export type ExternalFileRevision = {
96
70
  * the scene. Used to determine whether to delete unused files from storage.
97
71
  */
98
72
  lastRetrieved?: number;
99
- /** The actual file content bytes. */
73
+ };
74
+ /**
75
+ * Minimal resolved file data for rendering — just the bytes and their MIME type.
76
+ * Used by renderers and export pipelines that need active revision data.
77
+ */
78
+ export type ResolvedFileData = {
100
79
  data: Uint8Array;
80
+ mimeType: string;
101
81
  };
102
82
  export type DucExternalFile = {
103
83
  id: ExternalFileId;
104
84
  activeRevisionId: string;
105
85
  /** Epoch ms when the logical file was last mutated (revision added or active changed). */
106
86
  updated: number;
107
- /** All revisions of this file, keyed by their id. */
108
- revisions: Record<string, ExternalFileRevision>;
87
+ /** All revisions of this file, keyed by their id (metadata only, no data blobs). */
88
+ revisions: Record<string, ExternalFileRevisionMeta>;
109
89
  version?: number;
110
90
  };
111
91
  export type DucExternalFiles = Record<ExternalFileId, DucExternalFile>;
92
+ /** Revision data blobs keyed by revision id. */
93
+ export type ExternalFilesData = Record<string, Uint8Array>;
94
+ /** A fully-loaded external file including its revision data blobs. */
95
+ export type ExternalFileLoaded = DucExternalFile & {
96
+ data: Record<string, Uint8Array>;
97
+ };
112
98
  export type SuggestedBinding = NonDeleted<DucBindableElement> | SuggestedPointBinding;
113
99
  export type SuggestedPointBinding = [
114
100
  NonDeleted<DucLinearElement>,
115
101
  "start" | "end" | "both",
116
102
  NonDeleted<DucBindableElement>
117
103
  ];
118
- export type ToolType = "selection" | "rectangle" | "polygon" | "ellipse" | "line" | "freedraw" | "text" | "image" | "eraser" | "hand" | "frame" | "plot" | "embeddable" | "ruler" | "lasso" | "laser" | "table" | "doc" | "pdf";
104
+ export type ToolType = "selection" | "rectangle" | "polygon" | "ellipse" | "line" | "freedraw" | "text" | "image" | "eraser" | "hand" | "frame" | "plot" | "embeddable" | "ruler" | "lasso" | "laser" | "table" | "doc" | "pdf" | "model";
119
105
  export type ElementOrToolType = DucElementType | ToolType | "custom";
120
106
  /**
121
107
  * Defines the global, persistent settings for the drawing. These are fundamental
@@ -140,8 +126,6 @@ export type DucGlobalState = {
140
126
  * This value defines a +/- tolerance range around the exponent of the current scope.
141
127
  */
142
128
  scopeExponentThreshold: number;
143
- /** The level of pruning to the versions from the version graph. */
144
- pruningLevel: PruningLevel;
145
129
  };
146
130
  export type DucLocalState = {
147
131
  /**
@@ -277,7 +261,6 @@ export type EmbedsValidationStatus = Map<DucIframeLikeElement["id"], boolean>;
277
261
  export type ElementsPendingErasure = Set<DucElement["id"]>;
278
262
  export type PendingDucElements = DucElement[];
279
263
  export type VersionId = string;
280
- export type PruningLevel = ValueOf<typeof PRUNING_LEVEL>;
281
264
  export interface VersionBase {
282
265
  id: VersionId;
283
266
  parentId: VersionId | null;
@@ -323,7 +306,6 @@ export interface VersionGraphMetadata {
323
306
  currentVersion: number;
324
307
  currentSchemaVersion: number;
325
308
  chainCount: number;
326
- lastPruned: number;
327
309
  totalSize: number;
328
310
  }
329
311
  export interface VersionGraph {
@@ -17,7 +17,6 @@ export declare const ELEMENT_TRANSLATE_AMOUNT = 1;
17
17
  export declare const TEXT_TO_CENTER_SNAP_THRESHOLD = 30;
18
18
  export declare const SHIFT_LOCKING_ANGLE: number;
19
19
  export declare const DEFAULT_GRID_SIZE = 1;
20
- export declare const DEFAULT_GRID_STEP = 20;
21
20
  export declare const SVG_NS = "http://www.w3.org/2000/svg";
22
21
  export declare const IMAGE_MIME_TYPES: {
23
22
  readonly svg: "image/svg+xml";
@@ -20,7 +20,6 @@ export const ELEMENT_TRANSLATE_AMOUNT = 1;
20
20
  export const TEXT_TO_CENTER_SNAP_THRESHOLD = 30;
21
21
  export const SHIFT_LOCKING_ANGLE = Math.PI / 12;
22
22
  export const DEFAULT_GRID_SIZE = 1;
23
- export const DEFAULT_GRID_STEP = 20;
24
23
  export const SVG_NS = "http://www.w3.org/2000/svg";
25
24
  export const IMAGE_MIME_TYPES = {
26
25
  svg: "image/svg+xml",
@@ -159,7 +159,7 @@ export const newDocElement = (currentScope, opts) => {
159
159
  } }));
160
160
  };
161
161
  export const newPdfElement = (currentScope, opts) => (Object.assign(Object.assign({ fileId: null, gridConfig: { columns: 1, gapX: 0, gapY: 0, firstPageAlone: false, scale: 1 } }, _newElementBase("pdf", currentScope, opts)), { type: "pdf" }));
162
- export const newModelElement = (currentScope, opts) => (Object.assign(Object.assign({ modelType: null, code: null, svgPath: null, fileIds: [], viewerState: null }, _newElementBase("model", currentScope, opts)), { type: 'model' }));
162
+ export const newModelElement = (currentScope, opts) => (Object.assign(Object.assign({ modelType: null, code: null, thumbnail: null, fileIds: [], viewerState: null }, _newElementBase("model", currentScope, opts)), { type: 'model' }));
163
163
  // Simplified deep clone for the purpose of cloning DucElement.
164
164
  //
165
165
  // Only clones plain objects and arrays. Doesn't clone Date, RegExp, Map, Set,
@@ -174,6 +174,9 @@ const _deepCopyElement = (val, depth = 0) => {
174
174
  if (val == null || typeof val !== "object") {
175
175
  return val;
176
176
  }
177
+ if (ArrayBuffer.isView(val)) {
178
+ return val.slice(0);
179
+ }
177
180
  const objectType = Object.prototype.toString.call(val);
178
181
  if (objectType === "[object Object]") {
179
182
  const tmp = typeof val.constructor === "function"
@@ -1,8 +1,6 @@
1
1
  import type { NormalizedZoomValue, ScopedValue } from "../types";
2
2
  import { DucElement, FixedPoint } from "../types/elements";
3
3
  export declare const getNormalizedZoom: (zoom: number) => NormalizedZoomValue;
4
- export declare const getNormalizedGridSize: (gridStep: number) => number;
5
- export declare const getNormalizedGridStep: (gridStep: number) => number;
6
4
  export declare const normalizeFixedPoint: <T extends FixedPoint | null>(fixedPoint: T) => T extends null ? null : FixedPoint;
7
5
  export declare const getNormalizedDimensions: (element: Pick<DucElement, "width" | "height" | "x" | "y">) => {
8
6
  width: ScopedValue;
@@ -3,12 +3,6 @@ import { clamp } from "./math";
3
3
  export const getNormalizedZoom = (zoom) => {
4
4
  return clamp(zoom, MIN_ZOOM, MAX_ZOOM);
5
5
  };
6
- export const getNormalizedGridSize = (gridStep) => {
7
- return clamp(Math.round(gridStep), 1, 100);
8
- };
9
- export const getNormalizedGridStep = (gridStep) => {
10
- return clamp(Math.round(gridStep), 1, 100);
11
- };
12
6
  export const normalizeFixedPoint = (fixedPoint) => {
13
7
  // Do not allow a precise 0.5 for fixed point ratio
14
8
  // to avoid jumping arrow heading due to floating point imprecision
@@ -1,5 +1,5 @@
1
1
  import { isFiniteNumber } from "..";
2
- import { PRUNING_LEVEL, TEXT_ALIGN } from "../../enums";
2
+ import { TEXT_ALIGN } from "../../enums";
3
3
  import { isValidPrecisionScopeValue } from "../../restore/restoreDataState";
4
4
  import { getPrecisionValueFromRaw, getScaledZoomValueForScope, getScopedZoomValue, NEUTRAL_SCOPE, } from "../../technical/scopes";
5
5
  import { COLOR_PALETTE, DEFAULT_ELEMENT_PROPS, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, } from "../constants";
@@ -26,7 +26,6 @@ export const getDefaultGlobalState = () => {
26
26
  viewBackgroundColor: typeof window !== "undefined" ? (window.matchMedia("(prefers-color-scheme: dark)").matches ? COLOR_PALETTE.night : COLOR_PALETTE.white) : COLOR_PALETTE.white,
27
27
  scopeExponentThreshold: 3,
28
28
  mainScope: NEUTRAL_SCOPE,
29
- pruningLevel: PRUNING_LEVEL.BALANCED,
30
29
  };
31
30
  };
32
31
  export const getDefaultLocalState = () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ducjs",
3
- "version": "3.1.1",
3
+ "version": "3.2.1",
4
4
  "description": "The duc 2D CAD file format is a cornerstone of our advanced design system, conceived to cater to professionals seeking precision and efficiency in their design work.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",