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.
package/dist/serialize.js CHANGED
@@ -22,6 +22,22 @@ const decodeUserVersionToSemver = (userVersion) => {
22
22
  return `${major}.${minor}.${patch}`;
23
23
  };
24
24
  export const DUC_SCHEMA_VERSION = getSchemaVersionFromEnv();
25
+ export function prepareStateForSerialization(data, elementsConfig, restoreConfig) {
26
+ var _a, _b, _c, _d;
27
+ const inputVG = data === null || data === void 0 ? void 0 : data.versionGraph;
28
+ const restored = restore(Object.assign(Object.assign({}, data), {
29
+ // Version graph is preserved separately — bypass restore()'s VG processing.
30
+ versionGraph: undefined }), elementsConfig !== null && elementsConfig !== void 0 ? elementsConfig : { syncInvalidIndices: (els) => els }, restoreConfig);
31
+ const shouldDropLegacyVersionGraph = hasLegacyVersionGraphShape(inputVG);
32
+ const versionGraphForPayload = shouldDropLegacyVersionGraph
33
+ ? undefined
34
+ : prepareVersionGraphForSerialization(inputVG);
35
+ const normalizedVersionGraphForPayload = versionGraphForPayload
36
+ ? normalizeVersionGraphVersionNumbers(versionGraphForPayload)
37
+ : undefined;
38
+ const payloadForRust = Object.assign(Object.assign({ type: (_a = data.type) !== null && _a !== void 0 ? _a : "duc", version: (_c = (_b = data.version) !== null && _b !== void 0 ? _b : DUC_SCHEMA_VERSION) !== null && _c !== void 0 ? _c : decodeUserVersionToSemver(wasmGetCurrentSchemaVersion()), source: (_d = data.source) !== null && _d !== void 0 ? _d : "ducjs" }, restored), { versionGraph: normalizedVersionGraphForPayload });
39
+ return transformToRust(payloadForRust);
40
+ }
25
41
  /**
26
42
  * Serialize an ExportedDataState into `.duc` bytes (Uint8Array).
27
43
  *
@@ -31,27 +47,8 @@ export const DUC_SCHEMA_VERSION = getSchemaVersionFromEnv();
31
47
  */
