# Archive Decompression

> 将压缩归档解包为结构化的文件数组，便于用 `flow.split` 迭代并交给下游抽取节点处理。

Source: https://docs.sommatic.ai/zh/nodes/ai.archive.decompress/

- 标识: `ai.archive.decompress`
- 类别: AI
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

将压缩归档解包为结构化的文件数组，便于用 `flow.split` 迭代并交给下游抽取节点处理。

支持邮件附件、数据交付和文档导出中最常见的归档格式，并可在可配置的深度内递归解包嵌套归档。

**功能特性：**
- **支持的格式：** ZIP、TAR、TAR.GZ（tgz）、TAR.BZ2（tbz2）、7z。格式检测结合文件名提示和魔数（magic bytes），即使归档标错扩展名也能正确处理。
- **递归解包：** 嵌套归档（归档中的归档）会一直解包到 `max_depth`，并在每个输出文件的 `name` 中保留完整路径上下文。
- **逐条 MIME 检测：** 每个输出文件都带有规范化的 `content_type`，由扩展名加魔数嗅探得出，下游分发节点无需额外探测即可路由。
- **路径穿越防护：** 拒绝包含 `../` 或绝对路径的条目，以防范 Zip Slip 攻击。
- **加密/损坏的条目：** 无法解压的条目会被跳过并记录在元数据中，而不会中止整个归档的处理。
- **输出结构：** 由 `{ name, content_type, size, content_base64 }` 组成的数组，外加 `count` 和逐条目的元数据块。

## 配置

- `max_depth` (number, 可选): 嵌套归档解包的最大深度。 默认值: `3`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `extracted` (默认): Extracted
- `empty`: Empty
- `error`: Error

## 输入契约

- `content_base64` (string, 可选)
- `file_path` (string, 可选)
- `name` (string, 可选): 可选的归档文件名提示（有助于格式检测）。

## 输出契约

- `files` (array<object>, 可选)
- `count` (number, 可选)
- `empty` (boolean, 可选)
- `method` (string, 可选)
- `metadata` (object, 可选)

## 在表达式中

后续节点可通过 `$("Archive Decompression").item.json.<路径>` 读取此节点输出中的内容（请把 `Archive Decompression` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `extracted` 返回的路径，依据“端口”一节所示的输出。

- `$("Archive Decompression").item.json.files` (array) = `[…] (2)`
- `$("Archive Decompression").item.json.count` (number) = `2`
- `$("Archive Decompression").item.json.empty` (boolean) = `false`
- `$("Archive Decompression").item.json.method` (string) = `"zipfile"`
- `$("Archive Decompression").item.json.metadata` (object) = `{…}`
- `$("Archive Decompression").item.json.metadata.max_depth_applied` (number) = `3` (编辑器不提示)
- `$("Archive Decompression").item.json.metadata.total_size_bytes` (number) = `168257` (编辑器不提示)
- `$("Archive Decompression").item.json.metadata.skipped_unsafe` (number) = `0` (编辑器不提示)


## 工作原理

在 Python 进程中解压一个 ZIP、TAR（gz/bz2）或 7z 压缩包，以 base64 返回其中每个文件，并按 `max_depth` 递归解压嵌套压缩包。

