# SaveWorker Module data flow

**Purpose:** Concise summary of save worker.

**Primary role:** Perform server-backed save/export operations (JSON → remote endpoint) and marshal results back to the main thread or caller. Designed to run inside a Web Worker context or fall back to an in-thread call via `successCallBack`.

- **Constructor:** `new SaveWorker(parent)` — retains `parent` reference for contextual needs.

**API / Key methods**
- `processSheet(sheet: string, sheetIndex: number): Object`
  - Parses a JSON string `sheet` using `JSON.parse` with a replacer that drops empty arrays/strings (removes empty properties).
  - Returns a tuple-like array: `[sheetIndex, parsedSheet]` ready for transfer back to the main thread.

- `processSave(saveJSON, saveSettings, customParams, pdfLayoutSettings, successCallBack?)`
  - Builds a `FormData` payload:
    - `JSONData` := `JSON.stringify(saveJSON)`
    - Append all key/value pairs from `saveSettings` and `customParams`.
    - Append `pdfLayoutSettings` as JSON string.
  - Calls `fetch(saveSettings.url, { method: 'POST', body: formData })` to post payload to server.
  - On a successful `response.ok`:
    - Reads the response as a `Blob`.
    - Uses `FileReader.readAsDataURL` to convert blob to a data URL string.
    - Checks for embedded base64 prefixes (`data:text/plain;base64,`, `data:text/html;base64,`, `data:application/json;base64,`). If found, decodes base64 and extracts a dialog string (first segment) to send back as `{ dialog: text }`.
    - Otherwise returns raw `Blob` data.
    - Results are delivered either via `successCallBack` (if provided) or via `postMessage` (worker context).
  - On error:
    - Delivers `{ error: error.message }` via `successCallBack` or `postMessage`.

**Edge cases & notes**
- Detects an optional `customParams['customParams'] === 'saveashtml'` to alter base64 handling.
- The code contains a commented-out XHR fallback demonstrating synchronous POST behavior — retained for historical/reference purposes.
- Uses `postMessage` when running as a worker; otherwise invokes the provided `successCallBack`.

**Side effects & invariants**
- Network I/O via `fetch` is asynchronous; handlers must be prepared for blob/data URL or error objects.
- `processSheet` removes empty arrays/strings to reduce payload size before transferring across threads.
- Consumers must provide a valid `saveSettings.url` (or compatible field) to succeed.

**Where it's used**
- Invoked by `Workbook` save/export workflows when generating server-based outputs (paper/pdf/html/json). Can be executed inside a Web Worker for non-blocking behavior.

**Maintainer notes**
- If migrating to streams or large-file uploads, consider using `ReadableStream` / chunked uploads instead of full memory blob conversions.
- Ensure CORS and server response formats stay consistent with the base64/dataUrl parsing logic.