32
48
  export function serializeDuc(data, elementsConfig, restoreConfig) {
33
49
  return __awaiter(this, void 0, void 0, function* () {
34
- var _a, _b, _c, _d;
35
50
  yield ensureWasm();
36
- const inputVG = data === null || data === void 0 ? void 0 : data.versionGraph;
37
- const restored = restore(Object.assign(Object.assign({}, data), {
38
- // Version graph is preserved separately — bypass restore()'s VG processing.
39
- versionGraph: undefined }), elementsConfig !== null && elementsConfig !== void 0 ? elementsConfig : { syncInvalidIndices: (els) => els }, restoreConfig);
40
- const shouldDropLegacyVersionGraph = hasLegacyVersionGraphShape(inputVG);
41
- // Use the ORIGINAL version graph data instead of the restored one.
42
- // The restore pipeline (restoreCheckpoint/restoreDelta) filters checkpoints
43
- // and deltas through isValidUint8Array which can reject valid in-memory
44
- // Uint8Array data (e.g. empty remote placeholders or detached buffers),
45
- // silently dropping version history.
46
- // hasLegacyVersionGraphShape already validates structural integrity.
47
- const versionGraphForPayload = shouldDropLegacyVersionGraph
48
- ? undefined
49
- : prepareVersionGraphForSerialization(inputVG);
50
- const normalizedVersionGraphForPayload = versionGraphForPayload
51
- ? normalizeVersionGraphVersionNumbers(versionGraphForPayload)
52
- : undefined;
53
- const payloadForRust = Object.assign(Object.assign({ type: (_a = data.type) !== null && _a !== void 0 ? _a : "duc", version: (_c = (_b = data.version) !== null && _b !== void 0 ? _b : DUC_SCHEMA_VERSION) !== null && _c !== void 0 ? _c : decodeUserVersionToSemver(wasmGetCurrentSchemaVersion()), source: (_d = data.source) !== null && _d !== void 0 ? _d : "ducjs" }, restored), { versionGraph: normalizedVersionGraphForPayload });
54
- const prepared = transformToRust(payloadForRust);
51
+ const prepared = prepareStateForSerialization(data, elementsConfig, restoreConfig);
55
52
  const serialized = wasmSerializeDuc(prepared);
56
53
  return serialized;
57
54
  });
@@ -17,13 +17,13 @@ export const isPdfLikeElement = (element) => {
17
17
  * For `pdf` elements, this is simply `element.fileId`.
18
18
  * For `doc` elements, the `fileId` holds the Typst source file, and the
19
19
  * compiled PDF cache is stored in `referencedFileIds` with a
20
- * `doc_pdf_cache_` prefix. This function returns that cache file ID, or
21
- * falls back to `element.fileId` for backward compatibility with older
22
- * drawings where `fileId` was the PDF itself.
20
+ * `doc_pdf_cache_` prefix. This function returns that cache file ID. Older
21
+ * drawings may still use `element.fileId` when it is not a known Typst source.
23
22
  */
24
23
  const DOC_PDF_CACHE_FILE_ID_PREFIX = "doc_pdf_cache_";
24
+ const DOC_TYPST_SOURCE_FILE_ID_PREFIX = "doc_typst_source_";
25
25
  export const getRenderablePdfFileId = (element) => {
26
- var _a;
26
+ var _a, _b;
27
27
  if (element.type === "pdf") {
28
28
  return element.fileId;
29
29
  }
@@ -32,6 +32,9 @@ export const getRenderablePdfFileId = (element) => {
32
32
  if ((_a = element.referencedFileIds) === null || _a === void 0 ? void 0 : _a.includes(cacheId)) {
33
33
  return cacheId;
34
34
  }
35
+ if ((_b = element.fileId) === null || _b === void 0 ? void 0 : _b.startsWith(DOC_TYPST_SOURCE_FILE_ID_PREFIX)) {
36
+ return null;
37
+ }
35
38
  // Fallback for legacy drawings where fileId was the PDF
36
39
  return element.fileId;
37
40
  }
@@ -245,7 +245,7 @@ export declare class GestureEvent extends UIEvent {
245
245
  /** @deprecated legacy: do not use outside of migration paths */
246
246
  export type LibraryItem_v1 = readonly NonDeleted<DucElement>[];
247
247
  /** @deprecated legacy: do not use outside of migration paths */
248
- type LibraryItems_v1 = readonly LibraryItem_v1[];
248
+ export type LibraryItems_v1 = readonly LibraryItem_v1[];
249
249
  /** v2 library item */
250
250
  export type LibraryItem = {
251
251
  id: string;
@@ -1,7 +1,7 @@
1
1
  import { Scope, ScopedValue } from "../types";
2
2
  import { DucElement, DucFreeDrawElement, DucLine, DucLinearElement, DucPoint, DucTextContainer, DucTextElement, DucTextElementWithContainer, ElementsMap } from "../types/elements";
3
3
  import { Bounds, GeometricPoint } from "../types/geometry.types";
4
- type SV = ScopedValue;
4
+ export type SV = ScopedValue;
5
5
  /**
6
6
  * Common bounds calculation interface
7
7
  */
@@ -72,4 +72,3 @@ export declare const getFreeDrawElementAbsoluteCoords: (element: DucFreeDrawElem
72
72
  export declare const getBoundTextElementId: (container: DucElement | null) => string | null;
73
73
  export declare const getBoundTextElement: (element: DucElement | null, elementsMap: ElementsMap) => DucTextElementWithContainer | null;
74
74
  export declare const getResizedElementAbsoluteCoords: (element: DucElement, nextWidth: ScopedValue, nextHeight: ScopedValue, normalizePoints: boolean, currentScope: Scope) => Bounds;
75
- export {};
@@ -24,7 +24,7 @@ export declare const point: (x: number, y: number) => GAPoint;
24
24
  export declare const origin: () => GAPoint;
25
25
  export declare const direction: (x: number, y: number) => GADirection;
26
26
  export declare const offset: (x: number, y: number) => GADirection;
27
- type NVector = readonly [
27
+ export type NVector = readonly [
28
28
  number,
29
29
  number,
30
30
  number,
@@ -60,4 +60,3 @@ export declare const E20: NVector;
60
60
  export declare const E12: NVector;
61
61
  export declare const E012: NVector;
62
62
  export declare const I: NVector;
63
- export {};
@@ -28,7 +28,7 @@ export declare const getSizeFromPoints: (points: readonly GeometricPoint[]) => {
28
28
  width: ScopedValue;
29
29
  height: ScopedValue;
30
30
  };
31
- /** @arg dimension, 0 for rescaling only x, 1 for y */
31
+ /** @param dimension 0 for rescaling only x, 1 for y */
32
32
  export declare const rescalePoints: (dimension: "x" | "y", newSize: ScopedValue, points: readonly DucPoint[], normalize: boolean, elementScope: SupportedMeasures, currentScope: Scope) => DucPoint[];
33
33
  export declare const rescaleLines: (dimension: "x" | "y", newSize: ScopedValue, lines: readonly DucLine[], points: readonly DucPoint[], normalize: boolean, elementScope: SupportedMeasures, currentScope: Scope) => DucLine[];
34
34
  /**
@@ -256,7 +256,7 @@ export declare const pointInsideBounds: (p: GeometricPoint, bounds: Bounds) => b
256
256
  * Get the axis-aligned bounding box for a given element.
257
257
  */
258
258
  export declare const aabbForElement: (element: Readonly<DucElement>, offset?: [number, number, number, number]) => Bounds;
259
- type PolarCoords = [number, number];
259
+ export type PolarCoords = [number, number];
260
260
  /**
261
261
  * Returns the polar coordinates for the given cartesian point represented by
262
262
  * (x, y) for the center point 0,0 where the first number returned is the radius,
@@ -267,7 +267,7 @@ export declare const carthesian2Polar: ({ x, y }: GeometricPoint) => PolarCoords
267
267
  * Angles are in radians and centered on 0, 0. Zero radians on a 1 radius circle
268
268
  * corresponds to (1, 0) carthesian coordinates (point), i.e. to the "right".
269
269
  */
270
- type SymmetricArc = {
270
+ export type SymmetricArc = {
271
271
  radius: number;
272
272
  startAngle: number;
273
273
  endAngle: number;
@@ -48,7 +48,7 @@ export const getSizeFromPoints = (points) => {
48
48
  height: Math.max(...ys) - Math.min(...ys),
49
49
  };
50
50
  };
51
- /** @arg dimension, 0 for rescaling only x, 1 for y */
51
+ /** @param dimension 0 for rescaling only x, 1 for y */
52
52
  export const rescalePoints = (dimension, newSize, points, normalize, elementScope, currentScope) => {
53
53
  const coordinates = points.map((point) => point[dimension].scoped);
54
54
  const maxCoordinate = Math.max(...coordinates);
@@ -1 +1 @@
1
- export { DUC_SCHEMA_VERSION as DUC_VERSION } from "../serialize";
1
+ export declare const DUC_VERSION: string;
@@ -1 +1,3 @@
1
- export { DUC_SCHEMA_VERSION as DUC_VERSION } from "../serialize";
1
+ var _a, _b, _c;
2
+ const maybeProcess = globalThis;
3
+ export const DUC_VERSION = (_c = (_b = (_a = maybeProcess.process) === null || _a === void 0 ? void 0 : _a.env) === null || _b === void 0 ? void 0 : _b.DUC_SCHEMA_VERSION) !== null && _c !== void 0 ? _c : "0.0.0";
@@ -1,10 +1,4 @@
1
1
  import type { VersionGraph } from "./types";
2
- export interface RestoredVersion {
3
- versionNumber: number;
4
- schemaVersion: number;
5
- data: Uint8Array;
6
- fromCheckpoint: boolean;
7
- }
8
2
  export interface VersionEntry {
9
3
  id: string;
10
4
  versionNumber: number;
@@ -16,40 +10,25 @@ export interface VersionEntry {
16
10
  versionType: "checkpoint" | "delta";
17
11
  sizeBytes: number;
18
12
  }
19
- /**
20
- * Restore the full document state at a specific version number.
21
- *
22
- * If the version corresponds to a checkpoint, the raw data is returned directly.
23
- * Otherwise, the nearest preceding checkpoint is loaded and deltas are replayed
24
- * on top of it to reconstruct the state.
25
- *
26
- * All heavy lifting (SQLite access, decompression, delta replay) happens in
27
- * Rust/WASM.
28
- */
29
- export declare const restoreVersion: (ducBuffer: Uint8Array, versionNumber: number) => Promise<RestoredVersion>;
30
- /**
31
- * Restore a specific checkpoint by its ID.
32
- */
33
- export declare const restoreCheckpoint: (ducBuffer: Uint8Array, checkpointId: string) => Promise<RestoredVersion>;
13
+ export interface VersionControlDocument {
14
+ listVersions(): VersionEntry[];
15
+ readVersionGraph(): VersionGraph | undefined;
16
+ readCheckpointDataChunk(checkpointId: string, chunkIndex: number): Uint8Array | undefined;
17
+ readDeltaChangesetChunk(deltaId: string, chunkIndex: number): Uint8Array | undefined;
18
+ }
34
19
  /**
35
20
  * List all versions (checkpoints and deltas) in the .duc file,
36
21
  * ordered by version number descending. Does not load data blobs.
37
22
  */
38
- export declare const listVersions: (ducBuffer: Uint8Array) => Promise<VersionEntry[]>;
23
+ export declare const listVersions: (document: VersionControlDocument) => Promise<VersionEntry[]>;
39
24
  /**
40
- * Read the full version graph from the .duc file, including all
41
- * checkpoints, deltas, chains, and metadata.
42
- */
43
- export declare const readVersionGraph: (ducBuffer: Uint8Array) => Promise<VersionGraph | undefined>;
44
- /**
45
- * Revert the document to a specific version, deleting all versions
46
- * newer than the target. Returns the restored state at that version.
47
- *
48
- * **Warning**: This mutates the .duc buffer in-place (via the WASM
49
- * SQLite connection). The returned `RestoredVersion.data` contains the
50
- * full document state at the target version.
25
+ * Read version graph metadata from the document. Checkpoint `data` and delta
26
+ * `payload` arrays are intentionally empty; use the chunk readers below for
27
+ * payload bytes.
51
28
  */
52
- export declare const revertToVersion: (ducBuffer: Uint8Array, targetVersion: number) => Promise<RestoredVersion>;
29
+ export declare const readVersionGraph: (document: VersionControlDocument) => Promise<VersionGraph | undefined>;
30
+ export declare const readCheckpointDataChunk: (document: VersionControlDocument, checkpointId: string, chunkIndex: number) => Promise<Uint8Array | undefined>;
31
+ export declare const readDeltaChangesetChunk: (document: VersionControlDocument, deltaId: string, chunkIndex: number) => Promise<Uint8Array | undefined>;
53
32
  /**
54
33
  * Returns the current version-control schema version from Rust.
55
34
  *
@@ -71,8 +50,8 @@ export declare const getCurrentSchemaVersion: () => Promise<number>;
71
50
  * offsets, which is critical for SQLite databases where internal page
72
51
  * reordering makes simple byte-level diffs ineffective.
73
52
  *
74
- * Use this when constructing `Delta` objects for the `VersionGraph`
75
- * before calling `serializeDuc()`.
53
+ * Use this when constructing `Delta` objects for the `VersionGraph` before
54
+ * calling `writeDocumentState()` and streaming the resulting payload chunks.
76
55
  */
77
56
  export declare const createDeltaChangeset: (baseState: Uint8Array, currentState: Uint8Array) => Promise<Uint8Array>;
78
57
  /**
@@ -7,68 +7,28 @@ 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 { ensureWasm, wasmApplyDeltaChangeset, wasmCreateDeltaChangeset, wasmGetCurrentSchemaVersion, wasmListVersions, wasmReadVersionGraph, wasmRestoreCheckpoint, wasmRestoreVersion, wasmRevertToVersion, } from "./wasm";
11
- /**
12
- * Restore the full document state at a specific version number.
13
- *
14
- * If the version corresponds to a checkpoint, the raw data is returned directly.
15
- * Otherwise, the nearest preceding checkpoint is loaded and deltas are replayed
16
- * on top of it to reconstruct the state.
17
- *
18
- * All heavy lifting (SQLite access, decompression, delta replay) happens in
19
- * Rust/WASM.
20
- */
21
- export const restoreVersion = (ducBuffer, versionNumber) => __awaiter(void 0, void 0, void 0, function* () {
22
- yield ensureWasm();
23
- const result = wasmRestoreVersion(ducBuffer, versionNumber);
24
- if (!result) {
25
- throw new Error(`Failed to restore version ${versionNumber}`);
26
- }
27
- return result;
28
- });
29
- /**
30
- * Restore a specific checkpoint by its ID.
31
- */
32
- export const restoreCheckpoint = (ducBuffer, checkpointId) => __awaiter(void 0, void 0, void 0, function* () {
33
- yield ensureWasm();
34
- const result = wasmRestoreCheckpoint(ducBuffer, checkpointId);
35
- if (!result) {
36
- throw new Error(`Failed to restore checkpoint ${checkpointId}`);
37
- }
38
- return result;
39
- });
10
+ import { ensureWasm, wasmApplyDeltaChangeset, wasmCreateDeltaChangeset, wasmGetCurrentSchemaVersion, } from "./wasm";
40
11
  /**
41
12
  * List all versions (checkpoints and deltas) in the .duc file,
42
13
  * ordered by version number descending. Does not load data blobs.
43
14
  */
44
- export const listVersions = (ducBuffer) => __awaiter(void 0, void 0, void 0, function* () {
45
- yield ensureWasm();
46
- const result = wasmListVersions(ducBuffer);
15
+ export const listVersions = (document) => __awaiter(void 0, void 0, void 0, function* () {
16
+ const result = document.listVersions();
47
17
  return (result !== null && result !== void 0 ? result : []);
48
18
  });
49
19
  /**
50
- * Read the full version graph from the .duc file, including all
51
- * checkpoints, deltas, chains, and metadata.
20
+ * Read version graph metadata from the document. Checkpoint `data` and delta
21
+ * `payload` arrays are intentionally empty; use the chunk readers below for
22
+ * payload bytes.
52
23
  */
53
- export const readVersionGraph = (ducBuffer) => __awaiter(void 0, void 0, void 0, function* () {
54
- yield ensureWasm();
55
- return wasmReadVersionGraph(ducBuffer);
24
+ export const readVersionGraph = (document) => __awaiter(void 0, void 0, void 0, function* () {
25
+ return document.readVersionGraph();
56
26
  });
57
- /**
58
- * Revert the document to a specific version, deleting all versions
59
- * newer than the target. Returns the restored state at that version.
60
- *
61
- * **Warning**: This mutates the .duc buffer in-place (via the WASM
62
- * SQLite connection). The returned `RestoredVersion.data` contains the
63
- * full document state at the target version.
64
- */
65
- export const revertToVersion = (ducBuffer, targetVersion) => __awaiter(void 0, void 0, void 0, function* () {
66
- yield ensureWasm();
67
- const result = wasmRevertToVersion(ducBuffer, targetVersion);
68
- if (!result) {
69
- throw new Error(`Failed to revert to version ${targetVersion}`);
70
- }
71
- return result;
27
+ export const readCheckpointDataChunk = (document, checkpointId, chunkIndex) => __awaiter(void 0, void 0, void 0, function* () {
28
+ return document.readCheckpointDataChunk(checkpointId, chunkIndex);
29
+ });
30
+ export const readDeltaChangesetChunk = (document, deltaId, chunkIndex) => __awaiter(void 0, void 0, void 0, function* () {
31
+ return document.readDeltaChangesetChunk(deltaId, chunkIndex);
72
32
  });
73
33
  /**
74
34
  * Returns the current version-control schema version from Rust.
@@ -94,8 +54,8 @@ export const getCurrentSchemaVersion = () => __awaiter(void 0, void 0, void 0, f
94
54
  * offsets, which is critical for SQLite databases where internal page
95
55
  * reordering makes simple byte-level diffs ineffective.
96
56
  *
97
- * Use this when constructing `Delta` objects for the `VersionGraph`
98
- * before calling `serializeDuc()`.
57
+ * Use this when constructing `Delta` objects for the `VersionGraph` before
58
+ * calling `writeDocumentState()` and streaming the resulting payload chunks.
99
59
  */
100
60
  export const createDeltaChangeset = (baseState, currentState) => __awaiter(void 0, void 0, void 0, function* () {
101
61
  yield ensureWasm();
package/dist/wasi.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Server-side WASI streaming helper.
3
+ *
4
+ * Uses the `ducjs_wasi.wasm` binary via Node.js `node:wasi` for streaming
5
+ * .duc serialization. Unlike the browser WASM (limited by 32-bit address space),
6
+ * WASI has direct file system access and can handle files of any size.
7
+ *
8
+ * The WASI binary reads a JSON manifest from stdin (or a file path as argv[2]),
9
+ * streams files into a SQLite database, then gzip-compresses to produce a .duc file.
10
+ */
11
+ import type { ExportedDataState } from "./types";
12
+ export interface StreamFileEntry {
13
+ fileId: string;
14
+ revisionId: string;
15
+ sourcePath: string;
16
+ mimeType: string;
17
+ sizeBytes: number;
18
+ }
19
+ /**
20
+ * Stream multiple files into a single .duc file using the WASI binary.
21
+ *
22
+ * @param entries - Files to stream (fileId, revisionId, local sourcePath, mimeType, sizeBytes)
23
+ * @param outputPath - Where to write the resulting .duc file
24
+ * @param tempDir - Directory for temporary files (defaults to os.tmpdir())
25
+ * @returns The compressed .duc file size in bytes
26
+ */
27
+ export declare function streamToDucFile(entries: StreamFileEntry[], outputPath: string, tempDir?: string): Promise<number>;
28
+ export declare function serializeStateToDucFile(state: Partial<ExportedDataState>, outputPath: string, tempDir?: string): Promise<number>;
29
+ export declare function serializeStateToDucBytes(state: Partial<ExportedDataState>, tempDir?: string): Promise<Uint8Array>;
package/dist/wasi.js ADDED
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Server-side WASI streaming helper.
3
+ *
4
+ * Uses the `ducjs_wasi.wasm` binary via Node.js `node:wasi` for streaming
5
+ * .duc serialization. Unlike the browser WASM (limited by 32-bit address space),
6
+ * WASI has direct file system access and can handle files of any size.
7
+ *
8
+ * The WASI binary reads a JSON manifest from stdin (or a file path as argv[2]),
9
+ * streams files into a SQLite database, then gzip-compresses to produce a .duc file.
10
+ */
11
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
12
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
13
+ return new (P || (P = Promise))(function (resolve, reject) {
14
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
15
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
16
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
17
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
18
+ });
19
+ };
20
+ import { WASI } from "node:wasi";
21
+ import { readFileSync, existsSync, writeFileSync, unlinkSync, mkdirSync, statSync, rmdirSync, rmSync, mkdtempSync } from "node:fs";
22
+ import { join, dirname, resolve, relative } from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+ import os from "node:os";
25
+ import { prepareStateForSerialization } from "./serialize";
26
+ const _dirname = typeof import.meta !== "undefined"
27
+ ? dirname(fileURLToPath(import.meta.url))
28
+ : "";
29
+ const isBunRuntime = () => { var _a; return typeof process !== "undefined" && typeof ((_a = process.versions) === null || _a === void 0 ? void 0 : _a.bun) === "string"; };
30
+ const getDefaultTempDir = () => isBunRuntime()
31
+ ? join(process.cwd(), ".duc-wasi-tmp")
32
+ : os.tmpdir();
33
+ const toBunWasiPath = (path) => isBunRuntime()
34
+ ? relative(process.cwd(), path) || "."
35
+ : path;
36
+ const isSuccessfulWasiExit = (error) => {
37
+ const candidate = error;
38
+ return (candidate === null || candidate === void 0 ? void 0 : candidate.code) === 0
39
+ || (candidate === null || candidate === void 0 ? void 0 : candidate.exitCode) === 0
40
+ || (candidate === null || candidate === void 0 ? void 0 : candidate.message) === "Exited with status 0";
41
+ };
42
+ /**
43
+ * Resolve the WASI binary path.
44
+ * In development, it's in the ducjs dist directory.
45
+ * In production, it should be bundled or downloaded.
46
+ */
47
+ function resolveWasiBinary() {
48
+ var _a;
49
+ // Check for explicit override
50
+ const env = (_a = globalThis.process) === null || _a === void 0 ? void 0 : _a.env;
51
+ if (env === null || env === void 0 ? void 0 : env.DUCJS_WASI_PATH) {
52
+ return env.DUCJS_WASI_PATH;
53
+ }
54
+ // Try to find it relative to ducjs package
55
+ const candidates = [
56
+ // Relative to this file (if in node_modules)
57
+ resolve(_dirname, "..", "node_modules", "ducjs", "dist", "ducjs_wasi.wasm"),
58
+ // Relative to ducjs dist (if running from source)
59
+ resolve(_dirname, "..", "ducjs", "dist", "ducjs_wasi.wasm"),
60
+ // Direct path from ducjs package
61
+ resolve(_dirname, "ducjs_wasi.wasm"),
62
+ ];
63
+ for (const candidate of candidates) {
64
+ if (existsSync(candidate))
65
+ return candidate;
66
+ }
67
+ throw new Error(`ducjs WASI binary not found. Set DUCJS_WASI_PATH or ensure ducjs/dist/ducjs_wasi.wasm exists. Tried: ${candidates.join(", ")}`);
68
+ }
69
+ /**
70
+ * Stream multiple files into a single .duc file using the WASI binary.
71
+ *
72
+ * @param entries - Files to stream (fileId, revisionId, local sourcePath, mimeType, sizeBytes)
73
+ * @param outputPath - Where to write the resulting .duc file
74
+ * @param tempDir - Directory for temporary files (defaults to os.tmpdir())
75
+ * @returns The compressed .duc file size in bytes
76
+ */
77
+ export function streamToDucFile(entries, outputPath, tempDir) {
78
+ return __awaiter(this, void 0, void 0, function* () {
79
+ const tmpDir = tempDir !== null && tempDir !== void 0 ? tempDir : getDefaultTempDir();
80
+ mkdirSync(tmpDir, { recursive: true });
81
+ const manifestDir = mkdtempSync(join(tmpDir, "duc-wasi-"));
82
+ // Write manifest
83
+ const manifestPath = join(manifestDir, "manifest.jsonl");
84
+ const manifestContent = entries.map((e) => JSON.stringify(e)).join("\n") + "\n";
85
+ writeFileSync(manifestPath, manifestContent);
86
+ // Clean up old output
87
+ if (existsSync(outputPath)) {
88
+ unlinkSync(outputPath);
89
+ }
90
+ const outputDir = dirname(outputPath);
91
+ try {
92
+ yield runWasi(["ducjs-wasi", isBunRuntime() ? toBunWasiPath(outputPath) : `/output/${outputPath.split("/").pop()}`, isBunRuntime() ? toBunWasiPath(manifestPath) : "/tmp/manifest.jsonl"], {
93
+ "/": "/",
94
+ ".": process.cwd(),
95
+ "/tmp": manifestDir,
96
+ "/output": outputDir,
97
+ });
98
+ }
99
+ catch (e) {
100
+ if (!isSuccessfulWasiExit(e)) {
101
+ // Clean up and rethrow
102
+ try {
103
+ unlinkSync(manifestPath);
104
+ }
105
+ catch (_a) { }
106
+ try {
107
+ unlinkSync(join(manifestDir, "manifest.jsonl"));
108
+ }
109
+ catch (_b) { }
110
+ throw e;
111
+ }
112
+ }
113
+ // Verify output
114
+ if (!existsSync(outputPath)) {
115
+ throw new Error(`WASI binary did not produce output file: ${outputPath}`);
116
+ }
117
+ const size = statSync(outputPath).size;
118
+ // Clean up manifest
119
+ try {
120
+ unlinkSync(manifestPath);
121
+ }
122
+ catch (_c) { }
123
+ try {
124
+ rmdirSync(manifestDir);
125
+ }
126
+ catch (_d) { }
127
+ return size;
128
+ });
129
+ }
130
+ const jsonReplacer = (key, value) => {
131
+ if (value instanceof Uint8Array) {
132
+ if (value.byteLength > 64 * 1024 * 1024) {
133
+ throw new RangeError(`Binary field ${key || "<root>"} is too large for the WASI state JSON; external revisions must use filesData`);
134
+ }
135
+ return Array.from(value);
136
+ }
137
+ return value;
138
+ };
139
+ const prepareStateForWasi = (state) => {
140
+ var _a, _b;
141
+ const prepared = prepareStateForSerialization(Object.assign(Object.assign({}, state), { version: (_a = state.version) !== null && _a !== void 0 ? _a : "0.0.0", source: (_b = state.source) !== null && _b !== void 0 ? _b : "ducjs/wasi", filesData: undefined }));
142
+ delete prepared.filesData;
143
+ return prepared;
144
+ };
145
+ const writeExternalFileSidecars = (state, manifestDir) => {
146
+ var _a;
147
+ const filesData = state.filesData;
148
+ if (!filesData || Object.keys(filesData).length === 0)
149
+ return undefined;
150
+ const revisions = new Map();
151
+ for (const file of Object.values((_a = state.files) !== null && _a !== void 0 ? _a : {})) {
152
+ for (const revision of Object.values(file.revisions)) {
153
+ revisions.set(revision.id, {
154
+ fileId: file.id,
155
+ revisionId: revision.id,
156
+ mimeType: revision.mimeType,
157
+ sizeBytes: revision.sizeBytes,
158
+ });
159
+ }
160
+ }
161
+ const entries = [];
162
+ let index = 0;
163
+ for (const [revisionId, data] of Object.entries(filesData)) {
164
+ const revision = revisions.get(revisionId);
165
+ if (!revision) {
166
+ throw new Error(`filesData contains unknown external revision ${revisionId}`);
167
+ }
168
+ if (!(data instanceof Uint8Array)) {
169
+ throw new TypeError(`filesData revision ${revisionId} is not a Uint8Array`);
170
+ }
171
+ if (revision.sizeBytes > 0 && revision.sizeBytes !== data.byteLength) {
172
+ throw new Error(`External revision ${revisionId} has ${data.byteLength} bytes, expected ${revision.sizeBytes}`);
173
+ }
174
+ const filename = `external-${index}.bin`;
175
+ const sourcePath = join(manifestDir, filename);
176
+ writeFileSync(sourcePath, data);
177
+ entries.push(Object.assign(Object.assign({}, revision), { sourcePath: isBunRuntime() ? toBunWasiPath(sourcePath) : `/tmp/${filename}`, sizeBytes: revision.sizeBytes || data.byteLength }));
178
+ index += 1;
179
+ }
180
+ const manifestPath = join(manifestDir, "external-files.jsonl");
181
+ writeFileSync(manifestPath, entries.map((entry) => JSON.stringify(entry)).join("\n") + "\n");
182
+ return manifestPath;
183
+ };
184
+ const runWasi = (args, preopens) => __awaiter(void 0, void 0, void 0, function* () {
185
+ const wasmBinary = readFileSync(resolveWasiBinary());
186
+ const wasi = new WASI({
187
+ version: "preview1",
188
+ args,
189
+ env: {},
190
+ preopens,
191
+ });
192
+ const imports = typeof wasi.getImportObject === "function"
193
+ ? wasi.getImportObject()
194
+ : { wasi_snapshot_preview1: wasi.wasiImport };
195
+ const module = yield WebAssembly.compile(wasmBinary);
196
+ const instance = yield WebAssembly.instantiate(module, imports);
197
+ try {
198
+ wasi.start(instance);
199
+ }
200
+ catch (e) {
201
+ if (!isSuccessfulWasiExit(e)) {
202
+ throw e;
203
+ }
204
+ }
205
+ });
206
+ export function serializeStateToDucFile(state, outputPath, tempDir) {
207
+ return __awaiter(this, void 0, void 0, function* () {
208
+ const tmpDir = tempDir !== null && tempDir !== void 0 ? tempDir : getDefaultTempDir();
209
+ mkdirSync(tmpDir, { recursive: true });
210
+ const manifestDir = mkdtempSync(join(tmpDir, "duc-wasi-state-"));
211
+ const statePath = join(manifestDir, "state.json");
212
+ try {
213
+ writeFileSync(statePath, JSON.stringify(prepareStateForWasi(state), jsonReplacer));
214
+ const externalManifestPath = writeExternalFileSidecars(state, manifestDir);
215
+ if (existsSync(outputPath)) {
216
+ unlinkSync(outputPath);
217
+ }
218
+ yield runWasi([
219
+ "ducjs-wasi",
220
+ "--state-json",
221
+ isBunRuntime() ? toBunWasiPath(statePath) : "/tmp/state.json",
222
+ isBunRuntime() ? toBunWasiPath(outputPath) : `/output/${outputPath.split("/").pop()}`,
223
+ ...(externalManifestPath
224
+ ? [isBunRuntime() ? toBunWasiPath(externalManifestPath) : "/tmp/external-files.jsonl"]
225
+ : []),
226
+ ], {
227
+ "/": "/",
228
+ ".": process.cwd(),
229
+ "/tmp": manifestDir,
230
+ "/output": dirname(outputPath),
231
+ });
232
+ if (!existsSync(outputPath)) {
233
+ throw new Error(`WASI binary did not produce output file: ${outputPath}`);
234
+ }
235
+ return statSync(outputPath).size;
236
+ }
237
+ finally {
238
+ try {
239
+ rmSync(manifestDir, { recursive: true, force: true });
240
+ }
241
+ catch (_a) { }
242
+ }
243
+ });
244
+ }
245
+ export function serializeStateToDucBytes(state, tempDir) {
246
+ return __awaiter(this, void 0, void 0, function* () {
247
+ const tmpDir = tempDir !== null && tempDir !== void 0 ? tempDir : getDefaultTempDir();
248
+ mkdirSync(tmpDir, { recursive: true });
249
+ const outputDir = mkdtempSync(join(tmpDir, "duc-wasi-output-"));
250
+ const outputPath = join(outputDir, "state.duc");
251
+ try {
252
+ yield serializeStateToDucFile(state, outputPath, tmpDir);
253
+ return new Uint8Array(readFileSync(outputPath));
254
+ }
255
+ finally {
256
+ try {
257
+ unlinkSync(outputPath);
258
+ }
259
+ catch (_a) { }
260
+ try {
261
+ rmdirSync(outputDir);
262
+ }
263
+ catch (_b) { }
264
+ }
265
+ });
266
+ }