1. 从节点配置读取 `content_base64`、`file_path` 和 `name`，缺失时回退到上游载荷。两者都没有时从 `error` 输出。
2. 仅根据文件名判断格式：base64 输入用 `name`（默认 `archive`），否则用 `file_path` 的文件名。可识别 `.zip`、`.tar`、`.tar.gz`、`.tgz`、`.tar.bz2` 和 `.7z`；其他名称先按 ZIP 尝试，再按 TAR 尝试。
3. 遍历每个普通文件。路径为绝对路径或包含 `..` 段的条目会被跳过，并计入 `metadata.skipped_unsafe`。
4. 名称以压缩包扩展名结尾的条目，在深度小于 `max_depth`（默认 3）时会被递归解压，其中文件命名为 `<父级>/<内部路径>`。嵌套压缩包无法打开时，会作为普通文件保留。
5. 每个文件转换为 `{ name, content_type, size, content_base64 }`；`content_type` 仅根据扩展名推断（未知时为 `application/octet-stream`）。
6. 未产出任何文件时从 `empty` 输出，否则从 `extracted` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-unpack-delivery",
  "label": "Unpack delivery",
  "operator_slug": "ai.archive.decompress",
  "operator_version": "1.0.0",
  "config": {
    "content_base64": "{{ $json.attachment.content_base64 }}",
    "name": "{{ $json.attachment.name }}",
    "max_depth": 2,
    "execution": {
      "timeout_ms": 300000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "files": [
      {
        "name": "invoices/2026-10.pdf",
        "content_type": "application/pdf",
        "size": 48213,
        "content_base64": "JVBERi0xLjcK..."
      }
    ],
    "count": 1,
    "empty": false,
    "method": "zipfile",
    "metadata": {
      "max_depth_applied": 2,
      "total_size_bytes": 48213,
      "skipped_unsafe": 0
    }
  },
  "port": "extracted"
}
```

## 输出端口 (代码中的行为)

### `extracted`

至少解压出一个文件。

```json
{
  "files": [
    {
      "name": "invoices/2026-10.pdf",
      "content_type": "application/pdf",
      "size": 48213,
      "content_base64": "JVBERi0xLjcK..."
    },
    {
      "name": "scans.zip/page-1.png",
      "content_type": "image/png",
      "size": 120044,
      "content_base64": "iVBORw0KGgo..."
    }
  ],
  "count": 2,
  "empty": false,
  "method": "zipfile",
  "metadata": {
    "max_depth_applied": 3,
    "total_size_bytes": 168257,
    "skipped_unsafe": 0
  }
}
```

### `empty`

压缩包已打开，但不含可用文件（只有文件夹或只有不安全条目）。

```json
{
  "files": [],
  "count": 0,
  "empty": true,
  "method": "zipfile",
  "metadata": {
    "max_depth_applied": 3,
    "total_size_bytes": 0,
    "skipped_unsafe": 1
  }
}
```

### `error`

未提供输入、压缩包无法读取（损坏、加密、不支持）或脚本失败。

```json
{
  "error": "File is not a zip file",
  "stderr": ""
}
```

## 代码中的行为

- `content_base64, file_path, name`: 未在配置 schema 中声明，但会先从节点配置读取，再从上游载荷读取。通常用表达式从上一个节点映射。
- `max_depth`: 顶层条目深度为 0；仅当嵌套压缩包的深度小于 `max_depth` 时才会被打开。设为 `0` 时，嵌套压缩包作为文件返回。
- `execution`: 仅读取 `execution.timeout_ms`（缺省回退 300000 毫秒）。`retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail` 和 `alwaysOutputData` 均被忽略。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | 节点配置和上游载荷都没有提供文件。请从上一个节点映射 `content_base64`（或 `file_path`）。 |
| `Either content_base64 or file_path is required` | `error` | 当只提供了 `file_path` 而主机上不存在该文件时，由脚本抛出（末尾无句点）。 |
| `File <entry> is encrypted, password required for extraction` | `error` | 受密码保护的 ZIP 条目会使整个压缩包失败，不会被跳过。不支持密码。 |
| `py7zr is not installed; cannot handle 7z archives` | `error` | 主机缺少 7z 库。它通常会随脚本依赖一起安装。 |
| `<parser exception message>` | `error` | Python 解析器抛出异常（压缩包损坏或格式未知，例如未以 `.7z` 命名的 7z 文件）。该消息原样放入 `data.error`，脚本的 stderr 放入 `data.stderr`。 |
| `Python timed out after <timeout_ms>ms` | `error` | 脚本超出了节点超时。请调大 `execution.timeout_ms` 或发送更小的文件。 |
| `Python stdout exceeded MAX_STDOUT_BYTES (52428800 bytes)` | `error` | 结果（文本或 base64 文件）超过 50 MB 上限。请在上游拆分输入。 |
| `Python runtime not available (ENOENT)` | `error` | 主机上没有 Python 解释器。若依赖安装失败，消息为 `PythonRunner failed: <message>`。两者都是主机问题，而非工作流问题。 |

## 说明与限制

- 在子进程中运行 Python 脚本。某台 worker 主机上的首次运行会创建虚拟环境并安装脚本锁定的依赖（可能耗时数分钟，且不计入节点超时）；之后的运行会复用该环境。
- `file_path` 必须指向运行该节点的编排器主机本地磁盘上的文件；它不是 URL，也不会从存储中下载。
- 脚本会在 `execution.timeout_ms` 到期后被终止；未设置该键时代码使用 300000 毫秒，而不是 schema 默认的 300000。
- 脚本返回的 JSON 上限为 50 MB（52428800 字节，可在主机上配置）。文件以 base64 传输，较大的输入或输出可能触及该上限。
- 最多返回 5000 个文件，多余条目会被静默丢弃。除 50 MB 输出上限外，不限制解压后的大小。
- 格式和 MIME 检测只依据文件名，不检查魔数。base64 输入请务必传入带正确扩展名的 `name`，7z 尤其如此。
- 可配合对 `files` 使用 `flow.split`，在下游逐个处理文件。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "ai.archive.decompress",
  "name": "Archive Decompression",
  "category": "ai",
  "version": "1.0.0",
  "description": "Unpacks compressed archives into a structured array of files suitable for iteration with `flow.split` and downstream extraction nodes.\n\n  Supports the most common archive formats used for email attachments, data deliveries, and document exports, with recursive unpacking of nested archives up to a configurable depth.\n\n  **Features:**\n  - **Supported formats:** ZIP, TAR, TAR.GZ (tgz), TAR.BZ2 (tbz2), 7z. Format detection combines filename hints with magic bytes so mislabelled archives are still handled.\n  - **Recursive unpacking:** Nested archives (archive inside archive) are unpacked up to `max_depth`, preserving full path context in each emitted file's `name`.\n  - **MIME detection per entry:** Every output file carries a normalized `content_type` derived from its extension plus magic-byte sniffing so downstream dispatchers can route without extra probing.\n  - **Path traversal protection:** Entries with `../` or absolute paths are rejected to prevent Zip Slip attacks.\n  - **Encrypted / damaged entries:** Entries that cannot be decompressed are skipped and reported in metadata rather than aborting the whole archive.\n  - **Output shape:** Array of `{ name, content_type, size, content_base64 }` plus a `count` and per-entry metadata block.",
  "capabilities": [
    "archive",
    "zip",
    "tar",
    "7z",
    "decompression",
    "recursion"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "max_depth": {
        "type": "number",
        "title": "Max Recursion Depth",
        "default": 3,
        "description": "Maximum depth of nested archive unpacking."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "content_base64": {
        "type": "string"
      },
      "file_path": {
        "type": "string"
      },
      "name": {
        "type": "string",
        "description": "Optional archive filename hint (helps format detection)."
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "files": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "name": {
              "type": "string"
            },
            "content_type": {
              "type": "string"
            },
            "size": {
              "type": "number"
            },
            "content_base64": {
              "type": "string"
            }
          }
        }
      },
      "count": {
        "type": "number"
      },
      "empty": {
        "type": "boolean"
      },
      "method": {
        "type": "string"
      },
      "metadata": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Extracted",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "Empty",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "archive",
    "zip",
    "tar",
    "decompress"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "max_depth": {
      "type": "number",
      "title": "Max Recursion Depth",
      "default": 3,
      "description": "Maximum depth of nested archive unpacking."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "content_base64": {
      "type": "string"
    },
    "file_path": {
      "type": "string"
    },
    "name": {
      "type": "string",
      "description": "Optional archive filename hint (helps format detection)."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "files": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          },
          "content_type": {
            "type": "string"
          },
          "size": {
            "type": "number"
          },
          "content_base64": {
            "type": "string"
          }
        }
      }
    },
    "count": {
      "type": "number"
    },
    "empty": {
      "type": "boolean"
    },
    "method": {
      "type": "string"
    },
    "metadata": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "extracted",
    "label": "Extracted",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "Empty",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "is_default": false,
    "supports_condition": false
  }
]
```
