Compare commits

..
69 Commits
Author SHA1 Message Date
yunyingk 72b61819a1 Merge pull request #76 from yunyingk/codex/release-v0.10.16
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.16: Full knowledge sync, semantic versioning and local dev override
2026-09-11 12:25:24 +08:00
gitea 50131d1f4c Release v0.10.16: Full knowledge sync, semantic versioning and local dev override 2026-09-11 12:24:13 +08:00
yunyingk 39ca400322 Merge pull request #75 from yunyingk/codex/sync-test-knowledge-documents
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add full coverage knowledge document synchronization to sync-test
2026-09-11 12:21:29 +08:00
gitea 718d8b663d Include target test version in sync version name 2026-09-11 12:20:33 +08:00
gitea 93f61a807a Add full coverage knowledge document synchronization to sync-test 2026-09-11 12:17:44 +08:00
yunyingk 43a18d0515 Merge pull request #74 from yunyingk/codex/sync-test-semantic-naming-and-mapping
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add semantic sync-test naming, rule mapping and rules map command
2026-09-11 12:06:28 +08:00
gitea 3d9e25fd06 Add semantic sync-test naming, rule mapping and rules map command 2026-09-11 12:05:23 +08:00
yunyingk 8db4b87385 Merge pull request #73 from yunyingk/codex/fix-approval-style-preferences-post
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Use POST method for approval style preferences endpoint
2026-09-11 11:51:33 +08:00
gitea 55dcd20d48 Update corps-bind test mock to expect POST for approval style preferences 2026-09-11 11:50:36 +08:00
gitea 112473a2b7 Use POST method for approval style preferences endpoint 2026-09-11 11:48:28 +08:00
yunyingk efadcd0de4 Merge pull request #72 from yunyingk/codex/local-dev-version-override
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add local dev binary override and Git-aware versioning
2026-09-11 11:43:23 +08:00
gitea 883690e128 Add local dev binary override and Git-aware versioning 2026-09-11 11:42:12 +08:00
yunyingk 83ade4dbf9 Merge pull request #71 from yunyingk/codex/release-v0.10.15
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Release v0.10.15: Contextual help, test enterprise pairing & sync, and directory normalization
2026-09-11 11:07:13 +08:00
gitea 8fa0016d89 Release v0.10.15: Contextual help, test enterprise pairing & sync, and directory normalization 2026-09-11 11:06:16 +08:00
yunyingk a521a24fe3 Merge pull request #70 from yunyingk/codex/contextual-command-help
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add contextual subcommand help to avoid context pollution
2026-09-11 11:03:36 +08:00
gitea 9a7be16d3b Add contextual subcommand help to avoid context pollution 2026-09-11 11:02:17 +08:00
yunyingk 9d6d11628e Merge pull request #69 from yunyingk/codex/cleanup-legacy-enterprise-dir
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Auto-migrate legacy enterprise directory and drop legacy reads
2026-09-11 10:49:45 +08:00
gitea 3d16857aeb Auto-migrate legacy enterprise directory and drop legacy reads 2026-09-11 10:47:59 +08:00
yunyingk ae5387e9aa Merge PR #68: Fix Gitea release fallback when artifact quota is full
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Fix Gitea release fallback when artifact quota is full
2026-09-11 10:47:55 +08:00
gitea bc6209749b Fix Gitea release fallback when artifact quota is full 2026-09-11 10:42:56 +08:00
yunyingk 08cbc541b4 Merge pull request #67 from yunyingk/codex/test-corp-binding-and-sync
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add test enterprise marking, binding, and staging sync commands
2026-09-11 10:30:20 +08:00
gitea a56606af9c Add test enterprise marking, binding, and staging sync commands 2026-09-11 10:28:52 +08:00
yunyingk f2595bb275 Merge pull request #66 from yunyingk/codex/unify-unknown-command-exit-codes
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Unify unknown command and subcommand exit code classification
2026-09-11 10:06:12 +08:00
gitea 0534651e0a Refine runner test for domain unknown subcommands 2026-09-11 10:05:19 +08:00
gitea 225321f34a Unify unknown command and subcommand exit code classification 2026-09-11 10:02:50 +08:00
yunyingk bda8b82157 Merge pull request #65 from yunyingk/codex/release-v0.10.14
Release v0.10.14
2026-09-11 09:45:43 +08:00
gitea 0e1f744c53 Release v0.10.14: unify staging capability coverage 2026-09-11 09:44:38 +08:00
yunyingk 6df9c817d4 Merge pull request #64 from yunyingk/codex/simulation-approval-definitions
Add simulation approval definition lookup
2026-09-11 01:57:08 +08:00
gitea 2a82017e50 Add simulation approval definition lookup 2026-09-11 01:55:56 +08:00
yunyingk bffd3998a3 Merge pull request #63 from yunyingk/codex/insight-default-range
Default insight stats to current month
2026-09-11 01:53:18 +08:00
gitea 41e31774ee Default insight stats to current month 2026-09-11 01:52:02 +08:00
yunyingk 83c11b7588 Merge pull request #62 from yunyingk/codex/financial-data-query
Add financial data list queries
2026-09-11 01:49:34 +08:00
gitea b94d6d11d5 Add financial data list queries 2026-09-11 01:47:47 +08:00
yunyingk a9f5e2d3ef Merge pull request #61 from yunyingk/codex/insight-stats
Add insight stats query
2026-09-11 01:43:35 +08:00
gitea a946cf45c9 Add insight stats query 2026-09-11 01:42:41 +08:00
yunyingk d3c9302c14 Merge pull request #60 from yunyingk/codex/contacts-read-api
Add read-only contacts directory APIs
2026-09-11 01:38:31 +08:00
gitea 17a31042a1 Add read-only contacts directory APIs 2026-09-11 01:37:10 +08:00
yunyingk 42403130e0 Add universal mutation preview mode
Merge reviewed fix for #46 after rebasing onto main.
2026-09-11 01:19:48 +08:00
gitea 690ee604f1 Merge main into mutation preview 2026-09-11 01:18:41 +08:00
yunyingk 5eb7c87e8d Standardize semantic CLI error handling
Merge reviewed fixes for #43 and #44 after CI validation.
2026-09-11 01:15:40 +08:00
gitea 370435bef9 Merge main into semantic CLI errors 2026-09-11 01:13:47 +08:00
yunyingk 8623f1ab64 Add non-blocking simulation status checks
Merge reviewed fix for #45.
2026-09-11 01:09:48 +08:00
yunyingk 5912d22ce4 Apply approval rule pushes incrementally
Merge reviewed fix for #50.
2026-09-11 01:08:59 +08:00
yunyingk 9f559ad94e Document draft and published rule code spaces
Merge reviewed fix for #51.
2026-09-11 01:08:43 +08:00
yunyingk fa72a53d61 Clarify knowledge document creation constraints
Merge reviewed fixes for #49 and #52.
2026-09-11 01:08:31 +08:00
yunyingk eac331922c Fix HTTP error response body reporting
Merge reviewed fix for #48.
2026-09-11 01:06:33 +08:00
gitea 5242df2392 Update semantic exit code test 2026-09-11 01:05:25 +08:00
gitea 138a4a9498 Add universal mutation preview mode 2026-09-11 00:45:27 +08:00
gitea 7bf40dd726 Standardize semantic CLI error handling 2026-09-11 00:28:09 +08:00
gitea 995b9fa81e Add non-blocking simulation status checks 2026-09-11 00:15:35 +08:00
gitea 1910faa8ea Apply approval rule pushes incrementally 2026-09-11 00:10:10 +08:00
gitea 73c0b24b48 Document draft and published rule code spaces 2026-09-11 00:06:16 +08:00
gitea cc7da4f421 Clarify knowledge document creation constraints 2026-09-11 00:04:06 +08:00
gitea 64692fecba Fix HTTP error response body reporting 2026-09-10 23:58:28 +08:00
yunyingk 0b10a70924 Merge pull request #47 from yunyingk/codex/custom-http-headers
Add per-enterprise custom HTTP headers and cookies
2026-09-10 17:17:44 +08:00
gitea bb8b5edec6 Add per-enterprise custom HTTP headers and cookies
Some Seal tenants sit behind a gateway that only forwards requests
carrying its own session cookie. Corp configs can now set
seal.headers/seal.cookies, which the client merges into every request;
cookies are rendered into one Cookie header and the session bearer
token still wins over any configured Authorization.

corps add-seal accepts both fields and applies them when verifying the
tenant, so a gated enterprise can be registered in one step.
2026-09-10 16:25:11 +08:00
yunyingk fc06434813 Merge pull request #42 from yunyingk/codex/material-pack-file-policy
Add configurable material pack attachment file policy
2026-09-08 15:17:18 +08:00
gitea 799cdd1b17 Refine material pack policy recovery guidance 2026-09-08 15:10:39 +08:00
gitea 79c9420e4e Add material pack attachment file policy 2026-09-08 14:54:51 +08:00
yunyingk e512ee68dc Merge pull request #41 from yunyingk/codex/release-v0.10.13
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.13: Enforce material-pack scope isolation and strict path uniqueness
2026-09-08 10:01:04 +08:00
gitea 80e0dea178 Release v0.10.13: Enforce material-pack scope isolation and strict path uniqueness 2026-09-08 10:00:10 +08:00
yunyingk c60a7d0d18 Merge pull request #40 from yunyingk/codex/material-pack-path-declaration
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Refactor material-pack: [附件] column prefix + @ dir annotation + strict path validation
2026-09-07 18:31:32 +08:00
gitea 081ff0f8aa Refactor material-pack: [附件] column prefix + @ dir annotation + strict path validation
- Replace filename-heuristic attachment matching with explicit [附件] column declaration
- AttachmentGroup replaces MaterialAttachmentEntry: uses paths[] instead of entries[]
- parseMaterialWorkbook now exports DeclaredAttachment and full Parsed type including
  documentAttachments, expenseAttachments, personAttachments per row
- buildAttachmentPlans enforces strict bidirectional validation:
  1. Every Excel [附件] path must exist in ZIP
  2. Every ZIP file must be declared in some [附件] column
- validateDocIdDirectories now strips @annotation suffix when matching documentIds
- injectAttachmentPlan updated to work with new AttachmentGroup.paths API
- pushMaterialPack iterates group.paths for uploads, adding stderr diagnostics
- Key deduplication applied at parse time (deduplicateKeys)
- Tests updated: [附件] column fixtures, bidirectional validation error tests,
  @ annotation matching test, preview injection test
- Skill docs updated: Material Pack Workflow section in references/cli.md
- Version bumped to 0.10.12
2026-09-07 18:26:21 +08:00
yunyingk 2ab4e69122 Merge pull request #39 from yunyingk/codex/release-v0.10.11
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.11: Standard approval runs Excel export command and tool
2026-09-07 16:34:26 +08:00
gitea 06561bc893 Release v0.10.11: Standard approval runs Excel export command and tool 2026-09-07 16:33:12 +08:00
yunyingk b950e2b562 Merge pull request #38 from yunyingk/codex/release-v0.10.10
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.10: Remove default cwd enterprises loading and add global test-dir config
2026-09-07 15:27:25 +08:00
gitea b5cc7c874e Release v0.10.10: Remove default cwd enterprises loading and add global test-dir config 2026-09-07 15:26:21 +08:00
yunyingk 878e53ac81 Merge pull request #37 from yunyingk/codex/release-v0.10.9
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.9: Purge legacy MCP code, decouple CLI commands, and clean unused exports
2026-09-04 19:09:19 +08:00
gitea edafe033dc Release v0.10.9: Purge legacy MCP code, decouple CLI commands, and clean unused exports 2026-09-04 19:08:16 +08:00
80 changed files with 8442 additions and 1171 deletions

No files matched your search

+16 -5
View File
@@ -83,6 +83,7 @@ jobs:
publish-gitea:
name: 📦 Sync Gitea Mirror
needs: build-and-publish-github
if: ${{ always() }}
runs-on: ubuntu-latest
continue-on-error: true
steps:
@@ -91,11 +92,21 @@ jobs:
with:
fetch-depth: 0
- name: Download binaries artifact
uses: actions/download-artifact@v4
with:
name: release-binaries
path: dist/bin/
# The GitHub artifact service can be unavailable or quota-limited even
# after the release upload succeeds. Download from the release itself so
# Gitea mirroring remains independent of ephemeral workflow artifacts.
- name: Download release assets from GitHub Release
env:
GH_TOKEN: ${{ github.token }}
run: |
TAG_NAME="${{ github.event.inputs.tag || github.ref_name }}"
mkdir -p dist/bin
gh release download "${TAG_NAME}" \
--repo "${GITHUB_REPOSITORY}" \
--pattern 'seal-use-*' \
--pattern 'checksums.txt' \
--dir dist/bin \
--clobber
- name: Sync to Gitea Release
env:
+4
View File
@@ -14,4 +14,8 @@ enterprises/*.json
# Local generated reports and exported deliverables.
.local/
.apifox/
exports/
scripts/export-*.ts
# Local custom linters
linters/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.8",
"version": "0.10.16",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+1
View File
@@ -21,6 +21,7 @@ Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in
- `bun run openapi:bundle`: rebuild `dist/openapi.json`.
- `bun run build:binary`: compile the standalone `seal-use` binary to `dist/bin/seal-use` (gitignored).
- `bun run build:plugin`: bundle the MCP server to `dist/mcp/server.js` (tracked, used by `.mcp.json`).
- `bun run dev:override`: compile the host binary with Git dev version metadata, macOS sign, atomically override the Mac global command (`/opt/homebrew/bin/seal-use`), and sync the local Agent Skill.
## Coding Style & Naming Conventions
+123 -1
View File
@@ -5,6 +5,128 @@ All notable changes to `seal-use` will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.10.16] - 2026-09-11
### Added & Enhanced
- **Full-Coverage Knowledge Document Synchronization**:
- Extended `seal-use corps sync-test` to synchronize knowledge articles (`api/v1/knowledge/articles`) alongside rules and preferences.
- Natural key matching by title: creates missing documents, updates changed documents, and physically deletes redundant test documents (`DELETE /api/v1/knowledge/articles/:id`) to prevent stale background knowledge from distorting audit simulation.
- Safe scenario fallback: automatically defaults empty `scenarios` to `["audit"]`, preventing backend 400 validation failures.
- Added `deleteApprovalDocument` in Seal API, exported `seal_approval_delete_document` in MCP tools, and updated OpenAPI schema.
- Added `documentsPlan` to `--dry-run` output and structured `documents` execution summary.
- **Semantic Sync Versioning with Target Test Version Visibility**:
- Enhanced published version name format to `Sync from <ProdCorpName> [Prod v<ProdVersion> · #<Iteration> -> Test v<TestVersion>]`.
- Solves the Seal Web UI limitation where custom version names omit the assigned test version number.
- Backward-compatible regex parsing in `computeNextSyncIteration` handles legacy un-numbered, bracketed, and arrow-mapped formats.
- **Cross-Tenant Rule Mapping & Inspection**:
- Tracks bidirectional rule relationships (`versionMapping` and `ruleMapping`) between production source IDs/Codes and test target Codes/IDs.
- Automatically saves lightweight mapping snapshots to `~/.config/seal-use/mappings/<testCorpId>-v<versionNumber>.json`.
- Added `seal-use rules map [--corp <corpId>] [--code <ruleCode>]` command for easy querying and filtering of mapped rule origins.
- **Approval Style Preferences HTTP Method Alignment**:
- Aligned approval style preferences endpoint updates to use `POST` (`api/v1/agent/ai-approval/config`) matching Seal backend contract.
- **Local Dev Binary Override & Git-Aware Versioning**:
- Added `bun run dev:override` to compile host binaries with Git dev version metadata, macOS code sign, atomically override `/opt/homebrew/bin/seal-use`, and sync agent skills.
- CLI version output reports active channel (`dev` vs `release`), commits ahead, dirty state, and commit hash.
## [0.10.15] - 2026-09-11
### Added & Enhanced
- **Contextual & Subcommand-Scoped CLI Help System**:
- Implemented structured help registry in `src/cli/help.ts` supporting hierarchical command lookups.
- Subcommands (e.g. `seal-use corps bind-test --help`) now show only targeted usage, options, and descriptions instead of dumping all 120+ top-level commands across unrelated domains.
- Domains (e.g. `seal-use corps --help`) now show only relevant domain commands.
- Eliminates context window pollution for AI agent harnesses and human operators while preserving backwards-compatible global `help`.
- **Production to Test Enterprise Association & Staging Rule Sync**:
- Added `seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]` establishing a strict 1-to-1 association.
- Added anti-chaining validation preventing test enterprises from being nested or looped as production parents.
- Added `seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]` to synchronize production draft rules and decision preferences to the bound test enterprise.
- Automatically publishes a new rule version on the test enterprise while guaranteeing production rules remain safely in draft state.
- Added `seal-use corps unbind-test [<corpId>] [--confirm]` and `corps mark <corpId> --env <production|test> [--confirm]`.
- **Configuration Directory Normalization & Migration**:
- Automatically syncs legacy enterprise configs (`~/.config/seal-home/enterprises`) into primary directory (`~/.config/seal-use/enterprises`).
- Restricts runtime enterprise loading strictly to the primary directory once present, preventing stale legacy reads.
- Safely deletes the legacy directory when all files are synchronized and unmodified for more than 7 days.
- **Release Pipeline & Exit Code Standardization**:
- Fixed Gitea release asset fallback when artifact quota is full.
- Standardized unknown command and subcommand error classifications to exit code 2.
## [0.10.14] - 2026-09-11
### Added
- **Material Pack Webhook Attachment File Policy**:
- Added per-Webhook minimum file size (default 500 bytes), optional maximum file size, and configurable file-extension whitelist.
- Added unified configuration fields for creating and updating Webhook policies.
- Enforced the policy before attachment upload and document push, with detailed validation errors and no partial push on failure.
- Added default support for common PDF, Office, text, email, and image formats.
- **Unified CLI coverage for staging frontend capabilities**:
- Added read-only contacts queries for department trees, department details, department users, and last synchronization time.
- Added `analytics insight` for risk-tag statistics with date-range filtering and current-month defaults.
- Added paginated `data expenses` and `data invoices` queries with frontend-compatible filters.
- Added `simulation approval-definitions` to discover Feishu approval codes before creating a test batch.
### Fixed & Enhanced
- Added non-blocking simulation status checks and `simulation create --no-wait`.
- Added semantic CLI exit codes and actionable next-command guidance.
- Added universal `--dry-run` previews for supported configuration and destructive operations.
- Changed approval-rule pushes to apply incrementally while preserving existing rule IDs.
- Preserved HTTP error response bodies for actionable upstream diagnostics.
- Documented draft versus published rule code spaces and knowledge-document creation constraints.
## [0.10.13] - 2026-09-08
### Fixed & Enhanced
- **Material Pack Scope Isolation & Strict Path Uniqueness**:
- Enforced per-document directory scope isolation: all attachments declared for a document must strictly reside in its own folder (`<documentId>/` or `<documentId>@annotation/`), preventing cross-document file borrowing or path confusion.
- Enforced global declaration uniqueness: identical attachment file paths can no longer be declared more than once across the entire material pack (even within the same document or different line-items). Multiple uses require placing distinct physical files in independent paths.
- Added comprehensive unit tests covering cross-document directory violations, intra-document duplicate paths, and multi-document path collisions.
- Updated documentation in `cli.md` detailing the strict scope isolation and declaration uniqueness rules.
## [0.10.12] - 2026-09-07
### Added & Refactored
- **Material Pack Pure Path Declaration & Validation Refactor**:
- Replaced ambiguous filename heuristics with explicit `[附件]` Excel column headers and full ZIP-relative file paths.
- Added `@` annotation suffix support for ZIP root directories (`<documentId>@annotation/`) to bypass document idempotency blocks safely.
- Enforced bidirectional validation between Excel declarations and ZIP entries without fail-fast, collecting all errors together.
- Added automatic key collision deduplication with numeric suffixes (`-2`, `-3`).
## [0.10.11] - 2026-09-07
### Added & Enhanced
- **Standard Approval Runs Excel Export**:
- Added `seal-use approval-runs export` command to export tenant approval records into high-fidelity Excel workbooks with frozen headers, dynamic rule columns, and color-coded status badges.
- Automatically resolves document template names, manual approval statuses (`APPROVED`, `TERMINATED`, `PROCESSING`), and human reviewer reject comments from `manualApprovalRecord`.
- Dynamically fetches tenant active approval rules (`api.listApprovalRules`) and appends rule check results (`PASS`, `FAIL`, `TRIGGERED`) as individual column badges.
- Added `--downloads` flag to conveniently output directly to the user's `~/Downloads` folder.
- Added `seal_approval_runs_export` tool in MCP/agent tools for automated reporting and data inspection.
- Supports `--start`, `--end`, `--limit`, `--status`, `--manual-status`, and `--completed-only` filters with gentle pagination and progress reporting to `stderr`.
## [0.10.10] - 2026-09-07
### Changed & Fixed
- **Enterprise Config Resolution Isolation**:
- Removed default loading of `./enterprises` from the current working directory (`cwd`), ensuring local repo files never unintentionally leak or override user enterprise configs.
- Candidate enterprise directories now strictly default to user global configuration directories (`~/.config/seal-use/enterprises`, `~/.config/seal-home/enterprises`) unless an explicit environment variable or test directory is configured.
- **Global Test Enterprises Directory Configuration**:
- Added `testEnterprisesDir` field to `GlobalConfigSchema`.
- Added `seal-use config test-dir [<path>|--clear]` command to safely configure or clear a dedicated test enterprise directory without impacting normal user operations.
- Included `testEnterprisesDir` in global configuration summaries and candidate directory listings.
## [0.10.9] - 2026-09-04
### Refactored & Purged
- **MCP Legacy Code Purge & Strict CLI-First Architecture**:
- Removed obsolete intermediate MCP definitions (`sealMcpTools`, `mcpDirectToolNames`, `sealActionNames`, `sealActionAliases`, `runSealAction`, `sealActionHelp`, `findSealMcpTool`) from `src/domains/seal/tools.ts`.
- Removed mistakenly registered `seal_approval_run_attachments_download` tool definition and aliases from `tools.ts`.
- Decoupled `seal-use approval-runs attachments` (inspection & download) CLI commands to invoke pure domain functions in `src/domains/seal/attachments.ts` directly, bypassing the legacy tool runner.
- Purged obsolete "Fine-Grained Tools" lists from `README.md` and `skills/seal-use/references/cli.md`, reinforcing the CLI-First contract where agents execute `seal-use <command>` directly or via the single `seal_cli` MCP tool.
- **Repository-Wide Dead Code & Unused Export Cleanup**:
- Eliminated duplicate enterprise directory export aliases in `src/core/config/loader.ts`.
- Converted internal helpers in `src/core/embedded-skill.ts`, `src/cli/printer.ts`, `src/cli/commands/auth.ts`, `src/domains/seal/linter/loader.ts`, `src/domains/seal/material-pack/validate.ts`, and `src/core/auth/seal.ts` to private module functions.
## [0.10.8] - 2026-09-04
### Added & Enhanced
@@ -13,7 +135,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Extracted comprehensive metadata including `ossSignedUrl`, `token` (automatically parsing embedded `fileId` and object `key`), `ossFileSize`, `mimeType`, and preserved parent field labels as `sourceField`.
- Added `hasSignedUrl` and `ossFileSize` to compact summary outputs without exposing raw signed URLs.
- **New Attachments Download Command (Issue #35)**:
- Added `seal-use approval-runs attachments download <recordId> [--name <pattern>] [--all] [--out-dir <path>]` and the corresponding tool `seal_approval_run_attachments_download` (aliased as `runs.attachments.download`).
- Added `seal-use approval-runs attachments download <recordId> [--name <pattern>] [--all] [--out-dir <path>]` CLI command.
- Prioritizes direct `ossSignedUrl` links from the run record and verifies downloaded file size against `ossFileSize`.
- Automatically sanitizes sensitive temporary signatures in CLI logging (`?[MASKED]`) to prevent credential leakage in build/agent transcripts.
- Implemented graceful error recovery for expired temporary URLs (HTTP 403) or missing links, reporting diagnostics for failed items while allowing valid attachments to complete without interruption.
+12 -22
View File
@@ -257,30 +257,20 @@ The MCP server advertises exactly one tool, `seal_cli`:
It runs the same CLI dispatcher as the global binary, so read operations, write operations, `config`, `service`, and `update` remain available. Write-operation confirmations and explicit enterprise-ID rules continue to be defined by this skill.
## CLI Tools
## CLI-First Architecture
These tools remain available to the CLI:
All Agent and automation capabilities are accessed through standard `seal-use <command>` CLI invocations (or through the single `seal_cli` MCP tool passing the command string). Internal domain services output pure, parseable JSON on `stdout`, with human diagnostics and suggestions routed to `stderr`.
- `seal_source_config`: resolve current Seal enterprise config from the configured source.
- `seal_approval_runs_search`: search approval run history and optional bridge rows.
- `seal_session_get`: current Seal Bearer session and expiration.
- `seal_approval_rules_list`: current draft approval rules. Use `{"countOnly":true}` or `{"fields":["id"],"limit":0}` to return only `{"count":...}`; use `fields` for lightweight projections when rule descriptions are not needed.
- `seal_approval_rule_create`, `seal_approval_rule_update`, `seal_approval_rule_delete`: maintain approval rules.
- `seal_approval_rule_versions_list`, `seal_approval_rule_version_publish`: read and publish rule versions.
- `seal_approval_rule_get`: fetch one rule from a published version by `versionNumber` plus `code` such as `#0038`, or by `recordId` plus `runtimeId` such as `rule-205`.
- `seal_approval_documents_list`, `seal_approval_document_get`, `seal_approval_document_create`, `seal_approval_document_update`: maintain approval documents.
- `seal_approval_style_preferences_get`, `seal_approval_style_preferences_update`: read and update approval style preferences.
- `seal_approval_runs_summary`: summarize approval runs by local date and timezone. Use this for daily questions such as "what approval records did Tawen have today"; it returns status/task-mode counts and compact records.
- `seal_approval_run_get`: fetch one approval run. Pass `summary:true` or `fields` such as `"metadata"` or `"document.fields,result.summary"` to avoid returning full document, pipeline, and AI output payloads.
- `seal_approval_run_pick`: locate likely approval run records by document number, batch, latest flag, and optional field projection.
- `seal_approval_run_cited_rules_get`: extract rules cited or matched by the AI result, including runtime ID/code, version, scope, strictness, analysis, result, and findings when present.
- `seal_approval_run_document_summary_get`: return key document fields, invoice/attachment summary, AI result, and manual result.
- `seal_approval_run_attachments_get`: return attachment and invoice file metadata for one run without the full document or rule result; use `summary:true` for the smallest list.
- `seal_approval_run_attachments_download`: download attachments from an approval run to local disk; supports `--all`, `--name`, and `--out-dir`, prioritizes `ossSignedUrl`, validates `ossFileSize`, and masks credentials in logs.
- `seal_approval_run_result_get`: return one run result, with `{"summary":true}` for decision, summary, risk point count, matched rule count, trace ID, and record ID only.
- `seal_approval_run_url_get`: return the Hose enterprise assist URL, optionally with the original document URL for an approval run by `recordId`, `sourceDocumentSN`, or `sourceDocumentId`.
- `seal_simulation_batch_records_get`: read records from one simulation batch via `api/v1/simulation/batch/{batchId}/records`.
- `seal_approval_run_langfuse_bridge_get`: resolve approval run records to Langfuse lookup hints. It prefers `sourceExtendData._langfuseTraceId`; if that is missing, it returns `hosecloud-{sourceDocumentSN}` as the session fallback.
Key CLI command groups:
- **`seal-use corps ...`**: enterprise tenant management, onboarding, switching, and assistance link intake.
- **`seal-use auth ...`**: authentication diagnostics and Hose provisional authorization links.
- **`seal-use rules ...`**: rule listing, workspace pull/push, offline linting, version publishing, and clearing.
- **`seal-use approval-runs ...`**: run history search, summary by date, detail extraction, attachment inspection & download, cited rules, and Langfuse trace bridge.
- **`seal-use simulation ...`**: test simulation batch creation, polling wait, specifications, and cleanup.
- **`seal-use deploy ...`**: HoseCloud review node requirement inspection, status check, configuration, and sync.
- **`seal-use preference ...`**: decision preferences and thinking depth policies.
- **`seal-use webhook ...`**: webhook integration CRUD and material pack testing.
- **`seal-use service ...`**: persistent daemon service management with embedded HTTP server.
For rule list commands, prefer `seal-use rules count --corp <corpId>` or `seal-use rules list --corp <corpId> --summary` before requesting full rule descriptions. `seal-use rules list` protects large outputs and asks for `--summary`, `--count`, or explicit `--full` when the response would be too large.
+247 -193
View File
@@ -1,102 +1,97 @@
import{createRequire as OD0}from"node:module";var wD0=Object.create;var{getPrototypeOf:zD0,defineProperty:hO,getOwnPropertyNames:GD0}=Object;var HD0=Object.prototype.hasOwnProperty;function VD0($){return this[$]}var WD0,ZD0,RY=($,I,q)=>{var U=$!=null&&typeof $==="object";if(U){var Y=I?WD0??=new WeakMap:ZD0??=new WeakMap,J=Y.get($);if(J)return J}q=$!=null?wD0(zD0($)):{};let Q=I||!$||!$.__esModule?hO(q,"default",{value:$,enumerable:!0}):q;for(let K of GD0($))if(!HD0.call(Q,K))hO(Q,K,{get:VD0.bind($,K),enumerable:!0});if(U)Y.set($,Q);return Q};var L=($,I)=>()=>(I||$((I={exports:{}}).exports,I),I.exports);var XD0=($)=>$;function DD0($,I){this[$]=XD0.bind(null,I)}var m8=($,I)=>{for(var q in I)hO($,q,{get:I[q],enumerable:!0,configurable:!0,set:DD0.bind(I,q)})};var o=OD0(import.meta.url);var vJ=L((cf)=>{Object.defineProperty(cf,"__esModule",{value:!0});cf.regexpCode=cf.getEsmExportName=cf.getProperty=cf.safeStringify=cf.stringify=cf.strConcat=cf.addCodeArg=cf.str=cf._=cf.nil=cf._Code=cf.Name=cf.IDENTIFIER=cf._CodeOrName=void 0;class hG{}cf._CodeOrName=hG;cf.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class pI extends hG{constructor($){super();if(!cf.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}cf.Name=pI;class x$ extends hG{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((I,q)=>`${I}${q}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((I,q)=>{if(q instanceof pI)I[q.str]=(I[q.str]||0)+1;return I},{})}}cf._Code=x$;cf.nil=new x$("");function bf($,...I){let q=[$[0]],U=0;while(U<I.length)lg(q,I[U]),q.push($[++U]);return new x$(q)}cf._=bf;var dg=new x$("+");function pf($,...I){let q=[BJ($[0])],U=0;while(U<I.length)q.push(dg),lg(q,I[U]),q.push(dg,BJ($[++U]));return kF0(q),new x$(q)}cf.str=pf;function lg($,I){if(I instanceof x$)$.push(...I._items);else if(I instanceof pI)$.push(I);else $.push(iF0(I))}cf.addCodeArg=lg;function kF0($){let I=1;while(I<$.length-1){if($[I]===dg){let q=fF0($[I-1],$[I+1]);if(q!==void 0){$.splice(I-1,3,q);continue}$[I++]="+"}I++}}function fF0($,I){if(I==='""')return $;if($==='""')return I;if(typeof $=="string"){if(I instanceof pI||$[$.length-1]!=='"')return;if(typeof I!="string")return`${$.slice(0,-1)}${I}"`;if(I[0]==='"')return $.slice(0,-1)+I.slice(1);return}if(typeof I=="string"&&I[0]==='"'&&!($ instanceof pI))return`"${$}${I.slice(1)}`;return}function nF0($,I){return I.emptyStr()?$:$.emptyStr()?I:pf`${$}${I}`}cf.strConcat=nF0;function iF0($){return typeof $=="number"||typeof $=="boolean"||$===null?$:BJ(Array.isArray($)?$.join(","):$)}function bF0($){return new x$(BJ($))}cf.stringify=bF0;function BJ($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}cf.safeStringify=BJ;function pF0($){return typeof $=="string"&&cf.IDENTIFIER.test($)?new x$(`.${$}`):bf`[${$}]`}cf.getProperty=pF0;function cF0($){if(typeof $=="string"&&cf.IDENTIFIER.test($))return new x$(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}cf.getEsmExportName=cF0;function dF0($){return new x$($.toString())}cf.regexpCode=dF0});var tg=L((of)=>{Object.defineProperty(of,"__esModule",{value:!0});of.ValueScope=of.ValueScopeName=of.Scope=of.varKinds=of.UsedValueState=void 0;var x6=vJ();class lf extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var yG;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(yG||(of.UsedValueState=yG={}));of.varKinds={const:new x6.Name("const"),let:new x6.Name("let"),var:new x6.Name("var")};class og{constructor({prefixes:$,parent:I}={}){this._names={},this._prefixes=$,this._parent=I}toName($){return $ instanceof x6.Name?$:this.name($)}name($){return new x6.Name(this._newName($))}_newName($){let I=this._names[$]||this._nameGroup($);return`${$}${I.index++}`}_nameGroup($){var I,q;if(((q=(I=this._parent)===null||I===void 0?void 0:I._prefixes)===null||q===void 0?void 0:q.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}of.Scope=og;class rg extends x6.Name{constructor($,I){super(I);this.prefix=$}setValue($,{property:I,itemIndex:q}){this.value=$,this.scopePath=x6._`.${new x6.Name(I)}[${q}]`}}of.ValueScopeName=rg;var YM0=x6._`\n`;class mf extends og{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?YM0:x6.nil}}get(){return this._scope}name($){return new rg($,this._newName($))}value($,I){var q;if(I.ref===void 0)throw Error("CodeGen: ref must be passed in value");let U=this.toName($),{prefix:Y}=U,J=(q=I.key)!==null&&q!==void 0?q:I.ref,Q=this._values[Y];if(Q){let z=Q.get(J);if(Line truncated
`:""},this._extScope=$,this._scope=new k$.Scope({parent:$}),this._nodes=[new qn]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,I){let q=this._extScope.value($,I);return(this._values[q.prefix]||(this._values[q.prefix]=new Set)).add(q),q}getScopeValue($,I){return this._extScope.getValue($,I)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,I,q,U){let Y=this._scope.toName(I);if(q!==void 0&&U)this._constants[Y.str]=q;return this._leafNode(new tf($,Y,q)),Y}const($,I,q){return this._def(k$.varKinds.const,$,I,q)}let($,I,q){return this._def(k$.varKinds.let,$,I,q)}var($,I,q){return this._def(k$.varKinds.var,$,I,q)}assign($,I,q){return this._leafNode(new eg($,I,q))}add($,I){return this._leafNode(new af($,k6.operators.ADD,I))}code($){if(typeof $=="function")$();else if($!==U1.nil)this._leafNode(new In($));return this}object(...$){let I=["{"];for(let[q,U]of $){if(I.length>1)I.push(",");if(I.push(q),q!==U||this.opts.es5)I.push(":"),(0,U1.addCodeArg)(I,U)}return I.push("}"),new U1._Code(I)}if($,I,q){if(this._blockNode(new s8($)),I&&q)this.code(I).else().code(q).endIf();else if(I)this.code(I).endIf();else if(q)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new s8($))}else(){return this._elseNode(new RJ)}endIf(){return this._endBlockNode(s8,RJ)}_for($,I){if(this._blockNode($),I)this.code(I).endFor();return this}for($,I){return this._for(new Un($),I)}forRange($,I,q,U,Y=this.opts.es5?k$.varKinds.var:k$.varKinds.let){let J=this._scope.toName($);return this._for(new Yn(Y,J,I,q),()=>U(J))}forOf($,I,q,U=k$.varKinds.const){let Y=this._scope.toName($);if(this.opts.es5){let J=I instanceof U1.Name?I:this.var("_arr",I);return this.forRange("_i",0,U1._`${J}.length`,(Q)=>{this.var(Y,U1._`${J}[${Q}]`),q(Y)})}return this._for(new ag("of",U,Y,I),()=>q(Y))}forIn($,I,q,U=this.opts.es5?k$.varKinds.var:k$.varKinds.const){if(this.opts.ownProperties)return this.forOf($,U1._`Object.keys(${I})`,q);let Y=this._scope.toName($);return this._for(new ag("in",U,Y,I),()=>q(Y))}endFor(){return this._endBlockNode(cI)}label($){return this._leafNode(new sf($))}break($){return this._leafNode(new ef($))}return($){let I=new xG;if(this._blockNode(I),this.code($),I.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(xG)}try($,I,q){if(!I&&!q)throw Error('CodeGen: "try" without "catch" and "finally"');let U=new Jn;if(this._blockNode(U),this.code($),I){let Y=this.name("e");this._currNode=U.catch=new kG(Y),I(Y)}if(q)this._currNode=U.finally=new fG,this.code(q);return this._endBlockNode(kG,fG)}throw($){return this._leafNode(new $n($))}block($,I){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(I);return this}endBlock($){let I=this._blockStarts.pop();if(I===void 0)throw Error("CodeGen: not in self-balancing block");let q=this._nodes.length-I;if(q<0||$!==void 0&&q!==$)throw Error(`CodeGen: wrong number of nodes: ${q} vs ${$} expected`);return this._nodes.length=I,this}func($,I=U1.nil,q,U){if(this._blockNode(new uG($,I,q)),U)this.code(U).endFunc();return this}endFunc(){return this._endBlockNode(uG)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,I){let q=this._currNode;if(q instanceof $||I&&q instanceof I)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${I?`${$.kind}/${I.kind}`:$.kind}"`)}_elseNode($){let I=this._currNode;if(!(I instanceof s8))throw Error('CodeGen: "else" without "if"');return this._currNode=I.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let I=this._nodes;I[I.length-1]=$}}k6.CodeGen=Qn;function v7($,I){for(let q in I)$[q]=($[q]||0)+(I[q]||0);return $}function nG($,I){return I instanceof U1._CodeOrName?v7($,I.names):$}function dI($,I,q){if($ instanceof U1.Name)return U($);if(!Y($))return $;return new U1._Code($._items.reduce((J,Q)=>{if(Q instanceof U1.Name)Q=U(Q);if(Q instanceof U1._Code)J.push(...Q._items);else J.push(Q);return J},[]));function U(J){let Q=q[J.str];if(Q===void 0||I[J.str]!==1)return J;return delete I[J.str],Q}function Y(J){return J instanceof U1._Code&&J._items.some((Q)=>Q instanceof U1.Name&&I[Q.str]===1&&q[Q.str]!==void 0)}}function wM0($,I){for(let q in I)$[q]=($[q]||0)-(I[q]||0)}function Kn($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:U1._`!${sg($)}`}k6.not=Kn;var zM0=wn(k6.operators.AND);function GM0(...$){return $.reduce(zM0)}k6.and=GM0;var HM0=wn(k6.operators.OR);function VM0(...$){return $.reduce(HM0)}k6.or=VM0;function wn($){return(I,q)=>I===U1.nil?q:q===U1.nil?I:U1._`${sg(I)} ${$} ${sg(q)}`}function sg($){return $ instanceof U1.Name?$:U1._`(${Line truncated
|| (${Q} == "string" && ${Y} && ${Y} == +${Y})`).assign(K,d0._`+${Y}`);return;case"integer":U.elseIf(d0._`${Q} === "boolean" || ${Y} === null
|| (${Q} === "string" && ${Y} && ${Y} == +${Y} && !(${Y} % 1))`).assign(K,d0._`+${Y}`);return;case"boolean":U.elseIf(d0._`${Y} === "false" || ${Y} === 0 || ${Y} === null`).assign(K,!1).elseIf(d0._`${Y} === "true" || ${Y} === 1`).assign(K,!0);return;case"null":U.elseIf(d0._`${Y} === "" || ${Y} === 0 || ${Y} === false`),U.assign(K,null);return;case"array":U.elseIf(d0._`${Q} === "string" || ${Q} === "number"
|| ${Q} === "boolean" || ${Y} === null`).assign(K,d0._`[${Y}]`)}}}function TA0({gen:$,parentData:I,parentDataProperty:q},U){$.if(d0._`${I} !== undefined`,()=>$.assign(d0._`${I}[${q}]`,U))}function QP($,I,q,U=lI.Correct){let Y=U===lI.Correct?d0.operators.EQ:d0.operators.NEQ,J;switch($){case"null":return d0._`${I} ${Y} null`;case"array":J=d0._`Array.isArray(${I})`;break;case"object":J=d0._`${I} && typeof ${I} == "object" && !Array.isArray(${I})`;break;case"integer":J=Q(d0._`!(${I} % 1) && !isNaN(${I})`);break;case"number":J=Q();break;default:return d0._`typeof ${I} ${Y} ${$}`}return U===lI.Correct?J:(0,d0.not)(J);function Q(K=d0.nil){return(0,d0.and)(d0._`typeof ${I} == "number"`,K,q?d0._`isFinite(${I})`:d0.nil)}}kn.checkDataType=QP;function KP($,I,q,U){if($.length===1)return QP($[0],I,q,U);let Y,J=(0,yn.toHash)($);if(J.array&&J.object){let Q=d0._`typeof ${I} != "object"`;Y=J.null?Q:d0._`!${I} || ${Q}`,delete J.null,delete J.array,delete J.object}else Y=d0.nil;if(J.number)delete J.integer;for(let Q in J)Y=(0,d0.and)(Y,QP(Q,I,q,U));return Y}kn.checkDataTypes=KP;var EA0={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:I})=>typeof $=="string"?d0._`{type: ${$}}`:d0._`{type: ${I}}`};function wP($){let I=jA0($);(0,FA0.reportError)(I,EA0)}kn.reportTypeError=wP;function jA0($){let{gen:I,data:q,schema:U}=$,Y=(0,yn.schemaRefOrVal)($,U,"type");return{gen:I,keyword:"type",data:q,schema:U.type,schemaCode:Y,schemaValue:Y,parentSchema:U,params:{},it:$}}});var cn=L((bn)=>{Object.defineProperty(bn,"__esModule",{value:!0});bn.assignDefaults=void 0;var mI=m0(),SA0=w1();function yA0($,I){let{properties:q,items:U}=$.schema;if(I==="object"&&q)for(let Y in q)nn($,Y,q[Y].default);else if(I==="array"&&Array.isArray(U))U.forEach((Y,J)=>nn($,J,Y.default))}bn.assignDefaults=yA0;function nn($,I,q){let{gen:U,compositeRule:Y,data:J,opts:Q}=$;if(q===void 0)return;let K=mI._`${J}${(0,mI.getProperty)(I)}`;if(Y){(0,SA0.checkStrictMode)($,`default is ignored for: ${K}`);return}let w=mI._`${K} === undefined`;if(Q.useDefaults==="empty")w=mI._`${w} || ${K} === null || ${K} === ""`;U.if(w,mI._`${K} = ${(0,mI.stringify)(q)}`)}});var O$=L((mn)=>{Object.defineProperty(mn,"__esModule",{value:!0});mn.validateUnion=mn.validateArray=mn.usePattern=mn.callValidateCode=mn.schemaProperties=mn.allSchemaProperties=mn.noPropertyInData=mn.propertyInData=mn.isOwnProperty=mn.hasPropFunc=mn.reportMissingProp=mn.checkMissingProp=mn.checkReportMissingProp=void 0;var l1=m0(),zP=w1(),z9=e8(),uA0=w1();function xA0($,I){let{gen:q,data:U,it:Y}=$;q.if(HP(q,U,I,Y.opts.ownProperties),()=>{$.setParams({missingProperty:l1._`${I}`},!0),$.error()})}mn.checkReportMissingProp=xA0;function kA0({gen:$,data:I,it:{opts:q}},U,Y){return(0,l1.or)(...U.map((J)=>(0,l1.and)(HP($,I,J,q.ownProperties),l1._`${Y} = ${J}`)))}mn.checkMissingProp=kA0;function fA0($,I){$.setParams({missingProperty:I},!0),$.error()}mn.reportMissingProp=fA0;function dn($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:l1._`Object.prototype.hasOwnProperty`})}mn.hasPropFunc=dn;function GP($,I,q){return l1._`${dn($)}.call(${I}, ${q})`}mn.isOwnProperty=GP;function nA0($,I,q,U){let Y=l1._`${I}${(0,l1.getProperty)(q)} !== undefined`;return U?l1._`${Y} && ${GP($,I,q)}`:Y}mn.propertyInData=nA0;function HP($,I,q,U){let Y=l1._`${I}${(0,l1.getProperty)(q)} === undefined`;return U?(0,l1.or)(Y,(0,l1.not)(GP($,I,q))):Y}mn.noPropertyInData=HP;function ln($){return $?Object.keys($).filter((I)=>I!=="__proto__"):[]}mn.allSchemaProperties=ln;function iA0($,I){return ln(I).filter((q)=>!(0,zP.alwaysValidSchema)($,I[q]))}mn.schemaProperties=iA0;function bA0({schemaCode:$,data:I,it:{gen:q,topSchemaRef:U,schemaPath:Y,errorPath:J},it:Q},K,w,z){let G=z?l1._`${$}, ${I}, ${U}${Y}`:I,H=[[z9.default.instancePath,(0,l1.strConcat)(z9.default.instancePath,J)],[z9.default.parentData,Q.parentData],[z9.default.parentDataProperty,Q.parentDataProperty],[z9.default.rootData,z9.default.rootData]];if(Q.opts.dynamicRef)H.push([z9.default.dynamicAnchors,z9.default.dynamicAnchors]);let V=l1._`${G}, ${q.object(...H)}`;return w!==l1.nil?l1._`${K}.call(${w}, ${V})`:l1._`${K}(${V})`}mn.callValidateCode=bA0;var pA0=l1._`new RegExp`;function cA0({gen:$,it:{opts:I}},q){let U=I.unicodeRegExp?"u":"",{regExp:Y}=I.code,J=Y(q,U);return $.scopeValue("pattern",{key:J.toString(),ref:J,code:l1._`${Y.code==="new RegExp"?pA0:(0,uA0.useFunc)($,Y)}(${q}, ${U})`})}mn.usePattern=cA0;function dA0($){let{gen:I,data:q,keyword:U,it:Y}=$,J=I.name("valid");if(Y.allErrors){let K=I.let("valid",!0);return Q(()=>I.assign(K,!1)),K}return I.var(J,!0),Q(()=>I.break()),J;function Q(K){let w=I.const("len",l1._`${q}.length`);I.forRange("i",0,w,(z)=>{$.subschema({keyword:U,dataProp:z,dataPropType:zP.Type.Num},J),I.if((0,l1.not)(J),K)})}}mn.validateArray=dA0;function lA0($){let{gen:I,schema:q,keyword:U,it:Y}=$;if(!Array.isArray(q))throw Error("ajv implementation error");if(q.some((w)=>(0,zP.alwaysValidSchema)(Y,w))&&!Y.opts.unevaluated)return;le Line truncated
missingProperty: ${U},
import{createRequire as EL0}from"node:module";var LL0=Object.create;var{getPrototypeOf:DL0,defineProperty:eD,getOwnPropertyNames:FL0}=Object;var OL0=Object.prototype.hasOwnProperty;function NL0($){return this[$]}var ML0,AL0,OI=($,I,U)=>{var Y=$!=null&&typeof $==="object";if(Y){var J=I?ML0??=new WeakMap:AL0??=new WeakMap,Q=J.get($);if(Q)return Q}U=$!=null?LL0(DL0($)):{};let K=I||!$||!$.__esModule?eD(U,"default",{value:$,enumerable:!0}):U;for(let q of FL0($))if(!OL0.call(K,q))eD(K,q,{get:NL0.bind($,q),enumerable:!0});if(Y)J.set($,K);return K};var F=($,I)=>()=>(I||$((I={exports:{}}).exports,I),I.exports);var PL0=($)=>$;function TL0($,I){this[$]=PL0.bind(null,I)}var e8=($,I)=>{for(var U in I)eD($,U,{get:I[U],enumerable:!0,configurable:!0,set:TL0.bind(I,U)})};var a=EL0(import.meta.url);var fQ=F((Hi)=>{Object.defineProperty(Hi,"__esModule",{value:!0});Hi.regexpCode=Hi.getEsmExportName=Hi.getProperty=Hi.safeStringify=Hi.stringify=Hi.strConcat=Hi.addCodeArg=Hi.str=Hi._=Hi.nil=Hi._Code=Hi.Name=Hi.IDENTIFIER=Hi._CodeOrName=void 0;class iW{}Hi._CodeOrName=iW;Hi.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class YU extends iW{constructor($){super();if(!Hi.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}Hi.Name=YU;class c$ extends iW{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((I,U)=>`${I}${U}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((I,U)=>{if(U instanceof YU)I[U.str]=(I[U.str]||0)+1;return I},{})}}Hi._Code=c$;Hi.nil=new c$("");function Ki($,...I){let U=[$[0]],Y=0;while(Y<I.length)VT(U,I[Y]),U.push($[++Y]);return new c$(U)}Hi._=Ki;var wT=new c$("+");function qi($,...I){let U=[kQ($[0])],Y=0;while(Y<I.length)U.push(wT),VT(U,I[Y]),U.push(wT,kQ($[++Y]));return mN0(U),new c$(U)}Hi.str=qi;function VT($,I){if(I instanceof c$)$.push(...I._items);else if(I instanceof YU)$.push(I);else $.push(rN0(I))}Hi.addCodeArg=VT;function mN0($){let I=1;while(I<$.length-1){if($[I]===wT){let U=lN0($[I-1],$[I+1]);if(U!==void 0){$.splice(I-1,3,U);continue}$[I++]="+"}I++}}function lN0($,I){if(I==='""')return $;if($==='""')return I;if(typeof $=="string"){if(I instanceof YU||$[$.length-1]!=='"')return;if(typeof I!="string")return`${$.slice(0,-1)}${I}"`;if(I[0]==='"')return $.slice(0,-1)+I.slice(1);return}if(typeof I=="string"&&I[0]==='"'&&!($ instanceof YU))return`"${$}${I.slice(1)}`;return}function oN0($,I){return I.emptyStr()?$:$.emptyStr()?I:qi`${$}${I}`}Hi.strConcat=oN0;function rN0($){return typeof $=="number"||typeof $=="boolean"||$===null?$:kQ(Array.isArray($)?$.join(","):$)}function tN0($){return new c$(kQ($))}Hi.stringify=tN0;function kQ($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Hi.safeStringify=kQ;function aN0($){return typeof $=="string"&&Hi.IDENTIFIER.test($)?new c$(`.${$}`):Ki`[${$}]`}Hi.getProperty=aN0;function sN0($){if(typeof $=="string"&&Hi.IDENTIFIER.test($))return new c$(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}Hi.getEsmExportName=sN0;function eN0($){return new c$($.toString())}Hi.regexpCode=eN0});var LT=F((Vi)=>{Object.defineProperty(Vi,"__esModule",{value:!0});Vi.ValueScope=Vi.ValueScopeName=Vi.Scope=Vi.varKinds=Vi.UsedValueState=void 0;var c6=fQ();class Wi extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var nW;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(nW||(Vi.UsedValueState=nW={}));Vi.varKinds={const:new c6.Name("const"),let:new c6.Name("let"),var:new c6.Name("var")};class zT{constructor({prefixes:$,parent:I}={}){this._names={},this._prefixes=$,this._parent=I}toName($){return $ instanceof c6.Name?$:this.name($)}name($){return new c6.Name(this._newName($))}_newName($){let I=this._names[$]||this._nameGroup($);return`${$}${I.index++}`}_nameGroup($){var I,U;if(((U=(I=this._parent)===null||I===void 0?void 0:I._prefixes)===null||U===void 0?void 0:U.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}Vi.Scope=zT;class XT extends c6.Name{constructor($,I){super(I);this.prefix=$}setValue($,{property:I,itemIndex:U}){this.value=$,this.scopePath=c6._`.${new c6.Name(I)}[${U}]`}}Vi.ValueScopeName=XT;var VM0=c6._`\n`;class wi extends zT{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?VM0:c6.nil}}get(){return this._scope}name($){return new XT($,this._newName($))}value($,I){var U;if(I.ref===void 0)throw Error("CodeGen: ref must be passed in value");let Y=this.toName($),{prefix:J}=Y,Q=(U=I.key)!==null&&U!==void 0?U:I.ref,K=this._values[J];if(K){let G=K.get(Q);if(Line truncated
`:""},this._extScope=$,this._scope=new d$.Scope({parent:$}),this._nodes=[new Ni]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,I){let U=this._extScope.value($,I);return(this._values[U.prefix]||(this._values[U.prefix]=new Set)).add(U),U}getScopeValue($,I){return this._extScope.getValue($,I)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,I,U,Y){let J=this._scope.toName(I);if(U!==void 0&&Y)this._constants[J.str]=U;return this._leafNode(new zi($,J,U)),J}const($,I,U){return this._def(d$.varKinds.const,$,I,U)}let($,I,U){return this._def(d$.varKinds.let,$,I,U)}var($,I,U){return this._def(d$.varKinds.var,$,I,U)}assign($,I,U){return this._leafNode(new OT($,I,U))}add($,I){return this._leafNode(new Xi($,d6.operators.ADD,I))}code($){if(typeof $=="function")$();else if($!==G1.nil)this._leafNode(new Oi($));return this}object(...$){let I=["{"];for(let[U,Y]of $){if(I.length>1)I.push(",");if(I.push(U),U!==Y||this.opts.es5)I.push(":"),(0,G1.addCodeArg)(I,Y)}return I.push("}"),new G1._Code(I)}if($,I,U){if(this._blockNode(new J5($)),I&&U)this.code(I).else().code(U).endIf();else if(I)this.code(I).endIf();else if(U)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new J5($))}else(){return this._elseNode(new iQ)}endIf(){return this._endBlockNode(J5,iQ)}_for($,I){if(this._blockNode($),I)this.code(I).endFor();return this}for($,I){return this._for(new Mi($),I)}forRange($,I,U,Y,J=this.opts.es5?d$.varKinds.var:d$.varKinds.let){let Q=this._scope.toName($);return this._for(new Ai(J,Q,I,U),()=>Y(Q))}forOf($,I,U,Y=d$.varKinds.const){let J=this._scope.toName($);if(this.opts.es5){let Q=I instanceof G1.Name?I:this.var("_arr",I);return this.forRange("_i",0,G1._`${Q}.length`,(K)=>{this.var(J,G1._`${Q}[${K}]`),U(J)})}return this._for(new DT("of",Y,J,I),()=>U(J))}forIn($,I,U,Y=this.opts.es5?d$.varKinds.var:d$.varKinds.const){if(this.opts.ownProperties)return this.forOf($,G1._`Object.keys(${I})`,U);let J=this._scope.toName($);return this._for(new DT("in",Y,J,I),()=>U(J))}endFor(){return this._endBlockNode(JU)}label($){return this._leafNode(new Li($))}break($){return this._leafNode(new Di($))}return($){let I=new cW;if(this._blockNode(I),this.code($),I.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(cW)}try($,I,U){if(!I&&!U)throw Error('CodeGen: "try" without "catch" and "finally"');let Y=new Pi;if(this._blockNode(Y),this.code($),I){let J=this.name("e");this._currNode=Y.catch=new dW(J),I(J)}if(U)this._currNode=Y.finally=new mW,this.code(U);return this._endBlockNode(dW,mW)}throw($){return this._leafNode(new Fi($))}block($,I){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(I);return this}endBlock($){let I=this._blockStarts.pop();if(I===void 0)throw Error("CodeGen: not in self-balancing block");let U=this._nodes.length-I;if(U<0||$!==void 0&&U!==$)throw Error(`CodeGen: wrong number of nodes: ${U} vs ${$} expected`);return this._nodes.length=I,this}func($,I=G1.nil,U,Y){if(this._blockNode(new pW($,I,U)),Y)this.code(Y).endFunc();return this}endFunc(){return this._endBlockNode(pW)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,I){let U=this._currNode;if(U instanceof $||I&&U instanceof I)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${I?`${$.kind}/${I.kind}`:$.kind}"`)}_elseNode($){let I=this._currNode;if(!(I instanceof J5))throw Error('CodeGen: "else" without "if"');return this._currNode=I.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let I=this._nodes;I[I.length-1]=$}}d6.CodeGen=Ti;function u7($,I){for(let U in I)$[U]=($[U]||0)+(I[U]||0);return $}function lW($,I){return I instanceof G1._CodeOrName?u7($,I.names):$}function QU($,I,U){if($ instanceof G1.Name)return Y($);if(!J($))return $;return new G1._Code($._items.reduce((Q,K)=>{if(K instanceof G1.Name)K=Y(K);if(K instanceof G1._Code)Q.push(...K._items);else Q.push(K);return Q},[]));function Y(Q){let K=U[Q.str];if(K===void 0||I[Q.str]!==1)return Q;return delete I[Q.str],K}function J(Q){return Q instanceof G1._Code&&Q._items.some((K)=>K instanceof G1.Name&&I[K.str]===1&&U[K.str]!==void 0)}}function LM0($,I){for(let U in I)$[U]=($[U]||0)-(I[U]||0)}function Ei($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:G1._`!${FT($)}`}d6.not=Ei;var DM0=Bi(d6.operators.AND);function FM0(...$){return $.reduce(DM0)}d6.and=FM0;var OM0=Bi(d6.operators.OR);function NM0(...$){return $.reduce(OM0)}d6.or=NM0;function Bi($){return(I,U)=>I===G1.nil?U:U===G1.nil?I:G1._`${FT(I)} ${$} ${FT(U)}`}function FT($){return $ instanceof G1.Name?$:G1._`(${Line truncated
|| (${K} == "string" && ${J} && ${J} == +${J})`).assign(q,t0._`+${J}`);return;case"integer":Y.elseIf(t0._`${K} === "boolean" || ${J} === null
|| (${K} === "string" && ${J} && ${J} == +${J} && !(${J} % 1))`).assign(q,t0._`+${J}`);return;case"boolean":Y.elseIf(t0._`${J} === "false" || ${J} === 0 || ${J} === null`).assign(q,!1).elseIf(t0._`${J} === "true" || ${J} === 1`).assign(q,!0);return;case"null":Y.elseIf(t0._`${J} === "" || ${J} === 0 || ${J} === false`),Y.assign(q,null);return;case"array":Y.elseIf(t0._`${K} === "string" || ${K} === "number"
|| ${K} === "boolean" || ${J} === null`).assign(q,t0._`[${J}]`)}}}function gA0({gen:$,parentData:I,parentDataProperty:U},Y){$.if(t0._`${I} !== undefined`,()=>$.assign(t0._`${I}[${U}]`,Y))}function BT($,I,U,Y=KU.Correct){let J=Y===KU.Correct?t0.operators.EQ:t0.operators.NEQ,Q;switch($){case"null":return t0._`${I} ${J} null`;case"array":Q=t0._`Array.isArray(${I})`;break;case"object":Q=t0._`${I} && typeof ${I} == "object" && !Array.isArray(${I})`;break;case"integer":Q=K(t0._`!(${I} % 1) && !isNaN(${I})`);break;case"number":Q=K();break;default:return t0._`typeof ${I} ${J} ${$}`}return Y===KU.Correct?Q:(0,t0.not)(Q);function K(q=t0.nil){return(0,t0.and)(t0._`typeof ${I} == "number"`,q,U?t0._`isFinite(${I})`:t0.nil)}}Ub.checkDataType=BT;function vT($,I,U,Y){if($.length===1)return BT($[0],I,U,Y);let J,Q=(0,ei.toHash)($);if(Q.array&&Q.object){let K=t0._`typeof ${I} != "object"`;J=Q.null?K:t0._`!${I} || ${K}`,delete Q.null,delete Q.array,delete Q.object}else J=t0.nil;if(Q.number)delete Q.integer;for(let K in Q)J=(0,t0.and)(J,BT(K,I,U,Y));return J}Ub.checkDataTypes=vT;var yA0={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:I})=>typeof $=="string"?t0._`{type: ${$}}`:t0._`{type: ${I}}`};function RT($){let I=hA0($);(0,RA0.reportError)(I,yA0)}Ub.reportTypeError=RT;function hA0($){let{gen:I,data:U,schema:Y}=$,J=(0,ei.schemaRefOrVal)($,Y,"type");return{gen:I,keyword:"type",data:U,schema:Y.type,schemaCode:J,schemaValue:J,parentSchema:Y,params:{},it:$}}});var qb=F((Qb)=>{Object.defineProperty(Qb,"__esModule",{value:!0});Qb.assignDefaults=void 0;var qU=a0(),nA0=Z1();function pA0($,I){let{properties:U,items:Y}=$.schema;if(I==="object"&&U)for(let J in U)Jb($,J,U[J].default);else if(I==="array"&&Array.isArray(Y))Y.forEach((J,Q)=>Jb($,Q,J.default))}Qb.assignDefaults=pA0;function Jb($,I,U){let{gen:Y,compositeRule:J,data:Q,opts:K}=$;if(U===void 0)return;let q=qU._`${Q}${(0,qU.getProperty)(I)}`;if(J){(0,nA0.checkStrictMode)($,`default is ignored for: ${q}`);return}let H=qU._`${q} === undefined`;if(K.useDefaults==="empty")H=qU._`${H} || ${q} === null || ${q} === ""`;Y.if(H,qU._`${q} = ${(0,qU.stringify)(U)}`)}});var T$=F((Wb)=>{Object.defineProperty(Wb,"__esModule",{value:!0});Wb.validateUnion=Wb.validateArray=Wb.usePattern=Wb.callValidateCode=Wb.schemaProperties=Wb.allSchemaProperties=Wb.noPropertyInData=Wb.propertyInData=Wb.isOwnProperty=Wb.hasPropFunc=Wb.reportMissingProp=Wb.checkMissingProp=Wb.checkReportMissingProp=void 0;var t1=a0(),CT=Z1(),z9=Q5(),cA0=Z1();function dA0($,I){let{gen:U,data:Y,it:J}=$;U.if(_T(U,Y,I,J.opts.ownProperties),()=>{$.setParams({missingProperty:t1._`${I}`},!0),$.error()})}Wb.checkReportMissingProp=dA0;function mA0({gen:$,data:I,it:{opts:U}},Y,J){return(0,t1.or)(...Y.map((Q)=>(0,t1.and)(_T($,I,Q,U.ownProperties),t1._`${J} = ${Q}`)))}Wb.checkMissingProp=mA0;function lA0($,I){$.setParams({missingProperty:I},!0),$.error()}Wb.reportMissingProp=lA0;function Hb($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:t1._`Object.prototype.hasOwnProperty`})}Wb.hasPropFunc=Hb;function jT($,I,U){return t1._`${Hb($)}.call(${I}, ${U})`}Wb.isOwnProperty=jT;function oA0($,I,U,Y){let J=t1._`${I}${(0,t1.getProperty)(U)} !== undefined`;return Y?t1._`${J} && ${jT($,I,U)}`:J}Wb.propertyInData=oA0;function _T($,I,U,Y){let J=t1._`${I}${(0,t1.getProperty)(U)} === undefined`;return Y?(0,t1.or)(J,(0,t1.not)(jT($,I,U))):J}Wb.noPropertyInData=_T;function Gb($){return $?Object.keys($).filter((I)=>I!=="__proto__"):[]}Wb.allSchemaProperties=Gb;function rA0($,I){return Gb(I).filter((U)=>!(0,CT.alwaysValidSchema)($,I[U]))}Wb.schemaProperties=rA0;function tA0({schemaCode:$,data:I,it:{gen:U,topSchemaRef:Y,schemaPath:J,errorPath:Q},it:K},q,H,G){let W=G?t1._`${$}, ${I}, ${Y}${J}`:I,w=[[z9.default.instancePath,(0,t1.strConcat)(z9.default.instancePath,Q)],[z9.default.parentData,K.parentData],[z9.default.parentDataProperty,K.parentDataProperty],[z9.default.rootData,z9.default.rootData]];if(K.opts.dynamicRef)w.push([z9.default.dynamicAnchors,z9.default.dynamicAnchors]);let V=t1._`${W}, ${U.object(...w)}`;return H!==t1.nil?t1._`${q}.call(${H}, ${V})`:t1._`${q}(${V})`}Wb.callValidateCode=tA0;var aA0=t1._`new RegExp`;function sA0({gen:$,it:{opts:I}},U){let Y=I.unicodeRegExp?"u":"",{regExp:J}=I.code,Q=J(U,Y);return $.scopeValue("pattern",{key:Q.toString(),ref:Q,code:t1._`${J.code==="new RegExp"?aA0:(0,cA0.useFunc)($,J)}(${U}, ${Y})`})}Wb.usePattern=sA0;function eA0($){let{gen:I,data:U,keyword:Y,it:J}=$,Q=I.name("valid");if(J.allErrors){let q=I.let("valid",!0);return K(()=>I.assign(q,!1)),q}return I.var(Q,!0),K(()=>I.break()),Q;function K(q){let H=I.const("len",t1._`${U}.length`);I.forRange("i",0,H,(G)=>{$.subschema({keyword:Y,dataProp:G,dataPropType:CT.Type.Num},Q),I.if((0,t1.not)(Q),q)})}}Wb.validateArray=eA0;function $P0($){let{gen:I,schema:U,keyword:Y,it:J}=$;if(!Array.isArray(U))throw Error("ajv implementation error");if(U.some((H)=>(0,CT.alwaysValidSchema)(J,H))&&!J.opts.unevaluated)return;le Line truncated
missingProperty: ${Y},
depsCount: ${I},
deps: ${q}}`};var Hj0={keyword:"dependencies",type:"object",schemaType:"object",error:Gp.error,code($){let[I,q]=Vj0($);wp($,I),zp($,q)}};function Vj0({schema:$}){let I={},q={};for(let U in $){if(U==="__proto__")continue;let Y=Array.isArray($[U])?I:q;Y[U]=$[U]}return[I,q]}function wp($,I=$.schema){let{gen:q,data:U,it:Y}=$;if(Object.keys(I).length===0)return;let J=q.let("missing");for(let Q in I){let K=I[Q];if(K.length===0)continue;let w=(0,oJ.propertyInData)(q,U,Q,Y.opts.ownProperties);if($.setParams({property:Q,depsCount:K.length,deps:K.join(", ")}),Y.allErrors)q.if(w,()=>{for(let z of K)(0,oJ.checkReportMissingProp)($,z)});else q.if(SP._`${w} && (${(0,oJ.checkMissingProp)($,K,J)})`),(0,oJ.reportMissingProp)($,J),q.else()}}Gp.validatePropertyDeps=wp;function zp($,I=$.schema){let{gen:q,data:U,keyword:Y,it:J}=$,Q=q.name("valid");for(let K in I){if((0,Gj0.alwaysValidSchema)(J,I[K]))continue;q.if((0,oJ.propertyInData)(q,U,K,J.opts.ownProperties),()=>{let w=$.subschema({keyword:Y,schemaProp:K},Q);$.mergeValidEvaluated(w,Q)},()=>q.var(Q,!0)),$.ok(Q)}}Gp.validateSchemaDeps=zp;Gp.default=Hj0});var Dp=L((Xp)=>{Object.defineProperty(Xp,"__esModule",{value:!0});var Zp=m0(),Xj0=w1(),Dj0={message:"property name must be valid",params:({params:$})=>Zp._`{propertyName: ${$.propertyName}}`},Oj0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Dj0,code($){let{gen:I,schema:q,data:U,it:Y}=$;if((0,Xj0.alwaysValidSchema)(Y,q))return;let J=I.name("valid");I.forIn("key",U,(Q)=>{$.setParams({propertyName:Q}),$.subschema({keyword:"propertyNames",data:Q,dataTypes:["string"],propertyName:Q,compositeRule:!0},J),I.if((0,Zp.not)(J),()=>{if($.error(!0),!Y.allErrors)I.break()})}),$.ok(J)}};Xp.default=Oj0});var yP=L((Op)=>{Object.defineProperty(Op,"__esModule",{value:!0});var wH=O$(),i$=m0(),Nj0=e8(),zH=w1(),Fj0={message:"must NOT have additional properties",params:({params:$})=>i$._`{additionalProperty: ${$.additionalProperty}}`},Mj0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Fj0,code($){let{gen:I,schema:q,parentSchema:U,data:Y,errsCount:J,it:Q}=$;if(!J)throw Error("ajv implementation error");let{allErrors:K,opts:w}=Q;if(Q.props=!0,w.removeAdditional!=="all"&&(0,zH.alwaysValidSchema)(Q,q))return;let z=(0,wH.allSchemaProperties)(U.properties),G=(0,wH.allSchemaProperties)(U.patternProperties);H(),$.ok(i$._`${J} === ${Nj0.default.errors}`);function H(){I.forIn("key",Y,(O)=>{if(!z.length&&!G.length)X(O);else I.if(V(O),()=>X(O))})}function V(O){let N;if(z.length>8){let T=(0,zH.schemaRefOrVal)(Q,U.properties,"properties");N=(0,wH.isOwnProperty)(I,T,O)}else if(z.length)N=(0,i$.or)(...z.map((T)=>i$._`${O} === ${T}`));else N=i$.nil;if(G.length)N=(0,i$.or)(N,...G.map((T)=>i$._`${(0,wH.usePattern)($,T)}.test(${O})`));return(0,i$.not)(N)}function W(O){I.code(i$._`delete ${Y}[${O}]`)}function X(O){if(w.removeAdditional==="all"||w.removeAdditional&&q===!1){W(O);return}if(q===!1){if($.setParams({additionalProperty:O}),$.error(),!K)I.break();return}if(typeof q=="object"&&!(0,zH.alwaysValidSchema)(Q,q)){let N=I.name("valid");if(w.removeAdditional==="failing")D(O,N,!1),I.if((0,i$.not)(N),()=>{$.reset(),W(O)});else if(D(O,N),!K)I.if((0,i$.not)(N),()=>I.break())}}function D(O,N,T){let P={keyword:"additionalProperties",dataProp:O,dataPropType:zH.Type.Str};if(T===!1)Object.assign(P,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(P,N)}}};Op.default=Mj0});var Mp=L((Fp)=>{Object.defineProperty(Fp,"__esModule",{value:!0});var gj0=uJ(),Lp=O$(),uP=w1(),Np=yP(),Pj0={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:I,schema:q,parentSchema:U,data:Y,it:J}=$;if(J.opts.removeAdditional==="all"&&U.additionalProperties===void 0)Np.default.code(new gj0.KeywordCxt(J,Np.default,"additionalProperties"));let Q=(0,Lp.allSchemaProperties)(q);for(let H of Q)J.definedProperties.add(H);if(J.opts.unevaluated&&Q.length&&J.props!==!0)J.props=uP.mergeEvaluated.props(I,(0,uP.toHash)(Q),J.props);let K=Q.filter((H)=>!(0,uP.alwaysValidSchema)(J,q[H]));if(K.length===0)return;let w=I.name("valid");for(let H of K){if(z(H))G(H);else{if(I.if((0,Lp.propertyInData)(I,Y,H,J.opts.ownProperties)),G(H),!J.allErrors)I.else().var(w,!0);I.endIf()}$.it.definedProperties.add(H),$.ok(w)}function z(H){return J.opts.useDefaults&&!J.compositeRule&&q[H].default!==void 0}function G(H){$.subschema({keyword:"properties",schemaProp:H,dataProp:H},w)}}};Fp.default=Pj0});var Ep=L((Tp)=>{Object.defineProperty(Tp,"__esModule",{value:!0});var Ap=O$(),GH=m0(),gp=w1(),Pp=w1(),Ej0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:I,schema:q,data:U,parentSchema:Y,it:J}=$,{opts:Q}=J,K=(0,Ap.allSchemaProperties)(q),w=K.filter((D)=>(0,gp.alwaysValidSchema)(J,q[D]));if(K.length===0||w.length===K.length&&(!J.opts.unevaluated||J.props===!0))return;let z=Q.strictSchema&&!Q.allowMatchingProperties&&Y.properties,G=I.name("valid");if(J.props!==!0&&!(J.props instanceo Line truncated
\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�`},ibm864:"cp864",csibm864:"cp864",cp865:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm865:"cp865",csibm865:"cp865",cp866:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "},ibm866:"cp866",csibm866:"cp866",cp869:{type:"_sbcs",chars:"������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ "},ibm869:"cp869",csibm869:"cp869",cp922:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"},ibm922:"cp922",csibm922:"cp922",cp1046:{type:"_sbcs",chars:"ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"},ibm1046:"cp1046",csibm1046:"cp1046",cp1124:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"},ibm1124:"cp1124",csibm1124:"cp1124",cp1125:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "},ibm1125:"cp1125",csibm1125:"cp1125",cp1129:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},ibm1129:"cp1129",csibm1129:"cp1129",cp1133:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"},ibm1133:"cp1133",csibm1133:"cp1133",cp1161:{type:"_sbcs",chars:"��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "},ibm1161:"cp1161",csibm1161:"cp1161",cp1162:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"},ibm1162:"cp1162",csibm1162:"cp1162",cp1163:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},ibm1163:"cp1163",csiLine truncated
\v\f\r\x0E\x0F\x10ỨỰỲỶỸÝỴ\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ`},georgianacademy:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},georgianps:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},pt154:{type:"_sbcs",chars:"ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"},viscii:{type:"_sbcs",chars:`\x00\x01Ẳ\x03\x04ẴẪ\x07\b
\v\f\r\x0E\x0F\x10\x11\x12\x13Ỷ\x15\x16\x17\x18Ỹ\x1A\x1B\x1C\x1DỴ\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ`},iso646cn:{type:"_sbcs",chars:`\x00\x01\x02\x03\x04\x05\x06\x07\b
\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������`},iso646jp:{type:"_sbcs",chars:`\x00\x01\x02\x03\x04\x05\x06\x07\b
\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_\`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������`},hproman8:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¾—¼½ªº«■»±�"},macintosh:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"},ascii:{type:"_sbcs",chars:"��������������������������������������������������������������������������������������������������������������������������������"},tis620:{type:"_sbcs",chars:"���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"}}});var hm=L((Q_0)=>{var jE=Q5().Buffer;Q_0._dbcs=w5;var a4=-1,_m=-2,A$=-10,j6=-1000,Aq=Array(256),DQ=-1;for(XQ=0;XQ<256;XQ++)Aq[XQ]=a4;var XQ;function w5($,I){if(this.encodingName=$.encodingName,!$)throw Error("DBCS codec is called without the data.");if(!$.table)throw Error("Encoding '"+this.encodingName+"' has no data.");var q=$.table();this.decodeTables=[],this.decodeTables[0]=Aq.slice(0),this.decodeTableSeq=[];for(var U=0;U<q.length;U++)this._addDecodeChunk(q[U]);if(typeof $.gb18030==="function"){this.gb18030=$.gb18030();var Y=this.decodeTables.length;this.decodeTables.push(Aq.slice(0));var J=this.decodeTables.length;this.decodeTables.push(Aq.slice(0));var Q=this.decodeTables[0];for(var U=129;U<=254;U++){var K=this.decodeTables[j6-Q[U]];for(var w=48;w<=57;w++){if(K[w]===a4)K[w]=j6-Y;else if(K[w]>j6)throw Error("gb18030 decode tables conflict at byte 2");var z=this.decodeTables[j6-K[w]];for(var G=129;G<=254;G++){if(z[G]===a4)z[G]=j6-J;else if(z[G]===j6-J)continue;else if(z[G]>j6)throw Error("gb18030 decode tables conflict at byte 3");var H=this.decodeTables[j6-z[G]];for(var V=48;V<=57;V++)if(H[V]===a4)H[V]=_m}}}}this.defaultCharUnicode=I.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var W={};if($.encodeSkipVals)for(var U=0;U<$.encodeSkipVals.length;U++){var X=$.encodeSkipVals[U];if(typeof X==="number")W[X]=!0;else for(var w=X.from;w<=X.to;w++)W[w]=!0}if(this._fillEncodeTable(0,0,W),$.encodeAdd){for(var D in $.encodeAdd)if(Object.prototype.hasOwnProperty.call($.encodeAdd,D))this._setEncodeChar(D.charCodeAt(0),$.encodeAdd[D])}if(this.defCharSB=this.encodeTable[0][I.defaultCharSingleByte.charCodeAt(0)],this.defCharSB===a4)this.defCharSB=this.encodeTable[0]["?"];if(this.defCharSB===a4)this.defCharSB=63}w5.prototype.encoder=YV;w5.prototype.decoder=BE;w5.prototype._getDecodeTrieNode=function($){var I=[];for(;$>0;$>>>=8)I.push($&255);if(I.length==0)I.push(0);var q=this.decodeTables[0];for(var U=I.length-1;U>0;U--){var Y=q[I[U]];if(Y==a4)q[I[U]]=j6-this.decodeTables.length,this.decodeTables.push(q=Aq.slice(0));else if(Y<=j6)q=this.decodeTables[j6-Y];else throw Error("Overwrite byte in "+this.encodingName+", addr: "+$.toString(16))}return q};w5.prototype._addDecodeChunk=function($){var I=parseInt($[0],16),q=this._getDecodeTrieNode(I);I=I&255;for(var U=1;U<$.length;U++){var Y=$[U];if(typeof Y==="string")for(var J=0;J<Y.length;){var Q=Y.charCodeAt(J++);if(Q>=55296&&Q<56320){var K=Y.charCodeAt(J++);if(K>=56320&&K<57344)q[I++]=65536+(Q-55296)*1024+(K-56320);else throw Error("Incorrect surrogate pair in "+this.encodingName+" at chunk "+$[0])}else if(Q>4080&&Q<=4095){var w=4095-Q+2,z=[];for(var G=0;G<w;G++)z.push(Y.charCodeAt(J++));q[I++]=A$-this.decodeTableSeq.length,this.decodeTableSeq.push(z)}else q[I++]=Q}else if(typeof Y==="number"){var H=q[I-1]+1;for(var J=0;J<Y;J++)q[I++]=H++}else throw Error("Incorrect type '"+typeof Y+"' given in "+this.encodingName+" at chunk "+$[0])}if(I>255)throw Error("Incorrect chunk in "+this.encodinLine truncated
\x00`,p+=p1(f,2),p+=K.magic,p+=p1(O,2),p+=p1(N,2),p+=p1(h.crc32,4),p+=p1(h.compressedSize,4),p+=p1(h.uncompressedSize,4),p+=p1(z.length,2),p+=p1(T.length,2);var C=YW.LOCAL_FILE_HEADER+p+z+T,n=YW.CENTRAL_FILE_HEADER+p1(t,2)+p+p1(V.length,2)+"\x00\x00\x00\x00"+p1(S,4)+p1(U,4)+z+T+V;return{fileRecord:C,dirRecord:n}},Vf0=function($,I,q,U,Y){var J="",Q=cq.transformTo("string",Y(U));return J=YW.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+p1($,2)+p1($,2)+p1(I,4)+p1(q,4)+p1(Q.length,2)+Q,J},Wf0=function($){var I="";return I=YW.DATA_DESCRIPTOR+p1($.crc32,4)+p1($.compressedSize,4)+p1($.uncompressedSize,4),I};function o$($,I,q,U){dq.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=I,this.zipPlatform=q,this.encodeFileName=U,this.streamFiles=$,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}cq.inherits(o$,dq);o$.prototype.push=function($){var I=$.meta.percent||0,q=this.entriesCount,U=this._sources.length;if(this.accumulate)this.contentBuffer.push($);else this.bytesWritten+=$.data.length,dq.prototype.push.call(this,{data:$.data,meta:{currentFile:this.currentFile,percent:q?(I+100*(q-U-1))/q:100}})};o$.prototype.openedSource=function($){this.currentSourceOffset=this.bytesWritten,this.currentFile=$.file.name;var I=this.streamFiles&&!$.file.dir;if(I){var q=vs($,I,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:q.fileRecord,meta:{percent:0}})}else this.accumulate=!0};o$.prototype.closedSource=function($){this.accumulate=!1;var I=this.streamFiles&&!$.file.dir,q=vs($,I,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(q.dirRecord),I)this.push({data:Wf0($),meta:{percent:100}});else{this.push({data:q.fileRecord,meta:{percent:0}});while(this.contentBuffer.length)this.push(this.contentBuffer.shift())}this.currentFile=null};o$.prototype.flush=function(){var $=this.bytesWritten;for(var I=0;I<this.dirRecords.length;I++)this.push({data:this.dirRecords[I],meta:{percent:100}});var q=this.bytesWritten-$,U=Vf0(this.dirRecords.length,q,$,this.zipComment,this.encodeFileName);this.push({data:U,meta:{percent:100}})};o$.prototype.prepareNextSource=function(){if(this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused)this.previous.pause();else this.previous.resume()};o$.prototype.registerPrevious=function($){this._sources.push($);var I=this;return $.on("data",function(q){I.processChunk(q)}),$.on("end",function(){if(I.closedSource(I.previous.streamInfo),I._sources.length)I.prepareNextSource();else I.end()}),$.on("error",function(q){I.error(q)}),this};o$.prototype.resume=function(){if(!dq.prototype.resume.call(this))return!1;if(!this.previous&&this._sources.length)return this.prepareNextSource(),!0;if(!this.previous&&!this._sources.length&&!this.generatedError)return this.end(),!0};o$.prototype.error=function($){var I=this._sources;if(!dq.prototype.error.call(this,$))return!1;for(var q=0;q<I.length;q++)try{I[q].error($)}catch(U){}return!0};o$.prototype.lock=function(){dq.prototype.lock.call(this);var $=this._sources;for(var I=0;I<$.length;I++)$[I].lock()};Rs.exports=o$});var _s=L((Of0)=>{var Zf0=DB(),Xf0=Cs(),Df0=function($,I){var q=$||I,U=Zf0[q];if(!U)throw Error(q+" is not a valid compression method !");return U};Of0.generateWorker=function($,I,q){var U=new Xf0(I.streamFiles,q,I.platform,I.encodeFileName),Y=0;try{$.forEach(function(J,Q){Y++;var K=Df0(Q.options.compression,I.compression),w=Q.options.compressionOptions||I.compressionOptions||{},z=Q.dir,G=Q.date;Q._compressWorker(K,w).withStreamInfo("file",{name:J,dir:z,date:G,comment:Q.comment||"",unixPermissions:Q.unixPermissions,dosPermissions:Q.dosPermissions}).pipe(U)}),U.entriesCount=Y}catch(J){U.error(J)}return U}});var Ss=L((lg1,hs)=>{var Nf0=z4(),JW=q$();function q2($,I){JW.call(this,"Nodejs stream input adapter for "+$),this._upstreamEnded=!1,this._bindStream(I)}Nf0.inherits(q2,JW);q2.prototype._bindStream=function($){var I=this;this._stream=$,$.pause(),$.on("data",function(q){I.push({data:q,meta:{percent:0}})}).on("error",function(q){if(I.isPaused)this.generatedError=q;else I.error(q)}).on("end",function(){if(I.isPaused)I._upstreamEnded=!0;else I.end()})};q2.prototype.pause=function(){if(!JW.prototype.pause.call(this))return!1;return this._stream.pause(),!0};q2.prototype.resume=function(){if(!JW.prototype.resume.call(this))return!1;if(this._upstreamEnded)this.end();else this._stream.resume();return!0};hs.exports=q2});var cs=L((mg1,ps)=>{var Ff0=Sq(),U2=z4(),ks=q$(),Mf0=Aj(),fs=gj(),ys=nV(),Af0=ut(),gf0=_s(),us=yQ(),Pf0=Ss(),ns=function($,I,q){var U=U2.getTypeOf(I),Y,J=U2.extend(q||{},fs);if(J.date=J.date||new Date,J.compression!==null)J.compression=J.compression.toUpperCase();if(typeof J.unixPermissions==="string")J.unixPermissions=parseInt(J.unixPermissions,8);if(J.unixPermissions&&J.unixPermissions&16384)J.dir=!0;if(J.dosPermissions&&J.dosPermissions&16)J.dir=!0;if(J. Line truncated
`)}openNode($,I){let q=this.tos,U=this._xml;if(q&&this.open)U.push(">");this._stack.push($),U.push("<"),U.push($),$v(U,I),this.leaf=!0,this.open=!0}addAttribute($,I){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(I!==void 0)S00(this._xml,$,I)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");$v(this._xml,$)}writeText($){let I=this._xml;if(this.open)I.push(">"),this.open=!1;this.leaf=!1,I.push(h00.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),I=this._xml;if(this.leaf)I.push("/>");else I.push("</"),I.push($),I.push(">");this.open=!1,this.leaf=!1}leafNode($,I,q){if(this.openNode($,I),q!==void 0)this.writeText(q);this.closeNode()}closeAll(){while(this._stack.length)this.closeNode()}addRollback(){return this._rollbacks.push({xml:this._xml.length,stack:this._stack.length,leaf:this.leaf,open:this.open}),this.cursor}commit(){this._rollbacks.pop()}rollback(){let $=this._rollbacks.pop();if(this._xml.length>$.xml)this._xml.splice($.xml,this._xml.length-$.xml);if(this._stack.length>$.stack)this._stack.splice($.stack,this._stack.length-$.stack);this.leaf=$.leaf,this.open=$.open}get xml(){return this.closeAll(),this._xml.join("")}}Iv.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};y00.exports=Iv});var qv=L((Xb0)=>{var u00=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function Zb0($){if(typeof $==="string")return $;if(u00)return u00.decode($);return $.toString()}Xb0.bufferToString=Zb0});var i00=L((k00)=>{Object.defineProperty(k00,"__esModule",{value:!0});k00.CHAR=`
\r -퟿-�\uD800\uDC00-\uDBFF\uDFFF`;k00.S=` \r
`;k00.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";k00.NAME_CHAR="-"+k00.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";k00.CHAR_RE=new RegExp("^["+k00.CHAR+"]$","u");k00.S_RE=new RegExp("^["+k00.S+"]+$","u");k00.NAME_START_CHAR_RE=new RegExp("^["+k00.NAME_START_CHAR+"]$","u");k00.NAME_CHAR_RE=new RegExp("^["+k00.NAME_CHAR+"]$","u");k00.NAME_RE=new RegExp("^["+k00.NAME_START_CHAR+"]["+k00.NAME_CHAR+"]*$","u");k00.NMTOKEN_RE=new RegExp("^["+k00.NAME_CHAR+"]+$","u");var Uv=9,Yv=10,Jv=13,Qv=32;k00.S_LIST=[Qv,Yv,Jv,Uv];function Ob0($){return $>=Qv&&$<=55295||$===Yv||$===Jv||$===Uv||$>=57344&&$<=65533||$>=65536&&$<=1114111}k00.isChar=Ob0;function Lb0($){return $===Qv||$===Yv||$===Jv||$===Uv}k00.isS=Lb0;function x00($){return $>=65&&$<=90||$>=97&&$<=122||$===58||$===95||$===8204||$===8205||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}k00.isNameStartChar=x00;function Nb0($){return x00($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}k00.isNameChar=Nb0});var a00=L((m00)=>{Object.defineProperty(m00,"__esModule",{value:!0});m00.CHAR="\x01-퟿-�\uD800\uDC00-\uDBFF\uDFFF";m00.RESTRICTED_CHAR="\x01-\b\v\f\x0E-\x1F-„†-Ÿ";m00.S=` \r
`;m00.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";m00.NAME_CHAR="-"+m00.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";m00.CHAR_RE=new RegExp("^["+m00.CHAR+"]$","u");m00.RESTRICTED_CHAR_RE=new RegExp("^["+m00.RESTRICTED_CHAR+"]$","u");m00.S_RE=new RegExp("^["+m00.S+"]+$","u");m00.NAME_START_CHAR_RE=new RegExp("^["+m00.NAME_START_CHAR+"]$","u");m00.NAME_CHAR_RE=new RegExp("^["+m00.NAME_CHAR+"]$","u");m00.NAME_RE=new RegExp("^["+m00.NAME_START_CHAR+"]["+m00.NAME_CHAR+"]*$","u");m00.NMTOKEN_RE=new RegExp("^["+m00.NAME_CHAR+"]+$","u");var b00=9,p00=10,c00=13,d00=32;m00.S_LIST=[d00,p00,c00,b00];function Cb0($){return $>=1&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}m00.isChar=Cb0;function _b0($){return $>=1&&$<=8||$===11||$===12||$>=14&&$<=31||$>=127&&$<=132||$>=134&&$<=159}m00.isRestrictedChar=_b0;function hb0($){return $===9||$===10||$===13||$>31&&$<127||$===133||$>159&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}m00.isCharAndNotRestricted=hb0;function Sb0($){return $===d00||$===p00||$===c00||$===b00}m00.isS=Sb0;function l00($){return $>=65&&$<=90||$>=97&&$<=122||$===58||$===95||$===8204||$===8205||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}m00.isNameStartChar=l00;function yb0($){return l00($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}m00.isNameChar=yb0});var $10=L((e00)=>{Object.defineProperty(e00,"__esModule",{value:!0});e00.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";e00.NC_NAME_CHAR="-"+e00.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";e00.NC_NAME_START_CHAR_RE=new RegExp("^["+e00.NC_NAME_START_CHAR+"]$","u");e00.NC_NAME_CHAR_RE=new RegExp("^["+e00.NC_NAME_CHAR+"]$","u");e00.NC_NAME_RE=new RegExp("^["+e00.NC_NAME_START_CHAR+"]["+e00.NC_NAME_CHAR+"]*$","u");function s00($){return $>=65&&$<=90||$===95||$>=97&&$<=122||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8204&&$<=8205||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}e00.isNCNameStartChar=s00;function tb0($){return s00($)||($===45||$===46||$>=48&&$<=57||$===183||$>=768&&$<=879||$>=8255&&$<=8256)}e00.isNCNameChar=tb0});var A10=L((M10)=>{Object.defineProperty(M10,"__esModule",{value:!0});var qU=i00(),qp0=a00(),Fv=$10(),c6=qU.isS,Up0=qU.isChar,D2=qU.isNameStartChar,I10=qU.isNameChar,X10=qU.S_LIST,Yp0=qU.NAME_RE,Jp0=qp0.isChar,Qp0=Fv.isNCNameStartChar,Kp0=Fv.isNCNameChar,wp0=Fv.NC_NAME_RE,SW="http://www.w3.org/XML/1998/namespace",IU="http://www.w3.org/2000/xmlns/",zp0={__proto__:null,xml:SW,xmlns:IU},Gp0={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},Y4=-1,R8=-2,q10=0,Hp0=1,wv=2,Vp0=3,sq=4,Wp0=5,Zp0=6,Xp0=7,zv=8,Dp0=9,Op0=10,Lp0=11,Np0=12,v6=13,vW=14,Gv=15,Fp0=16,Hv=17,Mp0=18,Ap0=19,Vv=20,gp0=21,Pp0=22,Tp0=23,U10=24,Wv=25,RW=26,Y10=27,Ep0=28,jp0=29,J10=30,Bp0=31,vp0=32,K3=33,Rp0=34,Zv=35,O2=36,Xv=37,Cp0=38,Q10=39,K10=40,_p0=41,w10=42,hp0=43,Sp0=44,Dv=9,t$=10,Ov=13,z10=32,G10=33,D10=34,L2=38,O10=39,CW=45,_W=47,yp0=59,h9=60,eq=61,h4=62,I6=63,L10=91,$U=93,H10=133,V10=8232,hW=($)=>$===D10||$===O10,N10=[D10,O10],up0=[...N10,L10,h4],xp0=[...N10,h9,$U],kp0=[eq,I6,...X10],fp0=[...X10,h4,L2,h9];function Nv($,I,q){switch(I){case"xml":if(q!==SW)$.fail(`xml prefix must be bound to ${SW}.`);break;case"xmlns":if(q!==IU)$.fail(`xmlns prefix must be bound to ${IU}.`);break;default:}switch(q){case IU:$.fail(I===""?`the default namespace may not be set to ${q}.`:`may not assign a prefix (even "xmlns") to the URI ${IU}.`);break;case SW:switch(I){case"xml":break;case"":$.fail(`the default namespace may not be set to ${q}.`);break;default:$.fail("may not assign the xml namespace to another prefix.")}break;default:}}function np0($,I){for(let q of Object.keys(I))Nv($,q,I[q])}var ip0=($)=>wp0.test($),bp0=($)=>Yp0.test($),w3=0,W10=1,Lv=2;M10.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var Z10={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};class F10{constructor($){this.opt=$!==null&&$!==void 0?$:{},this.fragmentOpt=!!this.opt.fragment;let I=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=this.opt.position!==!1,this.fileName=this.opt.fileName,I){this.nameStartCheck=Qp0,this.nameCheck=Kp0,this.isName=ip0,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},zp0);let q=this.opt.additionalNamesp Line truncated
`,I=this.i}}captureToChar($){let{i:I}=this,{chunk:q}=this;while(!0){let U=this.getCode();switch(U){case R8:this.text+=`${q.slice(I,this.prevI)}
`,I=this.i,U=t$;break;case Y4:return this.text+=q.slice(I),!1;default:}if(U===$)return this.text+=q.slice(I,this.prevI),!0}}captureNameChars(){let{chunk:$,i:I}=this;while(!0){let q=this.getCode();if(q===Y4)return this.name+=$.slice(I),Y4;if(!I10(q))return this.name+=$.slice(I,this.prevI),q===R8?t$:q}}skipSpaces(){while(!0){let $=this.getCodeNorm();if($===Y4||!c6($))return $}}setXMLVersion($){if(this.currentXMLVersion=$,$==="1.0")this.isChar=Up0,this.getCode=this.getCode10;else this.isChar=Jp0,this.getCode=this.getCode11}sBegin(){if(this.chunk.charCodeAt(0)===65279)this.i++,this.column++;this.state=Hp0}sBeginWhitespace(){let $=this.i,I=this.skipSpaces();if(this.prevI!==$)this.xmlDeclPossible=!1;switch(I){case h9:if(this.state=Gv,this.text.length!==0)throw Error("no-empty text at start");break;case Y4:break;default:this.unget(),this.state=v6,this.xmlDeclPossible=!1}}sDoctype(){var $;let I=this.captureTo(up0);switch(I){case h4:{($=this.doctypeHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=v6,this.doctype=!0;break}case Y4:break;default:if(this.text+=String.fromCodePoint(I),I===L10)this.state=sq;else if(hW(I))this.state=Vp0,this.q=I}}sDoctypeQuote(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.q=null,this.state=wv}sDTD(){let $=this.captureTo(xp0);if($===Y4)return;if(this.text+=String.fromCodePoint($),$===$U)this.state=wv;else if($===h9)this.state=Zp0;else if(hW($))this.state=Wp0,this.q=$}sDTDQuoted(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.state=sq,this.q=null}sDTDOpenWaka(){let $=this.getCodeNorm();switch(this.text+=String.fromCodePoint($),$){case G10:this.state=Xp0,this.openWakaBang="";break;case I6:this.state=Lp0;break;default:this.state=sq}}sDTDOpenWakaBang(){let $=String.fromCodePoint(this.getCodeNorm()),I=this.openWakaBang+=$;if(this.text+=$,I!=="-")this.state=I==="--"?zv:sq,this.openWakaBang=""}sDTDComment(){if(this.captureToChar(CW))this.text+="-",this.state=Dp0}sDTDCommentEnding(){let $=this.getCodeNorm();this.text+=String.fromCodePoint($),this.state=$===CW?Op0:zv}sDTDCommentEnded(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===h4)this.state=sq;else this.fail("malformed comment."),this.state=zv}sDTDPI(){if(this.captureToChar(I6))this.text+="?",this.state=Np0}sDTDPIEnding(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===h4)this.state=sq}sText(){if(this.tags.length!==0)this.handleTextInRoot();else this.handleTextOutsideRoot()}sEntity(){let{i:$}=this,{chunk:I}=this;$:while(!0)switch(this.getCode()){case R8:this.entity+=`${I.slice($,this.prevI)}
`,$=this.i;break;case yp0:{let{entityReturnState:q}=this,U=this.entity+I.slice($,this.prevI);this.state=q;let Y;if(U==="")this.fail("empty entity name."),Y="&;";else Y=this.parseEntity(U),this.entity="";if(q!==v6||this.textHandler!==void 0)this.text+=Y;break $}case Y4:this.entity+=I.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(D2($))this.state=Rp0,this.unget(),this.xmlDeclPossible=!1;else switch($){case _W:this.state=hp0,this.xmlDeclPossible=!1;break;case G10:this.state=Fp0,this.openWakaBang="",this.xmlDeclPossible=!1;break;case I6:this.state=Tp0;break;default:this.fail("disallowed character in tag name"),this.state=v6,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0;this.state=Vv,this.openWakaBang="";break;case"--":this.state=Hv,this.openWakaBang="";break;case"DOCTYPE":if(this.state=wv,this.doctype||this.sawRoot)this.fail("inappropriately located doctype declaration.");this.openWakaBang="";break;default:if(this.openWakaBang.length>=7)this.fail("incorrect syntax.")}}sComment(){if(this.captureToChar(CW))this.state=Mp0}sCommentEnding(){var $;let I=this.getCodeNorm();if(I===CW)this.state=Ap0,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(I)}`,this.state=Hv}sCommentEnded(){let $=this.getCodeNorm();if($!==h4)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=Hv;else this.state=v6}sCData(){if(this.captureToChar($U))this.state=gp0}sCDataEnding(){let $=this.getCodeNorm();if($===$U)this.state=Pp0;else this.text+=`]${String.fromCodePoint($)}`,this.state=Vv}sCDataEnding2(){var $;let I=this.getCodeNorm();switch(I){case h4:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=v6;break}case $U:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(I)}`,this.state=Vv}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=U10;else if($===I6||c6($))this.fail("processing instruction without a target."),this.state=$===I6?RW:Wv;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=U10}sPIRest(){let{chunk:$,i:I}=this;while(!0){let q=this.getCodeNorm();if(q===Y4){this.piTarget+=$.slice(I);return}if(!this.nameCheck(q)){this.piTarget+=$.slice(I,this.prevI);let U=q===I6;if(U||c6(q))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=U?K3:Y10}else this.state=U?RW:Wv;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(q);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===I6)this.state=RW;else if(!c6($))this.text=String.fromCodePoint($)}else if(this.captureToChar(I6))this.state=RW}sPIEnding(){var $;let I=this.getCodeNorm();if(I===h4){let{piTarget:q}=this;if(q.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:q,body:this.text}),this.piTarget=this.text="",this.state=v6}else if(I===I6)this.text+="?";else this.text+=`?${String.fromCodePoint(I)}`,this.state=Wv;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===I6){this.state=K3;return}if($!==Y4)this.state=Ep0,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(kp0);if($===I6){this.state=K3,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(c6($)||$===eq))return;if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=$===eq?J10:jp0}sXMLDeclEq(){let $=this.getCodeNorm();if($===I6){this.state=K3,this.fail("XML declaration is incomplete.");return}if(c6($))return;if($!==eq)this.fail("value required.");this.state=J10}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===I6){this.state=K3,this.fail("XML declaration is incomplete.");return}if(c6($))return;if(!hW($))this.fail("value must be quoted."),this.q=z10;else this.q=$;this.state=Bp0}sXMLDeclValue(){let $=this.captureTo([this.q,I6]);if($===I6){this.state=K3,this.text="",this.fail("XML declaration is incomplete.");return}if($===Y4)return;let I=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let q=I;if(this.xmlDecl.version=q,!/^1\.[0-9]+$/.test(q))this.fail("ver Line truncated
`;$=this.i,I=w3;break;case Y4:if(U!==void 0)this.text+=q.slice($);break $;default:I=w3}this.forbiddenState=I}handleTextOutsideRoot(){let{i:$}=this,{chunk:I,textHandler:q}=this,U=!1;$:while(!0){let Y=this.getCode();switch(Y){case h9:{if(this.state=Gv,q!==void 0){let{text:J}=this,Q=I.slice($,this.prevI);if(J.length!==0)q(J+Q),this.text="";else if(Q.length!==0)q(Q)}break $}case L2:if(this.state=vW,this.entityReturnState=v6,q!==void 0)this.text+=I.slice($,this.prevI);U=!0;break $;case R8:if(q!==void 0)this.text+=`${I.slice($,this.prevI)}
`;$=this.i;break;case Y4:if(q!==void 0)this.text+=I.slice($);break $;default:if(!c6(Y))U=!0}}if(!U)return;if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0}pushAttribNS($,I){var q;let{prefix:U,local:Y}=this.qname($),J={name:$,prefix:U,local:Y,value:I};if(this.attribList.push(J),(q=this.attributeHandler)===null||q===void 0||q.call(this,J),U==="xmlns"){let Q=I.trim();if(this.currentXMLVersion==="1.0"&&Q==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[Y]=Q,Nv(this,Y,Q)}else if($==="xmlns"){let Q=I.trim();this.topNS[""]=Q,Nv(this,"",Q)}}pushAttribPlain($,I){var q;let U={name:$,value:I};this.attribList.push(U),(q=this.attributeHandler)===null||q===void 0||q.call(this,U)}end(){var $,I;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:q}=this;while(q.length>0){let Y=q.pop();this.fail(`unclosed tag: ${Y.name}`)}if(this.state!==q10&&this.state!==v6)this.fail("unexpected end.");let{text:U}=this;if(U.length!==0)($=this.textHandler)===null||$===void 0||$.call(this,U),this.text="";return this._closed=!0,(I=this.endHandler)===null||I===void 0||I.call(this),this._init(),this}resolve($){var I,q;let U=this.topNS[$];if(U!==void 0)return U;let{tags:Y}=this;for(let J=Y.length-1;J>=0;J--)if(U=Y[J].ns[$],U!==void 0)return U;if(U=this.ns[$],U!==void 0)return U;return(q=(I=this.opt).resolvePrefix)===null||q===void 0?void 0:q.call(I,$)}qname($){let I=$.indexOf(":");if(I===-1)return{prefix:"",local:$};let q=$.slice(I+1),U=$.slice(0,I);if(U===""||q===""||q.includes(":"))this.fail(`malformed name: ${$}.`);return{prefix:U,local:q}}processAttribsNS(){var $;let{attribList:I}=this,q=this.tag;{let{prefix:J,local:Q}=this.qname(q.name);q.prefix=J,q.local=Q;let K=q.uri=($=this.resolve(J))!==null&&$!==void 0?$:"";if(J!==""){if(J==="xmlns")this.fail('tags may not have "xmlns" as prefix.');if(K==="")this.fail(`unbound namespace prefix: ${JSON.stringify(J)}.`),q.uri=J}}if(I.length===0)return;let{attributes:U}=q,Y=new Set;for(let J of I){let{name:Q,prefix:K,local:w}=J,z,G;if(K==="")z=Q==="xmlns"?IU:"",G=Q;else{if(z=this.resolve(K),z===void 0)this.fail(`unbound namespace prefix: ${JSON.stringify(K)}.`),z=K;G=`{${z}}${w}`}if(Y.has(G))this.fail(`duplicate attribute: ${G}.`);Y.add(G),J.uri=z,U[Q]=J}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,I=this.tag.attributes;for(let{name:q,value:U}of $){if(I[q]!==void 0)this.fail(`duplicate attribute: ${q}.`);I[q]=U}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:I}=this,q=this.tag;q.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,q),I.push(q),this.state=v6,this.name=""}openSelfClosingTag(){var $,I,q;this.processAttribs();let{tags:U}=this,Y=this.tag;if(Y.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,Y),(I=this.closeTagHandler)===null||I===void 0||I.call(this,Y),(this.tag=(q=U[U.length-1])!==null&&q!==void 0?q:null)===null)this.closedRoot=!0;this.state=v6,this.name=""}closeTag(){let{tags:$,name:I}=this;if(this.state=v6,this.name="",I===""){this.fail("weird empty close tag."),this.text+="</>";return}let q=this.closeTagHandler,U=$.length;while(U-- >0){let Y=this.tag=$.pop();if(this.topNS=Y.ns,q===null||q===void 0||q(Y),Y.name===I)break;this.fail("unexpected close tag.")}if(U===0)this.closedRoot=!0;else if(U<0)this.fail(`unmatched closing tag: ${I}.`),this.text+=`</${I}>`}parseEntity($){if($[0]!=="#"){let q=this.ENTITIES[$];if(q!==void 0)return q;return this.fail(this.isName($)?"undefined entity.":"disallowed character in entity name."),`&${$};`}let I=NaN;if($[1]==="x"&&/^#x[0-9a-f]+$/i.test($))I=parseInt($.slice(2),16);else if(/^#[0-9]+$/.test($))I=parseInt($.slice(1),10);if(!this.isChar(I))return this.fail("malformed character entity."),`&${$};`;return String.fromCodePoint(I)}}M10.SaxesParser=F10});var N2=L((RP1,g10)=>{var{SaxesParser:dp0}=A10(),{PassThrough:lp0}=Z6(),{bufferToString:mp0}=qv();g10.exports=async function*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(new lp0);let I=new dp0,q;I.on("error",(Y)=>{q=Y});let U=[];I.on("opentag",(Y)=>U.push({eventType:"opentag",value:Y})),I.on("text",(Y)=>U.push({eventType:"text",value:Y})),I.on("closetag",(Y)=>U.push({eventType:"closetag",value:Y}));for await(let Y of $){if(I.write(mp0(Y)),q)throw q;yield U,U=[]}}});var Z0=L((CP1,P10)=>{var op0=N2(),rp0=$6();class UU{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,I){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($ instanceof UU)$.reset();else if($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}async parse($){for await(let I of $)for(let{eventType:q,value:U}of I)if(q==="opentag")this.parseOpen(U);else if(q==="text")this.parseText(U);else if(q==="closetag"){if(!this.parseClose(U.name))return thLine truncated
<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme"> <a:themeElements> <a:clrScheme name="Office"> <a:dk1> <a:sysClr val="windowText" lastClr="000000"/> </a:dk1> <a:lt1> <a:sysClr val="window" lastClr="FFFFFF"/> </a:lt1> <a:dk2> <a:srgbClr val="1F497D"/> </a:dk2> <a:lt2> <a:srgbClr val="EEECE1"/> </a:lt2> <a:accent1> <a:srgbClr val="4F81BD"/> </a:accent1> <a:accent2> <a:srgbClr val="C0504D"/> </a:accent2> <a:accent3> <a:srgbClr val="9BBB59"/> </a:accent3> <a:accent4> <a:srgbClr val="8064A2"/> </a:accent4> <a:accent5> <a:srgbClr val="4BACC6"/> </a:accent5> <a:accent6> <a:srgbClr val="F79646"/> </a:accent6> <a:hlink> <a:srgbClr val="0000FF"/> </a:hlink> <a:folHlink> <a:srgbClr val="800080"/> </a:folHlink> </a:clrScheme> <a:fontScheme name="Office"> <a:majorFont> <a:latin typeface="Cambria"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Times New Roman"/> <a:font script="Hebr" typeface="Times New Roman"/> <a:font script="Thai" typeface="Tahoma"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="MoolBoran"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Times New Roman"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:majorFont> <a:minorFont> <a:latin typeface="Calibri"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Arial"/> <a:font script="Hebr" typeface="Arial"/> <a:font script="Thai" typeface="Tahoma"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="DaunPenh"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Arial"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:minorFont> </a:fontScheme> <a:fmtScheme name="Office"> <a:fillStyleLst> <a:solidFill> <a:schemeClr val="phClr"/> </a:solidFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="35000"> <a:schemeClr val="phClr"> <a:tint val="37000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="15000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="1"/> </a:gradFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="100000"/> <a:shade val="100000"/> <a:satMod val="130000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:shade val="100000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="0"/> </a:gradFill> </a:fillStyleLst> <a:lnStyleLst> <a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:schemeClr val="phClr"> <a:shade val="95000"/> <a:satMod val="105000"/> </a:schemeClr> </a:solidFill> <a:prstDash val="solid"/> </a:ln> <a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:Line truncated
`,this.quote='"',this.escape=this.quote,this.quoteColumns=!1,this.quoteHeaders=this.quoteColumns,this.headers=null,this.includeEndRowDelimiter=!1,this.writeBOM=!1,this.BOM="\uFEFF",this.alwaysWriteHeaders=!1,Object.assign(this,$||{}),typeof($===null||$===void 0?void 0:$.quoteHeaders)>"u")this.quoteHeaders=this.quoteColumns;if(($===null||$===void 0?void 0:$.quote)===!0)this.quote='"';else if(($===null||$===void 0?void 0:$.quote)===!1)this.quote="";if(typeof($===null||$===void 0?void 0:$.escape)!=="string")this.escape=this.quote;this.shouldWriteHeaders=!!this.headers&&((I=$.writeHeaders)!==null&&I!==void 0?I:!0),this.headers=Array.isArray(this.headers)?this.headers:null,this.escapedQuote=`${this.escape}${this.quote}`}}$70.FormatterOptions=e90});var WZ=L((qj1,J70)=>{var Jt0="[object AsyncFunction]",Qt0="[object Function]",Kt0="[object GeneratorFunction]",wt0="[object Null]",zt0="[object Proxy]",Gt0="[object Undefined]",Ht0=typeof global=="object"&&global&&global.Object===Object&&global,Vt0=typeof self=="object"&&self&&self.Object===Object&&self,Wt0=Ht0||Vt0||Function("return this")(),U70=Object.prototype,Zt0=U70.hasOwnProperty,Y70=U70.toString,q70=Wt0.Symbol,X3=q70?q70.toStringTag:void 0;function Xt0($){if($==null)return $===void 0?Gt0:wt0;return X3&&X3 in Object($)?Dt0($):Ot0($)}function Dt0($){var I=Zt0.call($,X3),q=$[X3];try{$[X3]=void 0;var U=!0}catch(J){}var Y=Y70.call($);if(U)if(I)$[X3]=q;else delete $[X3];return Y}function Ot0($){return Y70.call($)}function Lt0($){if(!Nt0($))return!1;var I=Xt0($);return I==Qt0||I==Kt0||I==Jt0||I==zt0}function Nt0($){var I=typeof $;return $!=null&&(I=="object"||I=="function")}J70.exports=Lt0});var n70=L((ZZ,WU)=>{var Ft0=200,pR="__lodash_hash_undefined__",AZ=1,O70=2,L70=9007199254740991,XZ="[object Arguments]",uR="[object Array]",Mt0="[object AsyncFunction]",N70="[object Boolean]",F70="[object Date]",M70="[object Error]",A70="[object Function]",At0="[object GeneratorFunction]",DZ="[object Map]",g70="[object Number]",gt0="[object Null]",VU="[object Object]",Q70="[object Promise]",Pt0="[object Proxy]",P70="[object RegExp]",OZ="[object Set]",T70="[object String]",Tt0="[object Symbol]",Et0="[object Undefined]",xR="[object WeakMap]",E70="[object ArrayBuffer]",LZ="[object DataView]",jt0="[object Float32Array]",Bt0="[object Float64Array]",vt0="[object Int8Array]",Rt0="[object Int16Array]",Ct0="[object Int32Array]",_t0="[object Uint8Array]",ht0="[object Uint8ClampedArray]",St0="[object Uint16Array]",yt0="[object Uint32Array]",ut0=/[\\^$.*+?()[\]{}|]/g,xt0=/^\[object .+?Constructor\]$/,kt0=/^(?:0|[1-9]\d*)$/,o1={};o1[jt0]=o1[Bt0]=o1[vt0]=o1[Rt0]=o1[Ct0]=o1[_t0]=o1[ht0]=o1[St0]=o1[yt0]=!0;o1[XZ]=o1[uR]=o1[E70]=o1[N70]=o1[LZ]=o1[F70]=o1[M70]=o1[A70]=o1[DZ]=o1[g70]=o1[VU]=o1[P70]=o1[OZ]=o1[T70]=o1[xR]=!1;var j70=typeof global=="object"&&global&&global.Object===Object&&global,ft0=typeof self=="object"&&self&&self.Object===Object&&self,A5=j70||ft0||Function("return this")(),B70=typeof ZZ=="object"&&ZZ&&!ZZ.nodeType&&ZZ,K70=B70&&typeof WU=="object"&&WU&&!WU.nodeType&&WU,v70=K70&&K70.exports===B70,hR=v70&&j70.process,w70=function(){try{return hR&&hR.binding&&hR.binding("util")}catch($){}}(),z70=w70&&w70.isTypedArray;function nt0($,I){var q=-1,U=$==null?0:$.length,Y=0,J=[];while(++q<U){var Q=$[q];if(I(Q,q,$))J[Y++]=Q}return J}function it0($,I){var q=-1,U=I.length,Y=$.length;while(++q<U)$[Y+q]=I[q];return $}function bt0($,I){var q=-1,U=$==null?0:$.length;while(++q<U)if(I($[q],q,$))return!0;return!1}function pt0($,I){var q=-1,U=Array($);while(++q<$)U[q]=I(q);return U}function ct0($){return function(I){return $(I)}}function dt0($,I){return $.has(I)}function lt0($,I){return $==null?void 0:$[I]}function mt0($){var I=-1,q=Array($.size);return $.forEach(function(U,Y){q[++I]=[Y,U]}),q}function ot0($,I){return function(q){return $(I(q))}}function rt0($){var I=-1,q=Array($.size);return $.forEach(function(U){q[++I]=U}),q}var tt0=Array.prototype,at0=Function.prototype,gZ=Object.prototype,SR=A5["__core-js_shared__"],R70=at0.toString,_8=gZ.hasOwnProperty,G70=function(){var $=/[^.]+$/.exec(SR&&SR.keys&&SR.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),C70=gZ.toString,st0=RegExp("^"+R70.call(_8).replace(ut0,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),H70=v70?A5.Buffer:void 0,NZ=A5.Symbol,V70=A5.Uint8Array,_70=gZ.propertyIsEnumerable,et0=tt0.splice,D3=NZ?NZ.toStringTag:void 0,W70=Object.getOwnPropertySymbols,$a0=H70?H70.isBuffer:void 0,Ia0=ot0(Object.keys,Object),kR=ZU(A5,"DataView"),E2=ZU(A5,"Map"),fR=ZU(A5,"Promise"),nR=ZU(A5,"Set"),iR=ZU(A5,"WeakMap"),j2=ZU(Object,"create"),qa0=N3(kR),Ua0=N3(E2),Ya0=N3(fR),Ja0=N3(nR),Qa0=N3(iR),Z70=NZ?NZ.prototype:void 0,yR=Z70?Z70.valueOf:void 0;function O3($){var I=-1,q=$==null?0:$.length;this.clear();while(++I<q){var U=$[I];this.set(U[0],U[1])}}function Ka0(){this.__data__=j2?j2(null):{},this.size=0}function wa0($){var I=this.has($)&&delete this.__data__[$];return this.size-=I?1:0,I}function za0($){var I=this.__data Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(I)}set headers($){this._headers=$}shouldQuote($,I){let q=I?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(Xs0.default(q))return q;if(Array.isArray(q))return q[$];if(this._headers!==null)return q[this._headers[$]];return!1}format($,I,q){let U=`${Ds0.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:Y}=this;if(Y.quote!==""){if(U.indexOf(Y.quote)!==-1)return this.quoteField(U.replace(this.REPLACE_REGEXP,Y.escapedQuote))}if(U.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(I,q))return this.quoteField(U);return U}quoteField($){let{quote:I}=this.formatterOptions;return`${I}${$}${I}`}}XU.FieldFormatter=r70});var oR=L((t70)=>{Object.defineProperty(t70,"__esModule",{value:!0});t70.isSyncTransform=void 0;t70.isSyncTransform=($)=>$.length===1});var e70=L((DU)=>{var s70=DU&&DU.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(DU,"__esModule",{value:!0});DU.RowFormatter=void 0;var Ls0=s70(WZ()),Ns0=s70(n70()),Fs0=mR(),Ms0=oR();class F3{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new Fs0.FieldFormatter($),this.headers=$.headers,this.shouldWriteHeaders=$.shouldWriteHeaders,this.hasWrittenHeaders=!1,this.headers!==null)this.fieldFormatter.headers=this.headers;if($.transform)this.rowTransform=$.transform}static isRowHashArray($){if(Array.isArray($))return Array.isArray($[0])&&$[0].length===2;return!1}static isRowArray($){return Array.isArray($)&&!this.isRowHashArray($)}static gatherHeaders($){if(F3.isRowHashArray($))return $.map((I)=>I[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(Ms0.isSyncTransform($))return(I,q)=>{let U=null;try{U=$(I)}catch(Y){return q(Y)}return q(null,U)};return(I,q)=>{$(I,q)}}set rowTransform($){if(!Ls0.default($))throw TypeError("The transform should be a function");this._rowTransform=F3.createTransform($)}format($,I){this.callTransformer($,(q,U)=>{if(q)return I(q);if(!$)return I(null);let Y=[];if(U){let{shouldFormatColumns:J,headers:Q}=this.checkHeaders(U);if(this.shouldWriteHeaders&&Q&&!this.hasWrittenHeaders)Y.push(this.formatColumns(Q,!0)),this.hasWrittenHeaders=!0;if(J){let K=this.gatherColumns(U);Y.push(this.formatColumns(K,!1))}}return I(null,Y)})}finish($){let I=[];if(this.formatterOptions.alwaysWriteHeaders&&this.rowCount===0){if(!this.headers)return $(Error("`alwaysWriteHeaders` option is set to true but `headers` option not provided."));I.push(this.formatColumns(this.headers,!0))}if(this.formatterOptions.includeEndRowDelimiter)I.push(this.formatterOptions.rowDelimiter);return $(null,I)}checkHeaders($){if(this.headers)return{shouldFormatColumns:!0,headers:this.headers};let I=F3.gatherHeaders($);if(this.headers=I,this.fieldFormatter.headers=I,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!Ns0.default(I,$),headers:I}}gatherColumns($){if(this.headers===null)throw Error("Headers is currently null");if(!Array.isArray($))return this.headers.map((I)=>$[I]);if(F3.isRowHashArray($))return this.headers.map((I,q)=>{let U=$[q];if(U)return U[1];return""});if(F3.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((I,q)=>$[q])}callTransformer($,I){if(!this._rowTransform)return I(null,$);return this._rowTransform($,I)}formatColumns($,I){let q=$.map((Y,J)=>this.fieldFormatter.format(Y,J,I)).join(this.formatterOptions.delimiter),{rowCount:U}=this;if(this.rowCount+=1,U)return[this.formatterOptions.rowDelimiter,q].join("");return q}}DU.RowFormatter=F3});var $30=L((EZ)=>{Object.defineProperty(EZ,"__esModule",{value:!0});EZ.FieldFormatter=EZ.RowFormatter=void 0;var As0=e70();Object.defineProperty(EZ,"RowFormatter",{enumerable:!0,get:function(){return As0.RowFormatter}});var gs0=mR();Object.defineProperty(EZ,"FieldFormatter",{enumerable:!0,get:function(){return gs0.FieldFormatter}})});var rR=L((q30)=>{Object.defineProperty(q30,"__esModule",{value:!0});q30.CsvFormatterStream=void 0;var Ts0=o("stream"),Es0=$30();class I30 extends Ts0.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new Es0.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,I,q){let U=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(Y,J)=>{if(Y)return U=!0,q(Y);if(J)J.forEach((Q)=>{this.push(Buffer.from(Q,"utf8"))});return U=!0,q()})}catch(Y){if(U)throw Y;q(Y)}}_flush($){this.rowFormatter.finish((I,q)=>{if(I)return $(I);if(q)q.forEach((U)=>{this.push(Buffer.from(U,"utf8"))});return $()})}}q30.CsvFormatterStream=I30});var J30=L((D1)=>{var Y30=D1&&D1.__createBinding||(Object.create?function($,I,q,U){if(U===void 0)U=q;Object.defineProperty($,U,{enumerable:!0,get:function(){return I[q]}})}:function($,I,q,U){if(U===void 0)U=q;$[U]=I[q]}),js0=D1&&D1.__setModuleDefault||(Object.create?function($,I){Ob Line truncated
deps: ${U}}`};var Ov0={keyword:"dependencies",type:"object",schemaType:"object",error:Rp.error,code($){let[I,U]=Nv0($);Bp($,I),vp($,U)}};function Nv0({schema:$}){let I={},U={};for(let Y in $){if(Y==="__proto__")continue;let J=Array.isArray($[Y])?I:U;J[Y]=$[Y]}return[I,U]}function Bp($,I=$.schema){let{gen:U,data:Y,it:J}=$;if(Object.keys(I).length===0)return;let Q=U.let("missing");for(let K in I){let q=I[K];if(q.length===0)continue;let H=(0,J2.propertyInData)(U,Y,K,J.opts.ownProperties);if($.setParams({property:K,depsCount:q.length,deps:q.join(", ")}),J.allErrors)U.if(H,()=>{for(let G of q)(0,J2.checkReportMissingProp)($,G)});else U.if($E._`${H} && (${(0,J2.checkMissingProp)($,q,Q)})`),(0,J2.reportMissingProp)($,Q),U.else()}}Rp.validatePropertyDeps=Bp;function vp($,I=$.schema){let{gen:U,data:Y,keyword:J,it:Q}=$,K=U.name("valid");for(let q in I){if((0,Fv0.alwaysValidSchema)(Q,I[q]))continue;U.if((0,J2.propertyInData)(U,Y,q,Q.opts.ownProperties),()=>{let H=$.subschema({keyword:J,schemaProp:q},K);$.mergeValidEvaluated(H,K)},()=>U.var(K,!0)),$.ok(K)}}Rp.validateSchemaDeps=vp;Rp.default=Ov0});var yp=F((gp)=>{Object.defineProperty(gp,"__esModule",{value:!0});var Sp=a0(),Pv0=Z1(),Tv0={message:"property name must be valid",params:({params:$})=>Sp._`{propertyName: ${$.propertyName}}`},Ev0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Tv0,code($){let{gen:I,schema:U,data:Y,it:J}=$;if((0,Pv0.alwaysValidSchema)(J,U))return;let Q=I.name("valid");I.forIn("key",Y,(K)=>{$.setParams({propertyName:K}),$.subschema({keyword:"propertyNames",data:K,dataTypes:["string"],propertyName:K,compositeRule:!0},Q),I.if((0,Sp.not)(Q),()=>{if($.error(!0),!J.allErrors)I.break()})}),$.ok(Q)}};gp.default=Ev0});var IE=F((hp)=>{Object.defineProperty(hp,"__esModule",{value:!0});var Xw=T$(),o$=a0(),vv0=Q5(),Lw=Z1(),Rv0={message:"must NOT have additional properties",params:({params:$})=>o$._`{additionalProperty: ${$.additionalProperty}}`},Cv0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Rv0,code($){let{gen:I,schema:U,parentSchema:Y,data:J,errsCount:Q,it:K}=$;if(!Q)throw Error("ajv implementation error");let{allErrors:q,opts:H}=K;if(K.props=!0,H.removeAdditional!=="all"&&(0,Lw.alwaysValidSchema)(K,U))return;let G=(0,Xw.allSchemaProperties)(Y.properties),W=(0,Xw.allSchemaProperties)(Y.patternProperties);w(),$.ok(o$._`${Q} === ${vv0.default.errors}`);function w(){I.forIn("key",J,(D)=>{if(!G.length&&!W.length)X(D);else I.if(V(D),()=>X(D))})}function V(D){let O;if(G.length>8){let E=(0,Lw.schemaRefOrVal)(K,Y.properties,"properties");O=(0,Xw.isOwnProperty)(I,E,D)}else if(G.length)O=(0,o$.or)(...G.map((E)=>o$._`${D} === ${E}`));else O=o$.nil;if(W.length)O=(0,o$.or)(O,...W.map((E)=>o$._`${(0,Xw.usePattern)($,E)}.test(${D})`));return(0,o$.not)(O)}function Z(D){I.code(o$._`delete ${J}[${D}]`)}function X(D){if(H.removeAdditional==="all"||H.removeAdditional&&U===!1){Z(D);return}if(U===!1){if($.setParams({additionalProperty:D}),$.error(),!q)I.break();return}if(typeof U=="object"&&!(0,Lw.alwaysValidSchema)(K,U)){let O=I.name("valid");if(H.removeAdditional==="failing")L(D,O,!1),I.if((0,o$.not)(O),()=>{$.reset(),Z(D)});else if(L(D,O),!q)I.if((0,o$.not)(O),()=>I.break())}}function L(D,O,E){let T={keyword:"additionalProperties",dataProp:D,dataPropType:Lw.Type.Str};if(E===!1)Object.assign(T,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(T,O)}}};hp.default=Cv0});var fp=F((kp)=>{Object.defineProperty(kp,"__esModule",{value:!0});var _v0=mQ(),up=T$(),UE=Z1(),xp=IE(),Sv0={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:I,schema:U,parentSchema:Y,data:J,it:Q}=$;if(Q.opts.removeAdditional==="all"&&Y.additionalProperties===void 0)xp.default.code(new _v0.KeywordCxt(Q,xp.default,"additionalProperties"));let K=(0,up.allSchemaProperties)(U);for(let w of K)Q.definedProperties.add(w);if(Q.opts.unevaluated&&K.length&&Q.props!==!0)Q.props=UE.mergeEvaluated.props(I,(0,UE.toHash)(K),Q.props);let q=K.filter((w)=>!(0,UE.alwaysValidSchema)(Q,U[w]));if(q.length===0)return;let H=I.name("valid");for(let w of q){if(G(w))W(w);else{if(I.if((0,up.propertyInData)(I,J,w,Q.opts.ownProperties)),W(w),!Q.allErrors)I.else().var(H,!0);I.endIf()}$.it.definedProperties.add(w),$.ok(H)}function G(w){return Q.opts.useDefaults&&!Q.compositeRule&&U[w].default!==void 0}function W(w){$.subschema({keyword:"properties",schemaProp:w,dataProp:w},H)}}};kp.default=Sv0});var cp=F((pp)=>{Object.defineProperty(pp,"__esModule",{value:!0});var ip=T$(),Dw=a0(),bp=Z1(),np=Z1(),yv0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:I,schema:U,data:Y,parentSchema:J,it:Q}=$,{opts:K}=Q,q=(0,ip.allSchemaProperties)(U),H=q.filter((L)=>(0,bp.alwaysValidSchema)(Q,U[L]));if(q.length===0||H.length===q.length&&(!Q.opts.unevaluated||Q.props===!0))return;let G=K.strictSchema&&!K.allowMatchingProperties&&J.properties,W=I.name("valid");if(Q.props!==!0&&!(Q.props instanceo Line truncated
\x00`,n+=l1(f,2),n+=q.magic,n+=l1(D,2),n+=l1(O,2),n+=l1(g.crc32,4),n+=l1(g.compressedSize,4),n+=l1(g.uncompressedSize,4),n+=l1(G.length,2),n+=l1(E.length,2);var S=rV.LOCAL_FILE_HEADER+n+G+E,i=rV.CENTRAL_FILE_HEADER+l1(p,2)+n+l1(V.length,2)+"\x00\x00\x00\x00"+l1(C,4)+l1(Y,4)+G+E+V;return{fileRecord:S,dirRecord:i}},wx0=function($,I,U,Y,J){var Q="",K=mU.transformTo("string",J(Y));return Q=rV.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+l1($,2)+l1($,2)+l1(I,4)+l1(U,4)+l1(K.length,2)+K,Q},Vx0=function($){var I="";return I=rV.DATA_DESCRIPTOR+l1($.crc32,4)+l1($.compressedSize,4)+l1($.uncompressedSize,4),I};function I8($,I,U,Y){lU.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=I,this.zipPlatform=U,this.encodeFileName=Y,this.streamFiles=$,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}mU.inherits(I8,lU);I8.prototype.push=function($){var I=$.meta.percent||0,U=this.entriesCount,Y=this._sources.length;if(this.accumulate)this.contentBuffer.push($);else this.bytesWritten+=$.data.length,lU.prototype.push.call(this,{data:$.data,meta:{currentFile:this.currentFile,percent:U?(I+100*(U-Y-1))/U:100}})};I8.prototype.openedSource=function($){this.currentSourceOffset=this.bytesWritten,this.currentFile=$.file.name;var I=this.streamFiles&&!$.file.dir;if(I){var U=xa($,I,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:U.fileRecord,meta:{percent:0}})}else this.accumulate=!0};I8.prototype.closedSource=function($){this.accumulate=!1;var I=this.streamFiles&&!$.file.dir,U=xa($,I,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(U.dirRecord),I)this.push({data:Vx0($),meta:{percent:100}});else{this.push({data:U.fileRecord,meta:{percent:0}});while(this.contentBuffer.length)this.push(this.contentBuffer.shift())}this.currentFile=null};I8.prototype.flush=function(){var $=this.bytesWritten;for(var I=0;I<this.dirRecords.length;I++)this.push({data:this.dirRecords[I],meta:{percent:100}});var U=this.bytesWritten-$,Y=wx0(this.dirRecords.length,U,$,this.zipComment,this.encodeFileName);this.push({data:Y,meta:{percent:100}})};I8.prototype.prepareNextSource=function(){if(this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused)this.previous.pause();else this.previous.resume()};I8.prototype.registerPrevious=function($){this._sources.push($);var I=this;return $.on("data",function(U){I.processChunk(U)}),$.on("end",function(){if(I.closedSource(I.previous.streamInfo),I._sources.length)I.prepareNextSource();else I.end()}),$.on("error",function(U){I.error(U)}),this};I8.prototype.resume=function(){if(!lU.prototype.resume.call(this))return!1;if(!this.previous&&this._sources.length)return this.prepareNextSource(),!0;if(!this.previous&&!this._sources.length&&!this.generatedError)return this.end(),!0};I8.prototype.error=function($){var I=this._sources;if(!lU.prototype.error.call(this,$))return!1;for(var U=0;U<I.length;U++)try{I[U].error($)}catch(Y){}return!0};I8.prototype.lock=function(){lU.prototype.lock.call(this);var $=this._sources;for(var I=0;I<$.length;I++)$[I].lock()};ka.exports=I8});var ia=F((Lx0)=>{var Zx0=hv(),zx0=fa(),Xx0=function($,I){var U=$||I,Y=Zx0[U];if(!Y)throw Error(U+" is not a valid compression method !");return Y};Lx0.generateWorker=function($,I,U){var Y=new zx0(I.streamFiles,U,I.platform,I.encodeFileName),J=0;try{$.forEach(function(Q,K){J++;var q=Xx0(K.options.compression,I.compression),H=K.options.compressionOptions||I.compressionOptions||{},G=K.dir,W=K.date;K._compressWorker(q,H).withStreamInfo("file",{name:Q,dir:G,date:W,comment:K.comment||"",unixPermissions:K.unixPermissions,dosPermissions:K.dosPermissions}).pipe(Y)}),Y.entriesCount=J}catch(Q){Y.error(Q)}return Y}});var na=F((AP1,ba)=>{var Fx0=W4(),tV=G$();function qK($,I){tV.call(this,"Nodejs stream input adapter for "+$),this._upstreamEnded=!1,this._bindStream(I)}Fx0.inherits(qK,tV);qK.prototype._bindStream=function($){var I=this;this._stream=$,$.pause(),$.on("data",function(U){I.push({data:U,meta:{percent:0}})}).on("error",function(U){if(I.isPaused)this.generatedError=U;else I.error(U)}).on("end",function(){if(I.isPaused)I._upstreamEnded=!0;else I.end()})};qK.prototype.pause=function(){if(!tV.prototype.pause.call(this))return!1;return this._stream.pause(),!0};qK.prototype.resume=function(){if(!tV.prototype.resume.call(this))return!1;if(this._upstreamEnded)this.end();else this._stream.resume();return!0};ba.exports=qK});var sa=F((PP1,aa)=>{var Ox0=uU(),HK=W4(),ma=G$(),Nx0=bB(),la=nB(),pa=_V(),Mx0=cr(),Ax0=ia(),ca=i2(),Px0=na(),oa=function($,I,U){var Y=HK.getTypeOf(I),J,Q=HK.extend(U||{},la);if(Q.date=Q.date||new Date,Q.compression!==null)Q.compression=Q.compression.toUpperCase();if(typeof Q.unixPermissions==="string")Q.unixPermissions=parseInt(Q.unixPermissions,8);if(Q.unixPermissions&&Q.unixPermissions&16384)Q.dir=!0;if(Q.dosPermissions&&Q.dosPermissions&16)Q.dir=!0;if(Q. Line truncated
`)}openNode($,I){let U=this.tos,Y=this._xml;if(U&&this.open)Y.push(">");this._stack.push($),Y.push("<"),Y.push($),OR(Y,I),this.leaf=!0,this.open=!0}addAttribute($,I){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(I!==void 0)ne(this._xml,$,I)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");OR(this._xml,$)}writeText($){let I=this._xml;if(this.open)I.push(">"),this.open=!1;this.leaf=!1,I.push(be.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),I=this._xml;if(this.leaf)I.push("/>");else I.push("</"),I.push($),I.push(">");this.open=!1,this.leaf=!1}leafNode($,I,U){if(this.openNode($,I),U!==void 0)this.writeText(U);this.closeNode()}closeAll(){while(this._stack.length)this.closeNode()}addRollback(){return this._rollbacks.push({xml:this._xml.length,stack:this._stack.length,leaf:this.leaf,open:this.open}),this.cursor}commit(){this._rollbacks.pop()}rollback(){let $=this._rollbacks.pop();if(this._xml.length>$.xml)this._xml.splice($.xml,this._xml.length-$.xml);if(this._stack.length>$.stack)this._stack.splice($.stack,this._stack.length-$.stack);this.leaf=$.leaf,this.open=$.open}get xml(){return this.closeAll(),this._xml.join("")}}NR.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};pe.exports=NR});var MR=F((zi0)=>{var ce=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function Zi0($){if(typeof $==="string")return $;if(ce)return ce.decode($);return $.toString()}zi0.bufferToString=Zi0});var re=F((me)=>{Object.defineProperty(me,"__esModule",{value:!0});me.CHAR=`
\r -퟿-�\uD800\uDC00-\uDBFF\uDFFF`;me.S=` \r
`;me.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";me.NAME_CHAR="-"+me.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";me.CHAR_RE=new RegExp("^["+me.CHAR+"]$","u");me.S_RE=new RegExp("^["+me.S+"]+$","u");me.NAME_START_CHAR_RE=new RegExp("^["+me.NAME_START_CHAR+"]$","u");me.NAME_CHAR_RE=new RegExp("^["+me.NAME_CHAR+"]$","u");me.NAME_RE=new RegExp("^["+me.NAME_START_CHAR+"]["+me.NAME_CHAR+"]*$","u");me.NMTOKEN_RE=new RegExp("^["+me.NAME_CHAR+"]+$","u");var AR=9,PR=10,TR=13,ER=32;me.S_LIST=[ER,PR,TR,AR];function Li0($){return $>=ER&&$<=55295||$===PR||$===TR||$===AR||$>=57344&&$<=65533||$>=65536&&$<=1114111}me.isChar=Li0;function Di0($){return $===ER||$===PR||$===TR||$===AR}me.isS=Di0;function de($){return $>=65&&$<=90||$>=97&&$<=122||$===58||$===95||$===8204||$===8205||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}me.isNameStartChar=de;function Fi0($){return de($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}me.isNameChar=Fi0});var Q00=F((I00)=>{Object.defineProperty(I00,"__esModule",{value:!0});I00.CHAR="\x01-퟿-�\uD800\uDC00-\uDBFF\uDFFF";I00.RESTRICTED_CHAR="\x01-\b\v\f\x0E-\x1F-„†-Ÿ";I00.S=` \r
`;I00.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";I00.NAME_CHAR="-"+I00.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";I00.CHAR_RE=new RegExp("^["+I00.CHAR+"]$","u");I00.RESTRICTED_CHAR_RE=new RegExp("^["+I00.RESTRICTED_CHAR+"]$","u");I00.S_RE=new RegExp("^["+I00.S+"]+$","u");I00.NAME_START_CHAR_RE=new RegExp("^["+I00.NAME_START_CHAR+"]$","u");I00.NAME_CHAR_RE=new RegExp("^["+I00.NAME_CHAR+"]$","u");I00.NAME_RE=new RegExp("^["+I00.NAME_START_CHAR+"]["+I00.NAME_CHAR+"]*$","u");I00.NMTOKEN_RE=new RegExp("^["+I00.NAME_CHAR+"]+$","u");var te=9,ae=10,se=13,ee=32;I00.S_LIST=[ee,ae,se,te];function ji0($){return $>=1&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}I00.isChar=ji0;function _i0($){return $>=1&&$<=8||$===11||$===12||$>=14&&$<=31||$>=127&&$<=132||$>=134&&$<=159}I00.isRestrictedChar=_i0;function Si0($){return $===9||$===10||$===13||$>31&&$<127||$===133||$>159&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}I00.isCharAndNotRestricted=Si0;function gi0($){return $===ee||$===ae||$===se||$===te}I00.isS=gi0;function $00($){return $>=65&&$<=90||$>=97&&$<=122||$===58||$===95||$===8204||$===8205||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}I00.isNameStartChar=$00;function yi0($){return $00($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}I00.isNameChar=yi0});var H00=F((q00)=>{Object.defineProperty(q00,"__esModule",{value:!0});q00.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";q00.NC_NAME_CHAR="-"+q00.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";q00.NC_NAME_START_CHAR_RE=new RegExp("^["+q00.NC_NAME_START_CHAR+"]$","u");q00.NC_NAME_CHAR_RE=new RegExp("^["+q00.NC_NAME_CHAR+"]$","u");q00.NC_NAME_RE=new RegExp("^["+q00.NC_NAME_START_CHAR+"]["+q00.NC_NAME_CHAR+"]*$","u");function K00($){return $>=65&&$<=90||$===95||$>=97&&$<=122||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8204&&$<=8205||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}q00.isNCNameStartChar=K00;function ri0($){return K00($)||($===45||$===46||$>=48&&$<=57||$===183||$>=768&&$<=879||$>=8255&&$<=8256)}q00.isNCNameChar=ri0});var j00=F((C00)=>{Object.defineProperty(C00,"__esModule",{value:!0});var JY=re(),Ib0=Q00(),fR=H00(),r6=JY.isS,Ub0=JY.isChar,MK=JY.isNameStartChar,G00=JY.isNameChar,P00=JY.S_LIST,Yb0=JY.NAME_RE,Jb0=Ib0.isChar,Qb0=fR.isNCNameStartChar,Kb0=fR.isNCNameChar,qb0=fR.NC_NAME_RE,EZ="http://www.w3.org/XML/1998/namespace",YY="http://www.w3.org/2000/xmlns/",Hb0={__proto__:null,xml:EZ,xmlns:YY},Gb0={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},q4=-1,_8=-2,W00=0,Wb0=1,vR=2,wb0=3,$Y=4,Vb0=5,Zb0=6,zb0=7,RR=8,Xb0=9,Lb0=10,Db0=11,Fb0=12,g6=13,NZ=14,CR=15,Ob0=16,jR=17,Nb0=18,Mb0=19,_R=20,Ab0=21,Pb0=22,Tb0=23,w00=24,SR=25,MZ=26,V00=27,Eb0=28,Bb0=29,Z00=30,vb0=31,Rb0=32,W3=33,Cb0=34,gR=35,AK=36,yR=37,jb0=38,z00=39,X00=40,_b0=41,L00=42,Sb0=43,gb0=44,hR=9,Y8=10,uR=13,D00=32,F00=33,T00=34,PK=38,E00=39,AZ=45,PZ=47,yb0=59,k9=60,IY=61,y4=62,U6=63,B00=91,UY=93,O00=133,N00=8232,TZ=($)=>$===T00||$===E00,v00=[T00,E00],hb0=[...v00,B00,y4],ub0=[...v00,k9,UY],xb0=[IY,U6,...P00],kb0=[...P00,y4,PK,k9];function kR($,I,U){switch(I){case"xml":if(U!==EZ)$.fail(`xml prefix must be bound to ${EZ}.`);break;case"xmlns":if(U!==YY)$.fail(`xmlns prefix must be bound to ${YY}.`);break;default:}switch(U){case YY:$.fail(I===""?`the default namespace may not be set to ${U}.`:`may not assign a prefix (even "xmlns") to the URI ${YY}.`);break;case EZ:switch(I){case"xml":break;case"":$.fail(`the default namespace may not be set to ${U}.`);break;default:$.fail("may not assign the xml namespace to another prefix.")}break;default:}}function fb0($,I){for(let U of Object.keys(I))kR($,U,I[U])}var ib0=($)=>qb0.test($),bb0=($)=>Yb0.test($),w3=0,M00=1,xR=2;C00.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var A00={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};class R00{constructor($){this.opt=$!==null&&$!==void 0?$:{},this.fragmentOpt=!!this.opt.fragment;let I=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=this.opt.position!==!1,this.fileName=this.opt.fileName,I){this.nameStartCheck=Qb0,this.nameCheck=Kb0,this.isName=ib0,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},Hb0);let U=this.opt.additionalNamespaces;if(U!=nu Line truncated
`,I=this.i}}captureToChar($){let{i:I}=this,{chunk:U}=this;while(!0){let Y=this.getCode();switch(Y){case _8:this.text+=`${U.slice(I,this.prevI)}
`,I=this.i,Y=Y8;break;case q4:return this.text+=U.slice(I),!1;default:}if(Y===$)return this.text+=U.slice(I,this.prevI),!0}}captureNameChars(){let{chunk:$,i:I}=this;while(!0){let U=this.getCode();if(U===q4)return this.name+=$.slice(I),q4;if(!G00(U))return this.name+=$.slice(I,this.prevI),U===_8?Y8:U}}skipSpaces(){while(!0){let $=this.getCodeNorm();if($===q4||!r6($))return $}}setXMLVersion($){if(this.currentXMLVersion=$,$==="1.0")this.isChar=Ub0,this.getCode=this.getCode10;else this.isChar=Jb0,this.getCode=this.getCode11}sBegin(){if(this.chunk.charCodeAt(0)===65279)this.i++,this.column++;this.state=Wb0}sBeginWhitespace(){let $=this.i,I=this.skipSpaces();if(this.prevI!==$)this.xmlDeclPossible=!1;switch(I){case k9:if(this.state=CR,this.text.length!==0)throw Error("no-empty text at start");break;case q4:break;default:this.unget(),this.state=g6,this.xmlDeclPossible=!1}}sDoctype(){var $;let I=this.captureTo(hb0);switch(I){case y4:{($=this.doctypeHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=g6,this.doctype=!0;break}case q4:break;default:if(this.text+=String.fromCodePoint(I),I===B00)this.state=$Y;else if(TZ(I))this.state=wb0,this.q=I}}sDoctypeQuote(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.q=null,this.state=vR}sDTD(){let $=this.captureTo(ub0);if($===q4)return;if(this.text+=String.fromCodePoint($),$===UY)this.state=vR;else if($===k9)this.state=Zb0;else if(TZ($))this.state=Vb0,this.q=$}sDTDQuoted(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.state=$Y,this.q=null}sDTDOpenWaka(){let $=this.getCodeNorm();switch(this.text+=String.fromCodePoint($),$){case F00:this.state=zb0,this.openWakaBang="";break;case U6:this.state=Db0;break;default:this.state=$Y}}sDTDOpenWakaBang(){let $=String.fromCodePoint(this.getCodeNorm()),I=this.openWakaBang+=$;if(this.text+=$,I!=="-")this.state=I==="--"?RR:$Y,this.openWakaBang=""}sDTDComment(){if(this.captureToChar(AZ))this.text+="-",this.state=Xb0}sDTDCommentEnding(){let $=this.getCodeNorm();this.text+=String.fromCodePoint($),this.state=$===AZ?Lb0:RR}sDTDCommentEnded(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===y4)this.state=$Y;else this.fail("malformed comment."),this.state=RR}sDTDPI(){if(this.captureToChar(U6))this.text+="?",this.state=Fb0}sDTDPIEnding(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===y4)this.state=$Y}sText(){if(this.tags.length!==0)this.handleTextInRoot();else this.handleTextOutsideRoot()}sEntity(){let{i:$}=this,{chunk:I}=this;$:while(!0)switch(this.getCode()){case _8:this.entity+=`${I.slice($,this.prevI)}
`,$=this.i;break;case yb0:{let{entityReturnState:U}=this,Y=this.entity+I.slice($,this.prevI);this.state=U;let J;if(Y==="")this.fail("empty entity name."),J="&;";else J=this.parseEntity(Y),this.entity="";if(U!==g6||this.textHandler!==void 0)this.text+=J;break $}case q4:this.entity+=I.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(MK($))this.state=Cb0,this.unget(),this.xmlDeclPossible=!1;else switch($){case PZ:this.state=Sb0,this.xmlDeclPossible=!1;break;case F00:this.state=Ob0,this.openWakaBang="",this.xmlDeclPossible=!1;break;case U6:this.state=Tb0;break;default:this.fail("disallowed character in tag name"),this.state=g6,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0;this.state=_R,this.openWakaBang="";break;case"--":this.state=jR,this.openWakaBang="";break;case"DOCTYPE":if(this.state=vR,this.doctype||this.sawRoot)this.fail("inappropriately located doctype declaration.");this.openWakaBang="";break;default:if(this.openWakaBang.length>=7)this.fail("incorrect syntax.")}}sComment(){if(this.captureToChar(AZ))this.state=Nb0}sCommentEnding(){var $;let I=this.getCodeNorm();if(I===AZ)this.state=Mb0,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(I)}`,this.state=jR}sCommentEnded(){let $=this.getCodeNorm();if($!==y4)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=jR;else this.state=g6}sCData(){if(this.captureToChar(UY))this.state=Ab0}sCDataEnding(){let $=this.getCodeNorm();if($===UY)this.state=Pb0;else this.text+=`]${String.fromCodePoint($)}`,this.state=_R}sCDataEnding2(){var $;let I=this.getCodeNorm();switch(I){case y4:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=g6;break}case UY:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(I)}`,this.state=_R}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=w00;else if($===U6||r6($))this.fail("processing instruction without a target."),this.state=$===U6?MZ:SR;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=w00}sPIRest(){let{chunk:$,i:I}=this;while(!0){let U=this.getCodeNorm();if(U===q4){this.piTarget+=$.slice(I);return}if(!this.nameCheck(U)){this.piTarget+=$.slice(I,this.prevI);let Y=U===U6;if(Y||r6(U))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=Y?W3:V00}else this.state=Y?MZ:SR;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(U);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===U6)this.state=MZ;else if(!r6($))this.text=String.fromCodePoint($)}else if(this.captureToChar(U6))this.state=MZ}sPIEnding(){var $;let I=this.getCodeNorm();if(I===y4){let{piTarget:U}=this;if(U.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:U,body:this.text}),this.piTarget=this.text="",this.state=g6}else if(I===U6)this.text+="?";else this.text+=`?${String.fromCodePoint(I)}`,this.state=SR;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===U6){this.state=W3;return}if($!==q4)this.state=Eb0,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(xb0);if($===U6){this.state=W3,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(r6($)||$===IY))return;if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=$===IY?Z00:Bb0}sXMLDeclEq(){let $=this.getCodeNorm();if($===U6){this.state=W3,this.fail("XML declaration is incomplete.");return}if(r6($))return;if($!==IY)this.fail("value required.");this.state=Z00}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===U6){this.state=W3,this.fail("XML declaration is incomplete.");return}if(r6($))return;if(!TZ($))this.fail("value must be quoted."),this.q=D00;else this.q=$;this.state=vb0}sXMLDeclValue(){let $=this.captureTo([this.q,U6]);if($===U6){this.state=W3,this.text="",this.fail("XML declaration is incomplete.");return}if($===q4)return;let I=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let U=I;if(this.xmlDecl.version=U,!/^1\.[0-9]+$/.test(U))this.fail("ver Line truncated
`;$=this.i,I=w3;break;case q4:if(Y!==void 0)this.text+=U.slice($);break $;default:I=w3}this.forbiddenState=I}handleTextOutsideRoot(){let{i:$}=this,{chunk:I,textHandler:U}=this,Y=!1;$:while(!0){let J=this.getCode();switch(J){case k9:{if(this.state=CR,U!==void 0){let{text:Q}=this,K=I.slice($,this.prevI);if(Q.length!==0)U(Q+K),this.text="";else if(K.length!==0)U(K)}break $}case PK:if(this.state=NZ,this.entityReturnState=g6,U!==void 0)this.text+=I.slice($,this.prevI);Y=!0;break $;case _8:if(U!==void 0)this.text+=`${I.slice($,this.prevI)}
`;$=this.i;break;case q4:if(U!==void 0)this.text+=I.slice($);break $;default:if(!r6(J))Y=!0}}if(!Y)return;if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0}pushAttribNS($,I){var U;let{prefix:Y,local:J}=this.qname($),Q={name:$,prefix:Y,local:J,value:I};if(this.attribList.push(Q),(U=this.attributeHandler)===null||U===void 0||U.call(this,Q),Y==="xmlns"){let K=I.trim();if(this.currentXMLVersion==="1.0"&&K==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[J]=K,kR(this,J,K)}else if($==="xmlns"){let K=I.trim();this.topNS[""]=K,kR(this,"",K)}}pushAttribPlain($,I){var U;let Y={name:$,value:I};this.attribList.push(Y),(U=this.attributeHandler)===null||U===void 0||U.call(this,Y)}end(){var $,I;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:U}=this;while(U.length>0){let J=U.pop();this.fail(`unclosed tag: ${J.name}`)}if(this.state!==W00&&this.state!==g6)this.fail("unexpected end.");let{text:Y}=this;if(Y.length!==0)($=this.textHandler)===null||$===void 0||$.call(this,Y),this.text="";return this._closed=!0,(I=this.endHandler)===null||I===void 0||I.call(this),this._init(),this}resolve($){var I,U;let Y=this.topNS[$];if(Y!==void 0)return Y;let{tags:J}=this;for(let Q=J.length-1;Q>=0;Q--)if(Y=J[Q].ns[$],Y!==void 0)return Y;if(Y=this.ns[$],Y!==void 0)return Y;return(U=(I=this.opt).resolvePrefix)===null||U===void 0?void 0:U.call(I,$)}qname($){let I=$.indexOf(":");if(I===-1)return{prefix:"",local:$};let U=$.slice(I+1),Y=$.slice(0,I);if(Y===""||U===""||U.includes(":"))this.fail(`malformed name: ${$}.`);return{prefix:Y,local:U}}processAttribsNS(){var $;let{attribList:I}=this,U=this.tag;{let{prefix:Q,local:K}=this.qname(U.name);U.prefix=Q,U.local=K;let q=U.uri=($=this.resolve(Q))!==null&&$!==void 0?$:"";if(Q!==""){if(Q==="xmlns")this.fail('tags may not have "xmlns" as prefix.');if(q==="")this.fail(`unbound namespace prefix: ${JSON.stringify(Q)}.`),U.uri=Q}}if(I.length===0)return;let{attributes:Y}=U,J=new Set;for(let Q of I){let{name:K,prefix:q,local:H}=Q,G,W;if(q==="")G=K==="xmlns"?YY:"",W=K;else{if(G=this.resolve(q),G===void 0)this.fail(`unbound namespace prefix: ${JSON.stringify(q)}.`),G=q;W=`{${G}}${H}`}if(J.has(W))this.fail(`duplicate attribute: ${W}.`);J.add(W),Q.uri=G,Y[K]=Q}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,I=this.tag.attributes;for(let{name:U,value:Y}of $){if(I[U]!==void 0)this.fail(`duplicate attribute: ${U}.`);I[U]=Y}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:I}=this,U=this.tag;U.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,U),I.push(U),this.state=g6,this.name=""}openSelfClosingTag(){var $,I,U;this.processAttribs();let{tags:Y}=this,J=this.tag;if(J.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,J),(I=this.closeTagHandler)===null||I===void 0||I.call(this,J),(this.tag=(U=Y[Y.length-1])!==null&&U!==void 0?U:null)===null)this.closedRoot=!0;this.state=g6,this.name=""}closeTag(){let{tags:$,name:I}=this;if(this.state=g6,this.name="",I===""){this.fail("weird empty close tag."),this.text+="</>";return}let U=this.closeTagHandler,Y=$.length;while(Y-- >0){let J=this.tag=$.pop();if(this.topNS=J.ns,U===null||U===void 0||U(J),J.name===I)break;this.fail("unexpected close tag.")}if(Y===0)this.closedRoot=!0;else if(Y<0)this.fail(`unmatched closing tag: ${I}.`),this.text+=`</${I}>`}parseEntity($){if($[0]!=="#"){let U=this.ENTITIES[$];if(U!==void 0)return U;return this.fail(this.isName($)?"undefined entity.":"disallowed character in entity name."),`&${$};`}let I=NaN;if($[1]==="x"&&/^#x[0-9a-f]+$/i.test($))I=parseInt($.slice(2),16);else if(/^#[0-9]+$/.test($))I=parseInt($.slice(1),10);if(!this.isChar(I))return this.fail("malformed character entity."),`&${$};`;return String.fromCodePoint(I)}}C00.SaxesParser=R00});var TK=F((KT1,_00)=>{var{SaxesParser:cb0}=j00(),{PassThrough:db0}=L6(),{bufferToString:mb0}=MR();_00.exports=async function*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(new db0);let I=new cb0,U;I.on("error",(J)=>{U=J});let Y=[];I.on("opentag",(J)=>Y.push({eventType:"opentag",value:J})),I.on("text",(J)=>Y.push({eventType:"text",value:J})),I.on("closetag",(J)=>Y.push({eventType:"closetag",value:J}));for await(let J of $){if(I.write(mb0(J)),U)throw U;yield Y,Y=[]}}});var L0=F((qT1,S00)=>{var lb0=TK(),ob0=I6();class QY{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,I){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($ instanceof QY)$.reset();else if($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}async parse($){for await(let I of $)for(let{eventType:U,value:Y}of I)if(U==="opentag")this.parseOpen(Y);else if(U==="text")this.parseText(Y);else if(U==="closetag"){if(!this.parseClose(Y.name))return thLine truncated
<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme"> <a:themeElements> <a:clrScheme name="Office"> <a:dk1> <a:sysClr val="windowText" lastClr="000000"/> </a:dk1> <a:lt1> <a:sysClr val="window" lastClr="FFFFFF"/> </a:lt1> <a:dk2> <a:srgbClr val="1F497D"/> </a:dk2> <a:lt2> <a:srgbClr val="EEECE1"/> </a:lt2> <a:accent1> <a:srgbClr val="4F81BD"/> </a:accent1> <a:accent2> <a:srgbClr val="C0504D"/> </a:accent2> <a:accent3> <a:srgbClr val="9BBB59"/> </a:accent3> <a:accent4> <a:srgbClr val="8064A2"/> </a:accent4> <a:accent5> <a:srgbClr val="4BACC6"/> </a:accent5> <a:accent6> <a:srgbClr val="F79646"/> </a:accent6> <a:hlink> <a:srgbClr val="0000FF"/> </a:hlink> <a:folHlink> <a:srgbClr val="800080"/> </a:folHlink> </a:clrScheme> <a:fontScheme name="Office"> <a:majorFont> <a:latin typeface="Cambria"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Times New Roman"/> <a:font script="Hebr" typeface="Times New Roman"/> <a:font script="Thai" typeface="Tahoma"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="MoolBoran"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Times New Roman"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:majorFont> <a:minorFont> <a:latin typeface="Calibri"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Arial"/> <a:font script="Hebr" typeface="Arial"/> <a:font script="Thai" typeface="Tahoma"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="DaunPenh"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Arial"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:minorFont> </a:fontScheme> <a:fmtScheme name="Office"> <a:fillStyleLst> <a:solidFill> <a:schemeClr val="phClr"/> </a:solidFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="35000"> <a:schemeClr val="phClr"> <a:tint val="37000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="15000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="1"/> </a:gradFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="100000"/> <a:shade val="100000"/> <a:satMod val="130000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:shade val="100000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="0"/> </a:gradFill> </a:fillStyleLst> <a:lnStyleLst> <a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:schemeClr val="phClr"> <a:shade val="95000"/> <a:satMod val="105000"/> </a:schemeClr> </a:solidFill> <a:prstDash val="solid"/> </a:ln> <a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:Line truncated
`,this.quote='"',this.escape=this.quote,this.quoteColumns=!1,this.quoteHeaders=this.quoteColumns,this.headers=null,this.includeEndRowDelimiter=!1,this.writeBOM=!1,this.BOM="\uFEFF",this.alwaysWriteHeaders=!1,Object.assign(this,$||{}),typeof($===null||$===void 0?void 0:$.quoteHeaders)>"u")this.quoteHeaders=this.quoteColumns;if(($===null||$===void 0?void 0:$.quote)===!0)this.quote='"';else if(($===null||$===void 0?void 0:$.quote)===!1)this.quote="";if(typeof($===null||$===void 0?void 0:$.escape)!=="string")this.escape=this.quote;this.shouldWriteHeaders=!!this.headers&&((I=$.writeHeaders)!==null&&I!==void 0?I:!0),this.headers=Array.isArray(this.headers)?this.headers:null,this.escapedQuote=`${this.escape}${this.quote}`}}H90.FormatterOptions=q90});var Jz=F((SB1,Z90)=>{var Jo0="[object AsyncFunction]",Qo0="[object Function]",Ko0="[object GeneratorFunction]",qo0="[object Null]",Ho0="[object Proxy]",Go0="[object Undefined]",Wo0=typeof global=="object"&&global&&global.Object===Object&&global,wo0=typeof self=="object"&&self&&self.Object===Object&&self,Vo0=Wo0||wo0||Function("return this")(),w90=Object.prototype,Zo0=w90.hasOwnProperty,V90=w90.toString,W90=Vo0.Symbol,F3=W90?W90.toStringTag:void 0;function zo0($){if($==null)return $===void 0?Go0:qo0;return F3&&F3 in Object($)?Xo0($):Lo0($)}function Xo0($){var I=Zo0.call($,F3),U=$[F3];try{$[F3]=void 0;var Y=!0}catch(Q){}var J=V90.call($);if(Y)if(I)$[F3]=U;else delete $[F3];return J}function Lo0($){return V90.call($)}function Do0($){if(!Fo0($))return!1;var I=zo0($);return I==Qo0||I==Ko0||I==Jo0||I==Ho0}function Fo0($){var I=typeof $;return $!=null&&(I=="object"||I=="function")}Z90.exports=Do0});var o90=F((Qz,XY)=>{var Oo0=200,Hj="__lodash_hash_undefined__",Zz=1,E90=2,B90=9007199254740991,Kz="[object Arguments]",Ij="[object Array]",No0="[object AsyncFunction]",v90="[object Boolean]",R90="[object Date]",C90="[object Error]",j90="[object Function]",Mo0="[object GeneratorFunction]",qz="[object Map]",_90="[object Number]",Ao0="[object Null]",zY="[object Object]",z90="[object Promise]",Po0="[object Proxy]",S90="[object RegExp]",Hz="[object Set]",g90="[object String]",To0="[object Symbol]",Eo0="[object Undefined]",Uj="[object WeakMap]",y90="[object ArrayBuffer]",Gz="[object DataView]",Bo0="[object Float32Array]",vo0="[object Float64Array]",Ro0="[object Int8Array]",Co0="[object Int16Array]",jo0="[object Int32Array]",_o0="[object Uint8Array]",So0="[object Uint8ClampedArray]",go0="[object Uint16Array]",yo0="[object Uint32Array]",ho0=/[\\^$.*+?()[\]{}|]/g,uo0=/^\[object .+?Constructor\]$/,xo0=/^(?:0|[1-9]\d*)$/,s1={};s1[Bo0]=s1[vo0]=s1[Ro0]=s1[Co0]=s1[jo0]=s1[_o0]=s1[So0]=s1[go0]=s1[yo0]=!0;s1[Kz]=s1[Ij]=s1[y90]=s1[v90]=s1[Gz]=s1[R90]=s1[C90]=s1[j90]=s1[qz]=s1[_90]=s1[zY]=s1[S90]=s1[Hz]=s1[g90]=s1[Uj]=!1;var h90=typeof global=="object"&&global&&global.Object===Object&&global,ko0=typeof self=="object"&&self&&self.Object===Object&&self,T5=h90||ko0||Function("return this")(),u90=typeof Qz=="object"&&Qz&&!Qz.nodeType&&Qz,X90=u90&&typeof XY=="object"&&XY&&!XY.nodeType&&XY,x90=X90&&X90.exports===u90,sC=x90&&h90.process,L90=function(){try{return sC&&sC.binding&&sC.binding("util")}catch($){}}(),D90=L90&&L90.isTypedArray;function fo0($,I){var U=-1,Y=$==null?0:$.length,J=0,Q=[];while(++U<Y){var K=$[U];if(I(K,U,$))Q[J++]=K}return Q}function io0($,I){var U=-1,Y=I.length,J=$.length;while(++U<Y)$[J+U]=I[U];return $}function bo0($,I){var U=-1,Y=$==null?0:$.length;while(++U<Y)if(I($[U],U,$))return!0;return!1}function no0($,I){var U=-1,Y=Array($);while(++U<$)Y[U]=I(U);return Y}function po0($){return function(I){return $(I)}}function co0($,I){return $.has(I)}function do0($,I){return $==null?void 0:$[I]}function mo0($){var I=-1,U=Array($.size);return $.forEach(function(Y,J){U[++I]=[J,Y]}),U}function lo0($,I){return function(U){return $(I(U))}}function oo0($){var I=-1,U=Array($.size);return $.forEach(function(Y){U[++I]=Y}),U}var ro0=Array.prototype,to0=Function.prototype,zz=Object.prototype,eC=T5["__core-js_shared__"],k90=to0.toString,g8=zz.hasOwnProperty,F90=function(){var $=/[^.]+$/.exec(eC&&eC.keys&&eC.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),f90=zz.toString,ao0=RegExp("^"+k90.call(g8).replace(ho0,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),O90=x90?T5.Buffer:void 0,Wz=T5.Symbol,N90=T5.Uint8Array,i90=zz.propertyIsEnumerable,so0=ro0.splice,O3=Wz?Wz.toStringTag:void 0,M90=Object.getOwnPropertySymbols,eo0=O90?O90.isBuffer:void 0,$r0=lo0(Object.keys,Object),Yj=LY(T5,"DataView"),_K=LY(T5,"Map"),Jj=LY(T5,"Promise"),Qj=LY(T5,"Set"),Kj=LY(T5,"WeakMap"),SK=LY(Object,"create"),Ir0=A3(Yj),Ur0=A3(_K),Yr0=A3(Jj),Jr0=A3(Qj),Qr0=A3(Kj),A90=Wz?Wz.prototype:void 0,$j=A90?A90.valueOf:void 0;function N3($){var I=-1,U=$==null?0:$.length;this.clear();while(++I<U){var Y=$[I];this.set(Y[0],Y[1])}}function Kr0(){this.__data__=SK?SK(null):{},this.size=0}function qr0($){var I=this.has($)&&delete this.__data__[$];return this.size-=I?1:0,I}function Hr0($){var I=this.__data Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(I)}set headers($){this._headers=$}shouldQuote($,I){let U=I?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(zt0.default(U))return U;if(Array.isArray(U))return U[$];if(this._headers!==null)return U[this._headers[$]];return!1}format($,I,U){let Y=`${Xt0.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:J}=this;if(J.quote!==""){if(Y.indexOf(J.quote)!==-1)return this.quoteField(Y.replace(this.REPLACE_REGEXP,J.escapedQuote))}if(Y.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(I,U))return this.quoteField(Y);return Y}quoteField($){let{quote:I}=this.formatterOptions;return`${I}${$}${I}`}}DY.FieldFormatter=Y70});var Zj=F((J70)=>{Object.defineProperty(J70,"__esModule",{value:!0});J70.isSyncTransform=void 0;J70.isSyncTransform=($)=>$.length===1});var q70=F((FY)=>{var K70=FY&&FY.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(FY,"__esModule",{value:!0});FY.RowFormatter=void 0;var Dt0=K70(Jz()),Ft0=K70(o90()),Ot0=Vj(),Nt0=Zj();class P3{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new Ot0.FieldFormatter($),this.headers=$.headers,this.shouldWriteHeaders=$.shouldWriteHeaders,this.hasWrittenHeaders=!1,this.headers!==null)this.fieldFormatter.headers=this.headers;if($.transform)this.rowTransform=$.transform}static isRowHashArray($){if(Array.isArray($))return Array.isArray($[0])&&$[0].length===2;return!1}static isRowArray($){return Array.isArray($)&&!this.isRowHashArray($)}static gatherHeaders($){if(P3.isRowHashArray($))return $.map((I)=>I[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(Nt0.isSyncTransform($))return(I,U)=>{let Y=null;try{Y=$(I)}catch(J){return U(J)}return U(null,Y)};return(I,U)=>{$(I,U)}}set rowTransform($){if(!Dt0.default($))throw TypeError("The transform should be a function");this._rowTransform=P3.createTransform($)}format($,I){this.callTransformer($,(U,Y)=>{if(U)return I(U);if(!$)return I(null);let J=[];if(Y){let{shouldFormatColumns:Q,headers:K}=this.checkHeaders(Y);if(this.shouldWriteHeaders&&K&&!this.hasWrittenHeaders)J.push(this.formatColumns(K,!0)),this.hasWrittenHeaders=!0;if(Q){let q=this.gatherColumns(Y);J.push(this.formatColumns(q,!1))}}return I(null,J)})}finish($){let I=[];if(this.formatterOptions.alwaysWriteHeaders&&this.rowCount===0){if(!this.headers)return $(Error("`alwaysWriteHeaders` option is set to true but `headers` option not provided."));I.push(this.formatColumns(this.headers,!0))}if(this.formatterOptions.includeEndRowDelimiter)I.push(this.formatterOptions.rowDelimiter);return $(null,I)}checkHeaders($){if(this.headers)return{shouldFormatColumns:!0,headers:this.headers};let I=P3.gatherHeaders($);if(this.headers=I,this.fieldFormatter.headers=I,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!Ft0.default(I,$),headers:I}}gatherColumns($){if(this.headers===null)throw Error("Headers is currently null");if(!Array.isArray($))return this.headers.map((I)=>$[I]);if(P3.isRowHashArray($))return this.headers.map((I,U)=>{let Y=$[U];if(Y)return Y[1];return""});if(P3.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((I,U)=>$[U])}callTransformer($,I){if(!this._rowTransform)return I(null,$);return this._rowTransform($,I)}formatColumns($,I){let U=$.map((J,Q)=>this.fieldFormatter.format(J,Q,I)).join(this.formatterOptions.delimiter),{rowCount:Y}=this;if(this.rowCount+=1,Y)return[this.formatterOptions.rowDelimiter,U].join("");return U}}FY.RowFormatter=P3});var H70=F((Dz)=>{Object.defineProperty(Dz,"__esModule",{value:!0});Dz.FieldFormatter=Dz.RowFormatter=void 0;var Mt0=q70();Object.defineProperty(Dz,"RowFormatter",{enumerable:!0,get:function(){return Mt0.RowFormatter}});var At0=Vj();Object.defineProperty(Dz,"FieldFormatter",{enumerable:!0,get:function(){return At0.FieldFormatter}})});var zj=F((W70)=>{Object.defineProperty(W70,"__esModule",{value:!0});W70.CsvFormatterStream=void 0;var Tt0=a("stream"),Et0=H70();class G70 extends Tt0.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new Et0.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,I,U){let Y=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(J,Q)=>{if(J)return Y=!0,U(J);if(Q)Q.forEach((K)=>{this.push(Buffer.from(K,"utf8"))});return Y=!0,U()})}catch(J){if(Y)throw J;U(J)}}_flush($){this.rowFormatter.finish((I,U)=>{if(I)return $(I);if(U)U.forEach((Y)=>{this.push(Buffer.from(Y,"utf8"))});return $()})}}W70.CsvFormatterStream=G70});var Z70=F((N1)=>{var V70=N1&&N1.__createBinding||(Object.create?function($,I,U,Y){if(Y===void 0)Y=U;Object.defineProperty($,Y,{enumerable:!0,get:function(){return I[U]}})}:function($,I,U,Y){if(Y===void 0)Y=U;$[Y]=I[U]}),Bt0=N1&&N1.__setModuleDefault||(Object.create?function($,I){Ob Line truncated
`||I===`\r
`}static isTokenCarriageReturn($,I){return $.token===I.carriageReturn}static isTokenComment($,I){return I.supportsComments&&!!$&&$.token===I.comment}static isTokenEscapeCharacter($,I){return $.token===I.escapeChar}static isTokenQuote($,I){return $.token===I.quote}static isTokenDelimiter($,I){return $.token===I.delimiter}}QI0.Token=JI0});var NC=L((GI0)=>{Object.defineProperty(GI0,"__esModule",{value:!0});GI0.Scanner=void 0;var wI0=c9(),y11=/((?:\r\n)|\n|\r)/;class zI0{constructor($){this.cursor=0,this.line=$.line,this.lineLength=this.line.length,this.parserOptions=$.parserOptions,this.hasMoreData=$.hasMoreData,this.cursor=$.cursor||0}get hasMoreCharacters(){return this.lineLength>this.cursor}get nextNonSpaceToken(){let{lineFromCursor:$}=this,I=this.parserOptions.NEXT_TOKEN_REGEXP;if($.search(I)===-1)return null;let q=I.exec($);if(q==null)return null;let U=q[1],Y=this.cursor+(q.index||0);return new wI0.Token({token:U,startCursor:Y,endCursor:Y+U.length-1})}get nextCharacterToken(){let{cursor:$,lineLength:I}=this;if(I<=$)return null;return new wI0.Token({token:this.line[$],startCursor:$,endCursor:$})}get lineFromCursor(){return this.line.substr(this.cursor)}advancePastLine(){let $=y11.exec(this.lineFromCursor);if(!$){if(this.hasMoreData)return null;return this.cursor=this.lineLength,this}return this.cursor+=($.index||0)+$[0].length,this}advanceTo($){return this.cursor=$,this}advanceToToken($){return this.cursor=$.startCursor,this}advancePastToken($){return this.cursor=$.endCursor+1,this}truncateToCursor(){return this.line=this.lineFromCursor,this.lineLength=this.line.length,this.cursor=0,this}}GI0.Scanner=zI0});var rZ=L((WI0)=>{Object.defineProperty(WI0,"__esModule",{value:!0});WI0.ColumnFormatter=void 0;class VI0{constructor($){if($.trim)this.format=(I)=>I.trim();else if($.ltrim)this.format=(I)=>I.trimLeft();else if($.rtrim)this.format=(I)=>I.trimRight();else this.format=(I)=>I}}WI0.ColumnFormatter=VI0});var FC=L((OI0)=>{Object.defineProperty(OI0,"__esModule",{value:!0});OI0.NonQuotedColumnParser=void 0;var u11=rZ(),XI0=c9();class DI0{constructor($){this.parserOptions=$,this.columnFormatter=new u11.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let{parserOptions:I}=this,q=[],U=$.nextCharacterToken;for(;U;U=$.nextCharacterToken){if(XI0.Token.isTokenDelimiter(U,I)||XI0.Token.isTokenRowDelimiter(U))break;q.push(U.token),$.advancePastToken(U)}return this.columnFormatter.format(q.join(""))}}OI0.NonQuotedColumnParser=DI0});var MC=L((FI0)=>{Object.defineProperty(FI0,"__esModule",{value:!0});FI0.QuotedColumnParser=void 0;var x11=rZ(),jU=c9();class NI0{constructor($){this.parserOptions=$,this.columnFormatter=new x11.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let I=$.cursor,{foundClosingQuote:q,col:U}=this.gatherDataBetweenQuotes($);if(!q){if($.advanceTo(I),!$.hasMoreData)throw Error(`Parse Error: missing closing: '${this.parserOptions.quote||""}' in line: at '${$.lineFromCursor.replace(/[\r\n]/g,"\\n'")}'`);return null}return this.checkForMalformedColumn($),U}gatherDataBetweenQuotes($){let{parserOptions:I}=this,q=!1,U=!1,Y=[],J=$.nextCharacterToken;for(;!U&&J!==null;J=$.nextCharacterToken){let Q=jU.Token.isTokenQuote(J,I);if(!q&&Q)q=!0;else if(q)if(jU.Token.isTokenEscapeCharacter(J,I)){$.advancePastToken(J);let K=$.nextCharacterToken;if(K!==null&&(jU.Token.isTokenQuote(K,I)||jU.Token.isTokenEscapeCharacter(K,I)))Y.push(K.token),J=K;else if(Q)U=!0;else Y.push(J.token)}else if(Q)U=!0;else Y.push(J.token);$.advancePastToken(J)}return{col:this.columnFormatter.format(Y.join("")),foundClosingQuote:U}}checkForMalformedColumn($){let{parserOptions:I}=this,{nextNonSpaceToken:q}=$;if(q){let U=jU.Token.isTokenDelimiter(q,I),Y=jU.Token.isTokenRowDelimiter(q);if(!(U||Y)){let J=$.lineFromCursor.substr(0,10).replace(/[\r\n]/g,"\\n'");throw Error(`Parse Error: expected: '${I.escapedDelimiter}' OR new line got: '${q.token}'. at '${J}`)}$.advanceToToken(q)}else if(!$.hasMoreData)$.advancePastLine()}}FI0.QuotedColumnParser=NI0});var TI0=L((gI0)=>{Object.defineProperty(gI0,"__esModule",{value:!0});gI0.ColumnParser=void 0;var k11=FC(),f11=MC(),n11=c9();class AI0{constructor($){this.parserOptions=$,this.quotedColumnParser=new f11.QuotedColumnParser($),this.nonQuotedColumnParser=new k11.NonQuotedColumnParser($)}parse($){let{nextNonSpaceToken:I}=$;if(I!==null&&n11.Token.isTokenQuote(I,this.parserOptions))return $.advanceToToken(I),this.quotedColumnParser.parse($);return this.nonQuotedColumnParser.parse($)}}gI0.ColumnParser=AI0});var AC=L((BU)=>{Object.defineProperty(BU,"__esModule",{value:!0});BU.ColumnFormatter=BU.QuotedColumnParser=BU.NonQuotedColumnParser=BU.ColumnParser=void 0;var i11=TI0();Object.defineProperty(BU,"ColumnParser",{enumerable:!0,get:function(){return i11.ColumnParser}});var b11=FC();Object.defineProperty(BU,"NonQuotedColumnParser",{enumerable:!0,get:function(){return b11.NonQuotedColumnParser}});var p11=MC();Object.defineProperty(BU,"QuotedColumnParser",{enumerable:!0,get:function(){re Line truncated
%s`,k,k,W,U);let h=W.type==="*"?kC:W.type==="?"?iC:"\\"+W.type;Y=!0,U=U.slice(0,W.reStart)+h+"\\("+k}if(P(),J)U+="\\\\";let g=S41[U.charAt(0)];for(let k=K.length-1;k>-1;k--){let h=K[k],f=U.slice(0,h.reStart),S=U.slice(h.reStart,h.reEnd-8),t=U.slice(h.reEnd),p=U.slice(h.reEnd-8,h.reEnd)+t,C=f.split(")").length,n=f.split("(").length-C,i=t;for(let E=0;E<n;E++)i=i.replace(/\)[+*?]?/,"");t=i;let J0=t===""&&I!==fC?"(?:$|\\/)":"";U=f+S+t+J0+p}if(U!==""&&Y)U="(?=.)"+U;if(g)U=N()+U;if(I===fC)return[U,Y];if(q.nocase&&!Y)Y=$.toUpperCase()!==$.toLowerCase();if(!Y)return u41($);let B=q.nocase?"i":"";try{return Object.assign(new RegExp("^"+U+"$",B),{_glob:$,_src:U})}catch(k){return new RegExp("$.")}}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let $=this.set;if(!$.length)return this.regexp=!1,this.regexp;let I=this.options,q=I.noglobstar?kC:I.dot?_41:h41,U=I.nocase?"i":"",Y=$.map((J)=>{return J=J.map((Q)=>typeof Q==="string"?k41(Q):Q===R6?R6:Q._src).reduce((Q,K)=>{if(!(Q[Q.length-1]===R6&&K===R6))Q.push(K);return Q},[]),J.forEach((Q,K)=>{if(Q!==R6||J[K-1]===R6)return;if(K===0)if(J.length>1)J[K+1]="(?:\\/|"+q+"\\/)?"+J[K+1];else J[K]=q;else if(K===J.length-1)J[K-1]+="(?:\\/|"+q+")?";else J[K-1]+="(?:\\/|\\/"+q+"\\/)"+J[K+1],J[K+1]=R6}),J.filter((Q)=>Q!==R6).join("/")}).join("|");if(Y="^(?:"+Y+")$",this.negate)Y="^(?!"+Y+").*$";try{this.regexp=new RegExp(Y,U)}catch(J){this.regexp=!1}return this.regexp}match($,I=this.partial){if(this.debug("match",$,this.pattern),this.comment)return!1;if(this.empty)return $==="";if($==="/"&&I)return!0;let q=this.options;if(nC.sep!=="/")$=$.split(nC.sep).join("/");$=$.split(Oq0),this.debug(this.pattern,"split",$);let U=this.set;this.debug(this.pattern,"set",U);let Y;for(let J=$.length-1;J>=0;J--)if(Y=$[J],Y)break;for(let J=0;J<U.length;J++){let Q=U[J],K=$;if(q.matchBase&&Q.length===1)K=[Y];if(this.matchOne(K,Q,I)){if(q.flipNegate)return!0;return!this.negate}}if(q.flipNegate)return!1;return this.negate}static defaults($){return J$.defaults($).Minimatch}}J$.Minimatch=y2});var Tq0=L((HB1,Pq0)=>{Pq0.exports=gq0;var cC=o("fs"),{EventEmitter:n41}=o("events"),{Minimatch:pC}=Fq0(),{resolve:i41}=o("path");function b41($,I){return new Promise((q,U)=>{cC.readdir($,{withFileTypes:!0},(Y,J)=>{if(Y)switch(Y.code){case"ENOTDIR":if(I)U(Y);else q([]);break;case"ENOTSUP":case"ENOENT":case"ENAMETOOLONG":case"UNKNOWN":q([]);break;case"ELOOP":default:U(Y);break}else q(J)})})}function Mq0($,I){return new Promise((q,U)=>{(I?cC.stat:cC.lstat)($,(J,Q)=>{if(J)switch(J.code){case"ENOENT":if(I)q(Mq0($,!1));else q(null);break;default:q(null);break}else q(Q)})})}async function*Aq0($,I,q,U,Y,J){let Q=await b41(I+$,J);for(let K of Q){let w=K.name;if(w===void 0)w=K,U=!0;let z=$+"/"+w,G=z.slice(1),H=I+"/"+G,V=null;if(U||q)V=await Mq0(H,q);if(!V&&K.name!==void 0)V=K;if(V===null)V={isDirectory:()=>!1};if(V.isDirectory()){if(!Y(G))yield{relative:G,absolute:H,stats:V},yield*Aq0(z,I,q,U,Y,!1)}else yield{relative:G,absolute:H,stats:V}}}async function*p41($,I,q,U){yield*Aq0("",$,I,q,U,!0)}function c41($){return{pattern:$.pattern,dot:!!$.dot,noglobstar:!!$.noglobstar,matchBase:!!$.matchBase,nocase:!!$.nocase,ignore:$.ignore,skip:$.skip,follow:!!$.follow,stat:!!$.stat,nodir:!!$.nodir,mark:!!$.mark,silent:!!$.silent,absolute:!!$.absolute}}class dC extends n41{constructor($,I,q){super();if(typeof I==="function")q=I,I=null;if(this.options=c41(I||{}),this.matchers=[],this.options.pattern){let U=Array.isArray(this.options.pattern)?this.options.pattern:[this.options.pattern];this.matchers=U.map((Y)=>new pC(Y,{dot:this.options.dot,noglobstar:this.options.noglobstar,matchBase:this.options.matchBase,nocase:this.options.nocase}))}if(this.ignoreMatchers=[],this.options.ignore){let U=Array.isArray(this.options.ignore)?this.options.ignore:[this.options.ignore];this.ignoreMatchers=U.map((Y)=>new pC(Y,{dot:!0}))}if(this.skipMatchers=[],this.options.skip){let U=Array.isArray(this.options.skip)?this.options.skip:[this.options.skip];this.skipMatchers=U.map((Y)=>new pC(Y,{dot:!0}))}if(this.iterator=p41(i41($||"."),this.options.follow,this.options.stat,this._shouldSkipDirectory.bind(this)),this.paused=!1,this.inactive=!1,this.aborted=!1,q)this._matches=[],this.on("match",(U)=>this._matches.push(this.options.absolute?U.absolute:U.relative)),this.on("error",(U)=>q(U)),this.on("end",()=>q(null,this._matches));setTimeout(()=>this._next(),0)}_shouldSkipDirectory($){return this.skipMatchers.some((I)=>I.match($))}_fileMatches($,I){let q=$+(I?"/":"");return(this.matchers.length===0||this.matchers.some((U)=>U.match(q)))&&!this.ignoreMatchers.some((U)=>U.match(q))&&(!this.options.nodir||!I)}_next(){if(!this.paused&&!this.aborted)this.iterator.next().then(($)=>{if(!$.done){let I=$.value.stats.isDirectory();if(this._fileMatches($.value.relative,I)){let q=$.value.relative,U=$.value.absolute;if(this.options.mark&&I)q+="/",U+="/";if(this.options.stat)this.emit("match",{relative:q,absolute:U,stat:$.value.stats});else this.emit("match",{relative:q,ab Line truncated
`,R);R=$0===-1?A.length:$0}else if(b!==-1&&A[R]==="/"&&A[R+1]==="*"){let $0=A.indexOf("*/",R);if($0!==-1)R=$0+2,b=A.indexOf("*/",R);else j+=A[R],R++}else j+=A[R],R++;return j}function l8(A){let j=H$(A.toString()),R=j.match(G$);if(!R)R=j.match(S$);if(!R)throw Error(`could not parse args in autoInject
`}static isTokenCarriageReturn($,I){return $.token===I.carriageReturn}static isTokenComment($,I){return I.supportsComments&&!!$&&$.token===I.comment}static isTokenEscapeCharacter($,I){return $.token===I.escapeChar}static isTokenQuote($,I){return $.token===I.quote}static isTokenDelimiter($,I){return $.token===I.delimiter}}z30.Token=Z30});var kj=F((F30)=>{Object.defineProperty(F30,"__esModule",{value:!0});F30.Scanner=void 0;var L30=r9(),ye0=/((?:\r\n)|\n|\r)/;class D30{constructor($){this.cursor=0,this.line=$.line,this.lineLength=this.line.length,this.parserOptions=$.parserOptions,this.hasMoreData=$.hasMoreData,this.cursor=$.cursor||0}get hasMoreCharacters(){return this.lineLength>this.cursor}get nextNonSpaceToken(){let{lineFromCursor:$}=this,I=this.parserOptions.NEXT_TOKEN_REGEXP;if($.search(I)===-1)return null;let U=I.exec($);if(U==null)return null;let Y=U[1],J=this.cursor+(U.index||0);return new L30.Token({token:Y,startCursor:J,endCursor:J+Y.length-1})}get nextCharacterToken(){let{cursor:$,lineLength:I}=this;if(I<=$)return null;return new L30.Token({token:this.line[$],startCursor:$,endCursor:$})}get lineFromCursor(){return this.line.substr(this.cursor)}advancePastLine(){let $=ye0.exec(this.lineFromCursor);if(!$){if(this.hasMoreData)return null;return this.cursor=this.lineLength,this}return this.cursor+=($.index||0)+$[0].length,this}advanceTo($){return this.cursor=$,this}advanceToToken($){return this.cursor=$.startCursor,this}advancePastToken($){return this.cursor=$.endCursor+1,this}truncateToCursor(){return this.line=this.lineFromCursor,this.lineLength=this.line.length,this.cursor=0,this}}F30.Scanner=D30});var iz=F((M30)=>{Object.defineProperty(M30,"__esModule",{value:!0});M30.ColumnFormatter=void 0;class N30{constructor($){if($.trim)this.format=(I)=>I.trim();else if($.ltrim)this.format=(I)=>I.trimLeft();else if($.rtrim)this.format=(I)=>I.trimRight();else this.format=(I)=>I}}M30.ColumnFormatter=N30});var fj=F((E30)=>{Object.defineProperty(E30,"__esModule",{value:!0});E30.NonQuotedColumnParser=void 0;var he0=iz(),P30=r9();class T30{constructor($){this.parserOptions=$,this.columnFormatter=new he0.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let{parserOptions:I}=this,U=[],Y=$.nextCharacterToken;for(;Y;Y=$.nextCharacterToken){if(P30.Token.isTokenDelimiter(Y,I)||P30.Token.isTokenRowDelimiter(Y))break;U.push(Y.token),$.advancePastToken(Y)}return this.columnFormatter.format(U.join(""))}}E30.NonQuotedColumnParser=T30});var ij=F((R30)=>{Object.defineProperty(R30,"__esModule",{value:!0});R30.QuotedColumnParser=void 0;var ue0=iz(),CY=r9();class v30{constructor($){this.parserOptions=$,this.columnFormatter=new ue0.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let I=$.cursor,{foundClosingQuote:U,col:Y}=this.gatherDataBetweenQuotes($);if(!U){if($.advanceTo(I),!$.hasMoreData)throw Error(`Parse Error: missing closing: '${this.parserOptions.quote||""}' in line: at '${$.lineFromCursor.replace(/[\r\n]/g,"\\n'")}'`);return null}return this.checkForMalformedColumn($),Y}gatherDataBetweenQuotes($){let{parserOptions:I}=this,U=!1,Y=!1,J=[],Q=$.nextCharacterToken;for(;!Y&&Q!==null;Q=$.nextCharacterToken){let K=CY.Token.isTokenQuote(Q,I);if(!U&&K)U=!0;else if(U)if(CY.Token.isTokenEscapeCharacter(Q,I)){$.advancePastToken(Q);let q=$.nextCharacterToken;if(q!==null&&(CY.Token.isTokenQuote(q,I)||CY.Token.isTokenEscapeCharacter(q,I)))J.push(q.token),Q=q;else if(K)Y=!0;else J.push(Q.token)}else if(K)Y=!0;else J.push(Q.token);$.advancePastToken(Q)}return{col:this.columnFormatter.format(J.join("")),foundClosingQuote:Y}}checkForMalformedColumn($){let{parserOptions:I}=this,{nextNonSpaceToken:U}=$;if(U){let Y=CY.Token.isTokenDelimiter(U,I),J=CY.Token.isTokenRowDelimiter(U);if(!(Y||J)){let Q=$.lineFromCursor.substr(0,10).replace(/[\r\n]/g,"\\n'");throw Error(`Parse Error: expected: '${I.escapedDelimiter}' OR new line got: '${U.token}'. at '${Q}`)}$.advanceToToken(U)}else if(!$.hasMoreData)$.advancePastLine()}}R30.QuotedColumnParser=v30});var g30=F((_30)=>{Object.defineProperty(_30,"__esModule",{value:!0});_30.ColumnParser=void 0;var xe0=fj(),ke0=ij(),fe0=r9();class j30{constructor($){this.parserOptions=$,this.quotedColumnParser=new ke0.QuotedColumnParser($),this.nonQuotedColumnParser=new xe0.NonQuotedColumnParser($)}parse($){let{nextNonSpaceToken:I}=$;if(I!==null&&fe0.Token.isTokenQuote(I,this.parserOptions))return $.advanceToToken(I),this.quotedColumnParser.parse($);return this.nonQuotedColumnParser.parse($)}}_30.ColumnParser=j30});var bj=F((jY)=>{Object.defineProperty(jY,"__esModule",{value:!0});jY.ColumnFormatter=jY.QuotedColumnParser=jY.NonQuotedColumnParser=jY.ColumnParser=void 0;var ie0=g30();Object.defineProperty(jY,"ColumnParser",{enumerable:!0,get:function(){return ie0.ColumnParser}});var be0=fj();Object.defineProperty(jY,"NonQuotedColumnParser",{enumerable:!0,get:function(){return be0.NonQuotedColumnParser}});var ne0=ij();Object.defineProperty(jY,"QuotedColumnParser",{enumerable:!0,get:function(){re Line truncated
%s`,k,k,Z,Y);let g=Z.type==="*"?Y_:Z.type==="?"?K_:"\\"+Z.type;J=!0,Y=Y.slice(0,Z.reStart)+g+"\\("+k}if(T(),Q)Y+="\\\\";let A=g01[Y.charAt(0)];for(let k=q.length-1;k>-1;k--){let g=q[k],f=Y.slice(0,g.reStart),C=Y.slice(g.reStart,g.reEnd-8),p=Y.slice(g.reEnd),n=Y.slice(g.reEnd-8,g.reEnd)+p,S=f.split(")").length,i=f.split("(").length-S,b=p;for(let B=0;B<i;B++)b=b.replace(/\)[+*?]?/,"");p=b;let Y0=p===""&&I!==J_?"(?:$|\\/)":"";Y=f+C+p+Y0+n}if(Y!==""&&J)Y="(?=.)"+Y;if(A)Y=O()+Y;if(I===J_)return[Y,J];if(U.nocase&&!J)J=$.toUpperCase()!==$.toLowerCase();if(!J)return h01($);let R=U.nocase?"i":"";try{return Object.assign(new RegExp("^"+Y+"$",R),{_glob:$,_src:Y})}catch(k){return new RegExp("$.")}}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let $=this.set;if(!$.length)return this.regexp=!1,this.regexp;let I=this.options,U=I.noglobstar?Y_:I.dot?_01:S01,Y=I.nocase?"i":"",J=$.map((Q)=>{return Q=Q.map((K)=>typeof K==="string"?x01(K):K===y6?y6:K._src).reduce((K,q)=>{if(!(K[K.length-1]===y6&&q===y6))K.push(q);return K},[]),Q.forEach((K,q)=>{if(K!==y6||Q[q-1]===y6)return;if(q===0)if(Q.length>1)Q[q+1]="(?:\\/|"+U+"\\/)?"+Q[q+1];else Q[q]=U;else if(q===Q.length-1)Q[q-1]+="(?:\\/|"+U+")?";else Q[q-1]+="(?:\\/|\\/"+U+"\\/)"+Q[q+1],Q[q+1]=y6}),Q.filter((K)=>K!==y6).join("/")}).join("|");if(J="^(?:"+J+")$",this.negate)J="^(?!"+J+").*$";try{this.regexp=new RegExp(J,Y)}catch(Q){this.regexp=!1}return this.regexp}match($,I=this.partial){if(this.debug("match",$,this.pattern),this.comment)return!1;if(this.empty)return $==="";if($==="/"&&I)return!0;let U=this.options;if(Q_.sep!=="/")$=$.split(Q_.sep).join("/");$=$.split(EI0),this.debug(this.pattern,"split",$);let Y=this.set;this.debug(this.pattern,"set",Y);let J;for(let Q=$.length-1;Q>=0;Q--)if(J=$[Q],J)break;for(let Q=0;Q<Y.length;Q++){let K=Y[Q],q=$;if(U.matchBase&&K.length===1)q=[J];if(this.matchOne(q,K,I)){if(U.flipNegate)return!0;return!this.negate}}if(U.flipNegate)return!1;return this.negate}static defaults($){return V$.defaults($).Minimatch}}V$.Minimatch=iK});var gI0=F((bv1,SI0)=>{SI0.exports=_I0;var G_=a("fs"),{EventEmitter:f01}=a("events"),{Minimatch:H_}=RI0(),{resolve:i01}=a("path");function b01($,I){return new Promise((U,Y)=>{G_.readdir($,{withFileTypes:!0},(J,Q)=>{if(J)switch(J.code){case"ENOTDIR":if(I)Y(J);else U([]);break;case"ENOTSUP":case"ENOENT":case"ENAMETOOLONG":case"UNKNOWN":U([]);break;case"ELOOP":default:Y(J);break}else U(Q)})})}function CI0($,I){return new Promise((U,Y)=>{(I?G_.stat:G_.lstat)($,(Q,K)=>{if(Q)switch(Q.code){case"ENOENT":if(I)U(CI0($,!1));else U(null);break;default:U(null);break}else U(K)})})}async function*jI0($,I,U,Y,J,Q){let K=await b01(I+$,Q);for(let q of K){let H=q.name;if(H===void 0)H=q,Y=!0;let G=$+"/"+H,W=G.slice(1),w=I+"/"+W,V=null;if(Y||U)V=await CI0(w,U);if(!V&&q.name!==void 0)V=q;if(V===null)V={isDirectory:()=>!1};if(V.isDirectory()){if(!J(W))yield{relative:W,absolute:w,stats:V},yield*jI0(G,I,U,Y,J,!1)}else yield{relative:W,absolute:w,stats:V}}}async function*n01($,I,U,Y){yield*jI0("",$,I,U,Y,!0)}function p01($){return{pattern:$.pattern,dot:!!$.dot,noglobstar:!!$.noglobstar,matchBase:!!$.matchBase,nocase:!!$.nocase,ignore:$.ignore,skip:$.skip,follow:!!$.follow,stat:!!$.stat,nodir:!!$.nodir,mark:!!$.mark,silent:!!$.silent,absolute:!!$.absolute}}class W_ extends f01{constructor($,I,U){super();if(typeof I==="function")U=I,I=null;if(this.options=p01(I||{}),this.matchers=[],this.options.pattern){let Y=Array.isArray(this.options.pattern)?this.options.pattern:[this.options.pattern];this.matchers=Y.map((J)=>new H_(J,{dot:this.options.dot,noglobstar:this.options.noglobstar,matchBase:this.options.matchBase,nocase:this.options.nocase}))}if(this.ignoreMatchers=[],this.options.ignore){let Y=Array.isArray(this.options.ignore)?this.options.ignore:[this.options.ignore];this.ignoreMatchers=Y.map((J)=>new H_(J,{dot:!0}))}if(this.skipMatchers=[],this.options.skip){let Y=Array.isArray(this.options.skip)?this.options.skip:[this.options.skip];this.skipMatchers=Y.map((J)=>new H_(J,{dot:!0}))}if(this.iterator=n01(i01($||"."),this.options.follow,this.options.stat,this._shouldSkipDirectory.bind(this)),this.paused=!1,this.inactive=!1,this.aborted=!1,U)this._matches=[],this.on("match",(Y)=>this._matches.push(this.options.absolute?Y.absolute:Y.relative)),this.on("error",(Y)=>U(Y)),this.on("end",()=>U(null,this._matches));setTimeout(()=>this._next(),0)}_shouldSkipDirectory($){return this.skipMatchers.some((I)=>I.match($))}_fileMatches($,I){let U=$+(I?"/":"");return(this.matchers.length===0||this.matchers.some((Y)=>Y.match(U)))&&!this.ignoreMatchers.some((Y)=>Y.match(U))&&(!this.options.nodir||!I)}_next(){if(!this.paused&&!this.aborted)this.iterator.next().then(($)=>{if(!$.done){let I=$.value.stats.isDirectory();if(this._fileMatches($.value.relative,I)){let U=$.value.relative,Y=$.value.absolute;if(this.options.mark&&I)U+="/",Y+="/";if(this.options.stat)this.emit("match",{relative:U,absolute:Y,stat:$.value.stats});else this.emit("match",{relative:U,ab Line truncated
`,y);y=I0===-1?P.length:I0}else if(d!==-1&&P[y]==="/"&&P[y+1]==="*"){let I0=P.indexOf("*/",y);if(I0!==-1)y=I0+2,d=P.indexOf("*/",y);else v+=P[y],y++}else v+=P[y],y++;return v}function s8(P){let v=P6(P.toString()),y=v.match(A6);if(!y)y=v.match(f6);if(!y)throw Error(`could not parse args in autoInject
Source:
`+j);let[,b]=R;return b.replace(/\s/g,"").split(d8).map(($0)=>$0.replace(y$,"").trim())}function a6(A,j){var R={};return Object.keys(A).forEach((b)=>{var $0=A[b],q0,Q0=W($0),w0=!Q0&&$0.length===1||Q0&&$0.length===0;if(Array.isArray($0))q0=[...$0],$0=q0.pop(),R[b]=q0.concat(q0.length>0?V0:$0);else if(w0)R[b]=$0;else{if(q0=l8($0),$0.length===0&&!Q0&&q0.length===0)throw Error("autoInject task functions require explicit parameters.");if(!Q0)q0.pop();R[b]=q0.concat(V0)}function V0(E0,q1){var V1=q0.map((Q1)=>E0[Q1]);V1.push(q1),O($0)(...V1)}}),R4(R,j)}class O7{constructor(){this.head=this.tail=null,this.length=0}removeLink(A){if(A.prev)A.prev.next=A.next;else this.head=A.next;if(A.next)A.next.prev=A.prev;else this.tail=A.prev;return A.prev=A.next=null,this.length-=1,A}empty(){while(this.head)this.shift();return this}insertAfter(A,j){if(j.prev=A,j.next=A.next,A.next)A.next.prev=j;else this.tail=j;A.next=j,this.length+=1}insertBefore(A,j){if(j.prev=A.prev,j.next=A,A.prev)A.prev.next=j;else this.head=j;A.prev=j,this.length+=1}unshift(A){if(this.head)this.insertBefore(this.head,A);else s6(this,A)}push(A){if(this.tail)this.insertAfter(this.tail,A);else s6(this,A)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){var A=this.head;while(A)yield A.data,A=A.next}remove(A){var j=this.head;while(j){var{next:R}=j;if(A(j))this.removeLink(j);j=R}return this}}function s6(A,j){A.length=1,A.head=A.tail=j}function d5(A,j,R){if(j==null)j=1;else if(j===0)throw RangeError("Concurrency must not be zero");var b=O(A),$0=0,q0=[];let Q0={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};function w0(h0,P0){Q0[h0].push(P0)}function V0(h0,P0){let S0=(...K1)=>{E0(h0,S0),P0(...K1)};Q0[h0].push(S0)}function E0(h0,P0){if(!h0)return Object.keys(Q0).forEach((S0)=>Q0[S0]=[]);if(!P0)return Q0[h0]=[];Q0[h0]=Q0[h0].filter((S0)=>S0!==P0)}function q1(h0,...P0){Q0[h0].forEach((S0)=>S0(...P0))}var V1=!1;function Q1(h0,P0,S0,K1){if(K1!=null&&typeof K1!=="function")throw Error("task callback must be a function");W1.started=!0;var I4,k4;function W$(N7,...vY){if(N7)return S0?k4(N7):I4();if(vY.length<=1)return I4(vY[0]);I4(vY)}var JI=W1._createTaskItem(h0,S0?W$:K1||W$);if(P0)W1._tasks.unshift(JI);else W1._tasks.push(JI);if(!V1)V1=!0,z(()=>{V1=!1,W1.process()});if(S0||!K1)return new Promise((N7,vY)=>{I4=N7,k4=vY})}function V$(h0){return function(P0,...S0){$0-=1;for(var K1=0,I4=h0.length;K1<I4;K1++){var k4=h0[K1],W$=q0.indexOf(k4);if(W$===0)q0.shift();else if(W$>0)q0.splice(W$,1);if(k4.callback(P0,...S0),P0!=null)q1("error",P0,k4.data)}if($0<=W1.concurrency-W1.buffer)q1("unsaturated");if(W1.idle())q1("drain");W1.process()}}function YI(h0){if(h0.length===0&&W1.idle())return z(()=>q1("drain")),!0;return!1}let L7=(h0)=>(P0)=>{if(!P0)return new Promise((S0,K1)=>{V0(h0,(I4,k4)=>{if(I4)return K1(I4);S0(k4)})});E0(h0),w0(h0,P0)};var BY=!1,W1={_tasks:new O7,_createTaskItem(h0,P0){return{data:h0,callback:P0}},*[Symbol.iterator](){yield*W1._tasks[Symbol.iterator]()},concurrency:j,payload:R,buffer:j/4,started:!1,paused:!1,push(h0,P0){if(Array.isArray(h0)){if(YI(h0))return;return h0.map((S0)=>Q1(S0,!1,!1,P0))}return Q1(h0,!1,!1,P0)},pushAsync(h0,P0){if(Array.isArray(h0)){if(YI(h0))return;return h0.map((S0)=>Q1(S0,!1,!0,P0))}return Q1(h0,!1,!0,P0)},kill(){E0(),W1._tasks.empty()},unshift(h0,P0){if(Array.isArray(h0)){if(YI(h0))return;return h0.map((S0)=>Q1(S0,!0,!1,P0))}return Q1(h0,!0,!1,P0)},unshiftAsync(h0,P0){if(Array.isArray(h0)){if(YI(h0))return;return h0.map((S0)=>Q1(S0,!0,!0,P0))}return Q1(h0,!0,!0,P0)},remove(h0){W1._tasks.remove(h0)},process(){if(BY)return;BY=!0;while(!W1.paused&&$0<W1.concurrency&&W1._tasks.length){var h0=[],P0=[],S0=W1._tasks.length;if(W1.payload)S0=Math.min(S0,W1.payload);for(var K1=0;K1<S0;K1++){var I4=W1._tasks.shift();h0.push(I4),q0.push(I4),P0.push(I4.data)}if($0+=1,W1._tasks.length===0)q1("empty");if($0===W1.concurrency)q1("saturated");var k4=C(V$(h0));b(P0,k4)}BY=!1},length(){return W1._tasks.length},running(){return $0},workersList(){return q0},idle(){return W1._tasks.length+$0===0},pause(){W1.paused=!0},resume(){if(W1.paused===!1)return;W1.paused=!1,z(W1.process)}};return Object.defineProperties(W1,{saturated:{writable:!1,value:L7("saturated")},unsaturated:{writable:!1,value:L7("unsaturated")},empty:{writable:!1,value:L7("empty")},drain:{writable:!1,value:L7("drain")},error:{writable:!1,value:L7("error")}}),W1}function g0(A,j){return d5(A,1,j)}function r(A,j,R){return d5(A,j,R)}function F(A,j,R,b){b=k(b);var $0=O(R);return l0(A,(q0,Q0,w0)=>{$0(j,q0,(V0,E0)=>{j=E0,w0(V0)})},(q0)=>b(q0,j))}var M=N(F,4);function v(...A){var j=A.map(O);return function(...R){var b=this,$0=R[R.length-1];if(typeof $0=="function")R.pop();else $0=J4();return M(j,R,(q0,Q0,w0)=>{Q0.apply(b,q0.concat((V0,...E0)=>{w0(V0,E0)}))},(q0,Q0)=>$0(q0,...Q0)),$0[C1]}}function y(...A){return v(...A.reverse())}function s(A,j,R,b){return P(i(j),A,R,b)}var c=N(s,4);function e( Line truncated
GFS4: `),console.error($)};if(!H4[U6]){if(lC=global[U6]||[],uq0(H4,lC),H4.close=function($){function I(q,U){return $.call(H4,q,function(Y){if(!Y)yq0();if(typeof U==="function")U.apply(this,arguments)})}return Object.defineProperty(I,JX,{value:$}),I}(H4.close),H4.closeSync=function($){function I(q){$.apply(H4,arguments),yq0()}return Object.defineProperty(I,JX,{value:$}),I}(H4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){P3(H4[U6]),o("assert").equal(H4[U6].length,0)})}var lC;if(!global[U6])uq0(global,H4[U6]);rC.exports=mC(e41(H4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!H4.__patched)rC.exports=mC(H4),H4.__patched=!0;function mC($){a41($),$.gracefulify=mC,$.createReadStream=B,$.createWriteStream=k;var I=$.readFile;$.readFile=q;function q(S,t,p){if(typeof t==="function")p=t,t=null;return C(S,t,p);function C(n,i,J0,E){return I(n,i,function(u){if(u&&(u.code==="EMFILE"||u.code==="ENFILE"))CU([C,[n,i,J0],u,E||Date.now(),Date.now()]);else if(typeof J0==="function")J0.apply(this,arguments)})}}var U=$.writeFile;$.writeFile=Y;function Y(S,t,p,C){if(typeof p==="function")C=p,p=null;return n(S,t,p,C);function n(i,J0,E,u,d){return U(i,J0,E,function(a){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))CU([n,[i,J0,E,u],a,d||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var J=$.appendFile;if(J)$.appendFile=Q;function Q(S,t,p,C){if(typeof p==="function")C=p,p=null;return n(S,t,p,C);function n(i,J0,E,u,d){return J(i,J0,E,function(a){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))CU([n,[i,J0,E,u],a,d||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var K=$.copyFile;if(K)$.copyFile=w;function w(S,t,p,C){if(typeof p==="function")C=p,p=0;return n(S,t,p,C);function n(i,J0,E,u,d){return K(i,J0,E,function(a){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))CU([n,[i,J0,E,u],a,d||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var z=$.readdir;$.readdir=H;var G=/^v[0-5]\./;function H(S,t,p){if(typeof t==="function")p=t,t=null;var C=G.test(process.version)?function(J0,E,u,d){return z(J0,n(J0,E,u,d))}:function(J0,E,u,d){return z(J0,E,n(J0,E,u,d))};return C(S,t,p);function n(i,J0,E,u){return function(d,a){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))CU([C,[i,J0,E],d,u||Date.now(),Date.now()]);else{if(a&&a.sort)a.sort();if(typeof E==="function")E.call(this,d,a)}}}}if(process.version.substr(0,4)==="v0.8"){var V=s41($);N=V.ReadStream,P=V.WriteStream}var W=$.ReadStream;if(W)N.prototype=Object.create(W.prototype),N.prototype.open=T;var X=$.WriteStream;if(X)P.prototype=Object.create(X.prototype),P.prototype.open=g;Object.defineProperty($,"ReadStream",{get:function(){return N},set:function(S){N=S},enumerable:!0,configurable:!0}),Object.defineProperty($,"WriteStream",{get:function(){return P},set:function(S){P=S},enumerable:!0,configurable:!0});var D=N;Object.defineProperty($,"FileReadStream",{get:function(){return D},set:function(S){D=S},enumerable:!0,configurable:!0});var O=P;Object.defineProperty($,"FileWriteStream",{get:function(){return O},set:function(S){O=S},enumerable:!0,configurable:!0});function N(S,t){if(this instanceof N)return W.apply(this,arguments),this;else return N.apply(Object.create(N.prototype),arguments)}function T(){var S=this;f(S.path,S.flags,S.mode,function(t,p){if(t){if(S.autoClose)S.destroy();S.emit("error",t)}else S.fd=p,S.emit("open",p),S.read()})}function P(S,t){if(this instanceof P)return X.apply(this,arguments),this;else return P.apply(Object.create(P.prototype),arguments)}function g(){var S=this;f(S.path,S.flags,S.mode,function(t,p){if(t)S.destroy(),S.emit("error",t);else S.fd=p,S.emit("open",p)})}function B(S,t){return new $.ReadStream(S,t)}function k(S,t){return new $.WriteStream(S,t)}var h=$.open;$.open=f;function f(S,t,p,C){if(typeof p==="function")C=p,p=null;return n(S,t,p,C);function n(i,J0,E,u,d){return h(i,J0,E,function(a,K0){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))CU([n,[i,J0,E,u],a,d||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}return $}function CU($){P3("ENQUEUE",$[0].name,$[1]),H4[U6].push($),oC()}var YX;function yq0(){var $=Date.now();for(var I=0;I<H4[U6].length;++I)if(H4[U6][I].length>2)H4[U6][I][3]=$,H4[U6][I][4]=$;oC()}function oC(){if(clearTimeout(YX),YX=void 0,H4[U6].length===0)return;var $=H4[U6].shift(),I=$[0],q=$[1],U=$[2],Y=$[3],J=$[4];if(Y===void 0)P3("RETRY",I.name,q),I.apply(null,q);else if(Date.now()-Y>=60000){P3("TIMEOUT",I.name,q);var Q=q.pop();if(typeof Q==="function")Q.call(null,U)}else{var K=Date.now()-J,w=Math.max(J-Y,1),z=Math.min(w*1.2,100);if(K>=z)P3("RETRY",I.name,q),I.apply(null,q.concat([Y]));else H4[U6].push($)}if(YX===void 0)YX=setTimeout(oC,0)}});var kq0=L((DB1,tC)=>{function I61($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var xq0=M4().Buffer,u2=o("util");function q61($,I,q){$.copy(I,q)}tC.exports=function(){function $(){I61(this,$),this.head=null,this.tail=null,th Line truncated
`+v);let[,d]=y;return d.replace(/\s/g,"").split(F$).map((I0)=>I0.replace(i6,"").trim())}function Y$(P,v){var y={};return Object.keys(P).forEach((d)=>{var I0=P[d],J0,H0=Z(I0),G0=!H0&&I0.length===1||H0&&I0.length===0;if(Array.isArray(I0))J0=[...I0],I0=J0.pop(),y[d]=J0.concat(J0.length>0?z0:I0);else if(G0)y[d]=I0;else{if(J0=s8(I0),I0.length===0&&!H0&&J0.length===0)throw Error("autoInject task functions require explicit parameters.");if(!H0)J0.pop();y[d]=J0.concat(z0)}function z0(_0,H1){var D1=J0.map((w1)=>_0[w1]);D1.push(H1),D(I0)(...D1)}}),Z4(y,v)}class T7{constructor(){this.head=this.tail=null,this.length=0}removeLink(P){if(P.prev)P.prev.next=P.next;else this.head=P.next;if(P.next)P.next.prev=P.prev;else this.tail=P.prev;return P.prev=P.next=null,this.length-=1,P}empty(){while(this.head)this.shift();return this}insertAfter(P,v){if(v.prev=P,v.next=P.next,P.next)P.next.prev=v;else this.tail=v;P.next=v,this.length+=1}insertBefore(P,v){if(v.prev=P.prev,v.next=P,P.prev)P.prev.next=v;else this.head=v;P.prev=v,this.length+=1}unshift(P){if(this.head)this.insertBefore(this.head,P);else J$(this,P)}push(P){if(this.tail)this.insertAfter(this.tail,P);else J$(this,P)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){var P=this.head;while(P)yield P.data,P=P.next}remove(P){var v=this.head;while(v){var{next:y}=v;if(P(v))this.removeLink(v);v=y}return this}}function J$(P,v){P.length=1,P.head=P.tail=v}function t5(P,v,y){if(v==null)v=1;else if(v===0)throw RangeError("Concurrency must not be zero");var d=D(P),I0=0,J0=[];let H0={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};function G0(u0,C0){H0[u0].push(C0)}function z0(u0,C0){let x0=(...V1)=>{_0(u0,x0),C0(...V1)};H0[u0].push(x0)}function _0(u0,C0){if(!u0)return Object.keys(H0).forEach((x0)=>H0[x0]=[]);if(!C0)return H0[u0]=[];H0[u0]=H0[u0].filter((x0)=>x0!==C0)}function H1(u0,...C0){H0[u0].forEach((x0)=>x0(...C0))}var D1=!1;function w1(u0,C0,x0,V1){if(V1!=null&&typeof V1!=="function")throw Error("task callback must be a function");F1.started=!0;var Q4,f4;function N$(B7,...iJ){if(B7)return x0?f4(B7):Q4();if(iJ.length<=1)return Q4(iJ[0]);Q4(iJ)}var FI=F1._createTaskItem(u0,x0?N$:V1||N$);if(C0)F1._tasks.unshift(FI);else F1._tasks.push(FI);if(!D1)D1=!0,G(()=>{D1=!1,F1.process()});if(x0||!V1)return new Promise((B7,iJ)=>{Q4=B7,f4=iJ})}function O$(u0){return function(C0,...x0){I0-=1;for(var V1=0,Q4=u0.length;V1<Q4;V1++){var f4=u0[V1],N$=J0.indexOf(f4);if(N$===0)J0.shift();else if(N$>0)J0.splice(N$,1);if(f4.callback(C0,...x0),C0!=null)H1("error",C0,f4.data)}if(I0<=F1.concurrency-F1.buffer)H1("unsaturated");if(F1.idle())H1("drain");F1.process()}}function DI(u0){if(u0.length===0&&F1.idle())return G(()=>H1("drain")),!0;return!1}let E7=(u0)=>(C0)=>{if(!C0)return new Promise((x0,V1)=>{z0(u0,(Q4,f4)=>{if(Q4)return V1(Q4);x0(f4)})});_0(u0),G0(u0,C0)};var fJ=!1,F1={_tasks:new T7,_createTaskItem(u0,C0){return{data:u0,callback:C0}},*[Symbol.iterator](){yield*F1._tasks[Symbol.iterator]()},concurrency:v,payload:y,buffer:v/4,started:!1,paused:!1,push(u0,C0){if(Array.isArray(u0)){if(DI(u0))return;return u0.map((x0)=>w1(x0,!1,!1,C0))}return w1(u0,!1,!1,C0)},pushAsync(u0,C0){if(Array.isArray(u0)){if(DI(u0))return;return u0.map((x0)=>w1(x0,!1,!0,C0))}return w1(u0,!1,!0,C0)},kill(){_0(),F1._tasks.empty()},unshift(u0,C0){if(Array.isArray(u0)){if(DI(u0))return;return u0.map((x0)=>w1(x0,!0,!1,C0))}return w1(u0,!0,!1,C0)},unshiftAsync(u0,C0){if(Array.isArray(u0)){if(DI(u0))return;return u0.map((x0)=>w1(x0,!0,!0,C0))}return w1(u0,!0,!0,C0)},remove(u0){F1._tasks.remove(u0)},process(){if(fJ)return;fJ=!0;while(!F1.paused&&I0<F1.concurrency&&F1._tasks.length){var u0=[],C0=[],x0=F1._tasks.length;if(F1.payload)x0=Math.min(x0,F1.payload);for(var V1=0;V1<x0;V1++){var Q4=F1._tasks.shift();u0.push(Q4),J0.push(Q4),C0.push(Q4.data)}if(I0+=1,F1._tasks.length===0)H1("empty");if(I0===F1.concurrency)H1("saturated");var f4=S(O$(u0));d(C0,f4)}fJ=!1},length(){return F1._tasks.length},running(){return I0},workersList(){return J0},idle(){return F1._tasks.length+I0===0},pause(){F1.paused=!0},resume(){if(F1.paused===!1)return;F1.paused=!1,G(F1.process)}};return Object.defineProperties(F1,{saturated:{writable:!1,value:E7("saturated")},unsaturated:{writable:!1,value:E7("unsaturated")},empty:{writable:!1,value:E7("empty")},drain:{writable:!1,value:E7("drain")},error:{writable:!1,value:E7("error")}}),F1}function v0(P,v){return t5(P,1,v)}function s(P,v,y){return t5(P,v,y)}function N(P,v,y,d){d=k(d);var I0=D(y);return k0(P,(J0,H0,G0)=>{I0(v,J0,(z0,_0)=>{v=_0,G0(z0)})},(J0)=>d(J0,v))}var M=O(N,4);function j(...P){var v=P.map(D);return function(...y){var d=this,I0=y[y.length-1];if(typeof I0=="function")y.pop();else I0=g1();return M(v,y,(J0,H0,G0)=>{H0.apply(d,J0.concat((z0,..._0)=>{G0(z0,_0)}))},(J0,H0)=>I0(J0,...H0)),I0[y0]}}function u(...P){return j(...P.reverse())}function e(P,v,y,d){return T(b(v),P,y,d)}var m=O(e,4);function $0 Line truncated
GFS4: `),console.error($)};if(!V4[J6]){if(w_=global[J6]||[],cI0(V4,w_),V4.close=function($){function I(U,Y){return $.call(V4,U,function(J){if(!J)pI0();if(typeof Y==="function")Y.apply(this,arguments)})}return Object.defineProperty(I,tz,{value:$}),I}(V4.close),V4.closeSync=function($){function I(U){$.apply(V4,arguments),pI0()}return Object.defineProperty(I,tz,{value:$}),I}(V4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){v3(V4[J6]),a("assert").equal(V4[J6].length,0)})}var w_;if(!global[J6])cI0(global,V4[J6]);z_.exports=V_(s01(V4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!V4.__patched)z_.exports=V_(V4),V4.__patched=!0;function V_($){t01($),$.gracefulify=V_,$.createReadStream=R,$.createWriteStream=k;var I=$.readFile;$.readFile=U;function U(C,p,n){if(typeof p==="function")n=p,p=null;return S(C,p,n);function S(i,b,Y0,B){return I(i,b,function(x){if(x&&(x.code==="EMFILE"||x.code==="ENFILE"))gY([S,[i,b,Y0],x,B||Date.now(),Date.now()]);else if(typeof Y0==="function")Y0.apply(this,arguments)})}}var Y=$.writeFile;$.writeFile=J;function J(C,p,n,S){if(typeof n==="function")S=n,n=null;return i(C,p,n,S);function i(b,Y0,B,x,c){return Y(b,Y0,B,function(r){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))gY([i,[b,Y0,B,x],r,c||Date.now(),Date.now()]);else if(typeof x==="function")x.apply(this,arguments)})}}var Q=$.appendFile;if(Q)$.appendFile=K;function K(C,p,n,S){if(typeof n==="function")S=n,n=null;return i(C,p,n,S);function i(b,Y0,B,x,c){return Q(b,Y0,B,function(r){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))gY([i,[b,Y0,B,x],r,c||Date.now(),Date.now()]);else if(typeof x==="function")x.apply(this,arguments)})}}var q=$.copyFile;if(q)$.copyFile=H;function H(C,p,n,S){if(typeof n==="function")S=n,n=0;return i(C,p,n,S);function i(b,Y0,B,x,c){return q(b,Y0,B,function(r){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))gY([i,[b,Y0,B,x],r,c||Date.now(),Date.now()]);else if(typeof x==="function")x.apply(this,arguments)})}}var G=$.readdir;$.readdir=w;var W=/^v[0-5]\./;function w(C,p,n){if(typeof p==="function")n=p,p=null;var S=W.test(process.version)?function(Y0,B,x,c){return G(Y0,i(Y0,B,x,c))}:function(Y0,B,x,c){return G(Y0,B,i(Y0,B,x,c))};return S(C,p,n);function i(b,Y0,B,x){return function(c,r){if(c&&(c.code==="EMFILE"||c.code==="ENFILE"))gY([S,[b,Y0,B],c,x||Date.now(),Date.now()]);else{if(r&&r.sort)r.sort();if(typeof B==="function")B.call(this,c,r)}}}}if(process.version.substr(0,4)==="v0.8"){var V=a01($);O=V.ReadStream,T=V.WriteStream}var Z=$.ReadStream;if(Z)O.prototype=Object.create(Z.prototype),O.prototype.open=E;var X=$.WriteStream;if(X)T.prototype=Object.create(X.prototype),T.prototype.open=A;Object.defineProperty($,"ReadStream",{get:function(){return O},set:function(C){O=C},enumerable:!0,configurable:!0}),Object.defineProperty($,"WriteStream",{get:function(){return T},set:function(C){T=C},enumerable:!0,configurable:!0});var L=O;Object.defineProperty($,"FileReadStream",{get:function(){return L},set:function(C){L=C},enumerable:!0,configurable:!0});var D=T;Object.defineProperty($,"FileWriteStream",{get:function(){return D},set:function(C){D=C},enumerable:!0,configurable:!0});function O(C,p){if(this instanceof O)return Z.apply(this,arguments),this;else return O.apply(Object.create(O.prototype),arguments)}function E(){var C=this;f(C.path,C.flags,C.mode,function(p,n){if(p){if(C.autoClose)C.destroy();C.emit("error",p)}else C.fd=n,C.emit("open",n),C.read()})}function T(C,p){if(this instanceof T)return X.apply(this,arguments),this;else return T.apply(Object.create(T.prototype),arguments)}function A(){var C=this;f(C.path,C.flags,C.mode,function(p,n){if(p)C.destroy(),C.emit("error",p);else C.fd=n,C.emit("open",n)})}function R(C,p){return new $.ReadStream(C,p)}function k(C,p){return new $.WriteStream(C,p)}var g=$.open;$.open=f;function f(C,p,n,S){if(typeof n==="function")S=n,n=null;return i(C,p,n,S);function i(b,Y0,B,x,c){return g(b,Y0,B,function(r,Q0){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))gY([i,[b,Y0,B,x],r,c||Date.now(),Date.now()]);else if(typeof x==="function")x.apply(this,arguments)})}}return $}function gY($){v3("ENQUEUE",$[0].name,$[1]),V4[J6].push($),Z_()}var rz;function pI0(){var $=Date.now();for(var I=0;I<V4[J6].length;++I)if(V4[J6][I].length>2)V4[J6][I][3]=$,V4[J6][I][4]=$;Z_()}function Z_(){if(clearTimeout(rz),rz=void 0,V4[J6].length===0)return;var $=V4[J6].shift(),I=$[0],U=$[1],Y=$[2],J=$[3],Q=$[4];if(J===void 0)v3("RETRY",I.name,U),I.apply(null,U);else if(Date.now()-J>=60000){v3("TIMEOUT",I.name,U);var K=U.pop();if(typeof K==="function")K.call(null,Y)}else{var q=Date.now()-Q,H=Math.max(Q-J,1),G=Math.min(H*1.2,100);if(q>=G)v3("RETRY",I.name,U),I.apply(null,U.concat([J]));else V4[J6].push($)}if(rz===void 0)rz=setTimeout(Z_,0)}});var mI0=F((mv1,X_)=>{function $11($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var dI0=A4().Buffer,bK=a("util");function I11($,I,U){$.copy(I,U)}X_.exports=function(){function $(){$11(this,$),this.head=null,this.tail=null,th Line truncated
* normalize-path <https://github.com/jonschlinkert/normalize-path>
*
* Copyright (c) 2014-2018, Jon Schlinkert.
* Released under the MIT License.
*/PU0.exports=function($,I){if(typeof $!=="string")throw TypeError("expected path to be a string");if($==="\\"||$==="/")return"/";var q=$.length;if(q<=1)return $;var U="";if(q>4&&$[3]==="\\"){var Y=$[2];if((Y==="?"||Y===".")&&$.slice(0,2)==="\\\\")$=$.slice(2),U="//"}var J=$.split(/[/\\]+/);if(I!==!1&&J[J.length-1]==="")J.pop();return U+J.join("/")}});var D_=L((BB1,CU0)=>{var EU0=9007199254740991,w$1="[object Arguments]",z$1="[object Function]",G$1="[object GeneratorFunction]",H$1=/^(?:0|[1-9]\d*)$/;function jU0($,I,q){switch(q.length){case 0:return $.call(I);case 1:return $.call(I,q[0]);case 2:return $.call(I,q[0],q[1]);case 3:return $.call(I,q[0],q[1],q[2])}return $.apply(I,q)}function V$1($,I){var q=-1,U=Array($);while(++q<$)U[q]=I(q);return U}var d2=Object.prototype,l2=d2.hasOwnProperty,BU0=d2.toString,W$1=d2.propertyIsEnumerable,TU0=Math.max;function Z$1($,I){var q=P$1($)||g$1($)?V$1($.length,String):[],U=q.length,Y=!!U;for(var J in $)if((I||l2.call($,J))&&!(Y&&(J=="length"||RU0(J,U))))q.push(J);return q}function X$1($,I,q,U){if($===void 0||W_($,d2[q])&&!l2.call(U,q))return I;return $}function D$1($,I,q){var U=$[I];if(!(l2.call($,I)&&W_(U,q))||q===void 0&&!(I in $))$[I]=q}function O$1($){if(!X_($))return A$1($);var I=M$1($),q=[];for(var U in $)if(!(U=="constructor"&&(I||!l2.call($,U))))q.push(U);return q}function vU0($,I){return I=TU0(I===void 0?$.length-1:I,0),function(){var q=arguments,U=-1,Y=TU0(q.length-I,0),J=Array(Y);while(++U<Y)J[U]=q[I+U];U=-1;var Q=Array(I+1);while(++U<I)Q[U]=q[U];return Q[I]=J,jU0($,this,Q)}}function L$1($,I,q,U){q||(q={});var Y=-1,J=I.length;while(++Y<J){var Q=I[Y],K=U?U(q[Q],$[Q],Q,q,$):void 0;D$1(q,Q,K===void 0?$[Q]:K)}return q}function N$1($){return vU0(function(I,q){var U=-1,Y=q.length,J=Y>1?q[Y-1]:void 0,Q=Y>2?q[2]:void 0;if(J=$.length>3&&typeof J=="function"?(Y--,J):void 0,Q&&F$1(q[0],q[1],Q))J=Y<3?void 0:J,Y=1;I=Object(I);while(++U<Y){var K=q[U];if(K)$(I,K,U,J)}return I})}function RU0($,I){return I=I==null?EU0:I,!!I&&(typeof $=="number"||H$1.test($))&&($>-1&&$%1==0&&$<I)}function F$1($,I,q){if(!X_(q))return!1;var U=typeof I;if(U=="number"?Z_(q)&&RU0(I,q.length):U=="string"&&(I in q))return W_(q[I],$);return!1}function M$1($){var I=$&&$.constructor,q=typeof I=="function"&&I.prototype||d2;return $===q}function A$1($){var I=[];if($!=null)for(var q in Object($))I.push(q);return I}function W_($,I){return $===I||$!==$&&I!==I}function g$1($){return T$1($)&&l2.call($,"callee")&&(!W$1.call($,"callee")||BU0.call($)==w$1)}var P$1=Array.isArray;function Z_($){return $!=null&&j$1($.length)&&!E$1($)}function T$1($){return B$1($)&&Z_($)}function E$1($){var I=X_($)?BU0.call($):"";return I==z$1||I==G$1}function j$1($){return typeof $=="number"&&$>-1&&$%1==0&&$<=EU0}function X_($){var I=typeof $;return!!$&&(I=="object"||I=="function")}function B$1($){return!!$&&typeof $=="object"}var v$1=N$1(function($,I,q,U){L$1(I,C$1(I),$,U)}),R$1=vU0(function($){return $.push(void 0,X$1),jU0(v$1,void 0,$)});function C$1($){return Z_($)?Z$1($,!0):O$1($)}CU0.exports=R$1});var hU0=L((vB1,O_)=>{function _$1($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var _U0=M4().Buffer,m2=o("util");function h$1($,I,q){$.copy(I,q)}O_.exports=function(){function $(){_$1(this,$),this.head=null,this.tail=null,this.length=0}return $.prototype.push=function(q){var U={data:q,next:null};if(this.length>0)this.tail.next=U;else this.head=U;this.tail=U,++this.length},$.prototype.unshift=function(q){var U={data:q,next:this.head};if(this.length===0)this.tail=U;this.head=U,++this.length},$.prototype.shift=function(){if(this.length===0)return;var q=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,q},$.prototype.clear=function(){this.head=this.tail=null,this.length=0},$.prototype.join=function(q){if(this.length===0)return"";var U=this.head,Y=""+U.data;while(U=U.next)Y+=q+U.data;return Y},$.prototype.concat=function(q){if(this.length===0)return _U0.alloc(0);var U=_U0.allocUnsafe(q>>>0),Y=this.head,J=0;while(Y)h$1(Y.data,U,J),J+=Y.data.length,Y=Y.next;return U},$}();if(m2&&m2.inspect&&m2.inspect.custom)O_.exports.prototype[m2.inspect.custom]=function(){var $=m2.inspect({length:this.length});return this.constructor.name+" "+$}});var L_=L((RB1,SU0)=>{var LX=F4();function S$1($,I){var q=this,U=this._readableState&&this._readableState.destroyed,Y=this._writableState&&this._writableState.destroyed;if(U||Y){if(I)I($);else if($){if(!this._writableState)LX.nextTick(NX,this,$);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,LX.nextTick(NX,this,$)}return this}if(this._readableState)this._readableState.destroyed=!0;if(this._writableState)this._writableState.destroyed=!0;return this._destroy($||null,function(J){if(!I&&J){if(!q._writableState)LX.nextTick(NX,q,J);else if(!q._writableState.errorEmitted)q._writableState.errorEmitted=!0,LX.nextTick(NX,q,J)}else if(I)I(J)}),this}function y$1(){if(this._readableState)this._readable Line truncated
%s`,B,B,T,U);var k=T.type==="*"?qh:T.type==="?"?Ih:"\\"+T.type;Y=!0,U=U.slice(0,T.reStart)+k+"\\("+B}if(X(),J)U+="\\\\";var h=!1;switch(U.charAt(0)){case"[":case".":case"(":h=!0}for(var f=K.length-1;f>-1;f--){var S=K[f],t=U.slice(0,S.reStart),p=U.slice(S.reStart,S.reEnd-8),C=U.slice(S.reEnd-8,S.reEnd),n=U.slice(S.reEnd);C+=n;var i=t.split("(").length-1,J0=n;for(D=0;D<i;D++)J0=J0.replace(/\)[+*?]?/,"");n=J0;var E="";if(n===""&&I!==yX)E="$";var u=t+p+n+E+C;U=u}if(U!==""&&Y)U="(?=.)"+U;if(h)U=V+U;if(I===yX)return[U,Y];if(!Y)return $31($);var d=q.nocase?"i":"";try{var a=new RegExp("^"+U+"$",d)}catch(K0){return new RegExp("$.")}return a._glob=$,a._src=U,a}Q$.makeRe=function($,I){return new E4($,I||{}).makeRe()};E4.prototype.makeRe=e71;function e71(){if(this.regexp||this.regexp===!1)return this.regexp;var $=this.set;if(!$.length)return this.regexp=!1,this.regexp;var I=this.options,q=I.noglobstar?qh:I.dot?d71:l71,U=I.nocase?"i":"",Y=$.map(function(J){return J.map(function(Q){return Q===_3?q:typeof Q==="string"?I31(Q):Q._src}).join("\\/")}).join("|");if(Y="^(?:"+Y+")$",this.negate)Y="^(?!"+Y+").*$";try{this.regexp=new RegExp(Y,U)}catch(J){this.regexp=!1}return this.regexp}Q$.match=function($,I,q){q=q||{};var U=new E4(I,q);if($=$.filter(function(Y){return U.match(Y)}),U.options.nonull&&!$.length)$.push(I);return $};E4.prototype.match=function(I,q){if(typeof q>"u")q=this.partial;if(this.debug("match",I,this.pattern),this.comment)return!1;if(this.empty)return I==="";if(I==="/"&&q)return!0;var U=this.options;if(JK.sep!=="/")I=I.split(JK.sep).join("/");I=I.split(wJ0),this.debug(this.pattern,"split",I);var Y=this.set;this.debug(this.pattern,"set",Y);var J,Q;for(Q=I.length-1;Q>=0;Q--)if(J=I[Q],J)break;for(Q=0;Q<Y.length;Q++){var K=Y[Q],w=I;if(U.matchBase&&K.length===1)w=[J];var z=this.matchOne(w,K,q);if(z){if(U.flipNegate)return!0;return!this.negate}}if(U.flipNegate)return!1;return this.negate};E4.prototype.matchOne=function($,I,q){if(I.indexOf(_3)!==-1)return this._matchGlobstar($,I,q,0,0);return this._matchOne($,I,q,0,0)};E4.prototype._matchGlobstar=function($,I,q,U,Y){var J,Q=-1;for(J=Y;J<I.length;J++)if(I[J]===_3){Q=J;break}var K=-1;for(J=I.length-1;J>=0;J--)if(I[J]===_3){K=J;break}var w=I.slice(Y,Q),z=q?I.slice(Q+1):I.slice(Q+1,K),G=q?[]:I.slice(K+1);if(w.length){var H=$.slice(U,U+w.length);if(!this._matchOne(H,w,q,0,0))return!1;U+=w.length}var V=0;if(G.length){if(G.length+U>$.length)return!1;var W=$.length-G.length;if(this._matchOne($,G,q,W,0))V=G.length;else{if($[$.length-1]!==""||U+G.length===$.length)return!1;if(W--,!this._matchOne($,G,q,W,0))return!1;V=G.length+1}}if(!z.length){var X=!!V;for(J=U;J<$.length-V;J++){var D=String($[J]);if(X=!0,D==="."||D===".."||!this.options.dot&&D.charAt(0)===".")return!1}return q||X}var O=[[[],0]],N=O[0],T=0,P=[0];for(var g=0;g<z.length;g++){var B=z[g];if(B===_3)P.push(T),N=[[],0],O.push(N);else N[0].push(B),T++}var k=O.length-1,h=$.length-V;for(var f=0;f<O.length;f++)O[f][1]=h-(P[k--]+O[f][0].length);return!!this._matchGlobStarBodySections($,O,U,0,q,0,!!V)};E4.prototype._matchGlobStarBodySections=function($,I,q,U,Y,J,Q){var K=I[U];if(!K){for(var w=q;w<$.length;w++){Q=!0;var z=$[w];if(z==="."||z===".."||!this.options.dot&&z.charAt(0)===".")return!1}return Q}var G=K[0],H=K[1];while(q<=H){var V=this._matchOne($.slice(0,q+G.length),G,Y,q,0);if(V&&J<this.maxGlobstarRecursion){var W=this._matchGlobStarBodySections($,I,q+G.length,U+1,Y,J+1,Q);if(W!==!1)return W}var z=$[q];if(z==="."||z===".."||!this.options.dot&&z.charAt(0)===".")return!1;q++}return Y||null};E4.prototype._matchOne=function($,I,q,U,Y){var J,Q,K,w;for(J=U,Q=Y,K=$.length,w=I.length;J<K&&Q<w;J++,Q++){this.debug("matchOne loop");var z=I[Q],G=$[J];if(this.debug(I,z,G),z===!1||z===_3)return!1;var H;if(typeof z==="string")H=G===z,this.debug("string match",z,G,H);else H=G.match(z),this.debug("pattern match",z,G,H);if(!H)return!1}if(J===K&&Q===w)return!0;else if(J===K)return q;else if(Q===w)return J===K-1&&$[J]==="";throw Error("wtf?")};function $31($){return $.replace(/\\(.)/g,"$1")}function I31($){return $.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var fX=L((rB1,kX)=>{function HJ0($){return $.charAt(0)==="/"}function VJ0($){var I=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,q=I.exec($),U=q[1]||"",Y=Boolean(U&&U.charAt(1)!==":");return Boolean(q[2]||Y)}kX.exports=process.platform==="win32"?VJ0:HJ0;kX.exports.posix=HJ0;kX.exports.win32=VJ0});var Yh=L((H31)=>{H31.setopts=K31;H31.ownProp=WJ0;H31.makeAbs=QK;H31.finish=w31;H31.mark=z31;H31.isIgnored=XJ0;H31.childrenIgnored=G31;function WJ0($,I){return Object.prototype.hasOwnProperty.call($,I)}var q31=o("fs"),cU=o("path"),U31=xX(),ZJ0=fX(),Uh=U31.Minimatch;function Y31($,I){return $.localeCompare(I,"en")}function J31($,I){if($.ignore=I.ignore||[],!Array.isArray($.ignore))$.ignore=[$.ignore];if($.ignore.length)$.ignore=$.ignore.map(Q31)}function Q31($){var I=null;if($.slice(-3)==="/**"){var q=$.replace(/(\/\*\*)+$/,"");I=new Uh(q,{dot:!0})}return{matcher Line truncated
See: https://github.com/isaacs/node-glob/issues/167`);return new S4($,I).found}function S4($,I){if(!$)throw Error("must provide pattern");if(typeof I==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof S4))return new S4($,I);if(F31(this,$,I),this.noprocess)return this;var q=this.minimatch.set.length;this.matches=Array(q);for(var U=0;U<q;U++)this._process(this.minimatch.set[U],U,!1);this._finish()}S4.prototype._finish=function(){if(OJ0.ok(this instanceof S4),this.realpath){var $=this;this.matches.forEach(function(I,q){var U=$.matches[q]=Object.create(null);for(var Y in I)try{Y=$._makeAbs(Y);var J=N31.realpathSync(Y,$.realpathCache);U[J]=!0}catch(Q){if(Q.syscall==="stat")U[$._makeAbs(Y)]=!0;else throw Q}})}h3.finish(this)};S4.prototype._process=function($,I,q){OJ0.ok(this instanceof S4);var U=0;while(typeof $[U]==="string")U++;var Y;switch(U){case $.length:this._processSimple($.join("/"),I);return;case 0:Y=null;break;default:Y=$.slice(0,U).join("/");break}var J=$.slice(U),Q;if(Y===null)Q=".";else if(nX(Y)||nX($.map(function(z){return typeof z==="string"?z:"[*]"}).join("/"))){if(!Y||!nX(Y))Y="/"+Y;Q=Y}else Q=Y;var K=this._makeAbs(Q);if(M31(this,Q))return;var w=J[0]===DJ0.GLOBSTAR;if(w)this._processGlobStar(Y,Q,K,J,I,q);else this._processReaddir(Y,Q,K,J,I,q)};S4.prototype._processReaddir=function($,I,q,U,Y,J){var Q=this._readdir(q,J);if(!Q)return;var K=U[0],w=!!this.minimatch.negate,z=K._glob,G=this.dot||z.charAt(0)===".",H=[];for(var V=0;V<Q.length;V++){var W=Q[V];if(W.charAt(0)!=="."||G){var X;if(w&&!$)X=!W.match(K);else X=W.match(K);if(X)H.push(W)}}var D=H.length;if(D===0)return;if(U.length===1&&!this.mark&&!this.stat){if(!this.matches[Y])this.matches[Y]=Object.create(null);for(var V=0;V<D;V++){var W=H[V];if($)if($.slice(-1)!=="/")W=$+"/"+W;else W=$+W;if(W.charAt(0)==="/"&&!this.nomount)W=Jh.join(this.root,W);this._emitMatch(Y,W)}return}U.shift();for(var V=0;V<D;V++){var W=H[V],O;if($)O=[$,W];else O=[W];this._process(O.concat(U),Y,J)}};S4.prototype._emitMatch=function($,I){if(A31(this,I))return;var q=this._makeAbs(I);if(this.mark)I=this._mark(I);if(this.absolute)I=q;if(this.matches[$][I])return;if(this.nodir){var U=this.cache[q];if(U==="DIR"||Array.isArray(U))return}if(this.matches[$][I]=!0,this.stat)this._stat(I)};S4.prototype._readdirInGlobStar=function($){if(this.follow)return this._readdir($,!1);var I,q,U;try{q=this.fs.lstatSync($)}catch(J){if(J.code==="ENOENT")return null}var Y=q&&q.isSymbolicLink();if(this.symlinks[$]=Y,!Y&&q&&!q.isDirectory())this.cache[$]="FILE";else I=this._readdir($,!1);return I};S4.prototype._readdir=function($,I){var q;if(I&&!Qh(this.symlinks,$))return this._readdirInGlobStar($);if(Qh(this.cache,$)){var U=this.cache[$];if(!U||U==="FILE")return null;if(Array.isArray(U))return U}try{return this._readdirEntries($,this.fs.readdirSync($))}catch(Y){return this._readdirError($,Y),null}};S4.prototype._readdirEntries=function($,I){if(!this.mark&&!this.stat)for(var q=0;q<I.length;q++){var U=I[q];if($==="/")U=$+U;else U=$+"/"+U;this.cache[U]=!0}return this.cache[$]=I,I};S4.prototype._readdirError=function($,I){switch(I.code){case"ENOTSUP":case"ENOTDIR":var q=this._makeAbs($);if(this.cache[q]="FILE",q===this.cwdAbs){var U=Error(I.code+" invalid cwd "+this.cwd);throw U.path=this.cwd,U.code=I.code,U}break;case"ENOENT":case"ELOOP":case"ENAMETOOLONG":case"UNKNOWN":this.cache[this._makeAbs($)]=!1;break;default:if(this.cache[this._makeAbs($)]=!1,this.strict)throw I;if(!this.silent)console.error("glob error",I);break}};S4.prototype._processGlobStar=function($,I,q,U,Y,J){var Q=this._readdir(q,J);if(!Q)return;var K=U.slice(1),w=$?[$]:[],z=w.concat(K);this._process(z,Y,!1);var G=Q.length,H=this.symlinks[q];if(H&&J)return;for(var V=0;V<G;V++){var W=Q[V];if(W.charAt(0)==="."&&!this.dot)continue;var X=w.concat(Q[V],K);this._process(X,Y,!0);var D=w.concat(Q[V],U);this._process(D,Y,!0)}};S4.prototype._processSimple=function($,I){var q=this._stat($);if(!this.matches[I])this.matches[I]=Object.create(null);if(!q)return;if($&&nX($)&&!this.nomount){var U=/[\/\\]$/.test($);if($.charAt(0)==="/")$=Jh.join(this.root,$);else if($=Jh.resolve(this.root,$),U)$+="/"}if(process.platform==="win32")$=$.replace(/\\/g,"/");this._emitMatch(I,$)};S4.prototype._stat=function($){var I=this._makeAbs($),q=$.slice(-1)==="/";if($.length>this.maxLength)return!1;if(!this.stat&&Qh(this.cache,I)){var Q=this.cache[I];if(Array.isArray(Q))Q="DIR";if(!q||Q==="DIR")return Q;if(q&&Q==="FILE")return!1}var U,Y=this.statCache[I];if(!Y){var J;try{J=this.fs.lstatSync(I)}catch(K){if(K&&(K.code==="ENOENT"||K.code==="ENOTDIR"))return this.statCache[I]=!1,!1}if(J&&J.isSymbolicLink())try{Y=this.fs.statSync(I)}catch(K){Y=J}else Y=J}this.statCache[I]=Y;var Q=!0;if(Y)Q=Y.isDirectory()?"DIR":"FILE";if(this.cache[I]=this.cache[I]||Q,q&&Q==="FILE")return!1;return Q};S4.prototype._mark=function($){return h3.mark(this,$)};S4.prototype._makeAbs=function($){return h3.makeAbs(this,$)}});var Kh=L((Iv1,AJ0)=>{AJ0.exports=MJ0;function MJ0($,I){if($&&I)return MJ0($)(I);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(U){q[U]=$[U]}),q;f Line truncated
`);if($.linkname)I+=fh(" linkpath="+$.linkname+`
`);var q=$.pax;if(q)for(var U in q)I+=fh(" "+U+"="+q[U]+`
`);return Buffer.from(I)};kI1.decodePax=function($){var I={};while($.length){var q=0;while(q<$.length&&$[q]!==32)q++;var U=parseInt($.slice(0,q).toString(),10);if(!U)return I;var Y=$.slice(q+1,U-1).toString(),J=Y.indexOf("=");if(J===-1)return I;I[Y.slice(0,J)]=Y.slice(J+1),$=$.slice(U)}return I};kI1.encode=function($){var I=jI1(512),q=$.name,U="";if($.typeflag===5&&q[q.length-1]!=="/")q+="/";if(Buffer.byteLength(q)!==q.length)return null;while(Buffer.byteLength(q)>100){var Y=q.indexOf("/");if(Y===-1)return null;U+=U?"/"+q.slice(0,Y):q.slice(0,Y),q=q.slice(Y+1)}if(Buffer.byteLength(q)>100||Buffer.byteLength(U)>155)return null;if($.linkname&&Buffer.byteLength($.linkname)>100)return null;if(I.write(q),I.write($7($.mode&hI1,6),100),I.write($7($.uid,6),108),I.write($7($.gid,6),116),I.write($7($.size,11),124),I.write($7($.mtime.getTime()/1000|0,11),136),I[156]=nQ0+uI1($.type),$.linkname)I.write($.linkname,157);if(iQ0.copy(I,VK),RI1.copy(I,nh),$.uname)I.write($.uname,265);if($.gname)I.write($.gname,297);if(I.write($7($.devmajor||0,6),329),I.write($7($.devminor||0,6),337),U)I.write(U,345);return I.write($7(pQ0(I),6),148),I};kI1.decode=function($,I,q){var U=$[156]===0?0:$[156]-nQ0,Y=oU($,0,100,I),J=I7($,100,8),Q=I7($,108,8),K=I7($,116,8),w=I7($,124,12),z=I7($,136,12),G=yI1(U),H=$[157]===0?null:oU($,157,100,I),V=oU($,265,32),W=oU($,297,32),X=I7($,329,8),D=I7($,337,8),O=pQ0($);if(O===256)return null;if(O!==I7($,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(iQ0.compare($,VK,VK+6)===0){if($[345])Y=oU($,345,155,I)+"/"+Y}else if(CI1.compare($,VK,VK+6)===0&&_I1.compare($,nh,nh+2)===0);else if(!q)throw Error("Invalid tar header: unknown format.");if(U===0&&Y&&Y[Y.length-1]==="/")U=5;return{name:Y,mode:J,uid:Q,gid:K,size:w,mtime:new Date(1000*z),type:G,linkname:H,uname:V,gname:W,devmajor:X,devminor:D}}});var tQ0=L((uv1,rQ0)=>{var dQ0=o("util"),cI1=fQ0(),WK=ih(),lQ0=Z6().Writable,mQ0=Z6().PassThrough,oQ0=function(){},cQ0=function($){return $&=511,$&&512-$},dI1=function($,I){var q=new mX($,I);return q.end(),q},lI1=function($,I){if(I.path)$.name=I.path;if(I.linkpath)$.linkname=I.linkpath;if(I.size)$.size=parseInt(I.size,10);return $.pax=I,$},mX=function($,I){this._parent=$,this.offset=I,mQ0.call(this,{autoDestroy:!1})};dQ0.inherits(mX,mQ0);mX.prototype.destroy=function($){this._parent.destroy($)};var _5=function($){if(!(this instanceof _5))return new _5($);lQ0.call(this,$),$=$||{},this._offset=0,this._buffer=cI1(),this._missing=0,this._partial=!1,this._onparse=oQ0,this._header=null,this._stream=null,this._overflow=null,this._cb=null,this._locked=!1,this._destroyed=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null;var I=this,q=I._buffer,U=function(){I._continue()},Y=function(V){if(I._locked=!1,V)return I.destroy(V);if(!I._stream)U()},J=function(){I._stream=null;var V=cQ0(I._header.size);if(V)I._parse(V,Q);else I._parse(512,H);if(!I._locked)U()},Q=function(){I._buffer.consume(cQ0(I._header.size)),I._parse(512,H),U()},K=function(){var V=I._header.size;I._paxGlobal=WK.decodePax(q.slice(0,V)),q.consume(V),J()},w=function(){var V=I._header.size;if(I._pax=WK.decodePax(q.slice(0,V)),I._paxGlobal)I._pax=Object.assign({},I._paxGlobal,I._pax);q.consume(V),J()},z=function(){var V=I._header.size;this._gnuLongPath=WK.decodeLongPath(q.slice(0,V),$.filenameEncoding),q.consume(V),J()},G=function(){var V=I._header.size;this._gnuLongLinkPath=WK.decodeLongPath(q.slice(0,V),$.filenameEncoding),q.consume(V),J()},H=function(){var V=I._offset,W;try{W=I._header=WK.decode(q.slice(0,512),$.filenameEncoding,$.allowUnknownFormat)}catch(X){I.emit("error",X)}if(q.consume(512),!W){I._parse(512,H),U();return}if(W.type==="gnu-long-path"){I._parse(W.size,z),U();return}if(W.type==="gnu-long-link-path"){I._parse(W.size,G),U();return}if(W.type==="pax-global-header"){I._parse(W.size,K),U();return}if(W.type==="pax-header"){I._parse(W.size,w),U();return}if(I._gnuLongPath)W.name=I._gnuLongPath,I._gnuLongPath=null;if(I._gnuLongLinkPath)W.linkname=I._gnuLongLinkPath,I._gnuLongLinkPath=null;if(I._pax)I._header=W=lI1(W,I._pax),I._pax=null;if(I._locked=!0,!W.size||W.type==="directory"){I._parse(512,H),I.emit("entry",W,dI1(I,V),Y);return}I._stream=new mX(I,V),I.emit("entry",W,I._stream,Y),I._parse(W.size,J),U()};this._onheader=H,this._parse(512,H)};dQ0.inherits(_5,lQ0);_5.prototype.destroy=function($){if(this._destroyed)return;if(this._destroyed=!0,$)this.emit("error",$);if(this.emit("close"),this._stream)this._stream.emit("close")};_5.prototype._parse=function($,I){if(this._destroyed)return;if(this._offset+=$,this._missing=$,I===this._onheader)this._partial=!1;this._onparse=I};_5.prototype._continue=function(){if(this._destroyed)return;var $=this._cb;if(this._cb=oQ0,this._overflow)this._write(this._overflow,void 0,$);else $()};_5.prototype._write=function($,I,q){if(this._destroyed)return;var U=this._stream,Y=this._buffer,J=this._missing;if($.length)this._partial=!0;if($.length<J){ Line truncated
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`)}_writeRelationship($){if(!this.count)this._writeOpen();let I=`rId${++this.count}`;if($.TargetMode)this.stream.write(`<Relationship Id="${I}" Type="${$.Type}" Target="${Hq1.xmlEncode($.Target)}" TargetMode="${$.TargetMode}"/>`);else this.stream.write(`<Relationship Id="${I}" Type="${$.Type}" Target="${$.Target}"/>`);return I}_writeClose(){this.stream.write("</Relationships>")}}A20.exports=M20});var B20=L((lv1,j20)=>{var P20=$6(),T20=x9(),Wq1=w4(),Zq1=FR(),Xq1=AR();class E20{constructor($,I,q){this.id=q.id,this.count=0,this._worksheet=$,this._workbook=q.workbook,this._sheetRelsWriter=I}get commentsStream(){if(!this._commentsStream)this._commentsStream=this._workbook._openStream(`/xl/comments${this.id}.xml`);return this._commentsStream}get vmlStream(){if(!this._vmlStream)this._vmlStream=this._workbook._openStream(`xl/drawings/vmlDrawing${this.id}.vml`);return this._vmlStream}_addRelationships(){let $={Type:T20.Comments,Target:`../comments${this.id}.xml`};this._sheetRelsWriter.addRelationship($);let I={Type:T20.VmlDrawing,Target:`../drawings/vmlDrawing${this.id}.vml`};this.vmlRelId=this._sheetRelsWriter.addRelationship(I)}_addCommentRefs(){this._workbook.commentRefs.push({commentName:`comments${this.id}`,vmlDrawing:`vmlDrawing${this.id}`})}_writeOpen(){this.commentsStream.write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><comments xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><authors><author>Author</author></authors><commentList>'),this.vmlStream.write('<?xml version="1.0" encoding="UTF-8"?><xml xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:x="urn:schemas-microsoft-com:office:excel"><o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1" /></o:shapelayout><v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe"><v:stroke joinstyle="miter" /><v:path gradientshapeok="t" o:connecttype="rect" /></v:shapetype>')}_writeComment($,I){let q=new Zq1,U=new P20;q.render(U,$),this.commentsStream.write(U.xml);let Y=new Xq1,J=new P20;Y.render(J,$,I),this.vmlStream.write(J.xml)}_writeClose(){this.commentsStream.write("</commentList></comments>"),this.vmlStream.write("</xml>")}addComments($){if($&&$.length){if(!this.startedData)this._worksheet.comments=[],this._writeOpen(),this._addRelationships(),this._addCommentRefs(),this.startedData=!0;$.forEach((I)=>{I.refAddress=Wq1.decodeAddress(I.ref)}),$.forEach((I)=>{this._writeComment(I,this.count),this.count+=1})}}commit(){if(this.count)this._writeClose(),this.commentsStream.end(),this.vmlStream.end()}}j20.exports=E20});var S20=L((mv1,h20)=>{var Dq1=Z4(),Oq1=x9(),ch=w4(),v20=kE(),R20=G5(),Lq1=eB(),C20=HV(),dh=WV(),Nq1=g20(),Fq1=B20(),Mq1=uE(),n4=new Lq1,lh=S9(),Aq1=ov(),gq1=rv(),Pq1=tv(),Tq1=cv(),Eq1=bv(),jq1=dv(),Bq1=av(),vq1=sv(),Rq1=ev(),Cq1=$R(),_q1=IR(),hq1=qR(),Sq1=KR(),yq1=YR(),uq1=UR(),i4={dataValidations:new Aq1,sheetProperties:new gq1,sheetFormatProperties:new Pq1,columns:new lh({tag:"cols",length:!1,childXform:new Tq1}),row:new Eq1,hyperlinks:new lh({tag:"hyperlinks",length:!1,childXform:new jq1}),sheetViews:new lh({tag:"sheetViews",length:!1,childXform:new Bq1}),sheetProtection:new vq1,pageMargins:new Rq1,pageSeteup:new Cq1,autoFilter:new _q1,picture:new hq1,conditionalFormattings:new Sq1,headerFooter:new yq1,rowBreaks:new uq1};class _20{constructor($){this.id=$.id,this.name=$.name||`Sheet${this.id}`,this.state=$.state||"visible",this._rows=[],this._columns=null,this._keys={},this._merges=[],this._merges.add=function(){},this._sheetRelsWriter=new Nq1($),this._sheetCommentsWriter=new Fq1(this,this._sheetRelsWriter,$),this._dimensions=new R20,this._rowZero=1,this.committed=!1,this.dataValidations=new Mq1,this._formulae={},this._siFormulae=0,this.conditionalFormatting=[],this.rowBreaks=[],this.properties=Object.assign({},{defaultRowHeight:15,dyDescent:55,outlineLevelCol:0,outlineLevelRow:0},$.properties),this.headerFooter=Object.assign({},{differentFirst:!1,differentOddEven:!1,oddHeader:null,oddFooter:null,evenHeader:null,evenFooter:null,firstHeader:null,firstFooter:null},$.headerFooter),this.pageSetup=Object.assign({},{margins:{left:0.7,right:0.7,top:0.75,bottom:0.75,header:0.3,footer:0.3},orientation:"portrait",horizontalDpi:4294967295,verticalDpi:4294967295,fitToPage:!!($.pageSetup&&($.pageSetup.fitToWidth||$.pageSetup.fitToHeight)&&!$.pageSetup.scale),pageOrder:"downThenOver",blackAndWhite:!1,draft:!1,cellComments:"None",errors:"displayed",scale:100,fitToWidth:1,fitToHeight:1,paperSize:void 0,showRowColHeaders:!1,showGridLines:!1,horizontalCentered:!1,verticalCentered:!1,rowBreaks:null,colBreaks:null},$.pageSetup),this.useSharedStrings=$.useSharedStrings||!1,this._workbook=$.workbook,this.hasComments=!1,this._views=$.views||[],this.autoFilter=$.autoFilter||null,this._media=[],this.sheetProtection=null,this._writeOpenWorksheet(),this.startedData=!1}get Line truncated
*/SU0.exports=function($,I){if(typeof $!=="string")throw TypeError("expected path to be a string");if($==="\\"||$==="/")return"/";var U=$.length;if(U<=1)return $;var Y="";if(U>4&&$[3]==="\\"){var J=$[2];if((J==="?"||J===".")&&$.slice(0,2)==="\\\\")$=$.slice(2),Y="//"}var Q=$.split(/[/\\]+/);if(I!==!1&&Q[Q.length-1]==="")Q.pop();return Y+Q.join("/")}});var h_=F((JR1,fU0)=>{var yU0=9007199254740991,q41="[object Arguments]",H41="[object Function]",G41="[object GeneratorFunction]",W41=/^(?:0|[1-9]\d*)$/;function hU0($,I,U){switch(U.length){case 0:return $.call(I);case 1:return $.call(I,U[0]);case 2:return $.call(I,U[0],U[1]);case 3:return $.call(I,U[0],U[1],U[2])}return $.apply(I,U)}function w41($,I){var U=-1,Y=Array($);while(++U<$)Y[U]=I(U);return Y}var tK=Object.prototype,aK=tK.hasOwnProperty,uU0=tK.toString,V41=tK.propertyIsEnumerable,gU0=Math.max;function Z41($,I){var U=P41($)||A41($)?w41($.length,String):[],Y=U.length,J=!!Y;for(var Q in $)if((I||aK.call($,Q))&&!(J&&(Q=="length"||kU0(Q,Y))))U.push(Q);return U}function z41($,I,U,Y){if($===void 0||S_($,tK[U])&&!aK.call(Y,U))return I;return $}function X41($,I,U){var Y=$[I];if(!(aK.call($,I)&&S_(Y,U))||U===void 0&&!(I in $))$[I]=U}function L41($){if(!y_($))return M41($);var I=N41($),U=[];for(var Y in $)if(!(Y=="constructor"&&(I||!aK.call($,Y))))U.push(Y);return U}function xU0($,I){return I=gU0(I===void 0?$.length-1:I,0),function(){var U=arguments,Y=-1,J=gU0(U.length-I,0),Q=Array(J);while(++Y<J)Q[Y]=U[I+Y];Y=-1;var K=Array(I+1);while(++Y<I)K[Y]=U[Y];return K[I]=Q,hU0($,this,K)}}function D41($,I,U,Y){U||(U={});var J=-1,Q=I.length;while(++J<Q){var K=I[J],q=Y?Y(U[K],$[K],K,U,$):void 0;X41(U,K,q===void 0?$[K]:q)}return U}function F41($){return xU0(function(I,U){var Y=-1,J=U.length,Q=J>1?U[J-1]:void 0,K=J>2?U[2]:void 0;if(Q=$.length>3&&typeof Q=="function"?(J--,Q):void 0,K&&O41(U[0],U[1],K))Q=J<3?void 0:Q,J=1;I=Object(I);while(++Y<J){var q=U[Y];if(q)$(I,q,Y,Q)}return I})}function kU0($,I){return I=I==null?yU0:I,!!I&&(typeof $=="number"||W41.test($))&&($>-1&&$%1==0&&$<I)}function O41($,I,U){if(!y_(U))return!1;var Y=typeof I;if(Y=="number"?g_(U)&&kU0(I,U.length):Y=="string"&&(I in U))return S_(U[I],$);return!1}function N41($){var I=$&&$.constructor,U=typeof I=="function"&&I.prototype||tK;return $===U}function M41($){var I=[];if($!=null)for(var U in Object($))I.push(U);return I}function S_($,I){return $===I||$!==$&&I!==I}function A41($){return T41($)&&aK.call($,"callee")&&(!V41.call($,"callee")||uU0.call($)==q41)}var P41=Array.isArray;function g_($){return $!=null&&B41($.length)&&!E41($)}function T41($){return v41($)&&g_($)}function E41($){var I=y_($)?uU0.call($):"";return I==H41||I==G41}function B41($){return typeof $=="number"&&$>-1&&$%1==0&&$<=yU0}function y_($){var I=typeof $;return!!$&&(I=="object"||I=="function")}function v41($){return!!$&&typeof $=="object"}var R41=F41(function($,I,U,Y){D41(I,j41(I),$,Y)}),C41=xU0(function($){return $.push(void 0,z41),hU0(R41,void 0,$)});function j41($){return g_($)?Z41($,!0):L41($)}fU0.exports=C41});var bU0=F((QR1,u_)=>{function _41($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var iU0=A4().Buffer,sK=a("util");function S41($,I,U){$.copy(I,U)}u_.exports=function(){function $(){_41(this,$),this.head=null,this.tail=null,this.length=0}return $.prototype.push=function(U){var Y={data:U,next:null};if(this.length>0)this.tail.next=Y;else this.head=Y;this.tail=Y,++this.length},$.prototype.unshift=function(U){var Y={data:U,next:this.head};if(this.length===0)this.tail=Y;this.head=Y,++this.length},$.prototype.shift=function(){if(this.length===0)return;var U=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,U},$.prototype.clear=function(){this.head=this.tail=null,this.length=0},$.prototype.join=function(U){if(this.length===0)return"";var Y=this.head,J=""+Y.data;while(Y=Y.next)J+=U+Y.data;return J},$.prototype.concat=function(U){if(this.length===0)return iU0.alloc(0);var Y=iU0.allocUnsafe(U>>>0),J=this.head,Q=0;while(J)S41(J.data,Y,Q),Q+=J.data.length,J=J.next;return Y},$}();if(sK&&sK.inspect&&sK.inspect.custom)u_.exports.prototype[sK.inspect.custom]=function(){var $=sK.inspect({length:this.length});return this.constructor.name+" "+$}});var x_=F((KR1,nU0)=>{var GX=M4();function g41($,I){var U=this,Y=this._readableState&&this._readableState.destroyed,J=this._writableState&&this._writableState.destroyed;if(Y||J){if(I)I($);else if($){if(!this._writableState)GX.nextTick(WX,this,$);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,GX.nextTick(WX,this,$)}return this}if(this._readableState)this._readableState.destroyed=!0;if(this._writableState)this._writableState.destroyed=!0;return this._destroy($||null,function(Q){if(!I&&Q){if(!U._writableState)GX.nextTick(WX,U,Q);else if(!U._writableState.errorEmitted)U._writableState.errorEmitted=!0,GX.nextTick(WX,U,Q)}else if(I)I(Q)}),this}function y41(){if(this._readableState)this._readable Line truncated
%s`,R,R,E,Y);var k=E.type==="*"?MS:E.type==="?"?NS:"\\"+E.type;J=!0,Y=Y.slice(0,E.reStart)+k+"\\("+R}if(X(),Q)Y+="\\\\";var g=!1;switch(Y.charAt(0)){case"[":case".":case"(":g=!0}for(var f=q.length-1;f>-1;f--){var C=q[f],p=Y.slice(0,C.reStart),n=Y.slice(C.reStart,C.reEnd-8),S=Y.slice(C.reEnd-8,C.reEnd),i=Y.slice(C.reEnd);S+=i;var b=p.split("(").length-1,Y0=i;for(L=0;L<b;L++)Y0=Y0.replace(/\)[+*?]?/,"");i=Y0;var B="";if(i===""&&I!==BX)B="$";var x=p+n+i+B+S;Y=x}if(Y!==""&&J)Y="(?=.)"+Y;if(g)Y=V+Y;if(I===BX)return[Y,J];if(!J)return e51($);var c=U.nocase?"i":"";try{var r=new RegExp("^"+Y+"$",c)}catch(Q0){return new RegExp("$.")}return r._glob=$,r._src=Y,r}Z$.makeRe=function($,I){return new v4($,I||{}).makeRe()};v4.prototype.makeRe=s51;function s51(){if(this.regexp||this.regexp===!1)return this.regexp;var $=this.set;if(!$.length)return this.regexp=!1,this.regexp;var I=this.options,U=I.noglobstar?MS:I.dot?c51:d51,Y=I.nocase?"i":"",J=$.map(function(Q){return Q.map(function(K){return K===h3?U:typeof K==="string"?$91(K):K._src}).join("\\/")}).join("|");if(J="^(?:"+J+")$",this.negate)J="^(?!"+J+").*$";try{this.regexp=new RegExp(J,Y)}catch(Q){this.regexp=!1}return this.regexp}Z$.match=function($,I,U){U=U||{};var Y=new v4(I,U);if($=$.filter(function(J){return Y.match(J)}),Y.options.nonull&&!$.length)$.push(I);return $};v4.prototype.match=function(I,U){if(typeof U>"u")U=this.partial;if(this.debug("match",I,this.pattern),this.comment)return!1;if(this.empty)return I==="";if(I==="/"&&U)return!0;var Y=this.options;if(Wq.sep!=="/")I=I.split(Wq.sep).join("/");I=I.split(LJ0),this.debug(this.pattern,"split",I);var J=this.set;this.debug(this.pattern,"set",J);var Q,K;for(K=I.length-1;K>=0;K--)if(Q=I[K],Q)break;for(K=0;K<J.length;K++){var q=J[K],H=I;if(Y.matchBase&&q.length===1)H=[Q];var G=this.matchOne(H,q,U);if(G){if(Y.flipNegate)return!0;return!this.negate}}if(Y.flipNegate)return!1;return this.negate};v4.prototype.matchOne=function($,I,U){if(I.indexOf(h3)!==-1)return this._matchGlobstar($,I,U,0,0);return this._matchOne($,I,U,0,0)};v4.prototype._matchGlobstar=function($,I,U,Y,J){var Q,K=-1;for(Q=J;Q<I.length;Q++)if(I[Q]===h3){K=Q;break}var q=-1;for(Q=I.length-1;Q>=0;Q--)if(I[Q]===h3){q=Q;break}var H=I.slice(J,K),G=U?I.slice(K+1):I.slice(K+1,q),W=U?[]:I.slice(q+1);if(H.length){var w=$.slice(Y,Y+H.length);if(!this._matchOne(w,H,U,0,0))return!1;Y+=H.length}var V=0;if(W.length){if(W.length+Y>$.length)return!1;var Z=$.length-W.length;if(this._matchOne($,W,U,Z,0))V=W.length;else{if($[$.length-1]!==""||Y+W.length===$.length)return!1;if(Z--,!this._matchOne($,W,U,Z,0))return!1;V=W.length+1}}if(!G.length){var X=!!V;for(Q=Y;Q<$.length-V;Q++){var L=String($[Q]);if(X=!0,L==="."||L===".."||!this.options.dot&&L.charAt(0)===".")return!1}return U||X}var D=[[[],0]],O=D[0],E=0,T=[0];for(var A=0;A<G.length;A++){var R=G[A];if(R===h3)T.push(E),O=[[],0],D.push(O);else O[0].push(R),E++}var k=D.length-1,g=$.length-V;for(var f=0;f<D.length;f++)D[f][1]=g-(T[k--]+D[f][0].length);return!!this._matchGlobStarBodySections($,D,Y,0,U,0,!!V)};v4.prototype._matchGlobStarBodySections=function($,I,U,Y,J,Q,K){var q=I[Y];if(!q){for(var H=U;H<$.length;H++){K=!0;var G=$[H];if(G==="."||G===".."||!this.options.dot&&G.charAt(0)===".")return!1}return K}var W=q[0],w=q[1];while(U<=w){var V=this._matchOne($.slice(0,U+W.length),W,J,U,0);if(V&&Q<this.maxGlobstarRecursion){var Z=this._matchGlobStarBodySections($,I,U+W.length,Y+1,J,Q+1,K);if(Z!==!1)return Z}var G=$[U];if(G==="."||G===".."||!this.options.dot&&G.charAt(0)===".")return!1;U++}return J||null};v4.prototype._matchOne=function($,I,U,Y,J){var Q,K,q,H;for(Q=Y,K=J,q=$.length,H=I.length;Q<q&&K<H;Q++,K++){this.debug("matchOne loop");var G=I[K],W=$[Q];if(this.debug(I,G,W),G===!1||G===h3)return!1;var w;if(typeof G==="string")w=W===G,this.debug("string match",G,W,w);else w=W.match(G),this.debug("pattern match",G,W,w);if(!w)return!1}if(Q===q&&K===H)return!0;else if(Q===q)return U;else if(K===H)return Q===q-1&&$[Q]==="";throw Error("wtf?")};function e51($){return $.replace(/\\(.)/g,"$1")}function $91($){return $.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var jX=F((ER1,CX)=>{function OJ0($){return $.charAt(0)==="/"}function NJ0($){var I=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,U=I.exec($),Y=U[1]||"",J=Boolean(Y&&Y.charAt(1)!==":");return Boolean(U[2]||J)}CX.exports=process.platform==="win32"?NJ0:OJ0;CX.exports.posix=OJ0;CX.exports.win32=NJ0});var PS=F((W91)=>{W91.setopts=K91;W91.ownProp=MJ0;W91.makeAbs=wq;W91.finish=q91;W91.mark=H91;W91.isIgnored=PJ0;W91.childrenIgnored=G91;function MJ0($,I){return Object.prototype.hasOwnProperty.call($,I)}var I91=a("fs"),mY=a("path"),U91=RX(),AJ0=jX(),AS=U91.Minimatch;function Y91($,I){return $.localeCompare(I,"en")}function J91($,I){if($.ignore=I.ignore||[],!Array.isArray($.ignore))$.ignore=[$.ignore];if($.ignore.length)$.ignore=$.ignore.map(Q91)}function Q91($){var I=null;if($.slice(-3)==="/**"){var U=$.replace(/(\/\*\*)+$/,"");I=new AS(U,{dot:!0})}return{matcher Line truncated
See: https://github.com/isaacs/node-glob/issues/167`);return new h4($,I).found}function h4($,I){if(!$)throw Error("must provide pattern");if(typeof I==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof h4))return new h4($,I);if(O91(this,$,I),this.noprocess)return this;var U=this.minimatch.set.length;this.matches=Array(U);for(var Y=0;Y<U;Y++)this._process(this.minimatch.set[Y],Y,!1);this._finish()}h4.prototype._finish=function(){if(EJ0.ok(this instanceof h4),this.realpath){var $=this;this.matches.forEach(function(I,U){var Y=$.matches[U]=Object.create(null);for(var J in I)try{J=$._makeAbs(J);var Q=F91.realpathSync(J,$.realpathCache);Y[Q]=!0}catch(K){if(K.syscall==="stat")Y[$._makeAbs(J)]=!0;else throw K}})}u3.finish(this)};h4.prototype._process=function($,I,U){EJ0.ok(this instanceof h4);var Y=0;while(typeof $[Y]==="string")Y++;var J;switch(Y){case $.length:this._processSimple($.join("/"),I);return;case 0:J=null;break;default:J=$.slice(0,Y).join("/");break}var Q=$.slice(Y),K;if(J===null)K=".";else if(_X(J)||_X($.map(function(G){return typeof G==="string"?G:"[*]"}).join("/"))){if(!J||!_X(J))J="/"+J;K=J}else K=J;var q=this._makeAbs(K);if(N91(this,K))return;var H=Q[0]===TJ0.GLOBSTAR;if(H)this._processGlobStar(J,K,q,Q,I,U);else this._processReaddir(J,K,q,Q,I,U)};h4.prototype._processReaddir=function($,I,U,Y,J,Q){var K=this._readdir(U,Q);if(!K)return;var q=Y[0],H=!!this.minimatch.negate,G=q._glob,W=this.dot||G.charAt(0)===".",w=[];for(var V=0;V<K.length;V++){var Z=K[V];if(Z.charAt(0)!=="."||W){var X;if(H&&!$)X=!Z.match(q);else X=Z.match(q);if(X)w.push(Z)}}var L=w.length;if(L===0)return;if(Y.length===1&&!this.mark&&!this.stat){if(!this.matches[J])this.matches[J]=Object.create(null);for(var V=0;V<L;V++){var Z=w[V];if($)if($.slice(-1)!=="/")Z=$+"/"+Z;else Z=$+Z;if(Z.charAt(0)==="/"&&!this.nomount)Z=TS.join(this.root,Z);this._emitMatch(J,Z)}return}Y.shift();for(var V=0;V<L;V++){var Z=w[V],D;if($)D=[$,Z];else D=[Z];this._process(D.concat(Y),J,Q)}};h4.prototype._emitMatch=function($,I){if(M91(this,I))return;var U=this._makeAbs(I);if(this.mark)I=this._mark(I);if(this.absolute)I=U;if(this.matches[$][I])return;if(this.nodir){var Y=this.cache[U];if(Y==="DIR"||Array.isArray(Y))return}if(this.matches[$][I]=!0,this.stat)this._stat(I)};h4.prototype._readdirInGlobStar=function($){if(this.follow)return this._readdir($,!1);var I,U,Y;try{U=this.fs.lstatSync($)}catch(Q){if(Q.code==="ENOENT")return null}var J=U&&U.isSymbolicLink();if(this.symlinks[$]=J,!J&&U&&!U.isDirectory())this.cache[$]="FILE";else I=this._readdir($,!1);return I};h4.prototype._readdir=function($,I){var U;if(I&&!ES(this.symlinks,$))return this._readdirInGlobStar($);if(ES(this.cache,$)){var Y=this.cache[$];if(!Y||Y==="FILE")return null;if(Array.isArray(Y))return Y}try{return this._readdirEntries($,this.fs.readdirSync($))}catch(J){return this._readdirError($,J),null}};h4.prototype._readdirEntries=function($,I){if(!this.mark&&!this.stat)for(var U=0;U<I.length;U++){var Y=I[U];if($==="/")Y=$+Y;else Y=$+"/"+Y;this.cache[Y]=!0}return this.cache[$]=I,I};h4.prototype._readdirError=function($,I){switch(I.code){case"ENOTSUP":case"ENOTDIR":var U=this._makeAbs($);if(this.cache[U]="FILE",U===this.cwdAbs){var Y=Error(I.code+" invalid cwd "+this.cwd);throw Y.path=this.cwd,Y.code=I.code,Y}break;case"ENOENT":case"ELOOP":case"ENAMETOOLONG":case"UNKNOWN":this.cache[this._makeAbs($)]=!1;break;default:if(this.cache[this._makeAbs($)]=!1,this.strict)throw I;if(!this.silent)console.error("glob error",I);break}};h4.prototype._processGlobStar=function($,I,U,Y,J,Q){var K=this._readdir(U,Q);if(!K)return;var q=Y.slice(1),H=$?[$]:[],G=H.concat(q);this._process(G,J,!1);var W=K.length,w=this.symlinks[U];if(w&&Q)return;for(var V=0;V<W;V++){var Z=K[V];if(Z.charAt(0)==="."&&!this.dot)continue;var X=H.concat(K[V],q);this._process(X,J,!0);var L=H.concat(K[V],Y);this._process(L,J,!0)}};h4.prototype._processSimple=function($,I){var U=this._stat($);if(!this.matches[I])this.matches[I]=Object.create(null);if(!U)return;if($&&_X($)&&!this.nomount){var Y=/[\/\\]$/.test($);if($.charAt(0)==="/")$=TS.join(this.root,$);else if($=TS.resolve(this.root,$),Y)$+="/"}if(process.platform==="win32")$=$.replace(/\\/g,"/");this._emitMatch(I,$)};h4.prototype._stat=function($){var I=this._makeAbs($),U=$.slice(-1)==="/";if($.length>this.maxLength)return!1;if(!this.stat&&ES(this.cache,I)){var K=this.cache[I];if(Array.isArray(K))K="DIR";if(!U||K==="DIR")return K;if(U&&K==="FILE")return!1}var Y,J=this.statCache[I];if(!J){var Q;try{Q=this.fs.lstatSync(I)}catch(q){if(q&&(q.code==="ENOENT"||q.code==="ENOTDIR"))return this.statCache[I]=!1,!1}if(Q&&Q.isSymbolicLink())try{J=this.fs.statSync(I)}catch(q){J=Q}else J=Q}this.statCache[I]=J;var K=!0;if(J)K=J.isDirectory()?"DIR":"FILE";if(this.cache[I]=this.cache[I]||K,U&&K==="FILE")return!1;return K};h4.prototype._mark=function($){return u3.mark(this,$)};h4.prototype._makeAbs=function($){return u3.makeAbs(this,$)}});var BS=F((_R1,jJ0)=>{jJ0.exports=CJ0;function CJ0($,I){if($&&I)return CJ0($)(I);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(Y){U[Y]=$[Y]}),U;f Line truncated
`);if($.linkname)I+=Jg(" linkpath="+$.linkname+`
`);var U=$.pax;if(U)for(var Y in U)I+=Jg(" "+Y+"="+U[Y]+`
`);return Buffer.from(I)};x71.decodePax=function($){var I={};while($.length){var U=0;while(U<$.length&&$[U]!==32)U++;var Y=parseInt($.slice(0,U).toString(),10);if(!Y)return I;var J=$.slice(U+1,Y-1).toString(),Q=J.indexOf("=");if(Q===-1)return I;I[J.slice(0,Q)]=J.slice(Q+1),$=$.slice(Y)}return I};x71.encode=function($){var I=B71(512),U=$.name,Y="";if($.typeflag===5&&U[U.length-1]!=="/")U+="/";if(Buffer.byteLength(U)!==U.length)return null;while(Buffer.byteLength(U)>100){var J=U.indexOf("/");if(J===-1)return null;Y+=Y?"/"+U.slice(0,J):U.slice(0,J),U=U.slice(J+1)}if(Buffer.byteLength(U)>100||Buffer.byteLength(Y)>155)return null;if($.linkname&&Buffer.byteLength($.linkname)>100)return null;if(I.write(U),I.write(Q7($.mode&S71,6),100),I.write(Q7($.uid,6),108),I.write(Q7($.gid,6),116),I.write(Q7($.size,11),124),I.write(Q7($.mtime.getTime()/1000|0,11),136),I[156]=oQ0+h71($.type),$.linkname)I.write($.linkname,157);if(rQ0.copy(I,Dq),C71.copy(I,Qg),$.uname)I.write($.uname,265);if($.gname)I.write($.gname,297);if(I.write(Q7($.devmajor||0,6),329),I.write(Q7($.devminor||0,6),337),Y)I.write(Y,345);return I.write(Q7(aQ0(I),6),148),I};x71.decode=function($,I,U){var Y=$[156]===0?0:$[156]-oQ0,J=tY($,0,100,I),Q=K7($,100,8),K=K7($,108,8),q=K7($,116,8),H=K7($,124,12),G=K7($,136,12),W=y71(Y),w=$[157]===0?null:tY($,157,100,I),V=tY($,265,32),Z=tY($,297,32),X=K7($,329,8),L=K7($,337,8),D=aQ0($);if(D===256)return null;if(D!==K7($,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(rQ0.compare($,Dq,Dq+6)===0){if($[345])J=tY($,345,155,I)+"/"+J}else if(j71.compare($,Dq,Dq+6)===0&&_71.compare($,Qg,Qg+2)===0);else if(!U)throw Error("Invalid tar header: unknown format.");if(Y===0&&J&&J[J.length-1]==="/")Y=5;return{name:J,mode:Q,uid:K,gid:q,size:H,mtime:new Date(1000*G),type:W,linkname:w,uname:V,gname:Z,devmajor:X,devminor:L}}});var J20=F((VC1,Y20)=>{var eQ0=a("util"),p71=lQ0(),Fq=Kg(),$20=L6().Writable,I20=L6().PassThrough,U20=function(){},sQ0=function($){return $&=511,$&&512-$},c71=function($,I){var U=new kX($,I);return U.end(),U},d71=function($,I){if(I.path)$.name=I.path;if(I.linkpath)$.linkname=I.linkpath;if(I.size)$.size=parseInt(I.size,10);return $.pax=I,$},kX=function($,I){this._parent=$,this.offset=I,I20.call(this,{autoDestroy:!1})};eQ0.inherits(kX,I20);kX.prototype.destroy=function($){this._parent.destroy($)};var y5=function($){if(!(this instanceof y5))return new y5($);$20.call(this,$),$=$||{},this._offset=0,this._buffer=p71(),this._missing=0,this._partial=!1,this._onparse=U20,this._header=null,this._stream=null,this._overflow=null,this._cb=null,this._locked=!1,this._destroyed=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null;var I=this,U=I._buffer,Y=function(){I._continue()},J=function(V){if(I._locked=!1,V)return I.destroy(V);if(!I._stream)Y()},Q=function(){I._stream=null;var V=sQ0(I._header.size);if(V)I._parse(V,K);else I._parse(512,w);if(!I._locked)Y()},K=function(){I._buffer.consume(sQ0(I._header.size)),I._parse(512,w),Y()},q=function(){var V=I._header.size;I._paxGlobal=Fq.decodePax(U.slice(0,V)),U.consume(V),Q()},H=function(){var V=I._header.size;if(I._pax=Fq.decodePax(U.slice(0,V)),I._paxGlobal)I._pax=Object.assign({},I._paxGlobal,I._pax);U.consume(V),Q()},G=function(){var V=I._header.size;this._gnuLongPath=Fq.decodeLongPath(U.slice(0,V),$.filenameEncoding),U.consume(V),Q()},W=function(){var V=I._header.size;this._gnuLongLinkPath=Fq.decodeLongPath(U.slice(0,V),$.filenameEncoding),U.consume(V),Q()},w=function(){var V=I._offset,Z;try{Z=I._header=Fq.decode(U.slice(0,512),$.filenameEncoding,$.allowUnknownFormat)}catch(X){I.emit("error",X)}if(U.consume(512),!Z){I._parse(512,w),Y();return}if(Z.type==="gnu-long-path"){I._parse(Z.size,G),Y();return}if(Z.type==="gnu-long-link-path"){I._parse(Z.size,W),Y();return}if(Z.type==="pax-global-header"){I._parse(Z.size,q),Y();return}if(Z.type==="pax-header"){I._parse(Z.size,H),Y();return}if(I._gnuLongPath)Z.name=I._gnuLongPath,I._gnuLongPath=null;if(I._gnuLongLinkPath)Z.linkname=I._gnuLongLinkPath,I._gnuLongLinkPath=null;if(I._pax)I._header=Z=d71(Z,I._pax),I._pax=null;if(I._locked=!0,!Z.size||Z.type==="directory"){I._parse(512,w),I.emit("entry",Z,c71(I,V),J);return}I._stream=new kX(I,V),I.emit("entry",Z,I._stream,J),I._parse(Z.size,Q),Y()};this._onheader=w,this._parse(512,w)};eQ0.inherits(y5,$20);y5.prototype.destroy=function($){if(this._destroyed)return;if(this._destroyed=!0,$)this.emit("error",$);if(this.emit("close"),this._stream)this._stream.emit("close")};y5.prototype._parse=function($,I){if(this._destroyed)return;if(this._offset+=$,this._missing=$,I===this._onheader)this._partial=!1;this._onparse=I};y5.prototype._continue=function(){if(this._destroyed)return;var $=this._cb;if(this._cb=U20,this._overflow)this._write(this._overflow,void 0,$);else $()};y5.prototype._write=function($,I,U){if(this._destroyed)return;var Y=this._stream,J=this._buffer,Q=this._missing;if($.length)this._partial=!0;if($.length<Q){ Line truncated
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`)}_writeRelationship($){if(!this.count)this._writeOpen();let I=`rId${++this.count}`;if($.TargetMode)this.stream.write(`<Relationship Id="${I}" Type="${$.Type}" Target="${W31.xmlEncode($.Target)}" TargetMode="${$.TargetMode}"/>`);else this.stream.write(`<Relationship Id="${I}" Type="${$.Type}" Target="${$.Target}"/>`);return I}_writeClose(){this.stream.write("</Relationships>")}}j20.exports=C20});var u20=F((AC1,h20)=>{var S20=I6(),g20=n9(),V31=G4(),Z31=fC(),z31=bC();class y20{constructor($,I,U){this.id=U.id,this.count=0,this._worksheet=$,this._workbook=U.workbook,this._sheetRelsWriter=I}get commentsStream(){if(!this._commentsStream)this._commentsStream=this._workbook._openStream(`/xl/comments${this.id}.xml`);return this._commentsStream}get vmlStream(){if(!this._vmlStream)this._vmlStream=this._workbook._openStream(`xl/drawings/vmlDrawing${this.id}.vml`);return this._vmlStream}_addRelationships(){let $={Type:g20.Comments,Target:`../comments${this.id}.xml`};this._sheetRelsWriter.addRelationship($);let I={Type:g20.VmlDrawing,Target:`../drawings/vmlDrawing${this.id}.vml`};this.vmlRelId=this._sheetRelsWriter.addRelationship(I)}_addCommentRefs(){this._workbook.commentRefs.push({commentName:`comments${this.id}`,vmlDrawing:`vmlDrawing${this.id}`})}_writeOpen(){this.commentsStream.write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><comments xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><authors><author>Author</author></authors><commentList>'),this.vmlStream.write('<?xml version="1.0" encoding="UTF-8"?><xml xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:x="urn:schemas-microsoft-com:office:excel"><o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1" /></o:shapelayout><v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe"><v:stroke joinstyle="miter" /><v:path gradientshapeok="t" o:connecttype="rect" /></v:shapetype>')}_writeComment($,I){let U=new Z31,Y=new S20;U.render(Y,$),this.commentsStream.write(Y.xml);let J=new z31,Q=new S20;J.render(Q,$,I),this.vmlStream.write(Q.xml)}_writeClose(){this.commentsStream.write("</commentList></comments>"),this.vmlStream.write("</xml>")}addComments($){if($&&$.length){if(!this.startedData)this._worksheet.comments=[],this._writeOpen(),this._addRelationships(),this._addCommentRefs(),this.startedData=!0;$.forEach((I)=>{I.refAddress=V31.decodeAddress(I.ref)}),$.forEach((I)=>{this._writeComment(I,this.count),this.count+=1})}}commit(){if(this.count)this._writeClose(),this.commentsStream.end(),this.vmlStream.end()}}h20.exports=y20});var n20=F((PC1,b20)=>{var X31=X4(),L31=n9(),Gg=G4(),x20=YB(),k20=V5(),D31=FR(),f20=UV(),Wg=JV(),F31=_20(),O31=u20(),N31=IB(),n4=new D31,wg=f9(),M31=ZC(),A31=zC(),P31=XC(),T31=GC(),E31=qC(),B31=WC(),v31=LC(),R31=DC(),C31=FC(),j31=OC(),_31=NC(),S31=MC(),g31=BC(),y31=PC(),h31=AC(),p4={dataValidations:new M31,sheetProperties:new A31,sheetFormatProperties:new P31,columns:new wg({tag:"cols",length:!1,childXform:new T31}),row:new E31,hyperlinks:new wg({tag:"hyperlinks",length:!1,childXform:new B31}),sheetViews:new wg({tag:"sheetViews",length:!1,childXform:new v31}),sheetProtection:new R31,pageMargins:new C31,pageSeteup:new j31,autoFilter:new _31,picture:new S31,conditionalFormattings:new g31,headerFooter:new y31,rowBreaks:new h31};class i20{constructor($){this.id=$.id,this.name=$.name||`Sheet${this.id}`,this.state=$.state||"visible",this._rows=[],this._columns=null,this._keys={},this._merges=[],this._merges.add=function(){},this._sheetRelsWriter=new F31($),this._sheetCommentsWriter=new O31(this,this._sheetRelsWriter,$),this._dimensions=new k20,this._rowZero=1,this.committed=!1,this.dataValidations=new N31,this._formulae={},this._siFormulae=0,this.conditionalFormatting=[],this.rowBreaks=[],this.properties=Object.assign({},{defaultRowHeight:15,dyDescent:55,outlineLevelCol:0,outlineLevelRow:0},$.properties),this.headerFooter=Object.assign({},{differentFirst:!1,differentOddEven:!1,oddHeader:null,oddFooter:null,evenHeader:null,evenFooter:null,firstHeader:null,firstFooter:null},$.headerFooter),this.pageSetup=Object.assign({},{margins:{left:0.7,right:0.7,top:0.75,bottom:0.75,header:0.3,footer:0.3},orientation:"portrait",horizontalDpi:4294967295,verticalDpi:4294967295,fitToPage:!!($.pageSetup&&($.pageSetup.fitToWidth||$.pageSetup.fitToHeight)&&!$.pageSetup.scale),pageOrder:"downThenOver",blackAndWhite:!1,draft:!1,cellComments:"None",errors:"displayed",scale:100,fitToWidth:1,fitToHeight:1,paperSize:void 0,showRowColHeaders:!1,showGridLines:!1,horizontalCentered:!1,verticalCentered:!1,rowBreaks:null,colBreaks:null},$.pageSetup),this.useSharedStrings=$.useSharedStrings||!1,this._workbook=$.workbook,this.hasComments=!1,this._views=$.views||[],this.autoFilter=$.autoFilter||null,this._media=[],this.sheetProtection=null,this._writeOpenWorksheet(),this.startedData=!1}get Line truncated
See http://goo.gl/MqrFmX
`)},GS=HS.getNativePromise();if(HS.isNode&&typeof MutationObserver>"u")VS=global.setImmediate,WS=process.nextTick,i3=HS.isRecentNode?function($){VS.call(global,$)}:function($){WS.call(process,$)};else if(typeof GS==="function"&&typeof GS.resolve==="function")ZS=GS.resolve(),i3=function($){ZS.then($)};else if(typeof MutationObserver<"u"&&!(typeof window<"u"&&window.navigator&&(window.navigator.standalone||window.cordova)))i3=function(){var $=document.createElement("div"),I={attributes:!0},q=!1,U=document.createElement("div"),Y=new MutationObserver(function(){$.classList.toggle("foo"),q=!1});Y.observe(U,I);var J=function(){if(q)return;q=!0,U.classList.toggle("foo")};return function(K){var w=new MutationObserver(function(){w.disconnect(),K()});w.observe($,I),J()}}();else if(typeof setImmediate<"u")i3=function($){setImmediate($)};else if(typeof setTimeout<"u")i3=function($){setTimeout($,0)};else i3=jU1;var VS,WS,ZS;WK0.exports=i3});var DK0=L((JR1,XK0)=>{function BU1($,I,q,U,Y){for(var J=0;J<Y;++J)q[J+U]=$[J+I],$[J+I]=void 0}function Y7($){this._capacity=$,this._length=0,this._front=0}Y7.prototype._willBeOverCapacity=function($){return this._capacity<$};Y7.prototype._pushOne=function($){var I=this.length();this._checkCapacity(I+1);var q=this._front+I&this._capacity-1;this[q]=$,this._length=I+1};Y7.prototype.push=function($,I,q){var U=this.length()+3;if(this._willBeOverCapacity(U)){this._pushOne($),this._pushOne(I),this._pushOne(q);return}var Y=this._front+U-3;this._checkCapacity(U);var J=this._capacity-1;this[Y+0&J]=$,this[Y+1&J]=I,this[Y+2&J]=q,this._length=U};Y7.prototype.shift=function(){var $=this._front,I=this[$];return this[$]=void 0,this._front=$+1&this._capacity-1,this._length--,I};Y7.prototype.length=function(){return this._length};Y7.prototype._checkCapacity=function($){if(this._capacity<$)this._resizeTo(this._capacity<<1)};Y7.prototype._resizeTo=function($){var I=this._capacity;this._capacity=$;var q=this._front,U=this._length,Y=q+U&I-1;BU1(this,0,this,I,Y)};XK0.exports=Y7});var gK0=L((QR1,XS)=>{var MK0;try{throw Error()}catch($){MK0=$}var vU1=ZK0(),OK0=DK0(),AK0=n1();function b4(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new OK0(16),this._normalQueue=new OK0(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var $=this;this.drainQueues=function(){$._drainQueues()},this._schedule=vU1}b4.prototype.setScheduler=function($){var I=this._schedule;return this._schedule=$,this._customScheduler=!0,I};b4.prototype.hasCustomScheduler=function(){return this._customScheduler};b4.prototype.enableTrampoline=function(){this._trampolineEnabled=!0};b4.prototype.disableTrampolineIfNecessary=function(){if(AK0.hasDevTools)this._trampolineEnabled=!1};b4.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};b4.prototype.fatalError=function($,I){if(I)process.stderr.write("Fatal "+($ instanceof Error?$.stack:$)+`
`),process.exit(2);else this.throwLater($)};b4.prototype.throwLater=function($,I){if(arguments.length===1)I=$,$=function(){throw I};if(typeof setTimeout<"u")setTimeout(function(){$(I)},0);else try{this._schedule(function(){$(I)})}catch(q){throw Error(`No async scheduler available
`)},Cg=jg.getNativePromise();if(jg.isNode&&typeof MutationObserver>"u")_g=global.setImmediate,Sg=process.nextTick,c3=jg.isRecentNode?function($){_g.call(global,$)}:function($){Sg.call(process,$)};else if(typeof Cg==="function"&&typeof Cg.resolve==="function")gg=Cg.resolve(),c3=function($){gg.then($)};else if(typeof MutationObserver<"u"&&!(typeof window<"u"&&window.navigator&&(window.navigator.standalone||window.cordova)))c3=function(){var $=document.createElement("div"),I={attributes:!0},U=!1,Y=document.createElement("div"),J=new MutationObserver(function(){$.classList.toggle("foo"),U=!1});J.observe(Y,I);var Q=function(){if(U)return;U=!0,Y.classList.toggle("foo")};return function(q){var H=new MutationObserver(function(){H.disconnect(),q()});H.observe($,I),Q()}}();else if(typeof setImmediate<"u")c3=function($){setImmediate($)};else if(typeof setTimeout<"u")c3=function($){setTimeout($,0)};else c3=BI1;var _g,Sg,gg;MK0.exports=c3});var TK0=F((hC1,PK0)=>{function vI1($,I,U,Y,J){for(var Q=0;Q<J;++Q)U[Q+Y]=$[Q+I],$[Q+I]=void 0}function G7($){this._capacity=$,this._length=0,this._front=0}G7.prototype._willBeOverCapacity=function($){return this._capacity<$};G7.prototype._pushOne=function($){var I=this.length();this._checkCapacity(I+1);var U=this._front+I&this._capacity-1;this[U]=$,this._length=I+1};G7.prototype.push=function($,I,U){var Y=this.length()+3;if(this._willBeOverCapacity(Y)){this._pushOne($),this._pushOne(I),this._pushOne(U);return}var J=this._front+Y-3;this._checkCapacity(Y);var Q=this._capacity-1;this[J+0&Q]=$,this[J+1&Q]=I,this[J+2&Q]=U,this._length=Y};G7.prototype.shift=function(){var $=this._front,I=this[$];return this[$]=void 0,this._front=$+1&this._capacity-1,this._length--,I};G7.prototype.length=function(){return this._length};G7.prototype._checkCapacity=function($){if(this._capacity<$)this._resizeTo(this._capacity<<1)};G7.prototype._resizeTo=function($){var I=this._capacity;this._capacity=$;var U=this._front,Y=this._length,J=U+Y&I-1;vI1(this,0,this,I,J)};PK0.exports=G7});var _K0=F((uC1,yg)=>{var CK0;try{throw Error()}catch($){CK0=$}var RI1=AK0(),EK0=TK0(),jK0=c1();function c4(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new EK0(16),this._normalQueue=new EK0(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var $=this;this.drainQueues=function(){$._drainQueues()},this._schedule=RI1}c4.prototype.setScheduler=function($){var I=this._schedule;return this._schedule=$,this._customScheduler=!0,I};c4.prototype.hasCustomScheduler=function(){return this._customScheduler};c4.prototype.enableTrampoline=function(){this._trampolineEnabled=!0};c4.prototype.disableTrampolineIfNecessary=function(){if(jK0.hasDevTools)this._trampolineEnabled=!1};c4.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};c4.prototype.fatalError=function($,I){if(I)process.stderr.write("Fatal "+($ instanceof Error?$.stack:$)+`
`),process.exit(2);else this.throwLater($)};c4.prototype.throwLater=function($,I){if(arguments.length===1)I=$,$=function(){throw I};if(typeof setTimeout<"u")setTimeout(function(){$(I)},0);else try{this._schedule(function(){$(I)})}catch(U){throw Error(`No async scheduler available
See http://goo.gl/MqrFmX
`)}};function LK0($,I,q){this._lateQueue.push($,I,q),this._queueTick()}function NK0($,I,q){this._normalQueue.push($,I,q),this._queueTick()}function FK0($){this._normalQueue._pushOne($),this._queueTick()}if(!AK0.hasDevTools)b4.prototype.invokeLater=LK0,b4.prototype.invoke=NK0,b4.prototype.settlePromises=FK0;else b4.prototype.invokeLater=function($,I,q){if(this._trampolineEnabled)LK0.call(this,$,I,q);else this._schedule(function(){setTimeout(function(){$.call(I,q)},100)})},b4.prototype.invoke=function($,I,q){if(this._trampolineEnabled)NK0.call(this,$,I,q);else this._schedule(function(){$.call(I,q)})},b4.prototype.settlePromises=function($){if(this._trampolineEnabled)FK0.call(this,$);else this._schedule(function(){$._settlePromises()})};b4.prototype._drainQueue=function($){while($.length()>0){var I=$.shift();if(typeof I!=="function"){I._settlePromises();continue}var q=$.shift(),U=$.shift();I.call(q,U)}};b4.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)};b4.prototype._queueTick=function(){if(!this._isTickUsed)this._isTickUsed=!0,this._schedule(this.drainQueues)};b4.prototype._reset=function(){this._isTickUsed=!1};XS.exports=b4;XS.exports.firstLineError=MK0});var S5=L((KR1,EK0)=>{var LS=n3(),RU1=LS.freeze,PK0=n1(),TK0=PK0.inherits,eU=PK0.notEnumerableProp;function $Y($,I){function q(U){if(!(this instanceof q))return new q(U);if(eU(this,"message",typeof U==="string"?U:I),eU(this,"name",$),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else Error.call(this)}return TK0(q,Error),q}var DS,OS,CU1=$Y("Warning","warning"),_U1=$Y("CancellationError","cancellation error"),hU1=$Y("TimeoutError","timeout error"),NK=$Y("AggregateError","aggregate error");try{DS=TypeError,OS=RangeError}catch($){DS=$Y("TypeError","type error"),OS=$Y("RangeError","range error")}var qD="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" ");for(b3=0;b3<qD.length;++b3)if(typeof Array.prototype[qD[b3]]==="function")NK.prototype[qD[b3]]=Array.prototype[qD[b3]];var b3;LS.defineProperty(NK.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0});NK.prototype.isOperational=!0;var UD=0;NK.prototype.toString=function(){var $=Array(UD*4+1).join(" "),I=`
`)}};function BK0($,I,U){this._lateQueue.push($,I,U),this._queueTick()}function vK0($,I,U){this._normalQueue.push($,I,U),this._queueTick()}function RK0($){this._normalQueue._pushOne($),this._queueTick()}if(!jK0.hasDevTools)c4.prototype.invokeLater=BK0,c4.prototype.invoke=vK0,c4.prototype.settlePromises=RK0;else c4.prototype.invokeLater=function($,I,U){if(this._trampolineEnabled)BK0.call(this,$,I,U);else this._schedule(function(){setTimeout(function(){$.call(I,U)},100)})},c4.prototype.invoke=function($,I,U){if(this._trampolineEnabled)vK0.call(this,$,I,U);else this._schedule(function(){$.call(I,U)})},c4.prototype.settlePromises=function($){if(this._trampolineEnabled)RK0.call(this,$);else this._schedule(function(){$._settlePromises()})};c4.prototype._drainQueue=function($){while($.length()>0){var I=$.shift();if(typeof I!=="function"){I._settlePromises();continue}var U=$.shift(),Y=$.shift();I.call(U,Y)}};c4.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)};c4.prototype._queueTick=function(){if(!this._isTickUsed)this._isTickUsed=!0,this._schedule(this.drainQueues)};c4.prototype._reset=function(){this._isTickUsed=!1};yg.exports=c4;yg.exports.firstLineError=CK0});var u5=F((xC1,yK0)=>{var xg=p3(),CI1=xg.freeze,SK0=c1(),gK0=SK0.inherits,IJ=SK0.notEnumerableProp;function UJ($,I){function U(Y){if(!(this instanceof U))return new U(Y);if(IJ(this,"message",typeof Y==="string"?Y:I),IJ(this,"name",$),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else Error.call(this)}return gK0(U,Error),U}var hg,ug,jI1=UJ("Warning","warning"),_I1=UJ("CancellationError","cancellation error"),SI1=UJ("TimeoutError","timeout error"),Tq=UJ("AggregateError","aggregate error");try{hg=TypeError,ug=RangeError}catch($){hg=UJ("TypeError","type error"),ug=UJ("RangeError","range error")}var lX="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" ");for(d3=0;d3<lX.length;++d3)if(typeof Array.prototype[lX[d3]]==="function")Tq.prototype[lX[d3]]=Array.prototype[lX[d3]];var d3;xg.defineProperty(Tq.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0});Tq.prototype.isOperational=!0;var oX=0;Tq.prototype.toString=function(){var $=Array(oX*4+1).join(" "),I=`
`+$+`AggregateError of:
`;UD++,$=Array(UD*4+1).join(" ");for(var q=0;q<this.length;++q){var U=this[q]===this?"[Circular AggregateError]":this[q]+"",Y=U.split(`
`);for(var J=0;J<Y.length;++J)Y[J]=$+Y[J];U=Y.join(`
`),I+=U+`
`}return UD--,I};function LK($){if(!(this instanceof LK))return new LK($);if(eU(this,"name","OperationalError"),eU(this,"message",$),this.cause=$,this.isOperational=!0,$ instanceof Error)eU(this,"message",$.message),eU(this,"stack",$.stack);else if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}TK0(LK,Error);var p3=Error.__BluebirdErrorTypes__;if(!p3)p3=RU1({CancellationError:_U1,TimeoutError:hU1,OperationalError:LK,RejectionError:LK,AggregateError:NK}),LS.defineProperty(Error,"__BluebirdErrorTypes__",{value:p3,writable:!1,enumerable:!1,configurable:!1});EK0.exports={Error,TypeError:DS,RangeError:OS,CancellationError:p3.CancellationError,OperationalError:p3.OperationalError,TimeoutError:p3.TimeoutError,AggregateError:p3.AggregateError,Warning:CU1}});var BK0=L((wR1,jK0)=>{jK0.exports=function($,I){var q=n1(),U=q.errorObj,Y=q.isObject;function J(H,V){if(Y(H)){if(H instanceof $)return H;var W=K(H);if(W===U){if(V)V._pushContext();var X=$.reject(W.e);if(V)V._popContext();return X}else if(typeof W==="function"){if(z(H)){var X=new $(I);return H._then(X._fulfill,X._reject,void 0,X,null),X}return G(H,W,V)}}return H}function Q(H){return H.then}function K(H){try{return Q(H)}catch(V){return U.e=V,U}}var w={}.hasOwnProperty;function z(H){try{return w.call(H,"_promise0")}catch(V){return!1}}function G(H,V,W){var X=new $(I),D=X;if(W)W._pushContext();if(X._captureStackTrace(),W)W._popContext();var O=!0,N=q.tryCatch(V).call(H,T,P);if(O=!1,X&&N===U)X._rejectCallback(N.e,!0,!0),X=null;function T(g){if(!X)return;X._resolveCallback(g),X=null}function P(g){if(!X)return;X._rejectCallback(g,O,!0),X=null}return D}return J}});var RK0=L((zR1,vK0)=>{vK0.exports=function($,I,q,U,Y){var J=n1(),Q=J.isArray;function K(z){switch(z){case-2:return[];case-3:return{}}}function w(z){var G=this._promise=new $(I);if(z instanceof $)G._propagateFrom(z,3);G._setOnCancel(this),this._values=z,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return J.inherits(w,Y),w.prototype.length=function(){return this._length},w.prototype.promise=function(){return this._promise},w.prototype._init=function z(G,H){var V=q(this._values,this._promise);if(V instanceof $){V=V._target();var W=V._bitField;if(this._values=V,(W&50397184)===0)return this._promise._setAsyncGuaranteed(),V._then(z,this._reject,void 0,this,H);else if((W&33554432)!==0)V=V._value();else if((W&16777216)!==0)return this._reject(V._reason());else return this._cancel()}if(V=J.asArray(V),V===null){var X=U("expecting an array or an iterable object but got "+J.classString(V)).reason();this._promise._rejectCallback(X,!1);return}if(V.length===0){if(H===-5)this._resolveEmptyArray();else this._resolve(K(H));return}this._iterate(V)},w.prototype._iterate=function(z){var G=this.getActualLength(z.length);this._length=G,this._values=this.shouldCopyValues()?Array(G):this._values;var H=this._promise,V=!1,W=null;for(var X=0;X<G;++X){var D=q(z[X],H);if(D instanceof $)D=D._target(),W=D._bitField;else W=null;if(V){if(W!==null)D.suppressUnhandledRejections()}else if(W!==null)if((W&50397184)===0)D._proxy(this,X),this._values[X]=D;else if((W&33554432)!==0)V=this._promiseFulfilled(D._value(),X);else if((W&16777216)!==0)V=this._promiseRejected(D._reason(),X);else V=this._promiseCancelled(X);else V=this._promiseFulfilled(D,X)}if(!V)H._setAsyncGuaranteed()},w.prototype._isResolved=function(){return this._values===null},w.prototype._resolve=function(z){this._values=null,this._promise._fulfill(z)},w.prototype._cancel=function(){if(this._isResolved()||!this._promise._isCancellable())return;this._values=null,this._promise._cancel()},w.prototype._reject=function(z){this._values=null,this._promise._rejectCallback(z,!1)},w.prototype._promiseFulfilled=function(z,G){this._values[G]=z;var H=++this._totalResolved;if(H>=this._length)return this._resolve(this._values),!0;return!1},w.prototype._promiseCancelled=function(){return this._cancel(),!0},w.prototype._promiseRejected=function(z){return this._totalResolved++,this._reject(z),!0},w.prototype._resultCancelled=function(){if(this._isResolved())return;var z=this._values;if(this._cancel(),z instanceof $)z.cancel();else for(var G=0;G<z.length;++G)if(z[G]instanceof $)z[G].cancel()},w.prototype.shouldCopyValues=function(){return!0},w.prototype.getActualLength=function(z){return z},w}});var _K0=L((GR1,CK0)=>{CK0.exports=function($){var I=!1,q=[];$.prototype._promiseCreated=function(){},$.prototype._pushContext=function(){},$.prototype._popContext=function(){return null},$._peekContext=$.prototype._peekContext=function(){};function U(){this._trace=new U.CapturedTrace(J())}U.prototype._pushContext=function(){if(this._trace!==void 0)this._trace._promiseCreated=null,q.push(this._trace)},U.prototype._popContext=function(){if(this._trace!==void 0){var Q=q.pop(),K=Q._promiseCreated;return Q._promiseCreated=null,K}return null};function Y(){if(I)return new U}function J(){var Q=q.length-1;if(Q>=0)return q[Q];return}return U.CapturedTrace=null,U.create=Y,U.deactivateLong Line truncated
`;oX++,$=Array(oX*4+1).join(" ");for(var U=0;U<this.length;++U){var Y=this[U]===this?"[Circular AggregateError]":this[U]+"",J=Y.split(`
`);for(var Q=0;Q<J.length;++Q)J[Q]=$+J[Q];Y=J.join(`
`),I+=Y+`
`}return oX--,I};function Pq($){if(!(this instanceof Pq))return new Pq($);if(IJ(this,"name","OperationalError"),IJ(this,"message",$),this.cause=$,this.isOperational=!0,$ instanceof Error)IJ(this,"message",$.message),IJ(this,"stack",$.stack);else if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}gK0(Pq,Error);var m3=Error.__BluebirdErrorTypes__;if(!m3)m3=CI1({CancellationError:_I1,TimeoutError:SI1,OperationalError:Pq,RejectionError:Pq,AggregateError:Tq}),xg.defineProperty(Error,"__BluebirdErrorTypes__",{value:m3,writable:!1,enumerable:!1,configurable:!1});yK0.exports={Error,TypeError:hg,RangeError:ug,CancellationError:m3.CancellationError,OperationalError:m3.OperationalError,TimeoutError:m3.TimeoutError,AggregateError:m3.AggregateError,Warning:jI1}});var uK0=F((kC1,hK0)=>{hK0.exports=function($,I){var U=c1(),Y=U.errorObj,J=U.isObject;function Q(w,V){if(J(w)){if(w instanceof $)return w;var Z=q(w);if(Z===Y){if(V)V._pushContext();var X=$.reject(Z.e);if(V)V._popContext();return X}else if(typeof Z==="function"){if(G(w)){var X=new $(I);return w._then(X._fulfill,X._reject,void 0,X,null),X}return W(w,Z,V)}}return w}function K(w){return w.then}function q(w){try{return K(w)}catch(V){return Y.e=V,Y}}var H={}.hasOwnProperty;function G(w){try{return H.call(w,"_promise0")}catch(V){return!1}}function W(w,V,Z){var X=new $(I),L=X;if(Z)Z._pushContext();if(X._captureStackTrace(),Z)Z._popContext();var D=!0,O=U.tryCatch(V).call(w,E,T);if(D=!1,X&&O===Y)X._rejectCallback(O.e,!0,!0),X=null;function E(A){if(!X)return;X._resolveCallback(A),X=null}function T(A){if(!X)return;X._rejectCallback(A,D,!0),X=null}return L}return Q}});var kK0=F((fC1,xK0)=>{xK0.exports=function($,I,U,Y,J){var Q=c1(),K=Q.isArray;function q(G){switch(G){case-2:return[];case-3:return{}}}function H(G){var W=this._promise=new $(I);if(G instanceof $)W._propagateFrom(G,3);W._setOnCancel(this),this._values=G,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return Q.inherits(H,J),H.prototype.length=function(){return this._length},H.prototype.promise=function(){return this._promise},H.prototype._init=function G(W,w){var V=U(this._values,this._promise);if(V instanceof $){V=V._target();var Z=V._bitField;if(this._values=V,(Z&50397184)===0)return this._promise._setAsyncGuaranteed(),V._then(G,this._reject,void 0,this,w);else if((Z&33554432)!==0)V=V._value();else if((Z&16777216)!==0)return this._reject(V._reason());else return this._cancel()}if(V=Q.asArray(V),V===null){var X=Y("expecting an array or an iterable object but got "+Q.classString(V)).reason();this._promise._rejectCallback(X,!1);return}if(V.length===0){if(w===-5)this._resolveEmptyArray();else this._resolve(q(w));return}this._iterate(V)},H.prototype._iterate=function(G){var W=this.getActualLength(G.length);this._length=W,this._values=this.shouldCopyValues()?Array(W):this._values;var w=this._promise,V=!1,Z=null;for(var X=0;X<W;++X){var L=U(G[X],w);if(L instanceof $)L=L._target(),Z=L._bitField;else Z=null;if(V){if(Z!==null)L.suppressUnhandledRejections()}else if(Z!==null)if((Z&50397184)===0)L._proxy(this,X),this._values[X]=L;else if((Z&33554432)!==0)V=this._promiseFulfilled(L._value(),X);else if((Z&16777216)!==0)V=this._promiseRejected(L._reason(),X);else V=this._promiseCancelled(X);else V=this._promiseFulfilled(L,X)}if(!V)w._setAsyncGuaranteed()},H.prototype._isResolved=function(){return this._values===null},H.prototype._resolve=function(G){this._values=null,this._promise._fulfill(G)},H.prototype._cancel=function(){if(this._isResolved()||!this._promise._isCancellable())return;this._values=null,this._promise._cancel()},H.prototype._reject=function(G){this._values=null,this._promise._rejectCallback(G,!1)},H.prototype._promiseFulfilled=function(G,W){this._values[W]=G;var w=++this._totalResolved;if(w>=this._length)return this._resolve(this._values),!0;return!1},H.prototype._promiseCancelled=function(){return this._cancel(),!0},H.prototype._promiseRejected=function(G){return this._totalResolved++,this._reject(G),!0},H.prototype._resultCancelled=function(){if(this._isResolved())return;var G=this._values;if(this._cancel(),G instanceof $)G.cancel();else for(var W=0;W<G.length;++W)if(G[W]instanceof $)G[W].cancel()},H.prototype.shouldCopyValues=function(){return!0},H.prototype.getActualLength=function(G){return G},H}});var iK0=F((iC1,fK0)=>{fK0.exports=function($){var I=!1,U=[];$.prototype._promiseCreated=function(){},$.prototype._pushContext=function(){},$.prototype._popContext=function(){return null},$._peekContext=$.prototype._peekContext=function(){};function Y(){this._trace=new Y.CapturedTrace(Q())}Y.prototype._pushContext=function(){if(this._trace!==void 0)this._trace._promiseCreated=null,U.push(this._trace)},Y.prototype._popContext=function(){if(this._trace!==void 0){var K=U.pop(),q=K._promiseCreated;return K._promiseCreated=null,q}return null};function J(){if(I)return new Y}function Q(){var K=U.length-1;if(K>=0)return U[K];return}return Y.CapturedTrace=null,Y.create=J,Y.deactivateLong Line truncated
See http://goo.gl/MqrFmX
`);if(!g0.longStackTraces&&y$()){var r=$.prototype._captureStackTrace,F=$.prototype._attachExtraTrace;g0.longStackTraces=!0,g=function(){if(U.haveItemsQueued()&&!g0.longStackTraces)throw Error(`cannot enable long stack traces after promises have been created
`);if(!v0.longStackTraces&&i6()){var s=$.prototype._captureStackTrace,N=$.prototype._attachExtraTrace;v0.longStackTraces=!0,A=function(){if(Y.haveItemsQueued()&&!v0.longStackTraces)throw Error(`cannot enable long stack traces after promises have been created
See http://goo.gl/MqrFmX
`);$.prototype._captureStackTrace=r,$.prototype._attachExtraTrace=F,I.deactivateLongStackTraces(),U.enableTrampoline(),g0.longStackTraces=!1},$.prototype._captureStackTrace=K0,$.prototype._attachExtraTrace=G0,I.activateLongStackTraces(),U.disableTrampolineIfNecessary()}},$.hasLongStackTraces=function(){return g0.longStackTraces&&y$()};var B=function(){try{if(typeof CustomEvent==="function"){var r=new CustomEvent("CustomEvent");return J.global.dispatchEvent(r),function(F,M){var v=new CustomEvent(F.toLowerCase(),{detail:M,cancelable:!0});return!J.global.dispatchEvent(v)}}else if(typeof Event==="function"){var r=new Event("CustomEvent");return J.global.dispatchEvent(r),function(M,v){var y=new Event(M.toLowerCase(),{cancelable:!0});return y.detail=v,!J.global.dispatchEvent(y)}}else{var r=document.createEvent("CustomEvent");return r.initCustomEvent("testingtheevent",!1,!0,{}),J.global.dispatchEvent(r),function(M,v){var y=document.createEvent("CustomEvent");return y.initCustomEvent(M.toLowerCase(),!1,!0,v),!J.global.dispatchEvent(y)}}}catch(F){}return function(){return!1}}(),k=function(){if(J.isNode)return function(){return process.emit.apply(process,arguments)};else{if(!J.global)return function(){return!1};return function(r){var F="on"+r.toLowerCase(),M=J.global[F];if(!M)return!1;return M.apply(J.global,[].slice.call(arguments,1)),!0}}}();function h(r,F){return{promise:F}}var f={promiseCreated:h,promiseFulfilled:h,promiseRejected:h,promiseResolved:h,promiseCancelled:h,promiseChained:function(r,F,M){return{promise:F,child:M}},warning:function(r,F){return{warning:F}},unhandledRejection:function(r,F,M){return{reason:F,promise:M}},rejectionHandled:h},S=function(r){var F=!1;try{F=k.apply(null,arguments)}catch(v){U.throwLater(v),F=!0}var M=!1;try{M=B(r,f[r].apply(null,arguments))}catch(v){U.throwLater(v),M=!0}return M||F};$.config=function(r){if(r=Object(r),"longStackTraces"in r){if(r.longStackTraces)$.longStackTraces();else if(!r.longStackTraces&&$.hasLongStackTraces())g()}if("warnings"in r){var F=r.warnings;if(g0.warnings=!!F,P=g0.warnings,J.isObject(F)){if("wForgottenReturn"in F)P=!!F.wForgottenReturn}}if("cancellation"in r&&r.cancellation&&!g0.cancellation){if(U.haveItemsQueued())throw Error("cannot enable cancellation after promises are in use");$.prototype._clearCancellationData=J0,$.prototype._propagateFrom=E,$.prototype._onCancel=n,$.prototype._setOnCancel=i,$.prototype._attachCancellationCallback=C,$.prototype._execute=p,d=E,g0.cancellation=!0}if("monitoring"in r){if(r.monitoring&&!g0.monitoring)g0.monitoring=!0,$.prototype._fireEvent=S;else if(!r.monitoring&&g0.monitoring)g0.monitoring=!1,$.prototype._fireEvent=t}return $};function t(){return!1}$.prototype._fireEvent=t,$.prototype._execute=function(r,F,M){try{r(F,M)}catch(v){return v}},$.prototype._onCancel=function(){},$.prototype._setOnCancel=function(r){},$.prototype._attachCancellationCallback=function(r){},$.prototype._captureStackTrace=function(){},$.prototype._attachExtraTrace=function(){},$.prototype._clearCancellationData=function(){},$.prototype._propagateFrom=function(r,F){};function p(r,F,M){var v=this;try{r(F,M,function(y){if(typeof y!=="function")throw TypeError("onCancel must be a function, got: "+J.toString(y));v._attachCancellationCallback(y)})}catch(y){return y}}function C(r){if(!this._isCancellable())return this;var F=this._onCancel();if(F!==void 0)if(J.isArray(F))F.push(r);else this._setOnCancel([F,r]);else this._setOnCancel(r)}function n(){return this._onCancelField}function i(r){this._onCancelField=r}function J0(){this._cancellationParent=void 0,this._onCancelField=void 0}function E(r,F){if((F&1)!==0){this._cancellationParent=r;var M=r._branchesRemainingToCancel;if(M===void 0)M=0;r._branchesRemainingToCancel=M+1}if((F&2)!==0&&r._isBound())this._setBoundTo(r._boundTo)}function u(r,F){if((F&2)!==0&&r._isBound())this._setBoundTo(r._boundTo)}var d=u;function a(){var r=this._boundTo;if(r!==void 0){if(r instanceof $)if(r.isFulfilled())return r.value();else return}return r}function K0(){this._trace=new s6(this._peekContext())}function G0(r,F){if(Q(r)){var M=this._trace;if(M!==void 0){if(F)M=M._parent}if(M!==void 0)M.attachExtraTrace(r);else if(!r.__stackCleaned__){var v=J4(r);J.notEnumerableProp(r,"stack",v.message+`
`+v.stack.join(`
`)),J.notEnumerableProp(r,"__stackCleaned__",!0)}}}function M0(r,F,M,v,y){if(r===void 0&&F!==null&&P){if(y!==void 0&&y._returnedNonUndefined())return;if((v._bitField&65535)===0)return;if(M)M=M+" ";var s="",c="";if(F._trace){var e=F._trace.stack.split(`
`),U0=J1(e);for(var z0=U0.length-1;z0>=0;--z0){var T0=U0[z0];if(!G.test(T0)){var x0=T0.match(H);if(x0)s="at "+x0[1]+":"+x0[2]+":"+x0[3]+" ";break}}if(U0.length>0){var y0=U0[0];for(var z0=0;z0<e.length;++z0)if(e[z0]===y0){if(z0>0)c=`
`+e[z0-1];break}}}var I1="a promise was created in a "+M+"handler "+s+"but was not returned from it, see http://goo.gl/rRqMUw"+c;v._warn(I1,!0,F)}}function R0(r,F){var M=r+" is deprecated and will be removed in a future version.";if(F)M+=" Use "+F+" instead.";return v1(M)}function v1(r,F,M){if(!g0.warnings)return;var v=new Y(r),y;if(F)M._attachExtraTrace(v);else if(g0.longStackTraces&&(y=$._peekContext()))y.attachExtraTrace(v);else{var s=J4(v);v.stack=s.message+`
`+s.stack.join(`
`)}if(!S("warning",v))R4(v,"",!0)}function l0(r,F){for(var M=0;M<F.length-1;++M)F[M].push("From previous event:"),F[M]=F[M].join(`
`);if(M<F.length)F[M]=F[M].join(`
`);return r+`
`+F.join(`
`)}function L1(r){for(var F=0;F<r.length;++F)if(r[F].length===0||F+1<r.length&&r[F][0]===r[F+1][0])r.splice(F,1),F--}function N1(r){var F=r[0];for(var M=1;M<r.length;++M){var v=r[M],y=F.length-1,s=F[y],c=-1;for(var e=v.length-1;e>=0;--e)if(v[e]===s){c=e;break}for(var e=c;e>=0;--e){var U0=v[e];if(F[y]===U0)F.pop(),y--;else break}F=v}}function J1(r){var F=[];for(var M=0;M<r.length;++M){var v=r[M],y=v===" (No stack trace)"||V.test(v),s=y&&H$(v);if(y&&!s){if(X&&v.charAt(0)!==" ")v=" "+v;F.push(v)}}return F}function C1(r){var F=r.stack.replace(/\s+$/g,"").split(`
`);for(var M=0;M<F.length;++M){var v=F[M];if(v===" (No stack trace)"||V.test(v))break}if(M>0&&r.name!="SyntaxError")F=F.slice(M);return F}function J4(r){var F=r.stack,M=r.toString();return F=typeof F==="string"&&F.length>0?C1(r):[" (No stack trace)"],{message:M,stack:r.name=="SyntaxError"?F:J1(F)}}function R4(r,F,M){if(typeof console<"u"){var v;if(J.isObject(r)){var y=r.stack;v=F+W(y,r)}else v=F+String(r);if(typeof D==="function")D(v,M);else if(typeof console.log==="function"||typeof console.log==="object")console.log(v)}}function G$(r,F,M,v){var y=!1;try{if(typeof F==="function")if(y=!0,r==="rejectionHandled")F(v);else F(M,v)}catch(s){U.throwLater(s)}if(r==="unhandledRejection"){if(!S(r,M,v)&&!y)R4(M,"Unhandled rejection ")}else S(r,v)}function S$(r){var F;if(typeof r==="function")F="[function "+(r.name||"anonymous")+"]";else{F=r&&typeof r.toString==="function"?r.toString():J.toString(r);var M=/\[object [a-zA-Z0-9$_]+\]/;if(M.test(F))try{var v=JSON.stringify(r);F=v}catch(y){}if(F.length===0)F="(empty array)"}return"(<"+d8(F)+">, no stack trace)"}function d8(r){var F=41;if(r.length<F)return r;return r.substr(0,F-3)+"..."}function y$(){return typeof d5==="function"}var H$=function(){return!1},l8=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function a6(r){var F=r.match(l8);if(F)return{fileName:F[1],line:parseInt(F[2],10)}}function O7(r,F){if(!y$())return;var M=r.stack.split(`
`),v=F.stack.split(`
`),y=-1,s=-1,c,e;for(var U0=0;U0<M.length;++U0){var z0=a6(M[U0]);if(z0){c=z0.fileName,y=z0.line;break}}for(var U0=0;U0<v.length;++U0){var z0=a6(v[U0]);if(z0){e=z0.fileName,s=z0.line;break}}if(y<0||s<0||!c||!e||c!==e||y>=s)return;H$=function(T0){if(z.test(T0))return!0;var x0=a6(T0);if(x0){if(x0.fileName===c&&(y<=x0.line&&x0.line<=s))return!0}return!1}}function s6(r){this._parent=r,this._promisesCreated=0;var F=this._length=1+(r===void 0?0:r._length);if(d5(this,s6),F>32)this.uncycle()}J.inherits(s6,Error),I.CapturedTrace=s6,s6.prototype.uncycle=function(){var r=this._length;if(r<2)return;var F=[],M={};for(var v=0,y=this;y!==void 0;++v)F.push(y),y=y._parent;r=this._length=v;for(var v=r-1;v>=0;--v){var s=F[v].stack;if(M[s]===void 0)M[s]=v}for(var v=0;v<r;++v){var c=F[v].stack,e=M[c];if(e!==void 0&&e!==v){if(e>0)F[e-1]._parent=void 0,F[e-1]._length=1;F[v]._parent=void 0,F[v]._length=1;var U0=v>0?F[v-1]:this;if(e<r-1)U0._parent=F[e+1],U0._parent.uncycle(),U0._length=U0._parent._length+1;else U0._parent=void 0,U0._length=1;var z0=U0._length+1;for(var T0=v-2;T0>=0;--T0)F[T0]._length=z0,z0++;return}}},s6.prototype.attachExtraTrace=function(r){if(r.__stackCleaned__)return;this.uncycle();var F=J4(r),M=F.message,v=[F.stack],y=this;while(y!==void 0)v.push(J1(y.stack.split(`
`))),y=y._parent;N1(v),L1(v),J.notEnumerableProp(r,"stack",l0(M,v)),J.notEnumerableProp(r,"__stackCleaned__",!0)};var d5=function(){var F=/^\s*at\s*/,M=function(c,e){if(typeof c==="string")return c;if(e.name!==void 0&&e.message!==void 0)return e.toString();return S$(e)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6,V=F,W=M;var v=Error.captureStackTrace;return H$=function(c){return z.test(c)},function(c,e){Error.stackTraceLimit+=6,v(c,e),Error.stackTraceLimit-=6}}var y=Error();if(typeof y.stack==="string"&&y.stack.split(`
`)[0].indexOf("stackDetection@")>=0)return V=/@/,W=M,X=!0,function(e){e.stack=Error().stack};var s;try{throw Error()}catch(c){s="stack"in c}if(!("stack"in y)&&s&&typeof Error.stackTraceLimit==="number")return V=F,W=M,function(e){Error.stackTraceLimit+=6;try{throw Error()}catch(U0){e.stack=U0.stack}Error.stackTraceLimit-=6};return W=function(c,e){if(typeof c==="string")return c;if((typeof e==="object"||typeof e==="function")&&e.name!==void 0&&e.message!==void 0)return e.toString();return S$(e)},null}([]);if(typeof console<"u"&&typeof console.warn<"u"){if(D=function(r){console.warn(r)},J.isNode&&process.stderr.isTTY)D=function(r,F){var M=F?"\x1B[33m":"\x1B[31m";console.warn(M+r+`\x1B[0m
`)};else if(!J.isNode&&typeof Error().stack==="string")D=function(r,F){console.warn("%c"+r,F?"color: darkorange":"color: red")}}var g0={warnings:N,longStackTraces:!1,cancellation:!1,monitoring:!1};if(T)$.longStackTraces();return{longStackTraces:function(){return g0.longStackTraces},warnings:function(){return g0.warnings},cancellation:function(){return g0.cancellation},monitoring:function(){return g0.monitoring},propagateFromFunction:function(){return d},boundValueFunction:function(){return a},checkForgottenReturns:M0,setBounds:O7,warn:v1,deprecated:R0,CapturedTrace:s6,fireDomEvent:B,fireGlobalEvent:k}}});var uK0=L((VR1,yK0)=>{yK0.exports=function($,I){var q=n1(),U=$.CancellationError,Y=q.errorObj;function J(H,V,W){this.promise=H,this.type=V,this.handler=W,this.called=!1,this.cancelPromise=null}J.prototype.isFinallyHandler=function(){return this.type===0};function Q(H){this.finallyHandler=H}Q.prototype._resultCancelled=function(){K(this.finallyHandler)};function K(H,V){if(H.cancelPromise!=null){if(arguments.length>1)H.cancelPromise._reject(V);else H.cancelPromise._cancel();return H.cancelPromise=null,!0}return!1}function w(){return G.call(this,this.promise._target()._settledValue())}function z(H){if(K(this,H))return;return Y.e=H,Y}function G(H){var V=this.promise,W=this.handler;if(!this.called){this.called=!0;var X=this.isFinallyHandler()?W.call(V._boundValue()):W.call(V._boundValue(),H);if(X!==void 0){V._setReturnedNonUndefined();var D=I(X,V);if(D instanceof $){if(this.cancelPromise!=null){if(D._isCancelled()){var O=new U("late cancellation observer");return V._attachExtraTrace(O),Y.e=O,Y}else if(D.isPending())D._attachCancellationCallback(new Q(this))}return D._then(w,z,void 0,this,void 0)}}}if(V.isRejected())return K(this),Y.e=H,Y;else return K(this),H}return $.prototype._passThrough=function(H,V,W,X){if(typeof H!=="function")return this.then();return this._then(W,X,void 0,new J(this,V,H),void 0)},$.prototype.lastly=$.prototype.finally=function(H){return this._passThrough(H,0,G,G)},$.prototype.tap=function(H){return this._passThrough(H,1,G)},J}});var kK0=L((WR1,xK0)=>{xK0.exports=function($){var I=n1(),q=n3().keys,U=I.tryCatch,Y=I.errorObj;function J(Q,K,w){return function(z){var G=w._boundValue();$:for(var H=0;H<Q.length;++H){var V=Q[H];if(V===Error||V!=null&&V.prototype instanceof Error){if(z instanceof V)return U(K).call(G,z)}else if(typeof V==="function"){var W=U(V).call(G,z);if(W===Y)return W;else if(W)return U(K).call(G,z)}else if(I.isObject(z)){var X=q(V);for(var D=0;D<X.length;++D){var O=X[D];if(V[O]!=z[O])continue $}return U(K).call(G,z)}}return $}}return J}});var NS=L((ZR1,iK0)=>{var fK0=n1(),SU1=fK0.maybeWrapAsError,yU1=S5(),uU1=yU1.OperationalError,nK0=n3();function xU1($){return $ instanceof Error&&nK0.getPrototypeOf($)===Error.prototype}var kU1=/^(?:name|message|stack|cause)$/;function fU1($){var I;if(xU1($)){I=new uU1($),I.name=$.name,I.message=$.message,I.stack=$.stack;var q=nK0.keys($);for(var U=0;U<q.length;++U){var Y=q[U];if(!kU1.test(Y))I[Y]=$[Y]}return I}return fK0.markAsOriginatingFromRejection($),$}function nU1($,I){return function(q,U){if($===null)return;if(q){var Y=fU1(SU1(q));$._attachExtraTrace(Y),$._reject(Y)}else if(!I)$._fulfill(U);else{var J=arguments.length,Q=Array(Math.max(J-1,0));for(var K=1;K<J;++K)Q[K-1]=arguments[K];$._fulfill(Q)}$=null}}iK0.exports=nU1});var pK0=L((XR1,bK0)=>{bK0.exports=function($,I,q,U,Y){var J=n1(),Q=J.tryCatch;$.method=function(K){if(typeof K!=="function")throw new $.TypeError("expecting a function but got "+J.classString(K));return function(){var w=new $(I);w._captureStackTrace(),w._pushContext();var z=Q(K).apply(this,arguments),G=w._popContext();return Y.checkForgottenReturns(z,G,"Promise.method",w),w._resolveFromSyncValue(z),w}},$.attempt=$.try=function(K){if(typeof K!=="function")return U("expecting a function but got "+J.classString(K));var w=new $(I);w._captureStackTrace(),w._pushContext();var z;if(arguments.length>1){Y.deprecated("calling Promise.try with more than 1 argument");var G=arguments[1],H=arguments[2];z=J.isArray(G)?Q(K).apply(H,G):Q(K).call(H,G)}else z=Q(K)();var V=w._popContext();return Y.checkForgottenReturns(z,V,"Promise.try",w),w._resolveFromSyncValue(z),w},$.prototype._resolveFromSyncValue=function(K){if(K===J.errorObj)this._rejectCallback(K.e,!1);else this._resolveCallback(K,!0)}}});var dK0=L((DR1,cK0)=>{cK0.exports=function($,I,q,U){var Y=!1,J=function(z,G){this._reject(G)},Q=function(z,G){G.promiseRejectionQueued=!0,G.bindingPromise._then(J,J,null,this,z)},K=function(z,G){if((this._bitField&50397184)===0)this._resolveCallback(G.target)},w=function(z,G){if(!G.promiseRejectionQueued)this._reject(z)};$.prototype.bind=function(z){if(!Y)Y=!0,$.prototype._propagateFrom=U.propagateFromFunction(),$.prototype._boundValue=U.boundValueFunction();var G=q(z),H=new $(I);H._propagateFrom(this,1);var V=this._target();if(H._setBoundTo(G),G instanceof $){var W={promiseRejectionQueued:!1,promise:H,target:V,bindingPromise:G};V._then(I,Q,voi Line truncated
`);$.prototype._captureStackTrace=s,$.prototype._attachExtraTrace=N,I.deactivateLongStackTraces(),Y.enableTrampoline(),v0.longStackTraces=!1},$.prototype._captureStackTrace=Q0,$.prototype._attachExtraTrace=w0,I.activateLongStackTraces(),Y.disableTrampolineIfNecessary()}},$.hasLongStackTraces=function(){return v0.longStackTraces&&i6()};var R=function(){try{if(typeof CustomEvent==="function"){var s=new CustomEvent("CustomEvent");return Q.global.dispatchEvent(s),function(N,M){var j=new CustomEvent(N.toLowerCase(),{detail:M,cancelable:!0});return!Q.global.dispatchEvent(j)}}else if(typeof Event==="function"){var s=new Event("CustomEvent");return Q.global.dispatchEvent(s),function(M,j){var u=new Event(M.toLowerCase(),{cancelable:!0});return u.detail=j,!Q.global.dispatchEvent(u)}}else{var s=document.createEvent("CustomEvent");return s.initCustomEvent("testingtheevent",!1,!0,{}),Q.global.dispatchEvent(s),function(M,j){var u=document.createEvent("CustomEvent");return u.initCustomEvent(M.toLowerCase(),!1,!0,j),!Q.global.dispatchEvent(u)}}}catch(N){}return function(){return!1}}(),k=function(){if(Q.isNode)return function(){return process.emit.apply(process,arguments)};else{if(!Q.global)return function(){return!1};return function(s){var N="on"+s.toLowerCase(),M=Q.global[N];if(!M)return!1;return M.apply(Q.global,[].slice.call(arguments,1)),!0}}}();function g(s,N){return{promise:N}}var f={promiseCreated:g,promiseFulfilled:g,promiseRejected:g,promiseResolved:g,promiseCancelled:g,promiseChained:function(s,N,M){return{promise:N,child:M}},warning:function(s,N){return{warning:N}},unhandledRejection:function(s,N,M){return{reason:N,promise:M}},rejectionHandled:g},C=function(s){var N=!1;try{N=k.apply(null,arguments)}catch(j){Y.throwLater(j),N=!0}var M=!1;try{M=R(s,f[s].apply(null,arguments))}catch(j){Y.throwLater(j),M=!0}return M||N};$.config=function(s){if(s=Object(s),"longStackTraces"in s){if(s.longStackTraces)$.longStackTraces();else if(!s.longStackTraces&&$.hasLongStackTraces())A()}if("warnings"in s){var N=s.warnings;if(v0.warnings=!!N,T=v0.warnings,Q.isObject(N)){if("wForgottenReturn"in N)T=!!N.wForgottenReturn}}if("cancellation"in s&&s.cancellation&&!v0.cancellation){if(Y.haveItemsQueued())throw Error("cannot enable cancellation after promises are in use");$.prototype._clearCancellationData=Y0,$.prototype._propagateFrom=B,$.prototype._onCancel=i,$.prototype._setOnCancel=b,$.prototype._attachCancellationCallback=S,$.prototype._execute=n,c=B,v0.cancellation=!0}if("monitoring"in s){if(s.monitoring&&!v0.monitoring)v0.monitoring=!0,$.prototype._fireEvent=C;else if(!s.monitoring&&v0.monitoring)v0.monitoring=!1,$.prototype._fireEvent=p}return $};function p(){return!1}$.prototype._fireEvent=p,$.prototype._execute=function(s,N,M){try{s(N,M)}catch(j){return j}},$.prototype._onCancel=function(){},$.prototype._setOnCancel=function(s){},$.prototype._attachCancellationCallback=function(s){},$.prototype._captureStackTrace=function(){},$.prototype._attachExtraTrace=function(){},$.prototype._clearCancellationData=function(){},$.prototype._propagateFrom=function(s,N){};function n(s,N,M){var j=this;try{s(N,M,function(u){if(typeof u!=="function")throw TypeError("onCancel must be a function, got: "+Q.toString(u));j._attachCancellationCallback(u)})}catch(u){return u}}function S(s){if(!this._isCancellable())return this;var N=this._onCancel();if(N!==void 0)if(Q.isArray(N))N.push(s);else this._setOnCancel([N,s]);else this._setOnCancel(s)}function i(){return this._onCancelField}function b(s){this._onCancelField=s}function Y0(){this._cancellationParent=void 0,this._onCancelField=void 0}function B(s,N){if((N&1)!==0){this._cancellationParent=s;var M=s._branchesRemainingToCancel;if(M===void 0)M=0;s._branchesRemainingToCancel=M+1}if((N&2)!==0&&s._isBound())this._setBoundTo(s._boundTo)}function x(s,N){if((N&2)!==0&&s._isBound())this._setBoundTo(s._boundTo)}var c=x;function r(){var s=this._boundTo;if(s!==void 0){if(s instanceof $)if(s.isFulfilled())return s.value();else return}return s}function Q0(){this._trace=new J$(this._peekContext())}function w0(s,N){if(K(s)){var M=this._trace;if(M!==void 0){if(N)M=M._parent}if(M!==void 0)M.attachExtraTrace(s);else if(!s.__stackCleaned__){var j=g1(s);Q.notEnumerableProp(s,"stack",j.message+`
`+j.stack.join(`
`)),Q.notEnumerableProp(s,"__stackCleaned__",!0)}}}function M0(s,N,M,j,u){if(s===void 0&&N!==null&&T){if(u!==void 0&&u._returnedNonUndefined())return;if((j._bitField&65535)===0)return;if(M)M=M+" ";var e="",m="";if(N._trace){var $0=N._trace.stack.split(`
`),K0=T0($0);for(var W0=K0.length-1;W0>=0;--W0){var j0=K0[W0];if(!W.test(j0)){var b0=j0.match(w);if(b0)e="at "+b0[1]+":"+b0[2]+":"+b0[3]+" ";break}}if(K0.length>0){var f0=K0[0];for(var W0=0;W0<$0.length;++W0)if($0[W0]===f0){if(W0>0)m=`
`+$0[W0-1];break}}}var q1="a promise was created in a "+M+"handler "+e+"but was not returned from it, see http://goo.gl/rRqMUw"+m;j._warn(q1,!0,N)}}function R0(s,N){var M=s+" is deprecated and will be removed in a future version.";if(N)M+=" Use "+N+" instead.";return K1(M)}function K1(s,N,M){if(!v0.warnings)return;var j=new J(s),u;if(N)M._attachExtraTrace(j);else if(v0.longStackTraces&&(u=$._peekContext()))u.attachExtraTrace(j);else{var e=g1(j);j.stack=e.message+`
`+e.stack.join(`
`)}if(!C("warning",j))Z4(j,"",!0)}function k0(s,N){for(var M=0;M<N.length-1;++M)N[M].push("From previous event:"),N[M]=N[M].join(`
`);if(M<N.length)N[M]=N[M].join(`
`);return s+`
`+N.join(`
`)}function I1(s){for(var N=0;N<s.length;++N)if(s[N].length===0||N+1<s.length&&s[N][0]===s[N+1][0])s.splice(N,1),N--}function t(s){var N=s[0];for(var M=1;M<s.length;++M){var j=s[M],u=N.length-1,e=N[u],m=-1;for(var $0=j.length-1;$0>=0;--$0)if(j[$0]===e){m=$0;break}for(var $0=m;$0>=0;--$0){var K0=j[$0];if(N[u]===K0)N.pop(),u--;else break}N=j}}function T0(s){var N=[];for(var M=0;M<s.length;++M){var j=s[M],u=j===" (No stack trace)"||V.test(j),e=u&&P6(j);if(u&&!e){if(X&&j.charAt(0)!==" ")j=" "+j;N.push(j)}}return N}function y0(s){var N=s.stack.replace(/\s+$/g,"").split(`
`);for(var M=0;M<N.length;++M){var j=N[M];if(j===" (No stack trace)"||V.test(j))break}if(M>0&&s.name!="SyntaxError")N=N.slice(M);return N}function g1(s){var N=s.stack,M=s.toString();return N=typeof N==="string"&&N.length>0?y0(s):[" (No stack trace)"],{message:M,stack:s.name=="SyntaxError"?N:T0(N)}}function Z4(s,N,M){if(typeof console<"u"){var j;if(Q.isObject(s)){var u=s.stack;j=N+Z(u,s)}else j=N+String(s);if(typeof L==="function")L(j,M);else if(typeof console.log==="function"||typeof console.log==="object")console.log(j)}}function A6(s,N,M,j){var u=!1;try{if(typeof N==="function")if(u=!0,s==="rejectionHandled")N(j);else N(M,j)}catch(e){Y.throwLater(e)}if(s==="unhandledRejection"){if(!C(s,M,j)&&!u)Z4(M,"Unhandled rejection ")}else C(s,j)}function f6(s){var N;if(typeof s==="function")N="[function "+(s.name||"anonymous")+"]";else{N=s&&typeof s.toString==="function"?s.toString():Q.toString(s);var M=/\[object [a-zA-Z0-9$_]+\]/;if(M.test(N))try{var j=JSON.stringify(s);N=j}catch(u){}if(N.length===0)N="(empty array)"}return"(<"+F$(N)+">, no stack trace)"}function F$(s){var N=41;if(s.length<N)return s;return s.substr(0,N-3)+"..."}function i6(){return typeof t5==="function"}var P6=function(){return!1},s8=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function Y$(s){var N=s.match(s8);if(N)return{fileName:N[1],line:parseInt(N[2],10)}}function T7(s,N){if(!i6())return;var M=s.stack.split(`
`),j=N.stack.split(`
`),u=-1,e=-1,m,$0;for(var K0=0;K0<M.length;++K0){var W0=Y$(M[K0]);if(W0){m=W0.fileName,u=W0.line;break}}for(var K0=0;K0<j.length;++K0){var W0=Y$(j[K0]);if(W0){$0=W0.fileName,e=W0.line;break}}if(u<0||e<0||!m||!$0||m!==$0||u>=e)return;P6=function(j0){if(G.test(j0))return!0;var b0=Y$(j0);if(b0){if(b0.fileName===m&&(u<=b0.line&&b0.line<=e))return!0}return!1}}function J$(s){this._parent=s,this._promisesCreated=0;var N=this._length=1+(s===void 0?0:s._length);if(t5(this,J$),N>32)this.uncycle()}Q.inherits(J$,Error),I.CapturedTrace=J$,J$.prototype.uncycle=function(){var s=this._length;if(s<2)return;var N=[],M={};for(var j=0,u=this;u!==void 0;++j)N.push(u),u=u._parent;s=this._length=j;for(var j=s-1;j>=0;--j){var e=N[j].stack;if(M[e]===void 0)M[e]=j}for(var j=0;j<s;++j){var m=N[j].stack,$0=M[m];if($0!==void 0&&$0!==j){if($0>0)N[$0-1]._parent=void 0,N[$0-1]._length=1;N[j]._parent=void 0,N[j]._length=1;var K0=j>0?N[j-1]:this;if($0<s-1)K0._parent=N[$0+1],K0._parent.uncycle(),K0._length=K0._parent._length+1;else K0._parent=void 0,K0._length=1;var W0=K0._length+1;for(var j0=j-2;j0>=0;--j0)N[j0]._length=W0,W0++;return}}},J$.prototype.attachExtraTrace=function(s){if(s.__stackCleaned__)return;this.uncycle();var N=g1(s),M=N.message,j=[N.stack],u=this;while(u!==void 0)j.push(T0(u.stack.split(`
`))),u=u._parent;t(j),I1(j),Q.notEnumerableProp(s,"stack",k0(M,j)),Q.notEnumerableProp(s,"__stackCleaned__",!0)};var t5=function(){var N=/^\s*at\s*/,M=function(m,$0){if(typeof m==="string")return m;if($0.name!==void 0&&$0.message!==void 0)return $0.toString();return f6($0)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6,V=N,Z=M;var j=Error.captureStackTrace;return P6=function(m){return G.test(m)},function(m,$0){Error.stackTraceLimit+=6,j(m,$0),Error.stackTraceLimit-=6}}var u=Error();if(typeof u.stack==="string"&&u.stack.split(`
`)[0].indexOf("stackDetection@")>=0)return V=/@/,Z=M,X=!0,function($0){$0.stack=Error().stack};var e;try{throw Error()}catch(m){e="stack"in m}if(!("stack"in u)&&e&&typeof Error.stackTraceLimit==="number")return V=N,Z=M,function($0){Error.stackTraceLimit+=6;try{throw Error()}catch(K0){$0.stack=K0.stack}Error.stackTraceLimit-=6};return Z=function(m,$0){if(typeof m==="string")return m;if((typeof $0==="object"||typeof $0==="function")&&$0.name!==void 0&&$0.message!==void 0)return $0.toString();return f6($0)},null}([]);if(typeof console<"u"&&typeof console.warn<"u"){if(L=function(s){console.warn(s)},Q.isNode&&process.stderr.isTTY)L=function(s,N){var M=N?"\x1B[33m":"\x1B[31m";console.warn(M+s+`\x1B[0m
`)};else if(!Q.isNode&&typeof Error().stack==="string")L=function(s,N){console.warn("%c"+s,N?"color: darkorange":"color: red")}}var v0={warnings:O,longStackTraces:!1,cancellation:!1,monitoring:!1};if(E)$.longStackTraces();return{longStackTraces:function(){return v0.longStackTraces},warnings:function(){return v0.warnings},cancellation:function(){return v0.cancellation},monitoring:function(){return v0.monitoring},propagateFromFunction:function(){return c},boundValueFunction:function(){return r},checkForgottenReturns:M0,setBounds:T7,warn:K1,deprecated:R0,CapturedTrace:J$,fireDomEvent:R,fireGlobalEvent:k}}});var cK0=F((nC1,pK0)=>{pK0.exports=function($,I){var U=c1(),Y=$.CancellationError,J=U.errorObj;function Q(w,V,Z){this.promise=w,this.type=V,this.handler=Z,this.called=!1,this.cancelPromise=null}Q.prototype.isFinallyHandler=function(){return this.type===0};function K(w){this.finallyHandler=w}K.prototype._resultCancelled=function(){q(this.finallyHandler)};function q(w,V){if(w.cancelPromise!=null){if(arguments.length>1)w.cancelPromise._reject(V);else w.cancelPromise._cancel();return w.cancelPromise=null,!0}return!1}function H(){return W.call(this,this.promise._target()._settledValue())}function G(w){if(q(this,w))return;return J.e=w,J}function W(w){var V=this.promise,Z=this.handler;if(!this.called){this.called=!0;var X=this.isFinallyHandler()?Z.call(V._boundValue()):Z.call(V._boundValue(),w);if(X!==void 0){V._setReturnedNonUndefined();var L=I(X,V);if(L instanceof $){if(this.cancelPromise!=null){if(L._isCancelled()){var D=new Y("late cancellation observer");return V._attachExtraTrace(D),J.e=D,J}else if(L.isPending())L._attachCancellationCallback(new K(this))}return L._then(H,G,void 0,this,void 0)}}}if(V.isRejected())return q(this),J.e=w,J;else return q(this),w}return $.prototype._passThrough=function(w,V,Z,X){if(typeof w!=="function")return this.then();return this._then(Z,X,void 0,new Q(this,V,w),void 0)},$.prototype.lastly=$.prototype.finally=function(w){return this._passThrough(w,0,W,W)},$.prototype.tap=function(w){return this._passThrough(w,1,W)},Q}});var mK0=F((pC1,dK0)=>{dK0.exports=function($){var I=c1(),U=p3().keys,Y=I.tryCatch,J=I.errorObj;function Q(K,q,H){return function(G){var W=H._boundValue();$:for(var w=0;w<K.length;++w){var V=K[w];if(V===Error||V!=null&&V.prototype instanceof Error){if(G instanceof V)return Y(q).call(W,G)}else if(typeof V==="function"){var Z=Y(V).call(W,G);if(Z===J)return Z;else if(Z)return Y(q).call(W,G)}else if(I.isObject(G)){var X=U(V);for(var L=0;L<X.length;++L){var D=X[L];if(V[D]!=G[D])continue $}return Y(q).call(W,G)}}return $}}return Q}});var kg=F((cC1,rK0)=>{var lK0=c1(),gI1=lK0.maybeWrapAsError,yI1=u5(),hI1=yI1.OperationalError,oK0=p3();function uI1($){return $ instanceof Error&&oK0.getPrototypeOf($)===Error.prototype}var xI1=/^(?:name|message|stack|cause)$/;function kI1($){var I;if(uI1($)){I=new hI1($),I.name=$.name,I.message=$.message,I.stack=$.stack;var U=oK0.keys($);for(var Y=0;Y<U.length;++Y){var J=U[Y];if(!xI1.test(J))I[J]=$[J]}return I}return lK0.markAsOriginatingFromRejection($),$}function fI1($,I){return function(U,Y){if($===null)return;if(U){var J=kI1(gI1(U));$._attachExtraTrace(J),$._reject(J)}else if(!I)$._fulfill(Y);else{var Q=arguments.length,K=Array(Math.max(Q-1,0));for(var q=1;q<Q;++q)K[q-1]=arguments[q];$._fulfill(K)}$=null}}rK0.exports=fI1});var aK0=F((dC1,tK0)=>{tK0.exports=function($,I,U,Y,J){var Q=c1(),K=Q.tryCatch;$.method=function(q){if(typeof q!=="function")throw new $.TypeError("expecting a function but got "+Q.classString(q));return function(){var H=new $(I);H._captureStackTrace(),H._pushContext();var G=K(q).apply(this,arguments),W=H._popContext();return J.checkForgottenReturns(G,W,"Promise.method",H),H._resolveFromSyncValue(G),H}},$.attempt=$.try=function(q){if(typeof q!=="function")return Y("expecting a function but got "+Q.classString(q));var H=new $(I);H._captureStackTrace(),H._pushContext();var G;if(arguments.length>1){J.deprecated("calling Promise.try with more than 1 argument");var W=arguments[1],w=arguments[2];G=Q.isArray(W)?K(q).apply(w,W):K(q).call(w,W)}else G=K(q)();var V=H._popContext();return J.checkForgottenReturns(G,V,"Promise.try",H),H._resolveFromSyncValue(G),H},$.prototype._resolveFromSyncValue=function(q){if(q===Q.errorObj)this._rejectCallback(q.e,!1);else this._resolveCallback(q,!0)}}});var eK0=F((mC1,sK0)=>{sK0.exports=function($,I,U,Y){var J=!1,Q=function(G,W){this._reject(W)},K=function(G,W){W.promiseRejectionQueued=!0,W.bindingPromise._then(Q,Q,null,this,G)},q=function(G,W){if((this._bitField&50397184)===0)this._resolveCallback(W.target)},H=function(G,W){if(!W.promiseRejectionQueued)this._reject(G)};$.prototype.bind=function(G){if(!J)J=!0,$.prototype._propagateFrom=Y.propagateFromFunction(),$.prototype._boundValue=Y.boundValueFunction();var W=U(G),w=new $(I);w._propagateFrom(this,1);var V=this._target();if(w._setBoundTo(W),W instanceof $){var Z={promiseRejectionQueued:!1,promise:w,target:V,bindingPromise:W};V._then(I,K,voi Line truncated
See http://goo.gl/MqrFmX
`);return this._settledValue()},U=I.prototype.error=I.prototype.reason=function(){if(!this.isRejected())throw TypeError(`cannot get rejection reason of a non-rejected promise
`);return this._settledValue()},Y=I.prototype.error=I.prototype.reason=function(){if(!this.isRejected())throw TypeError(`cannot get rejection reason of a non-rejected promise
See http://goo.gl/MqrFmX
`);return this._settledValue()},Y=I.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0},J=I.prototype.isRejected=function(){return(this._bitField&16777216)!==0},Q=I.prototype.isPending=function(){return(this._bitField&50397184)===0},K=I.prototype.isResolved=function(){return(this._bitField&50331648)!==0};I.prototype.isCancelled=function(){return(this._bitField&8454144)!==0},$.prototype.__isCancelled=function(){return(this._bitField&65536)===65536},$.prototype._isCancelled=function(){return this._target().__isCancelled()},$.prototype.isCancelled=function(){return(this._target()._bitField&8454144)!==0},$.prototype.isPending=function(){return Q.call(this._target())},$.prototype.isRejected=function(){return J.call(this._target())},$.prototype.isFulfilled=function(){return Y.call(this._target())},$.prototype.isResolved=function(){return K.call(this._target())},$.prototype.value=function(){return q.call(this._target())},$.prototype.reason=function(){var w=this._target();return w._unsetRejectionIsUnhandled(),U.call(w)},$.prototype._value=function(){return this._settledValue()},$.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},$.PromiseInspection=I}});var eK0=L((FR1,sK0)=>{sK0.exports=function($,I,q,U,Y,J){var Q=n1(),K=Q.canEvaluate,w=Q.tryCatch,z=Q.errorObj,G;if(K){var H=function(T){return Function("value","holder",`
`);return this._settledValue()},J=I.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0},Q=I.prototype.isRejected=function(){return(this._bitField&16777216)!==0},K=I.prototype.isPending=function(){return(this._bitField&50397184)===0},q=I.prototype.isResolved=function(){return(this._bitField&50331648)!==0};I.prototype.isCancelled=function(){return(this._bitField&8454144)!==0},$.prototype.__isCancelled=function(){return(this._bitField&65536)===65536},$.prototype._isCancelled=function(){return this._target().__isCancelled()},$.prototype.isCancelled=function(){return(this._target()._bitField&8454144)!==0},$.prototype.isPending=function(){return K.call(this._target())},$.prototype.isRejected=function(){return Q.call(this._target())},$.prototype.isFulfilled=function(){return J.call(this._target())},$.prototype.isResolved=function(){return q.call(this._target())},$.prototype.value=function(){return U.call(this._target())},$.prototype.reason=function(){var H=this._target();return H._unsetRejectionIsUnhandled(),Y.call(H)},$.prototype._value=function(){return this._settledValue()},$.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},$.PromiseInspection=I}});var qq0=F((tC1,Kq0)=>{Kq0.exports=function($,I,U,Y,J,Q){var K=c1(),q=K.canEvaluate,H=K.tryCatch,G=K.errorObj,W;if(q){var w=function(E){return Function("value","holder",`
'use strict';
holder.pIndex = value;
holder.checkFulfillment(this);
`.replace(/Index/g,T))},V=function(T){return Function("promise","holder",`
`.replace(/Index/g,E))},V=function(E){return Function("promise","holder",`
'use strict';
holder.pIndex = promise;
`.replace(/Index/g,T))},W=function(T){var P=Array(T);for(var g=0;g<P.length;++g)P[g]="this.p"+(g+1);var B=P.join(" = ")+" = null;",k=`var promise;
`+P.map(function(t){return`
promise = `+t+`;
`.replace(/Index/g,E))},Z=function(E){var T=Array(E);for(var A=0;A<T.length;++A)T[A]="this.p"+(A+1);var R=T.join(" = ")+" = null;",k=`var promise;
`+T.map(function(p){return`
promise = `+p+`;
if (promise instanceof Promise) {
promise.cancel();
}
`}).join(`
`),h=P.join(", "),f="Holder$"+T,S=`return function(tryCatch, errorObj, Promise, async) {
`),g=T.join(", "),f="Holder$"+E,C=`return function(tryCatch, errorObj, Promise, async) {
'use strict';
function [TheName](fn) {
[TheProperties]
@@ -134,7 +129,7 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof S4))r
return [TheName];
}(tryCatch, errorObj, Promise, async);
`;return S=S.replace(/\[TheName\]/g,f).replace(/\[TheTotal\]/g,T).replace(/\[ThePassedArguments\]/g,h).replace(/\[TheProperties\]/g,B).replace(/\[CancellationCode\]/g,k),Function("tryCatch","errorObj","Promise","async",S)(w,z,$,Y)},X=[],D=[],O=[];for(var N=0;N<8;++N)X.push(W(N+1)),D.push(H(N+1)),O.push(V(N+1));G=function(T){this._reject(T)}}$.join=function(){var T=arguments.length-1,P;if(T>0&&typeof arguments[T]==="function"){if(P=arguments[T],T<=8&&K){var i=new $(U);i._captureStackTrace();var g=X[T-1],B=new g(P),k=D;for(var h=0;h<T;++h){var f=q(arguments[h],i);if(f instanceof $){f=f._target();var S=f._bitField;if((S&50397184)===0)f._then(k[h],G,void 0,i,B),O[h](f,B),B.asyncNeeded=!1;else if((S&33554432)!==0)k[h].call(i,f._value(),B);else if((S&16777216)!==0)i._reject(f._reason());else i._cancel()}else k[h].call(i,f,B)}if(!i._isFateSealed()){if(B.asyncNeeded){var t=J();if(t!==null)B.fn=Q.domainBind(t,B.fn)}i._setAsyncGuaranteed(),i._setOnCancel(B)}return i}}var p=arguments.length,C=Array(p);for(var n=0;n<p;++n)C[n]=arguments[n];if(P)C.pop();var i=new I(C).promise();return P!==void 0?i.spread(P):i}}});var Iw0=L((MR1,$w0)=>{$w0.exports=function($,I,q,U,Y,J){var Q=$._getDomain,K=n1(),w=K.tryCatch,z=K.errorObj,G=$._async;function H(W,X,D,O){this.constructor$(W),this._promise._captureStackTrace();var N=Q();this._callback=N===null?X:K.domainBind(N,X),this._preservedValues=O===Y?Array(this.length()):null,this._limit=D,this._inFlight=0,this._queue=[],G.invoke(this._asyncInit,this,void 0)}K.inherits(H,I),H.prototype._asyncInit=function(){this._init$(void 0,-2)},H.prototype._init=function(){},H.prototype._promiseFulfilled=function(W,X){var D=this._values,O=this.length(),N=this._preservedValues,T=this._limit;if(X<0){if(X=X*-1-1,D[X]=W,T>=1){if(this._inFlight--,this._drainQueue(),this._isResolved())return!0}}else{if(T>=1&&this._inFlight>=T)return D[X]=W,this._queue.push(X),!1;if(N!==null)N[X]=W;var P=this._promise,g=this._callback,B=P._boundValue();P._pushContext();var k=w(g).call(B,W,X,O),h=P._popContext();if(J.checkForgottenReturns(k,h,N!==null?"Promise.filter":"Promise.map",P),k===z)return this._reject(k.e),!0;var f=U(k,this._promise);if(f instanceof $){f=f._target();var S=f._bitField;if((S&50397184)===0){if(T>=1)this._inFlight++;return D[X]=f,f._proxy(this,(X+1)*-1),!1}else if((S&33554432)!==0)k=f._value();else if((S&16777216)!==0)return this._reject(f._reason()),!0;else return this._cancel(),!0}D[X]=k}var t=++this._totalResolved;if(t>=O){if(N!==null)this._filter(D,N);else this._resolve(D);return!0}return!1},H.prototype._drainQueue=function(){var W=this._queue,X=this._limit,D=this._values;while(W.length>0&&this._inFlight<X){if(this._isResolved())return;var O=W.pop();this._promiseFulfilled(D[O],O)}},H.prototype._filter=function(W,X){var D=X.length,O=Array(D),N=0;for(var T=0;T<D;++T)if(W[T])O[N++]=X[T];O.length=N,this._resolve(O)},H.prototype.preservedValues=function(){return this._preservedValues};function V(W,X,D,O){if(typeof X!=="function")return q("expecting a function but got "+K.classString(X));var N=0;if(D!==void 0)if(typeof D==="object"&&D!==null){if(typeof D.concurrency!=="number")return $.reject(TypeError("'concurrency' must be a number but it is "+K.classString(D.concurrency)));N=D.concurrency}else return $.reject(TypeError("options argument must be an object but it is "+K.classString(D)));return N=typeof N==="number"&&isFinite(N)&&N>=1?N:0,new H(W,X,N,O).promise()}$.prototype.map=function(W,X){return V(this,W,X,null)},$.map=function(W,X,D,O){return V(W,X,D,O)}}});var Uw0=L((AR1,qw0)=>{var FS=Object.create;if(FS)YD=FS(null),JD=FS(null),YD[" size"]=JD[" size"]=0;var YD,JD;qw0.exports=function($){var I=n1(),q=I.canEvaluate,U=I.isIdentifier,Y,J,Q=function(W){return Function("ensureMethod",`
`;return C=C.replace(/\[TheName\]/g,f).replace(/\[TheTotal\]/g,E).replace(/\[ThePassedArguments\]/g,g).replace(/\[TheProperties\]/g,R).replace(/\[CancellationCode\]/g,k),Function("tryCatch","errorObj","Promise","async",C)(H,G,$,J)},X=[],L=[],D=[];for(var O=0;O<8;++O)X.push(Z(O+1)),L.push(w(O+1)),D.push(V(O+1));W=function(E){this._reject(E)}}$.join=function(){var E=arguments.length-1,T;if(E>0&&typeof arguments[E]==="function"){if(T=arguments[E],E<=8&&q){var b=new $(Y);b._captureStackTrace();var A=X[E-1],R=new A(T),k=L;for(var g=0;g<E;++g){var f=U(arguments[g],b);if(f instanceof $){f=f._target();var C=f._bitField;if((C&50397184)===0)f._then(k[g],W,void 0,b,R),D[g](f,R),R.asyncNeeded=!1;else if((C&33554432)!==0)k[g].call(b,f._value(),R);else if((C&16777216)!==0)b._reject(f._reason());else b._cancel()}else k[g].call(b,f,R)}if(!b._isFateSealed()){if(R.asyncNeeded){var p=Q();if(p!==null)R.fn=K.domainBind(p,R.fn)}b._setAsyncGuaranteed(),b._setOnCancel(R)}return b}}var n=arguments.length,S=Array(n);for(var i=0;i<n;++i)S[i]=arguments[i];if(T)S.pop();var b=new I(S).promise();return T!==void 0?b.spread(T):b}}});var Gq0=F((aC1,Hq0)=>{Hq0.exports=function($,I,U,Y,J,Q){var K=$._getDomain,q=c1(),H=q.tryCatch,G=q.errorObj,W=$._async;function w(Z,X,L,D){this.constructor$(Z),this._promise._captureStackTrace();var O=K();this._callback=O===null?X:q.domainBind(O,X),this._preservedValues=D===J?Array(this.length()):null,this._limit=L,this._inFlight=0,this._queue=[],W.invoke(this._asyncInit,this,void 0)}q.inherits(w,I),w.prototype._asyncInit=function(){this._init$(void 0,-2)},w.prototype._init=function(){},w.prototype._promiseFulfilled=function(Z,X){var L=this._values,D=this.length(),O=this._preservedValues,E=this._limit;if(X<0){if(X=X*-1-1,L[X]=Z,E>=1){if(this._inFlight--,this._drainQueue(),this._isResolved())return!0}}else{if(E>=1&&this._inFlight>=E)return L[X]=Z,this._queue.push(X),!1;if(O!==null)O[X]=Z;var T=this._promise,A=this._callback,R=T._boundValue();T._pushContext();var k=H(A).call(R,Z,X,D),g=T._popContext();if(Q.checkForgottenReturns(k,g,O!==null?"Promise.filter":"Promise.map",T),k===G)return this._reject(k.e),!0;var f=Y(k,this._promise);if(f instanceof $){f=f._target();var C=f._bitField;if((C&50397184)===0){if(E>=1)this._inFlight++;return L[X]=f,f._proxy(this,(X+1)*-1),!1}else if((C&33554432)!==0)k=f._value();else if((C&16777216)!==0)return this._reject(f._reason()),!0;else return this._cancel(),!0}L[X]=k}var p=++this._totalResolved;if(p>=D){if(O!==null)this._filter(L,O);else this._resolve(L);return!0}return!1},w.prototype._drainQueue=function(){var Z=this._queue,X=this._limit,L=this._values;while(Z.length>0&&this._inFlight<X){if(this._isResolved())return;var D=Z.pop();this._promiseFulfilled(L[D],D)}},w.prototype._filter=function(Z,X){var L=X.length,D=Array(L),O=0;for(var E=0;E<L;++E)if(Z[E])D[O++]=X[E];D.length=O,this._resolve(D)},w.prototype.preservedValues=function(){return this._preservedValues};function V(Z,X,L,D){if(typeof X!=="function")return U("expecting a function but got "+q.classString(X));var O=0;if(L!==void 0)if(typeof L==="object"&&L!==null){if(typeof L.concurrency!=="number")return $.reject(TypeError("'concurrency' must be a number but it is "+q.classString(L.concurrency)));O=L.concurrency}else return $.reject(TypeError("options argument must be an object but it is "+q.classString(L)));return O=typeof O==="number"&&isFinite(O)&&O>=1?O:0,new w(Z,X,O,D).promise()}$.prototype.map=function(Z,X){return V(this,Z,X,null)},$.map=function(Z,X,L,D){return V(Z,X,L,D)}}});var wq0=F((sC1,Wq0)=>{var fg=Object.create;if(fg)rX=fg(null),tX=fg(null),rX[" size"]=tX[" size"]=0;var rX,tX;Wq0.exports=function($){var I=c1(),U=I.canEvaluate,Y=I.isIdentifier,J,Q,K=function(Z){return Function("ensureMethod",`
return function(obj) {
'use strict'
var len = this.length;
@@ -148,29 +143,29 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof S4))r
return obj.methodName.apply(obj, this);
}
};
`.replace(/methodName/g,W))(z)},K=function(W){return Function("obj",`
`.replace(/methodName/g,Z))(G)},q=function(Z){return Function("obj",`
'use strict';
return obj.propertyName;
`.replace("propertyName",W))},w=function(W,X,D){var O=D[W];if(typeof O!=="function"){if(!U(W))return null;if(O=X(W),D[W]=O,D[" size"]++,D[" size"]>512){var N=Object.keys(D);for(var T=0;T<256;++T)delete D[N[T]];D[" size"]=N.length-256}}return O};Y=function(W){return w(W,Q,YD)},J=function(W){return w(W,K,JD)};function z(W,X){var D;if(W!=null)D=W[X];if(typeof D!=="function"){var O="Object "+I.classString(W)+" has no method '"+I.toString(X)+"'";throw new $.TypeError(O)}return D}function G(W){var X=this.pop(),D=z(W,X);return D.apply(W,this)}$.prototype.call=function(W){var X=arguments.length,D=Array(Math.max(X-1,0));for(var O=1;O<X;++O)D[O-1]=arguments[O];if(q){var N=Y(W);if(N!==null)return this._then(N,void 0,void 0,D,void 0)}return D.push(W),this._then(G,void 0,void 0,D,void 0)};function H(W){return W[this]}function V(W){var X=+this;if(X<0)X=Math.max(0,X+W.length);return W[X]}$.prototype.get=function(W){var X=typeof W==="number",D;if(!X)if(q){var O=J(W);D=O!==null?O:H}else D=H;else D=V;return this._then(D,void 0,void 0,W,void 0)}}});var Jw0=L((gR1,Yw0)=>{Yw0.exports=function($,I,q,U,Y,J){var Q=n1(),K=S5().TypeError,w=n1().inherits,z=Q.errorObj,G=Q.tryCatch,H={};function V(P){setTimeout(function(){throw P},0)}function W(P){var g=q(P);if(g!==P&&typeof P._isDisposable==="function"&&typeof P._getDisposer==="function"&&P._isDisposable())g._setDisposable(P._getDisposer());return g}function X(P,g){var B=0,k=P.length,h=new $(Y);function f(){if(B>=k)return h._fulfill();var S=W(P[B++]);if(S instanceof $&&S._isDisposable()){try{S=q(S._getDisposer().tryDispose(g),P.promise)}catch(t){return V(t)}if(S instanceof $)return S._then(f,V,null,null,null)}f()}return f(),h}function D(P,g,B){this._data=P,this._promise=g,this._context=B}D.prototype.data=function(){return this._data},D.prototype.promise=function(){return this._promise},D.prototype.resource=function(){if(this.promise().isFulfilled())return this.promise().value();return H},D.prototype.tryDispose=function(P){var g=this.resource(),B=this._context;if(B!==void 0)B._pushContext();var k=g!==H?this.doDispose(g,P):null;if(B!==void 0)B._popContext();return this._promise._unsetDisposable(),this._data=null,k},D.isDisposer=function(P){return P!=null&&typeof P.resource==="function"&&typeof P.tryDispose==="function"};function O(P,g,B){this.constructor$(P,g,B)}w(O,D),O.prototype.doDispose=function(P,g){var B=this.data();return B.call(P,P,g)};function N(P){if(D.isDisposer(P))return this.resources[this.index]._setDisposable(P),P.promise();return P}function T(P){this.length=P,this.promise=null,this[P-1]=null}T.prototype._resultCancelled=function(){var P=this.length;for(var g=0;g<P;++g){var B=this[g];if(B instanceof $)B.cancel()}},$.using=function(){var P=arguments.length;if(P<2)return I("you must pass at least 2 arguments to Promise.using");var g=arguments[P-1];if(typeof g!=="function")return I("expecting a function but got "+Q.classString(g));var B,k=!0;if(P===2&&Array.isArray(arguments[0]))B=arguments[0],P=B.length,k=!1;else B=arguments,P--;var h=new T(P);for(var f=0;f<P;++f){var S=B[f];if(D.isDisposer(S)){var t=S;S=S.promise(),S._setDisposable(t)}else{var p=q(S);if(p instanceof $)S=p._then(N,null,null,{resources:h,index:f},void 0)}h[f]=S}var C=Array(h.length);for(var f=0;f<C.length;++f)C[f]=$.resolve(h[f]).reflect();var n=$.all(C).then(function(J0){for(var E=0;E<J0.length;++E){var u=J0[E];if(u.isRejected())return z.e=u.error(),z;else if(!u.isFulfilled()){n.cancel();return}J0[E]=u.value()}i._pushContext(),g=G(g);var d=k?g.apply(void 0,J0):g(J0),a=i._popContext();return J.checkForgottenReturns(d,a,"Promise.using",i),d}),i=n.lastly(function(){var J0=new $.PromiseInspection(n);return X(h,J0)});return h.promise=i,i._setOnCancel(h),i},$.prototype._setDisposable=function(P){this._bitField=this._bitField|131072,this._disposer=P},$.prototype._isDisposable=function(){return(this._bitField&131072)>0},$.prototype._getDisposer=function(){return this._disposer},$.prototype._unsetDisposable=function(){this._bitField=this._bitField&-131073,this._disposer=void 0},$.prototype.disposer=function(P){if(typeof P==="function")return new O(P,this,U());throw new K}}});var Kw0=L((PR1,Qw0)=>{Qw0.exports=function($,I,q){var U=n1(),Y=$.TimeoutError;function J(H){this.handle=H}J.prototype._resultCancelled=function(){clearTimeout(this.handle)};var Q=function(H){return K(+this).thenReturn(H)},K=$.delay=function(H,V){var W,X;if(V!==void 0){if(W=$.resolve(V)._then(Q,null,null,H,void 0),q.cancellation()&&V instanceof $)W._setOnCancel(V)}else{if(W=new $(I),X=setTimeout(function(){W._fulfill()},+H),q.cancellation())W._setOnCancel(new J(X));W._captureStackTrace()}return W._setAsyncGuaranteed(),W};$.prototype.delay=function(H){return K(H,this)};var w=function(H,V,W){var X;if(typeof V!=="string")if(V instanceof Error)X=V;else X=new Y("operation timed out");else X=new Y(V);if(U.markAsOriginatingFromRejection(X),H._attachExtraTrace(X),H._reject(X),W!=null)W.cancel()};function z(H){return clearTimeout(this.handle),H}f Line truncated
`.replace("propertyName",Z))},H=function(Z,X,L){var D=L[Z];if(typeof D!=="function"){if(!Y(Z))return null;if(D=X(Z),L[Z]=D,L[" size"]++,L[" size"]>512){var O=Object.keys(L);for(var E=0;E<256;++E)delete L[O[E]];L[" size"]=O.length-256}}return D};J=function(Z){return H(Z,K,rX)},Q=function(Z){return H(Z,q,tX)};function G(Z,X){var L;if(Z!=null)L=Z[X];if(typeof L!=="function"){var D="Object "+I.classString(Z)+" has no method '"+I.toString(X)+"'";throw new $.TypeError(D)}return L}function W(Z){var X=this.pop(),L=G(Z,X);return L.apply(Z,this)}$.prototype.call=function(Z){var X=arguments.length,L=Array(Math.max(X-1,0));for(var D=1;D<X;++D)L[D-1]=arguments[D];if(U){var O=J(Z);if(O!==null)return this._then(O,void 0,void 0,L,void 0)}return L.push(Z),this._then(W,void 0,void 0,L,void 0)};function w(Z){return Z[this]}function V(Z){var X=+this;if(X<0)X=Math.max(0,X+Z.length);return Z[X]}$.prototype.get=function(Z){var X=typeof Z==="number",L;if(!X)if(U){var D=Q(Z);L=D!==null?D:w}else L=w;else L=V;return this._then(L,void 0,void 0,Z,void 0)}}});var Zq0=F((eC1,Vq0)=>{Vq0.exports=function($,I,U,Y,J,Q){var K=c1(),q=u5().TypeError,H=c1().inherits,G=K.errorObj,W=K.tryCatch,w={};function V(T){setTimeout(function(){throw T},0)}function Z(T){var A=U(T);if(A!==T&&typeof T._isDisposable==="function"&&typeof T._getDisposer==="function"&&T._isDisposable())A._setDisposable(T._getDisposer());return A}function X(T,A){var R=0,k=T.length,g=new $(J);function f(){if(R>=k)return g._fulfill();var C=Z(T[R++]);if(C instanceof $&&C._isDisposable()){try{C=U(C._getDisposer().tryDispose(A),T.promise)}catch(p){return V(p)}if(C instanceof $)return C._then(f,V,null,null,null)}f()}return f(),g}function L(T,A,R){this._data=T,this._promise=A,this._context=R}L.prototype.data=function(){return this._data},L.prototype.promise=function(){return this._promise},L.prototype.resource=function(){if(this.promise().isFulfilled())return this.promise().value();return w},L.prototype.tryDispose=function(T){var A=this.resource(),R=this._context;if(R!==void 0)R._pushContext();var k=A!==w?this.doDispose(A,T):null;if(R!==void 0)R._popContext();return this._promise._unsetDisposable(),this._data=null,k},L.isDisposer=function(T){return T!=null&&typeof T.resource==="function"&&typeof T.tryDispose==="function"};function D(T,A,R){this.constructor$(T,A,R)}H(D,L),D.prototype.doDispose=function(T,A){var R=this.data();return R.call(T,T,A)};function O(T){if(L.isDisposer(T))return this.resources[this.index]._setDisposable(T),T.promise();return T}function E(T){this.length=T,this.promise=null,this[T-1]=null}E.prototype._resultCancelled=function(){var T=this.length;for(var A=0;A<T;++A){var R=this[A];if(R instanceof $)R.cancel()}},$.using=function(){var T=arguments.length;if(T<2)return I("you must pass at least 2 arguments to Promise.using");var A=arguments[T-1];if(typeof A!=="function")return I("expecting a function but got "+K.classString(A));var R,k=!0;if(T===2&&Array.isArray(arguments[0]))R=arguments[0],T=R.length,k=!1;else R=arguments,T--;var g=new E(T);for(var f=0;f<T;++f){var C=R[f];if(L.isDisposer(C)){var p=C;C=C.promise(),C._setDisposable(p)}else{var n=U(C);if(n instanceof $)C=n._then(O,null,null,{resources:g,index:f},void 0)}g[f]=C}var S=Array(g.length);for(var f=0;f<S.length;++f)S[f]=$.resolve(g[f]).reflect();var i=$.all(S).then(function(Y0){for(var B=0;B<Y0.length;++B){var x=Y0[B];if(x.isRejected())return G.e=x.error(),G;else if(!x.isFulfilled()){i.cancel();return}Y0[B]=x.value()}b._pushContext(),A=W(A);var c=k?A.apply(void 0,Y0):A(Y0),r=b._popContext();return Q.checkForgottenReturns(c,r,"Promise.using",b),c}),b=i.lastly(function(){var Y0=new $.PromiseInspection(i);return X(g,Y0)});return g.promise=b,b._setOnCancel(g),b},$.prototype._setDisposable=function(T){this._bitField=this._bitField|131072,this._disposer=T},$.prototype._isDisposable=function(){return(this._bitField&131072)>0},$.prototype._getDisposer=function(){return this._disposer},$.prototype._unsetDisposable=function(){this._bitField=this._bitField&-131073,this._disposer=void 0},$.prototype.disposer=function(T){if(typeof T==="function")return new D(T,this,Y());throw new q}}});var Xq0=F(($j1,zq0)=>{zq0.exports=function($,I,U){var Y=c1(),J=$.TimeoutError;function Q(w){this.handle=w}Q.prototype._resultCancelled=function(){clearTimeout(this.handle)};var K=function(w){return q(+this).thenReturn(w)},q=$.delay=function(w,V){var Z,X;if(V!==void 0){if(Z=$.resolve(V)._then(K,null,null,w,void 0),U.cancellation()&&V instanceof $)Z._setOnCancel(V)}else{if(Z=new $(I),X=setTimeout(function(){Z._fulfill()},+w),U.cancellation())Z._setOnCancel(new Q(X));Z._captureStackTrace()}return Z._setAsyncGuaranteed(),Z};$.prototype.delay=function(w){return q(w,this)};var H=function(w,V,Z){var X;if(typeof V!=="string")if(V instanceof Error)X=V;else X=new J("operation timed out");else X=new J(V);if(Y.markAsOriginatingFromRejection(X),w._attachExtraTrace(X),w._reject(X),Z!=null)Z.cancel()};function G(w){return clearTimeout(this.handle),w}f Line truncated
See http://goo.gl/MqrFmX
`.replace("%s",O)+`From coroutine:
`.replace("%s",D)+`From coroutine:
`+this._stack.split(`
`).slice(1,-7).join(`
`)));return}}N=N._target();var T=N._bitField;if((T&50397184)===0)this._yieldedPromise=N,N._proxy(this,null);else if((T&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,N._value());else if((T&16777216)!==0)$._async.invoke(this._promiseRejected,this,N._reason());else this._promiseCancelled()}},$.coroutine=function(X,D){if(typeof X!=="function")throw new K(`generatorFunction must be a function
`)));return}}O=O._target();var E=O._bitField;if((E&50397184)===0)this._yieldedPromise=O,O._proxy(this,null);else if((E&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,O._value());else if((E&16777216)!==0)$._async.invoke(this._promiseRejected,this,O._reason());else this._promiseCancelled()}},$.coroutine=function(X,L){if(typeof X!=="function")throw new q(`generatorFunction must be a function
See http://goo.gl/MqrFmX
`);var O=Object(D).yieldHandler,N=W,T=Error().stack;return function(){var P=X.apply(this,arguments),g=new N(void 0,void 0,O,T),B=g.promise();return g._generator=P,g._promiseFulfilled(void 0),B}},$.coroutine.addYieldHandler=function(X){if(typeof X!=="function")throw new K("expecting a function but got "+w.classString(X));H.push(X)},$.spawn=function(X){if(J.deprecated("Promise.spawn()","Promise.coroutine()"),typeof X!=="function")return I(`generatorFunction must be a function
`);var D=Object(L).yieldHandler,O=Z,E=Error().stack;return function(){var T=X.apply(this,arguments),A=new O(void 0,void 0,D,E),R=A.promise();return A._generator=T,A._promiseFulfilled(void 0),R}},$.coroutine.addYieldHandler=function(X){if(typeof X!=="function")throw new q("expecting a function but got "+H.classString(X));w.push(X)},$.spawn=function(X){if(Q.deprecated("Promise.spawn()","Promise.coroutine()"),typeof X!=="function")return I(`generatorFunction must be a function
See http://goo.gl/MqrFmX
`);var D=new W(X,this),O=D.promise();return D._run($.spawn),O}}});var Hw0=L((ER1,Gw0)=>{Gw0.exports=function($){var I=n1(),q=$._async,U=I.tryCatch,Y=I.errorObj;function J(w,z){var G=this;if(!I.isArray(w))return Q.call(G,w,z);var H=U(z).apply(G._boundValue(),[null].concat(w));if(H===Y)q.throwLater(H.e)}function Q(w,z){var G=this,H=G._boundValue(),V=w===void 0?U(z).call(H,null):U(z).call(H,null,w);if(V===Y)q.throwLater(V.e)}function K(w,z){var G=this;if(!w){var H=Error(w+"");H.cause=w,w=H}var V=U(z).call(G._boundValue(),w);if(V===Y)q.throwLater(V.e)}$.prototype.asCallback=$.prototype.nodeify=function(w,z){if(typeof w=="function"){var G=Q;if(z!==void 0&&Object(z).spread)G=J;this._then(G,K,void 0,this,w)}return this}}});var Ww0=L((jR1,Vw0)=>{Vw0.exports=function($,I){var q={},U=n1(),Y=NS(),J=U.withAppended,Q=U.maybeWrapAsError,K=U.canEvaluate,w=S5().TypeError,z="Async",G={__isPromisified__:!0},H=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],V=new RegExp("^(?:"+H.join("|")+")$"),W=function(n){return U.isIdentifier(n)&&n.charAt(0)!=="_"&&n!=="constructor"};function X(n){return!V.test(n)}function D(n){try{return n.__isPromisified__===!0}catch(i){return!1}}function O(n,i,J0){var E=U.getDataPropertyOrDefault(n,i+J0,G);return E?D(E):!1}function N(n,i,J0){for(var E=0;E<n.length;E+=2){var u=n[E];if(J0.test(u)){var d=u.replace(J0,"");for(var a=0;a<n.length;a+=2)if(n[a]===d)throw new w(`Cannot promisify an API that has normal methods with '%s'-suffix
`);var L=new Z(X,this),D=L.promise();return L._run($.spawn),D}}});var Oq0=F((Uj1,Fq0)=>{Fq0.exports=function($){var I=c1(),U=$._async,Y=I.tryCatch,J=I.errorObj;function Q(H,G){var W=this;if(!I.isArray(H))return K.call(W,H,G);var w=Y(G).apply(W._boundValue(),[null].concat(H));if(w===J)U.throwLater(w.e)}function K(H,G){var W=this,w=W._boundValue(),V=H===void 0?Y(G).call(w,null):Y(G).call(w,null,H);if(V===J)U.throwLater(V.e)}function q(H,G){var W=this;if(!H){var w=Error(H+"");w.cause=H,H=w}var V=Y(G).call(W._boundValue(),H);if(V===J)U.throwLater(V.e)}$.prototype.asCallback=$.prototype.nodeify=function(H,G){if(typeof H=="function"){var W=K;if(G!==void 0&&Object(G).spread)W=Q;this._then(W,q,void 0,this,H)}return this}}});var Mq0=F((Yj1,Nq0)=>{Nq0.exports=function($,I){var U={},Y=c1(),J=kg(),Q=Y.withAppended,K=Y.maybeWrapAsError,q=Y.canEvaluate,H=u5().TypeError,G="Async",W={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],V=new RegExp("^(?:"+w.join("|")+")$"),Z=function(i){return Y.isIdentifier(i)&&i.charAt(0)!=="_"&&i!=="constructor"};function X(i){return!V.test(i)}function L(i){try{return i.__isPromisified__===!0}catch(b){return!1}}function D(i,b,Y0){var B=Y.getDataPropertyOrDefault(i,b+Y0,W);return B?L(B):!1}function O(i,b,Y0){for(var B=0;B<i.length;B+=2){var x=i[B];if(Y0.test(x)){var c=x.replace(Y0,"");for(var r=0;r<i.length;r+=2)if(i[r]===c)throw new H(`Cannot promisify an API that has normal methods with '%s'-suffix
See http://goo.gl/MqrFmX
`.replace("%s",i))}}}function T(n,i,J0,E){var u=U.inheritedDataKeys(n),d=[];for(var a=0;a<u.length;++a){var K0=u[a],G0=n[K0],M0=E===W?!0:W(K0,G0,n);if(typeof G0==="function"&&!D(G0)&&!O(n,K0,i)&&E(K0,G0,n,M0))d.push(K0,G0)}return N(d,i,J0),d}var P=function(n){return n.replace(/([$])/,"\\$")},g,B=function(n){var i=[n],J0=Math.max(0,n-1-3);for(var E=n-1;E>=J0;--E)i.push(E);for(var E=n+1;E<=3;++E)i.push(E);return i},k=function(n){return U.filledRange(n,"_arg","")},h=function(n){return U.filledRange(Math.max(n,3),"_arg","")},f=function(n){if(typeof n.length==="number")return Math.max(Math.min(n.length,1024),0);return 0};g=function(n,i,J0,E,u,d){var a=Math.max(0,f(E)-1),K0=B(a),G0=typeof n==="string"||i===q;function M0(L1){var N1=k(L1).join(", "),J1=L1>0?", ":"",C1;if(G0)C1=`ret = callback.call(this, {{args}}, nodeback); break;
`;else C1=i===void 0?`ret = callback({{args}}, nodeback); break;
`.replace("%s",b))}}}function E(i,b,Y0,B){var x=Y.inheritedDataKeys(i),c=[];for(var r=0;r<x.length;++r){var Q0=x[r],w0=i[Q0],M0=B===Z?!0:Z(Q0,w0,i);if(typeof w0==="function"&&!L(w0)&&!D(i,Q0,b)&&B(Q0,w0,i,M0))c.push(Q0,w0)}return O(c,b,Y0),c}var T=function(i){return i.replace(/([$])/,"\\$")},A,R=function(i){var b=[i],Y0=Math.max(0,i-1-3);for(var B=i-1;B>=Y0;--B)b.push(B);for(var B=i+1;B<=3;++B)b.push(B);return b},k=function(i){return Y.filledRange(i,"_arg","")},g=function(i){return Y.filledRange(Math.max(i,3),"_arg","")},f=function(i){if(typeof i.length==="number")return Math.max(Math.min(i.length,1024),0);return 0};A=function(i,b,Y0,B,x,c){var r=Math.max(0,f(B)-1),Q0=R(r),w0=typeof i==="string"||b===U;function M0(I1){var t=k(I1).join(", "),T0=I1>0?", ":"",y0;if(w0)y0=`ret = callback.call(this, {{args}}, nodeback); break;
`;else y0=b===void 0?`ret = callback({{args}}, nodeback); break;
`:`ret = callback.call(receiver, {{args}}, nodeback); break;
`;return C1.replace("{{args}}",N1).replace(", ",J1)}function R0(){var L1="";for(var N1=0;N1<K0.length;++N1)L1+="case "+K0[N1]+":"+M0(K0[N1]);return L1+=`
`;return y0.replace("{{args}}",t).replace(", ",T0)}function R0(){var I1="";for(var t=0;t<Q0.length;++t)I1+="case "+Q0[t]+":"+M0(Q0[t]);return I1+=`
default:
var args = new Array(len + 1);
var i = 0;
@@ -180,15 +175,15 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof S4))r
args[i] = nodeback;
[CodeForCall]
break;
`.replace("[CodeForCall]",G0?`ret = callback.apply(this, args);
`.replace("[CodeForCall]",w0?`ret = callback.apply(this, args);
`:`ret = callback.apply(receiver, args);
`),L1}var v1=typeof n==="string"?"this != null ? this['"+n+"'] : fn":"fn",l0=`'use strict';
`),I1}var K1=typeof i==="string"?"this != null ? this['"+i+"'] : fn":"fn",k0=`'use strict';
var ret = function (Parameters) {
'use strict';
var len = arguments.length;
var promise = new Promise(INTERNAL);
promise._captureStackTrace();
var nodeback = nodebackForPromise(promise, `+d+`);
var nodeback = nodebackForPromise(promise, `+c+`);
var ret;
var callback = tryCatch([GetFunctionCode]);
switch(len) {
@@ -202,25 +197,25 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof S4))r
};
notEnumerableProp(ret, '__isPromisified__', true);
return ret;
`.replace("[CodeForSwitchCase]",R0()).replace("[GetFunctionCode]",v1);return l0=l0.replace("Parameters",h(a)),Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",l0)($,E,i,J,Q,Y,U.tryCatch,U.errorObj,U.notEnumerableProp,I)};function S(n,i,J0,E,u,d){var a=function(){return this}(),K0=n;if(typeof K0==="string")n=E;function G0(){var M0=i;if(i===q)M0=this;var R0=new $(I);R0._captureStackTrace();var v1=typeof K0==="string"&&this!==a?this[K0]:n,l0=Y(R0,d);try{v1.apply(M0,J(arguments,l0))}catch(L1){R0._rejectCallback(Q(L1),!0,!0)}if(!R0._isFateSealed())R0._setAsyncGuaranteed();return R0}return U.notEnumerableProp(G0,"__isPromisified__",!0),G0}var t=K?g:S;function p(n,i,J0,E,u){var d=new RegExp(P(i)+"$"),a=T(n,i,d,J0);for(var K0=0,G0=a.length;K0<G0;K0+=2){var M0=a[K0],R0=a[K0+1],v1=M0+i;if(E===t)n[v1]=t(M0,q,M0,R0,i,u);else{var l0=E(R0,function(){return t(M0,q,M0,R0,i,u)});U.notEnumerableProp(l0,"__isPromisified__",!0),n[v1]=l0}}return U.toFastProperties(n),n}function C(n,i,J0){return t(n,i,void 0,n,null,J0)}$.promisify=function(n,i){if(typeof n!=="function")throw new w("expecting a function but got "+U.classString(n));if(D(n))return n;i=Object(i);var J0=i.context===void 0?q:i.context,E=!!i.multiArgs,u=C(n,J0,E);return U.copyDescriptors(n,u,X),u},$.promisifyAll=function(n,i){if(typeof n!=="function"&&typeof n!=="object")throw new w(`the target of promisifyAll must be an object or a function
`.replace("[CodeForSwitchCase]",R0()).replace("[GetFunctionCode]",K1);return k0=k0.replace("Parameters",g(r)),Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",k0)($,B,b,Q,K,J,Y.tryCatch,Y.errorObj,Y.notEnumerableProp,I)};function C(i,b,Y0,B,x,c){var r=function(){return this}(),Q0=i;if(typeof Q0==="string")i=B;function w0(){var M0=b;if(b===U)M0=this;var R0=new $(I);R0._captureStackTrace();var K1=typeof Q0==="string"&&this!==r?this[Q0]:i,k0=J(R0,c);try{K1.apply(M0,Q(arguments,k0))}catch(I1){R0._rejectCallback(K(I1),!0,!0)}if(!R0._isFateSealed())R0._setAsyncGuaranteed();return R0}return Y.notEnumerableProp(w0,"__isPromisified__",!0),w0}var p=q?A:C;function n(i,b,Y0,B,x){var c=new RegExp(T(b)+"$"),r=E(i,b,c,Y0);for(var Q0=0,w0=r.length;Q0<w0;Q0+=2){var M0=r[Q0],R0=r[Q0+1],K1=M0+b;if(B===p)i[K1]=p(M0,U,M0,R0,b,x);else{var k0=B(R0,function(){return p(M0,U,M0,R0,b,x)});Y.notEnumerableProp(k0,"__isPromisified__",!0),i[K1]=k0}}return Y.toFastProperties(i),i}function S(i,b,Y0){return p(i,b,void 0,i,null,Y0)}$.promisify=function(i,b){if(typeof i!=="function")throw new H("expecting a function but got "+Y.classString(i));if(L(i))return i;b=Object(b);var Y0=b.context===void 0?U:b.context,B=!!b.multiArgs,x=S(i,Y0,B);return Y.copyDescriptors(i,x,X),x},$.promisifyAll=function(i,b){if(typeof i!=="function"&&typeof i!=="object")throw new H(`the target of promisifyAll must be an object or a function
See http://goo.gl/MqrFmX
`);i=Object(i);var J0=!!i.multiArgs,E=i.suffix;if(typeof E!=="string")E=z;var u=i.filter;if(typeof u!=="function")u=W;var d=i.promisifier;if(typeof d!=="function")d=t;if(!U.isIdentifier(E))throw RangeError(`suffix must be a valid identifier
`);b=Object(b);var Y0=!!b.multiArgs,B=b.suffix;if(typeof B!=="string")B=G;var x=b.filter;if(typeof x!=="function")x=Z;var c=b.promisifier;if(typeof c!=="function")c=p;if(!Y.isIdentifier(B))throw RangeError(`suffix must be a valid identifier
See http://goo.gl/MqrFmX
`);var a=U.inheritedDataKeys(n);for(var K0=0;K0<a.length;++K0){var G0=n[a[K0]];if(a[K0]!=="constructor"&&U.isClass(G0))p(G0.prototype,E,u,d,J0),p(G0,E,u,d,J0)}return p(n,E,u,d,J0)}}});var Xw0=L((BR1,Zw0)=>{Zw0.exports=function($,I,q,U){var Y=n1(),J=Y.isObject,Q=n3(),K;if(typeof Map==="function")K=Map;var w=function(){var V=0,W=0;function X(D,O){this[V]=D,this[V+W]=O,V++}return function(O){W=O.size,V=0;var N=Array(O.size*2);return O.forEach(X,N),N}}(),z=function(V){var W=new K,X=V.length/2|0;for(var D=0;D<X;++D){var O=V[X+D],N=V[D];W.set(O,N)}return W};function G(V){var W=!1,X;if(K!==void 0&&V instanceof K)X=w(V),W=!0;else{var D=Q.keys(V),O=D.length;X=Array(O*2);for(var N=0;N<O;++N){var T=D[N];X[N]=V[T],X[N+O]=T}}this.constructor$(X),this._isMap=W,this._init$(void 0,-3)}Y.inherits(G,I),G.prototype._init=function(){},G.prototype._promiseFulfilled=function(V,W){this._values[W]=V;var X=++this._totalResolved;if(X>=this._length){var D;if(this._isMap)D=z(this._values);else{D={};var O=this.length();for(var N=0,T=this.length();N<T;++N)D[this._values[N+O]]=this._values[N]}return this._resolve(D),!0}return!1},G.prototype.shouldCopyValues=function(){return!1},G.prototype.getActualLength=function(V){return V>>1};function H(V){var W,X=q(V);if(!J(X))return U(`cannot await properties of a non-object
`);var r=Y.inheritedDataKeys(i);for(var Q0=0;Q0<r.length;++Q0){var w0=i[r[Q0]];if(r[Q0]!=="constructor"&&Y.isClass(w0))n(w0.prototype,B,x,c,Y0),n(w0,B,x,c,Y0)}return n(i,B,x,c,Y0)}}});var Pq0=F((Jj1,Aq0)=>{Aq0.exports=function($,I,U,Y){var J=c1(),Q=J.isObject,K=p3(),q;if(typeof Map==="function")q=Map;var H=function(){var V=0,Z=0;function X(L,D){this[V]=L,this[V+Z]=D,V++}return function(D){Z=D.size,V=0;var O=Array(D.size*2);return D.forEach(X,O),O}}(),G=function(V){var Z=new q,X=V.length/2|0;for(var L=0;L<X;++L){var D=V[X+L],O=V[L];Z.set(D,O)}return Z};function W(V){var Z=!1,X;if(q!==void 0&&V instanceof q)X=H(V),Z=!0;else{var L=K.keys(V),D=L.length;X=Array(D*2);for(var O=0;O<D;++O){var E=L[O];X[O]=V[E],X[O+D]=E}}this.constructor$(X),this._isMap=Z,this._init$(void 0,-3)}J.inherits(W,I),W.prototype._init=function(){},W.prototype._promiseFulfilled=function(V,Z){this._values[Z]=V;var X=++this._totalResolved;if(X>=this._length){var L;if(this._isMap)L=G(this._values);else{L={};var D=this.length();for(var O=0,E=this.length();O<E;++O)L[this._values[O+D]]=this._values[O]}return this._resolve(L),!0}return!1},W.prototype.shouldCopyValues=function(){return!1},W.prototype.getActualLength=function(V){return V>>1};function w(V){var Z,X=U(V);if(!Q(X))return Y(`cannot await properties of a non-object
See http://goo.gl/MqrFmX
`);else if(X instanceof $)W=X._then($.props,void 0,void 0,void 0,void 0);else W=new G(X).promise();if(X instanceof $)W._propagateFrom(X,2);return W}$.prototype.props=function(){return H(this)},$.props=function(V){return H(V)}}});var Ow0=L((vR1,Dw0)=>{Dw0.exports=function($,I,q,U){var Y=n1(),J=function(K){return K.then(function(w){return Q(w,K)})};function Q(K,w){var z=q(K);if(z instanceof $)return J(z);else if(K=Y.asArray(K),K===null)return U("expecting an array or an iterable object but got "+Y.classString(K));var G=new $(I);if(w!==void 0)G._propagateFrom(w,3);var{_fulfill:H,_reject:V}=G;for(var W=0,X=K.length;W<X;++W){var D=K[W];if(D===void 0&&!(W in K))continue;$.cast(D)._then(H,V,void 0,G,null)}return G}$.race=function(K){return Q(K,void 0)},$.prototype.race=function(){return Q(this,void 0)}}});var Nw0=L((RR1,Lw0)=>{Lw0.exports=function($,I,q,U,Y,J){var Q=$._getDomain,K=n1(),w=K.tryCatch;function z(X,D,O,N){this.constructor$(X);var T=Q();if(this._fn=T===null?D:K.domainBind(T,D),O!==void 0)O=$.resolve(O),O._attachCancellationCallback(this);if(this._initialValue=O,this._currentCancellable=null,N===Y)this._eachValues=Array(this._length);else if(N===0)this._eachValues=null;else this._eachValues=void 0;this._promise._captureStackTrace(),this._init$(void 0,-5)}K.inherits(z,I),z.prototype._gotAccum=function(X){if(this._eachValues!==void 0&&this._eachValues!==null&&X!==Y)this._eachValues.push(X)},z.prototype._eachComplete=function(X){if(this._eachValues!==null)this._eachValues.push(X);return this._eachValues},z.prototype._init=function(){},z.prototype._resolveEmptyArray=function(){this._resolve(this._eachValues!==void 0?this._eachValues:this._initialValue)},z.prototype.shouldCopyValues=function(){return!1},z.prototype._resolve=function(X){this._promise._resolveCallback(X),this._values=null},z.prototype._resultCancelled=function(X){if(X===this._initialValue)return this._cancel();if(this._isResolved())return;if(this._resultCancelled$(),this._currentCancellable instanceof $)this._currentCancellable.cancel();if(this._initialValue instanceof $)this._initialValue.cancel()},z.prototype._iterate=function(X){this._values=X;var D,O,N=X.length;if(this._initialValue!==void 0)D=this._initialValue,O=0;else D=$.resolve(X[0]),O=1;if(this._currentCancellable=D,!D.isRejected())for(;O<N;++O){var T={accum:null,value:X[O],index:O,length:N,array:this};D=D._then(V,void 0,void 0,T,void 0)}if(this._eachValues!==void 0)D=D._then(this._eachComplete,void 0,void 0,this,void 0);D._then(G,G,void 0,D,this)},$.prototype.reduce=function(X,D){return H(this,X,D,null)},$.reduce=function(X,D,O,N){return H(X,D,O,N)};function G(X,D){if(this.isFulfilled())D._resolve(X);else D._reject(X)}function H(X,D,O,N){if(typeof D!=="function")return q("expecting a function but got "+K.classString(D));var T=new z(X,D,O,N);return T.promise()}function V(X){this.accum=X,this.array._gotAccum(X);var D=U(this.value,this.array._promise);if(D instanceof $)return this.array._currentCancellable=D,D._then(W,void 0,void 0,this,void 0);else return W.call(this,D)}function W(X){var D=this.array,O=D._promise,N=w(D._fn);O._pushContext();var T;if(D._eachValues!==void 0)T=N.call(O._boundValue(),X,this.index,this.length);else T=N.call(O._boundValue(),this.accum,X,this.index,this.length);if(T instanceof $)D._currentCancellable=T;var P=O._popContext();return J.checkForgottenReturns(T,P,D._eachValues!==void 0?"Promise.each":"Promise.reduce",O),T}}});var Mw0=L((CR1,Fw0)=>{Fw0.exports=function($,I,q){var U=$.PromiseInspection,Y=n1();function J(Q){this.constructor$(Q)}Y.inherits(J,I),J.prototype._promiseResolved=function(Q,K){this._values[Q]=K;var w=++this._totalResolved;if(w>=this._length)return this._resolve(this._values),!0;return!1},J.prototype._promiseFulfilled=function(Q,K){var w=new U;return w._bitField=33554432,w._settledValueField=Q,this._promiseResolved(K,w)},J.prototype._promiseRejected=function(Q,K){var w=new U;return w._bitField=16777216,w._settledValueField=Q,this._promiseResolved(K,w)},$.settle=function(Q){return q.deprecated(".settle()",".reflect()"),new J(Q).promise()},$.prototype.settle=function(){return $.settle(this)}}});var gw0=L((_R1,Aw0)=>{Aw0.exports=function($,I,q){var U=n1(),Y=S5().RangeError,J=S5().AggregateError,Q=U.isArray,K={};function w(G){this.constructor$(G),this._howMany=0,this._unwrap=!1,this._initialized=!1}U.inherits(w,I),w.prototype._init=function(){if(!this._initialized)return;if(this._howMany===0){this._resolve([]);return}this._init$(void 0,-5);var G=Q(this._values);if(!this._isResolved()&&G&&this._howMany>this._canPossiblyFulfill())this._reject(this._getRangeError(this.length()))},w.prototype.init=function(){this._initialized=!0,this._init()},w.prototype.setUnwrap=function(){this._unwrap=!0},w.prototype.howMany=function(){return this._howMany},w.prototype.setHowMany=function(G){this._howMany=G},w.prototype._promiseFulfilled=function(G){if(this._addFulfilled(G),this._fulfilled()===this.howMany()){if(this._values.length=this.howMany(),this.howMany()= Line truncated
`);else if(X instanceof $)Z=X._then($.props,void 0,void 0,void 0,void 0);else Z=new W(X).promise();if(X instanceof $)Z._propagateFrom(X,2);return Z}$.prototype.props=function(){return w(this)},$.props=function(V){return w(V)}}});var Eq0=F((Qj1,Tq0)=>{Tq0.exports=function($,I,U,Y){var J=c1(),Q=function(q){return q.then(function(H){return K(H,q)})};function K(q,H){var G=U(q);if(G instanceof $)return Q(G);else if(q=J.asArray(q),q===null)return Y("expecting an array or an iterable object but got "+J.classString(q));var W=new $(I);if(H!==void 0)W._propagateFrom(H,3);var{_fulfill:w,_reject:V}=W;for(var Z=0,X=q.length;Z<X;++Z){var L=q[Z];if(L===void 0&&!(Z in q))continue;$.cast(L)._then(w,V,void 0,W,null)}return W}$.race=function(q){return K(q,void 0)},$.prototype.race=function(){return K(this,void 0)}}});var vq0=F((Kj1,Bq0)=>{Bq0.exports=function($,I,U,Y,J,Q){var K=$._getDomain,q=c1(),H=q.tryCatch;function G(X,L,D,O){this.constructor$(X);var E=K();if(this._fn=E===null?L:q.domainBind(E,L),D!==void 0)D=$.resolve(D),D._attachCancellationCallback(this);if(this._initialValue=D,this._currentCancellable=null,O===J)this._eachValues=Array(this._length);else if(O===0)this._eachValues=null;else this._eachValues=void 0;this._promise._captureStackTrace(),this._init$(void 0,-5)}q.inherits(G,I),G.prototype._gotAccum=function(X){if(this._eachValues!==void 0&&this._eachValues!==null&&X!==J)this._eachValues.push(X)},G.prototype._eachComplete=function(X){if(this._eachValues!==null)this._eachValues.push(X);return this._eachValues},G.prototype._init=function(){},G.prototype._resolveEmptyArray=function(){this._resolve(this._eachValues!==void 0?this._eachValues:this._initialValue)},G.prototype.shouldCopyValues=function(){return!1},G.prototype._resolve=function(X){this._promise._resolveCallback(X),this._values=null},G.prototype._resultCancelled=function(X){if(X===this._initialValue)return this._cancel();if(this._isResolved())return;if(this._resultCancelled$(),this._currentCancellable instanceof $)this._currentCancellable.cancel();if(this._initialValue instanceof $)this._initialValue.cancel()},G.prototype._iterate=function(X){this._values=X;var L,D,O=X.length;if(this._initialValue!==void 0)L=this._initialValue,D=0;else L=$.resolve(X[0]),D=1;if(this._currentCancellable=L,!L.isRejected())for(;D<O;++D){var E={accum:null,value:X[D],index:D,length:O,array:this};L=L._then(V,void 0,void 0,E,void 0)}if(this._eachValues!==void 0)L=L._then(this._eachComplete,void 0,void 0,this,void 0);L._then(W,W,void 0,L,this)},$.prototype.reduce=function(X,L){return w(this,X,L,null)},$.reduce=function(X,L,D,O){return w(X,L,D,O)};function W(X,L){if(this.isFulfilled())L._resolve(X);else L._reject(X)}function w(X,L,D,O){if(typeof L!=="function")return U("expecting a function but got "+q.classString(L));var E=new G(X,L,D,O);return E.promise()}function V(X){this.accum=X,this.array._gotAccum(X);var L=Y(this.value,this.array._promise);if(L instanceof $)return this.array._currentCancellable=L,L._then(Z,void 0,void 0,this,void 0);else return Z.call(this,L)}function Z(X){var L=this.array,D=L._promise,O=H(L._fn);D._pushContext();var E;if(L._eachValues!==void 0)E=O.call(D._boundValue(),X,this.index,this.length);else E=O.call(D._boundValue(),this.accum,X,this.index,this.length);if(E instanceof $)L._currentCancellable=E;var T=D._popContext();return Q.checkForgottenReturns(E,T,L._eachValues!==void 0?"Promise.each":"Promise.reduce",D),E}}});var Cq0=F((qj1,Rq0)=>{Rq0.exports=function($,I,U){var Y=$.PromiseInspection,J=c1();function Q(K){this.constructor$(K)}J.inherits(Q,I),Q.prototype._promiseResolved=function(K,q){this._values[K]=q;var H=++this._totalResolved;if(H>=this._length)return this._resolve(this._values),!0;return!1},Q.prototype._promiseFulfilled=function(K,q){var H=new Y;return H._bitField=33554432,H._settledValueField=K,this._promiseResolved(q,H)},Q.prototype._promiseRejected=function(K,q){var H=new Y;return H._bitField=16777216,H._settledValueField=K,this._promiseResolved(q,H)},$.settle=function(K){return U.deprecated(".settle()",".reflect()"),new Q(K).promise()},$.prototype.settle=function(){return $.settle(this)}}});var _q0=F((Hj1,jq0)=>{jq0.exports=function($,I,U){var Y=c1(),J=u5().RangeError,Q=u5().AggregateError,K=Y.isArray,q={};function H(W){this.constructor$(W),this._howMany=0,this._unwrap=!1,this._initialized=!1}Y.inherits(H,I),H.prototype._init=function(){if(!this._initialized)return;if(this._howMany===0){this._resolve([]);return}this._init$(void 0,-5);var W=K(this._values);if(!this._isResolved()&&W&&this._howMany>this._canPossiblyFulfill())this._reject(this._getRangeError(this.length()))},H.prototype.init=function(){this._initialized=!0,this._init()},H.prototype.setUnwrap=function(){this._unwrap=!0},H.prototype.howMany=function(){return this._howMany},H.prototype.setHowMany=function(W){this._howMany=W},H.prototype._promiseFulfilled=function(W){if(this._addFulfilled(W),this._fulfilled()===this.howMany()){if(this._values.length=this.howMany(),this.howMany()= Line truncated
See http://goo.gl/MqrFmX
`);var V=new w(G),W=V.promise();return V.setHowMany(H),V.init(),W}$.some=function(G,H){return z(G,H)},$.prototype.some=function(G){return z(this,G)},$._SomePromiseArray=w}});var Tw0=L((hR1,Pw0)=>{Pw0.exports=function($,I){var q=$.map;$.prototype.filter=function(U,Y){return q(this,U,Y,I)},$.filter=function(U,Y,J){return q(U,Y,J,I)}}});var jw0=L((SR1,Ew0)=>{Ew0.exports=function($,I){var{reduce:q,all:U}=$;function Y(){return U(this)}function J(Q,K){return q(Q,K,I,I)}$.prototype.each=function(Q){return q(this,Q,I,0)._then(Y,void 0,void 0,this,void 0)},$.prototype.mapSeries=function(Q){return q(this,Q,I,I)},$.each=function(Q,K){return q(Q,K,I,0)._then(Y,void 0,void 0,Q,void 0)},$.mapSeries=J}});var vw0=L((yR1,Bw0)=>{Bw0.exports=function($){var I=$._SomePromiseArray;function q(U){var Y=new I(U),J=Y.promise();return Y.setHowMany(1),Y.setUnwrap(),Y.init(),J}$.any=function(U){return q(U)},$.prototype.any=function(){return q(this)}}});var Rw0=L((uR1,MS)=>{MS.exports=function(){var $=function(){return new H(`circular promise resolution chain
`);var V=new H(W),Z=V.promise();return V.setHowMany(w),V.init(),Z}$.some=function(W,w){return G(W,w)},$.prototype.some=function(W){return G(this,W)},$._SomePromiseArray=H}});var gq0=F((Gj1,Sq0)=>{Sq0.exports=function($,I){var U=$.map;$.prototype.filter=function(Y,J){return U(this,Y,J,I)},$.filter=function(Y,J,Q){return U(Y,J,Q,I)}}});var hq0=F((Wj1,yq0)=>{yq0.exports=function($,I){var{reduce:U,all:Y}=$;function J(){return Y(this)}function Q(K,q){return U(K,q,I,I)}$.prototype.each=function(K){return U(this,K,I,0)._then(J,void 0,void 0,this,void 0)},$.prototype.mapSeries=function(K){return U(this,K,I,I)},$.each=function(K,q){return U(K,q,I,0)._then(J,void 0,void 0,K,void 0)},$.mapSeries=Q}});var xq0=F((wj1,uq0)=>{uq0.exports=function($){var I=$._SomePromiseArray;function U(Y){var J=new I(Y),Q=J.promise();return J.setHowMany(1),J.setUnwrap(),J.init(),Q}$.any=function(Y){return U(Y)},$.prototype.any=function(){return U(this)}}});var kq0=F((Vj1,ig)=>{ig.exports=function(){var $=function(){return new w(`circular promise resolution chain
See http://goo.gl/MqrFmX
`)},I=function(){return new C.PromiseInspection(this._target())},q=function(E){return C.reject(new H(E))};function U(){}var Y={},J=n1(),Q;if(J.isNode)Q=function(){var E=process.domain;if(E===void 0)E=null;return E};else Q=function(){return null};J.notEnumerableProp(C,"_getDomain",Q);var K=n3(),w=gK0(),z=new w;K.defineProperty(C,"_async",{value:z});var G=S5(),H=C.TypeError=G.TypeError;C.RangeError=G.RangeError;var V=C.CancellationError=G.CancellationError;C.TimeoutError=G.TimeoutError,C.OperationalError=G.OperationalError,C.RejectionError=G.OperationalError,C.AggregateError=G.AggregateError;var W=function(){},X={},D={},O=BK0()(C,W),N=RK0()(C,W,O,q,U),T=_K0()(C),P=T.create,g=SK0()(C,T),B=g.CapturedTrace,k=uK0()(C,O),h=kK0()(D),f=NS(),S=J.errorObj,t=J.tryCatch;function p(E,u){if(typeof u!=="function")throw new H("expecting a function but got "+J.classString(u));if(E.constructor!==C)throw new H(`the promise constructor cannot be invoked directly
`)},I=function(){return new S.PromiseInspection(this._target())},U=function(B){return S.reject(new w(B))};function Y(){}var J={},Q=c1(),K;if(Q.isNode)K=function(){var B=process.domain;if(B===void 0)B=null;return B};else K=function(){return null};Q.notEnumerableProp(S,"_getDomain",K);var q=p3(),H=_K0(),G=new H;q.defineProperty(S,"_async",{value:G});var W=u5(),w=S.TypeError=W.TypeError;S.RangeError=W.RangeError;var V=S.CancellationError=W.CancellationError;S.TimeoutError=W.TimeoutError,S.OperationalError=W.OperationalError,S.RejectionError=W.OperationalError,S.AggregateError=W.AggregateError;var Z=function(){},X={},L={},D=uK0()(S,Z),O=kK0()(S,Z,D,U,Y),E=iK0()(S),T=E.create,A=nK0()(S,E),R=A.CapturedTrace,k=cK0()(S,D),g=mK0()(L),f=kg(),C=Q.errorObj,p=Q.tryCatch;function n(B,x){if(typeof x!=="function")throw new w("expecting a function but got "+Q.classString(x));if(B.constructor!==S)throw new w(`the promise constructor cannot be invoked directly
See http://goo.gl/MqrFmX
`)}function C(E){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,E!==W)p(this,E),this._resolveFromExecutor(E);this._promiseCreated(),this._fireEvent("promiseCreated",this)}C.prototype.toString=function(){return"[object Promise]"},C.prototype.caught=C.prototype.catch=function(E){var u=arguments.length;if(u>1){var d=Array(u-1),a=0,K0;for(K0=0;K0<u-1;++K0){var G0=arguments[K0];if(J.isObject(G0))d[a++]=G0;else return q("expecting an object but got A catch statement predicate "+J.classString(G0))}return d.length=a,E=arguments[K0],this.then(void 0,h(d,E,this))}return this.then(void 0,E)},C.prototype.reflect=function(){return this._then(I,I,void 0,this,void 0)},C.prototype.then=function(E,u){if(g.warnings()&&arguments.length>0&&typeof E!=="function"&&typeof u!=="function"){var d=".then() only accepts functions but was passed: "+J.classString(E);if(arguments.length>1)d+=", "+J.classString(u);this._warn(d)}return this._then(E,u,void 0,void 0,void 0)},C.prototype.done=function(E,u){var d=this._then(E,u,void 0,void 0,void 0);d._setIsFinal()},C.prototype.spread=function(E){if(typeof E!=="function")return q("expecting a function but got "+J.classString(E));return this.all()._then(E,void 0,void 0,X,void 0)},C.prototype.toJSON=function(){var E={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())E.fulfillmentValue=this.value(),E.isFulfilled=!0;else if(this.isRejected())E.rejectionReason=this.reason(),E.isRejected=!0;return E},C.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new N(this).promise()},C.prototype.error=function(E){return this.caught(J.originatesFromRejection,E)},C.getNewLibraryCopy=MS.exports,C.is=function(E){return E instanceof C},C.fromNode=C.fromCallback=function(E){var u=new C(W);u._captureStackTrace();var d=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,a=t(E)(f(u,d));if(a===S)u._rejectCallback(a.e,!0);if(!u._isFateSealed())u._setAsyncGuaranteed();return u},C.all=function(E){return new N(E).promise()},C.cast=function(E){var u=O(E);if(!(u instanceof C))u=new C(W),u._captureStackTrace(),u._setFulfilled(),u._rejectionHandler0=E;return u},C.resolve=C.fulfilled=C.cast,C.reject=C.rejected=function(E){var u=new C(W);return u._captureStackTrace(),u._rejectCallback(E,!0),u},C.setScheduler=function(E){if(typeof E!=="function")throw new H("expecting a function but got "+J.classString(E));return z.setScheduler(E)},C.prototype._then=function(E,u,d,a,K0){var G0=K0!==void 0,M0=G0?K0:new C(W),R0=this._target(),v1=R0._bitField;if(!G0){if(M0._propagateFrom(this,3),M0._captureStackTrace(),a===void 0&&(this._bitField&2097152)!==0)if((v1&50397184)!==0)a=this._boundValue();else a=R0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,M0)}var l0=Q();if((v1&50397184)!==0){var L1,N1,J1=R0._settlePromiseCtx;if((v1&33554432)!==0)N1=R0._rejectionHandler0,L1=E;else if((v1&16777216)!==0)N1=R0._fulfillmentHandler0,L1=u,R0._unsetRejectionIsUnhandled();else J1=R0._settlePromiseLateCancellationObserver,N1=new V("late cancellation observer"),R0._attachExtraTrace(N1),L1=u;z.invoke(J1,R0,{handler:l0===null?L1:typeof L1==="function"&&J.domainBind(l0,L1),promise:M0,receiver:a,value:N1})}else R0._addCallbacks(E,u,M0,a,l0);return M0},C.prototype._length=function(){return this._bitField&65535},C.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},C.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},C.prototype._setLength=function(E){this._bitField=this._bitField&-65536|E&65535},C.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},C.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},C.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},C.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},C.prototype._isFinal=function(){return(this._bitField&4194304)>0},C.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},C.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},C.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},C.prototype._setAsyncGuaranteed=function(){if(z.hasCustomScheduler())return;this._bitField=this._bitField|134217728},C.prototype._receiverAt=function(E){var u=E===0?this._receiver0:this[E*4-4+3];if(u===Y)return;else if(u===void 0&&this._isBound())return this._boundValue();return u},C.prototype._promiseAt=function(E){return this[E*4-4+2]},C.prototype._fulfillmentHandlerAt=function(E){return this[E*4-4+0]},C.prototype._rejectionHandlerAt=function(E){return this[E*4-4+1]},C.prototype._boundValue=function(){},C.prototype._migrateCallback0=function(E){var{_bit Line truncated
`)}function S(B){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,B!==Z)n(this,B),this._resolveFromExecutor(B);this._promiseCreated(),this._fireEvent("promiseCreated",this)}S.prototype.toString=function(){return"[object Promise]"},S.prototype.caught=S.prototype.catch=function(B){var x=arguments.length;if(x>1){var c=Array(x-1),r=0,Q0;for(Q0=0;Q0<x-1;++Q0){var w0=arguments[Q0];if(Q.isObject(w0))c[r++]=w0;else return U("expecting an object but got A catch statement predicate "+Q.classString(w0))}return c.length=r,B=arguments[Q0],this.then(void 0,g(c,B,this))}return this.then(void 0,B)},S.prototype.reflect=function(){return this._then(I,I,void 0,this,void 0)},S.prototype.then=function(B,x){if(A.warnings()&&arguments.length>0&&typeof B!=="function"&&typeof x!=="function"){var c=".then() only accepts functions but was passed: "+Q.classString(B);if(arguments.length>1)c+=", "+Q.classString(x);this._warn(c)}return this._then(B,x,void 0,void 0,void 0)},S.prototype.done=function(B,x){var c=this._then(B,x,void 0,void 0,void 0);c._setIsFinal()},S.prototype.spread=function(B){if(typeof B!=="function")return U("expecting a function but got "+Q.classString(B));return this.all()._then(B,void 0,void 0,X,void 0)},S.prototype.toJSON=function(){var B={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())B.fulfillmentValue=this.value(),B.isFulfilled=!0;else if(this.isRejected())B.rejectionReason=this.reason(),B.isRejected=!0;return B},S.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new O(this).promise()},S.prototype.error=function(B){return this.caught(Q.originatesFromRejection,B)},S.getNewLibraryCopy=ig.exports,S.is=function(B){return B instanceof S},S.fromNode=S.fromCallback=function(B){var x=new S(Z);x._captureStackTrace();var c=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=p(B)(f(x,c));if(r===C)x._rejectCallback(r.e,!0);if(!x._isFateSealed())x._setAsyncGuaranteed();return x},S.all=function(B){return new O(B).promise()},S.cast=function(B){var x=D(B);if(!(x instanceof S))x=new S(Z),x._captureStackTrace(),x._setFulfilled(),x._rejectionHandler0=B;return x},S.resolve=S.fulfilled=S.cast,S.reject=S.rejected=function(B){var x=new S(Z);return x._captureStackTrace(),x._rejectCallback(B,!0),x},S.setScheduler=function(B){if(typeof B!=="function")throw new w("expecting a function but got "+Q.classString(B));return G.setScheduler(B)},S.prototype._then=function(B,x,c,r,Q0){var w0=Q0!==void 0,M0=w0?Q0:new S(Z),R0=this._target(),K1=R0._bitField;if(!w0){if(M0._propagateFrom(this,3),M0._captureStackTrace(),r===void 0&&(this._bitField&2097152)!==0)if((K1&50397184)!==0)r=this._boundValue();else r=R0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,M0)}var k0=K();if((K1&50397184)!==0){var I1,t,T0=R0._settlePromiseCtx;if((K1&33554432)!==0)t=R0._rejectionHandler0,I1=B;else if((K1&16777216)!==0)t=R0._fulfillmentHandler0,I1=x,R0._unsetRejectionIsUnhandled();else T0=R0._settlePromiseLateCancellationObserver,t=new V("late cancellation observer"),R0._attachExtraTrace(t),I1=x;G.invoke(T0,R0,{handler:k0===null?I1:typeof I1==="function"&&Q.domainBind(k0,I1),promise:M0,receiver:r,value:t})}else R0._addCallbacks(B,x,M0,r,k0);return M0},S.prototype._length=function(){return this._bitField&65535},S.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},S.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},S.prototype._setLength=function(B){this._bitField=this._bitField&-65536|B&65535},S.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},S.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},S.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},S.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},S.prototype._isFinal=function(){return(this._bitField&4194304)>0},S.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},S.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},S.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},S.prototype._setAsyncGuaranteed=function(){if(G.hasCustomScheduler())return;this._bitField=this._bitField|134217728},S.prototype._receiverAt=function(B){var x=B===0?this._receiver0:this[B*4-4+3];if(x===J)return;else if(x===void 0&&this._isBound())return this._boundValue();return x},S.prototype._promiseAt=function(B){return this[B*4-4+2]},S.prototype._fulfillmentHandlerAt=function(B){return this[B*4-4+0]},S.prototype._rejectionHandlerAt=function(B){return this[B*4-4+1]},S.prototype._boundValue=function(){},S.prototype._migrateCallback0=function(B){var{_bitField: Line truncated
path = %s
syscall = %s
fstream_type = %s
@@ -229,91 +224,101 @@ fstream_unc_path = %s
fstream_class = %s
fstream_stack =
%s
`,I||"UNKNOWN",U.stack,U.path,U.syscall,U.fstream_type,U.fstream_path,U.fstream_unc_path,U.fstream_class,U.fstream_stack.join(`
`));else q.emit("warn",U)};K7.prototype.info=function($,I){this.emit("info",$,I)};K7.prototype.error=function($,I,q){var U=zG0($,I,this);if(q)throw U;else this.emit("error",U)};function zG0($,I,q){if(!($ instanceof Error))$=Error($);if($.code=$.code||I,$.path=$.path||q.path,$.fstream_type=$.fstream_type||q.type,$.fstream_path=$.fstream_path||q.path,q._path!==q.path)$.fstream_unc_path=$.fstream_unc_path||q._path;if(q.linkpath)$.fstream_linkpath=$.fstream_linkpath||q.linkpath;return $.fstream_class=$.fstream_class||q.constructor.name,$.fstream_stack=$.fstream_stack||Error().stack.split(/\n/).slice(3).map(function(U){return U.replace(/^ {4}at /,"")}),$}});var bK=L((VC1,HG0)=>{HG0.exports=NQ1;function NQ1($){var I=["Directory","File","SymbolicLink","Link","BlockDevice","CharacterDevice","FIFO","Socket"],q;if($.type&&I.indexOf($.type)!==-1)return $[$.type]=!0,$.type;for(var U=0,Y=I.length;U<Y;U++){q=I[U];var J=$[q]||$["is"+q];if(typeof J==="function")J=J.call($);if(J)return $[q]=!0,$.type=q,q}return null}});var Ky=L((WC1,VG0)=>{VG0.exports=pK;var FQ1=m6(),MQ1=n0(),Qy=r3();MQ1(pK,Qy);function pK($){var I=this;if(!(I instanceof pK))throw Error("LinkReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="SymbolicLink"&&$.SymbolicLink))throw Error("Non-link type "+$.type);Qy.call(I,$)}pK.prototype._stat=function($){var I=this;FQ1.readlink(I._path,function(q,U){if(q)return I.error(q);I.linkpath=I.props.linkpath=U,I.emit("linkpath",U),Qy.prototype._stat.call(I,$)})};pK.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var zy=L((ZC1,XG0)=>{XG0.exports=i8;var ZG0=m6(),AQ1=n0(),cK=o("path"),wy=r3(),WG0=o("assert").ok;AQ1(i8,wy);function i8($){var I=this;if(!(I instanceof i8))throw Error("DirReader must be called as constructor.");if($.type!=="Directory"||!$.Directory)throw Error("Non-directory type "+$.type);if(I.entries=null,I._index=-1,I._paused=!1,I._length=-1,$.sort)this.sort=$.sort;wy.call(this,$)}i8.prototype._getEntries=function(){var $=this;if($._gotEntries)return;$._gotEntries=!0,ZG0.readdir($._path,function(I,q){if(I)return $.error(I);if($.entries=q,$.emit("entries",q),$._paused)$.once("resume",U);else U();function U(){if($._length=$.entries.length,typeof $.sort==="function")$.entries=$.entries.sort($.sort.bind($));$._read()}})};i8.prototype._read=function(){var $=this;if(!$.entries)return $._getEntries();if($._paused||$._currentEntry||$._aborted)return;if($._index++,$._index>=$.entries.length){if(!$._ended)$._ended=!0,$.emit("end"),$.emit("close");return}var I=cK.resolve($._path,$.entries[$._index]);WG0(I!==$._path),WG0($.entries[$._index]),$._currentEntry=I,ZG0[$.props.follow?"stat":"lstat"](I,function(q,U){if(q)return $.error(q);var Y=$._proxy||$;U.path=I,U.basename=cK.basename(I),U.dirname=cK.dirname(I);var J=$.getChildProps.call(Y,U);J.path=I,J.basename=cK.basename(I),J.dirname=cK.dirname(I);var Q=wy(J,U);$._currentEntry=Q,Q.on("pause",function(z){if(!$._paused&&!Q._disowned)$.pause(z)}),Q.on("resume",function(z){if($._paused&&!Q._disowned)$.resume(z)}),Q.on("stat",function(z){if($.emit("_entryStat",Q,z),Q._aborted)return;if(Q._paused)Q.once("resume",function(){$.emit("entryStat",Q,z)});else $.emit("entryStat",Q,z)}),Q.on("ready",function z(){if($._paused)return Q.pause($),$.once("resume",z);if(Q.type==="Socket")$.emit("socket",Q);else $.emitEntry(Q)});var K=!1;Q.on("close",w),Q.on("disown",w);function w(){if(K)return;if(K=!0,$.emit("childEnd",Q),$.emit("entryEnd",Q),$._currentEntry=null,!$._paused)$._read()}Q.on("error",function(z){if(Q._swallowErrors)$.warn(z),Q.emit("end"),Q.emit("close");else $.emit("error",z)}),["child","childEnd","warn"].forEach(function(z){Q.on(z,$.emit.bind($,z))})})};i8.prototype.disown=function($){if($.emit("beforeDisown"),$._disowned=!0,$.parent=$.root=null,$===this._currentEntry)this._currentEntry=null;$.emit("disown")};i8.prototype.getChildProps=function(){return{depth:this.depth+1,root:this.root||this,parent:this,follow:this.follow,filter:this.filter,sort:this.props.sort,hardlinks:this.props.hardlinks}};i8.prototype.pause=function($){var I=this;if(I._paused)return;if($=$||I,I._paused=!0,I._currentEntry&&I._currentEntry.pause)I._currentEntry.pause($);I.emit("pause",$)};i8.prototype.resume=function($){var I=this;if(!I._paused)return;if($=$||I,I._paused=!1,I.emit("resume",$),I._paused)return;if(I._currentEntry){if(I._currentEntry.resume)I._currentEntry.resume($)}else I._read()};i8.prototype.emitEntry=function($){this.emit("entry",$),this.emit("child",$)}});var Gy=L((XC1,NG0)=>{NG0.exports=t3;var gQ1=m6(),PQ1=n0(),DG0=r3(),OG0={EOF:!0},LG0={CLOSE:!0};PQ1(t3,DG0);function t3($){var I=this;if(!(I instanceof t3))throw Error("FileReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="File"&&$.File))throw Error("Non-file type "+$.type);I._buffer=[],I._bytesEmitted=0,DG0.call(I,$)}t3.prototype._getStream=function(){var $=this,I=$._stream=gQ1.createReadStream($._path,$.pro Line truncated
`,I||"UNKNOWN",Y.stack,Y.path,Y.syscall,Y.fstream_type,Y.fstream_path,Y.fstream_unc_path,Y.fstream_class,Y.fstream_stack.join(`
`));else U.emit("warn",Y)};V7.prototype.info=function($,I){this.emit("info",$,I)};V7.prototype.error=function($,I,U){var Y=DG0($,I,this);if(U)throw Y;else this.emit("error",Y)};function DG0($,I,U){if(!($ instanceof Error))$=Error($);if($.code=$.code||I,$.path=$.path||U.path,$.fstream_type=$.fstream_type||U.type,$.fstream_path=$.fstream_path||U.path,U._path!==U.path)$.fstream_unc_path=$.fstream_unc_path||U._path;if(U.linkpath)$.fstream_linkpath=$.fstream_linkpath||U.linkpath;return $.fstream_class=$.fstream_class||U.constructor.name,$.fstream_stack=$.fstream_stack||Error().stack.split(/\n/).slice(3).map(function(Y){return Y.replace(/^ {4}at /,"")}),$}});var lq=F((nj1,OG0)=>{OG0.exports=FJ1;function FJ1($){var I=["Directory","File","SymbolicLink","Link","BlockDevice","CharacterDevice","FIFO","Socket"],U;if($.type&&I.indexOf($.type)!==-1)return $[$.type]=!0,$.type;for(var Y=0,J=I.length;Y<J;Y++){U=I[Y];var Q=$[U]||$["is"+U];if(typeof Q==="function")Q=Q.call($);if(Q)return $[U]=!0,$.type=U,U}return null}});var By=F((pj1,NG0)=>{NG0.exports=oq;var OJ1=s6(),NJ1=c0(),Ey=s3();NJ1(oq,Ey);function oq($){var I=this;if(!(I instanceof oq))throw Error("LinkReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="SymbolicLink"&&$.SymbolicLink))throw Error("Non-link type "+$.type);Ey.call(I,$)}oq.prototype._stat=function($){var I=this;OJ1.readlink(I._path,function(U,Y){if(U)return I.error(U);I.linkpath=I.props.linkpath=Y,I.emit("linkpath",Y),Ey.prototype._stat.call(I,$)})};oq.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var Ry=F((cj1,PG0)=>{PG0.exports=n8;var AG0=s6(),MJ1=c0(),rq=a("path"),vy=s3(),MG0=a("assert").ok;MJ1(n8,vy);function n8($){var I=this;if(!(I instanceof n8))throw Error("DirReader must be called as constructor.");if($.type!=="Directory"||!$.Directory)throw Error("Non-directory type "+$.type);if(I.entries=null,I._index=-1,I._paused=!1,I._length=-1,$.sort)this.sort=$.sort;vy.call(this,$)}n8.prototype._getEntries=function(){var $=this;if($._gotEntries)return;$._gotEntries=!0,AG0.readdir($._path,function(I,U){if(I)return $.error(I);if($.entries=U,$.emit("entries",U),$._paused)$.once("resume",Y);else Y();function Y(){if($._length=$.entries.length,typeof $.sort==="function")$.entries=$.entries.sort($.sort.bind($));$._read()}})};n8.prototype._read=function(){var $=this;if(!$.entries)return $._getEntries();if($._paused||$._currentEntry||$._aborted)return;if($._index++,$._index>=$.entries.length){if(!$._ended)$._ended=!0,$.emit("end"),$.emit("close");return}var I=rq.resolve($._path,$.entries[$._index]);MG0(I!==$._path),MG0($.entries[$._index]),$._currentEntry=I,AG0[$.props.follow?"stat":"lstat"](I,function(U,Y){if(U)return $.error(U);var J=$._proxy||$;Y.path=I,Y.basename=rq.basename(I),Y.dirname=rq.dirname(I);var Q=$.getChildProps.call(J,Y);Q.path=I,Q.basename=rq.basename(I),Q.dirname=rq.dirname(I);var K=vy(Q,Y);$._currentEntry=K,K.on("pause",function(G){if(!$._paused&&!K._disowned)$.pause(G)}),K.on("resume",function(G){if($._paused&&!K._disowned)$.resume(G)}),K.on("stat",function(G){if($.emit("_entryStat",K,G),K._aborted)return;if(K._paused)K.once("resume",function(){$.emit("entryStat",K,G)});else $.emit("entryStat",K,G)}),K.on("ready",function G(){if($._paused)return K.pause($),$.once("resume",G);if(K.type==="Socket")$.emit("socket",K);else $.emitEntry(K)});var q=!1;K.on("close",H),K.on("disown",H);function H(){if(q)return;if(q=!0,$.emit("childEnd",K),$.emit("entryEnd",K),$._currentEntry=null,!$._paused)$._read()}K.on("error",function(G){if(K._swallowErrors)$.warn(G),K.emit("end"),K.emit("close");else $.emit("error",G)}),["child","childEnd","warn"].forEach(function(G){K.on(G,$.emit.bind($,G))})})};n8.prototype.disown=function($){if($.emit("beforeDisown"),$._disowned=!0,$.parent=$.root=null,$===this._currentEntry)this._currentEntry=null;$.emit("disown")};n8.prototype.getChildProps=function(){return{depth:this.depth+1,root:this.root||this,parent:this,follow:this.follow,filter:this.filter,sort:this.props.sort,hardlinks:this.props.hardlinks}};n8.prototype.pause=function($){var I=this;if(I._paused)return;if($=$||I,I._paused=!0,I._currentEntry&&I._currentEntry.pause)I._currentEntry.pause($);I.emit("pause",$)};n8.prototype.resume=function($){var I=this;if(!I._paused)return;if($=$||I,I._paused=!1,I.emit("resume",$),I._paused)return;if(I._currentEntry){if(I._currentEntry.resume)I._currentEntry.resume($)}else I._read()};n8.prototype.emitEntry=function($){this.emit("entry",$),this.emit("child",$)}});var Cy=F((dj1,vG0)=>{vG0.exports=e3;var AJ1=s6(),PJ1=c0(),TG0=s3(),EG0={EOF:!0},BG0={CLOSE:!0};PJ1(e3,TG0);function e3($){var I=this;if(!(I instanceof e3))throw Error("FileReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="File"&&$.File))throw Error("Non-file type "+$.type);I._buffer=[],I._bytesEmitted=0,TG0.call(I,$)}e3.prototype._getStream=function(){var $=this,I=$._stream=AJ1.createReadStream($._path,$.pro Line truncated
expect: `+$.props.size+`
actual: `+$._bytesEmitted)}),I.on("close",function(){if($._paused||$._buffer.length)$._buffer.push(LG0),$._read();else $.emit("close")}),I.on("error",function(q){$.emit("error",q)}),$._read()};t3.prototype._read=function(){var $=this;if($._paused)return;if(!$._stream)return $._getStream();if($._buffer.length){var I=$._buffer;for(var q=0,U=I.length;q<U;q++){var Y=I[q];if(Y===OG0)$.emit("end");else if(Y===LG0)$.emit("close");else $.emit("data",Y);if($._paused){$._buffer=I.slice(q);return}}$._buffer.length=0}};t3.prototype.pause=function($){var I=this;if(I._paused)return;if($=$||I,I._paused=!0,I._stream)I._stream.pause();I.emit("pause",$)};t3.prototype.resume=function($){var I=this;if(!I._paused)return;if($=$||I,I.emit("resume",$),I._paused=!1,I._stream)I._stream.resume();I._read()}});var AG0=L((DC1,MG0)=>{MG0.exports=CD;var TQ1=n0(),FG0=r3();TQ1(CD,FG0);function CD($){var I=this;if(!(I instanceof CD))throw Error("SocketReader must be called as constructor.");if(!($.type==="Socket"&&$.Socket))throw Error("Non-socket type "+$.type);FG0.call(I,$)}CD.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var Vy=L((OC1,gG0)=>{gG0.exports=a3;var Hy=r3(),EQ1=bK(),jQ1=n0(),BQ1=m6();jQ1(a3,Hy);function a3($){var I=this;if(!(I instanceof a3))throw Error("ProxyReader must be called as constructor.");I.props=$,I._buffer=[],I.ready=!1,Hy.call(I,$)}a3.prototype._stat=function(){var $=this,I=$.props,q=I.follow?"stat":"lstat";BQ1[q](I.path,function(U,Y){var J;if(U||!Y)J="File";else J=EQ1(Y);I[J]=!0,I.type=$.type=J,$._old=Y,$._addProxy(Hy(I,Y))})};a3.prototype._addProxy=function($){var I=this;if(I._proxyTarget)return I.error("proxy already set");I._proxyTarget=$,$._proxy=I,["error","data","end","close","linkpath","entry","entryEnd","child","childEnd","warn","stat"].forEach(function(U){$.on(U,I.emit.bind(I,U))}),I.emit("proxy",$),$.on("ready",function(){I.ready=!0,I.emit("ready")});var q=I._buffer;I._buffer.length=0,q.forEach(function(U){$[U[0]].apply($,U[1])})};a3.prototype.pause=function(){return this._proxyTarget?this._proxyTarget.pause():!1};a3.prototype.resume=function(){return this._proxyTarget?this._proxyTarget.resume():!1}});var r3=L((LC1,EG0)=>{EG0.exports=q8;var vQ1=m6(),RQ1=o("stream").Stream,CQ1=n0(),Wy=o("path"),Zy=bK(),_D=q8.hardLinks={},PG0=RD();CQ1(q8,PG0);var TG0=Ky();function q8($,I){var q=this;if(!(q instanceof q8))return new q8($,I);if(typeof $==="string")$={path:$};var U,Y;if($.type&&typeof $.type==="function")U=$.type,Y=U;else U=Zy($),Y=q8;if(I&&!U)U=Zy(I),$[U]=!0,$.type=U;switch(U){case"Directory":Y=zy();break;case"Link":case"File":Y=Gy();break;case"SymbolicLink":Y=TG0;break;case"Socket":Y=AG0();break;case null:Y=Vy();break}if(!(q instanceof Y))return new Y($);if(PG0.call(q),!$.path)q.error("Must provide a path",null,!0);if(q.readable=!0,q.writable=!1,q.type=U,q.props=$,q.depth=$.depth=$.depth||0,q.parent=$.parent||null,q.root=$.root||$.parent&&$.parent.root||q,q._path=q.path=Wy.resolve($.path),process.platform==="win32"){if(q.path=q._path=q.path.replace(/\?/g,"_"),q._path.length>=260)q._swallowErrors=!0,q._path="\\\\?\\"+q.path.replace(/\//g,"\\")}if(q.basename=$.basename=Wy.basename(q.path),q.dirname=$.dirname=Wy.dirname(q.path),$.parent=$.root=null,q.size=$.size,q.filter=typeof $.filter==="function"?$.filter:null,$.sort==="alpha")$.sort=_Q1;q._stat(I)}function _Q1($,I){return $===I?0:$.toLowerCase()>I.toLowerCase()?1:$.toLowerCase()<I.toLowerCase()?-1:$>I?1:-1}q8.prototype._stat=function($){var I=this,q=I.props,U=q.follow?"stat":"lstat";if($)process.nextTick(Y.bind(null,null,$));else vQ1[U](I._path,Y);function Y(J,Q){if(J)return I.error(J);if(Object.keys(Q).forEach(function(W){q[W]=Q[W]}),I.size!==void 0&&q.size!==I.size)return I.error("incorrect size");I.size=q.size;var K=Zy(q),w=q.hardlinks!==!1;if(w&&K!=="Directory"&&q.nlink&&q.nlink>1){var z=q.dev+":"+q.ino;if(_D[z]===I._path||!_D[z])_D[z]=I._path;else K=I.type=I.props.type="Link",I.Link=I.props.Link=!0,I.linkpath=I.props.linkpath=_D[z],I._stat=I._read=TG0.prototype._read}if(I.type&&I.type!==K)I.error("Unexpected type: "+K);if(I.filter){var G=I._proxy||I;if(!I.filter.call(G,G,q)){if(!I._disowned)I.abort(),I.emit("end"),I.emit("close");return}}var H=["_stat","stat","ready"],V=0;(function W(){if(I._aborted){I.emit("end"),I.emit("close");return}if(I._paused&&I.type!=="Directory"){I.once("resume",W);return}var X=H[V++];if(!X)return I._read();I.emit(X,q),W()})()}};q8.prototype.pipe=function($){var I=this;if(typeof $.add==="function")I.on("entry",function(q){var U=$.add(q);if(U===!1)I.pause()});return RQ1.prototype.pipe.apply(this,arguments)};q8.prototype.pause=function($){if(this._paused=!0,$=$||this,this.emit("pause",$),this._stream)this._stream.pause($)};q8.prototype.resume=function($){if(this._paused=!1,$=$||this,this.emit("resume",$),this._stream)this._stream.resume($);this._read()};q8.prototype._read=function(){this.error("Cannot read unknown type: "+this.type)}});var Ly=L((NC1,SG0)=>{S Line truncated
actual: `+$._bytesEmitted)}),I.on("close",function(){if($._paused||$._buffer.length)$._buffer.push(BG0),$._read();else $.emit("close")}),I.on("error",function(U){$.emit("error",U)}),$._read()};e3.prototype._read=function(){var $=this;if($._paused)return;if(!$._stream)return $._getStream();if($._buffer.length){var I=$._buffer;for(var U=0,Y=I.length;U<Y;U++){var J=I[U];if(J===EG0)$.emit("end");else if(J===BG0)$.emit("close");else $.emit("data",J);if($._paused){$._buffer=I.slice(U);return}}$._buffer.length=0}};e3.prototype.pause=function($){var I=this;if(I._paused)return;if($=$||I,I._paused=!0,I._stream)I._stream.pause();I.emit("pause",$)};e3.prototype.resume=function($){var I=this;if(!I._paused)return;if($=$||I,I.emit("resume",$),I._paused=!1,I._stream)I._stream.resume();I._read()}});var jG0=F((mj1,CG0)=>{CG0.exports=AL;var TJ1=c0(),RG0=s3();TJ1(AL,RG0);function AL($){var I=this;if(!(I instanceof AL))throw Error("SocketReader must be called as constructor.");if(!($.type==="Socket"&&$.Socket))throw Error("Non-socket type "+$.type);RG0.call(I,$)}AL.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var _y=F((lj1,_G0)=>{_G0.exports=$I;var jy=s3(),EJ1=lq(),BJ1=c0(),vJ1=s6();BJ1($I,jy);function $I($){var I=this;if(!(I instanceof $I))throw Error("ProxyReader must be called as constructor.");I.props=$,I._buffer=[],I.ready=!1,jy.call(I,$)}$I.prototype._stat=function(){var $=this,I=$.props,U=I.follow?"stat":"lstat";vJ1[U](I.path,function(Y,J){var Q;if(Y||!J)Q="File";else Q=EJ1(J);I[Q]=!0,I.type=$.type=Q,$._old=J,$._addProxy(jy(I,J))})};$I.prototype._addProxy=function($){var I=this;if(I._proxyTarget)return I.error("proxy already set");I._proxyTarget=$,$._proxy=I,["error","data","end","close","linkpath","entry","entryEnd","child","childEnd","warn","stat"].forEach(function(Y){$.on(Y,I.emit.bind(I,Y))}),I.emit("proxy",$),$.on("ready",function(){I.ready=!0,I.emit("ready")});var U=I._buffer;I._buffer.length=0,U.forEach(function(Y){$[Y[0]].apply($,Y[1])})};$I.prototype.pause=function(){return this._proxyTarget?this._proxyTarget.pause():!1};$I.prototype.resume=function(){return this._proxyTarget?this._proxyTarget.resume():!1}});var s3=F((oj1,yG0)=>{yG0.exports=G8;var RJ1=s6(),CJ1=a("stream").Stream,jJ1=c0(),Sy=a("path"),gy=lq(),PL=G8.hardLinks={},SG0=ML();jJ1(G8,SG0);var gG0=By();function G8($,I){var U=this;if(!(U instanceof G8))return new G8($,I);if(typeof $==="string")$={path:$};var Y,J;if($.type&&typeof $.type==="function")Y=$.type,J=Y;else Y=gy($),J=G8;if(I&&!Y)Y=gy(I),$[Y]=!0,$.type=Y;switch(Y){case"Directory":J=Ry();break;case"Link":case"File":J=Cy();break;case"SymbolicLink":J=gG0;break;case"Socket":J=jG0();break;case null:J=_y();break}if(!(U instanceof J))return new J($);if(SG0.call(U),!$.path)U.error("Must provide a path",null,!0);if(U.readable=!0,U.writable=!1,U.type=Y,U.props=$,U.depth=$.depth=$.depth||0,U.parent=$.parent||null,U.root=$.root||$.parent&&$.parent.root||U,U._path=U.path=Sy.resolve($.path),process.platform==="win32"){if(U.path=U._path=U.path.replace(/\?/g,"_"),U._path.length>=260)U._swallowErrors=!0,U._path="\\\\?\\"+U.path.replace(/\//g,"\\")}if(U.basename=$.basename=Sy.basename(U.path),U.dirname=$.dirname=Sy.dirname(U.path),$.parent=$.root=null,U.size=$.size,U.filter=typeof $.filter==="function"?$.filter:null,$.sort==="alpha")$.sort=_J1;U._stat(I)}function _J1($,I){return $===I?0:$.toLowerCase()>I.toLowerCase()?1:$.toLowerCase()<I.toLowerCase()?-1:$>I?1:-1}G8.prototype._stat=function($){var I=this,U=I.props,Y=U.follow?"stat":"lstat";if($)process.nextTick(J.bind(null,null,$));else RJ1[Y](I._path,J);function J(Q,K){if(Q)return I.error(Q);if(Object.keys(K).forEach(function(Z){U[Z]=K[Z]}),I.size!==void 0&&U.size!==I.size)return I.error("incorrect size");I.size=U.size;var q=gy(U),H=U.hardlinks!==!1;if(H&&q!=="Directory"&&U.nlink&&U.nlink>1){var G=U.dev+":"+U.ino;if(PL[G]===I._path||!PL[G])PL[G]=I._path;else q=I.type=I.props.type="Link",I.Link=I.props.Link=!0,I.linkpath=I.props.linkpath=PL[G],I._stat=I._read=gG0.prototype._read}if(I.type&&I.type!==q)I.error("Unexpected type: "+q);if(I.filter){var W=I._proxy||I;if(!I.filter.call(W,W,U)){if(!I._disowned)I.abort(),I.emit("end"),I.emit("close");return}}var w=["_stat","stat","ready"],V=0;(function Z(){if(I._aborted){I.emit("end"),I.emit("close");return}if(I._paused&&I.type!=="Directory"){I.once("resume",Z);return}var X=w[V++];if(!X)return I._read();I.emit(X,U),Z()})()}};G8.prototype.pipe=function($){var I=this;if(typeof $.add==="function")I.on("entry",function(U){var Y=$.add(U);if(Y===!1)I.pause()});return CJ1.prototype.pipe.apply(this,arguments)};G8.prototype.pause=function($){if(this._paused=!0,$=$||this,this.emit("pause",$),this._stream)this._stream.pause($)};G8.prototype.resume=function($){if(this._paused=!1,$=$||this,this.emit("resume",$),this._stream)this._stream.resume($);this._read()};G8.prototype._read=function(){this.error("Cannot read unknown type: "+this.type)}});var xy=F((rj1,nG0)=>{n Line truncated
expect: `+$.size+`
actual: `+$._bytesWritten);pD.prototype._finish.call($)}});var vy=L((xC1,gH0)=>{gH0.exports=V7;var By=VY(),J21=bK(),Q21=n0(),K21=iD(),w21=o("fs");Q21(V7,By);function V7($){var I=this;if(!(I instanceof V7))throw Error("ProxyWriter must be called as constructor.");I.props=$,I._needDrain=!1,By.call(I,$)}V7.prototype._stat=function(){var $=this,I=$.props,q=I.follow?"stat":"lstat";w21[q](I.path,function(U,Y){var J;if(U||!Y)J="File";else J=J21(Y);I[J]=!0,I.type=$.type=J,$._old=Y,$._addProxy(By(I,Y))})};V7.prototype._addProxy=function($){var I=this;if(I._proxy)return I.error("proxy already set");I._proxy=$,["ready","error","close","pipe","drain","warn"].forEach(function(U){$.on(U,I.emit.bind(I,U))}),I.emit("proxy",$);var q=I._buffer;if(q.forEach(function(U){$[U[0]].apply($,U[1])}),I._buffer.length=0,I._needsDrain)I.emit("drain")};V7.prototype.add=function($){if(K21($),!this._proxy)return this._buffer.push(["add",[$]]),this._needDrain=!0,!1;return this._proxy.add($)};V7.prototype.write=function($){if(!this._proxy)return this._buffer.push(["write",[$]]),this._needDrain=!0,!1;return this._proxy.write($)};V7.prototype.end=function($){if(!this._proxy)return this._buffer.push(["end",[$]]),!1;return this._proxy.end($)}});var VY=L((kC1,_H0)=>{_H0.exports=h$;var _$=m6(),z21=n0(),G21=Ly(),H21=gy(),oK=o("path"),TH0=process.platform==="win32"?0:process.umask(),EH0=bK(),jH0=RD();z21(h$,jH0);h$.dirmode=parseInt("0777",8)&~TH0;h$.filemode=parseInt("0666",8)&~TH0;var V21=Ty(),W21=Ey(),Z21=jy(),X21=vy();function h$($,I){var q=this;if(typeof $==="string")$={path:$};var U=EH0($),Y=h$;switch(U){case"Directory":Y=V21;break;case"File":Y=Z21;break;case"Link":case"SymbolicLink":Y=W21;break;case null:default:Y=X21;break}if(!(q instanceof Y))return new Y($);if(jH0.call(q),!$.path)q.error("Must provide a path",null,!0);if(q.type=$.type,q.props=$,q.depth=$.depth||0,q.clobber=$.clobber===!1?$.clobber:!0,q.parent=$.parent||null,q.root=$.root||$.parent&&$.parent.root||q,q._path=q.path=oK.resolve($.path),process.platform==="win32"){if(q.path=q._path=q.path.replace(/\?/g,"_"),q._path.length>=260)q._swallowErrors=!0,q._path="\\\\?\\"+q.path.replace(/\//g,"\\")}if(q.basename=oK.basename($.path),q.dirname=oK.dirname($.path),q.linkpath=$.linkpath||null,$.parent=$.root=null,q.size=$.size,typeof $.mode==="string")$.mode=parseInt($.mode,8);q.readable=!1,q.writable=!0,q._buffer=[],q.ready=!1,q.filter=typeof $.filter==="function"?$.filter:null,q._stat(I)}h$.prototype._create=function(){var $=this;_$[$.props.follow?"stat":"lstat"]($._path,function(I){if(I)return $.warn("Cannot create "+$._path+`
Unsupported type: `+$.type,"ENOTSUP");$._finish()})};h$.prototype._stat=function($){var I=this,q=I.props,U=q.follow?"stat":"lstat",Y=I._proxy||I;if($)J(null,$);else _$[U](I._path,J);function J(Q,K){if(I.filter&&!I.filter.call(Y,Y,K)){I._aborted=!0,I.emit("end"),I.emit("close");return}if(Q||!K)return Ry(I);I._old=K;var w=EH0(K);if(w!==I.type||I.type==="File"&&K.nlink>1)return G21(I._path,function(z){if(z)return I.error(z);I._old=null,Ry(I)});Ry(I)}};function Ry($){H21(oK.dirname($._path),h$.dirmode,function(I,q){if(I)return $.error(I);return $._madeDir=q,$._create()})}function BH0($,I,q,U,Y){var J=I.mode,Q=I.follow||$.type!=="SymbolicLink"?"chmod":"lchmod";if(!_$[Q])return Y();if(typeof J!=="number")return Y();var K=q.mode&parseInt("0777",8);if(J=J&parseInt("0777",8),J===K)return Y();_$[Q](U,J,Y)}function vH0($,I,q,U,Y){if(process.platform==="win32")return Y();if(!process.getuid||process.getuid()!==0)return Y();if(typeof I.uid!=="number"&&typeof I.gid!=="number")return Y();if(q.uid===I.uid&&q.gid===I.gid)return Y();var J=$.props.follow||$.type!=="SymbolicLink"?"chown":"lchown";if(!_$[J])return Y();if(typeof I.uid!=="number")I.uid=q.uid;if(typeof I.gid!=="number")I.gid=q.gid;_$[J](U,I.uid,I.gid,Y)}function RH0($,I,q,U,Y){if(!_$.utimes||process.platform==="win32")return Y();var J=I.follow||$.type!=="SymbolicLink"?"utimes":"lutimes";if(J==="lutimes"&&!_$[J])J="utimes";if(!_$[J])return Y();var{atime:Q,mtime:K}=q,w=I.atime,z=I.mtime;if(w===void 0)w=Q;if(z===void 0)z=K;if(!PH0(w))w=new Date(w);if(!PH0(z))w=new Date(z);if(w.getTime()===Q.getTime()&&z.getTime()===K.getTime())return Y();_$[J](U,w,z,Y)}h$.prototype._finish=function(){var $=this;if($._finishing)return;$._finishing=!0;var I=0,q=null,U=!1;if($._old)$._old.atime=new Date(0),$._old.mtime=new Date(0),J($._old);else{var Y=$.props.follow?"stat":"lstat";_$[Y]($._path,function(K,w){if(K)if(K.code==="ENOENT"&&($.type==="Link"||$.type==="SymbolicLink")&&process.platform==="win32"){$.ready=!0,$.emit("ready"),$.emit("end"),$.emit("close"),$.end=$._finish=function(){};return}else return $.error(K);J($._old=w)})}return;function J(K){I+=3,BH0($,$.props,K,$._path,Q("chmod")),vH0($,$.props,K,$._path,Q("chown")),RH0($,$.props,K,$._path,Q("utimes"))}function Q(K){return function(w){if(q)return;if(w)return w.fstream_finish_call=K,$.error(q=w);if(--I>0)return;if(U)return;if(U=!0,!$._madeDir)return z();else CH0($,$._path,z);function z(G){if(G)return G.fstream_finish_call="setupMadeDir",$.error(G);$.emit("end"),$.emit("close")}}}};function CH0($,I,q){var U=$._madeDir,Y=oK.dirname(I);D21($,Y,function(J){if(J)return q(J);if(Y===U)return q();CH0($,Y,q)})}function D21($,I,q){var U={};Object.keys($.props).forEach(function(K){if(U[K]=$.props[K],K==="mode"&&$.type!=="Directory")U[K]=U[K]|parseInt("0111",8)});var Y=3,J=null;_$.stat(I,function(K,w){if(K)return q(J=K);BH0($,U,w,I,Q),vH0($,U,w,I,Q),RH0($,U,w,I,Q)});function Q(K){if(J)return;if(K)return q(J=K);if(--Y===0)return q()}}h$.prototype.pipe=function(){this.error("Can't pipe from writable stream")};h$.prototype.add=function(){this.error("Can't add to non-Directory type")};h$.prototype.write=function(){return!0};function O21($){return Object.prototype.toString.call($)}function PH0($){return typeof $==="object"&&O21($)==="[object Date]"}});var yy=L((L21)=>{L21.Abstract=RD();L21.Reader=r3();L21.Writer=VY();L21.File={Reader:Gy(),Writer:jy()};L21.Dir={Reader:zy(),Writer:Ty()};L21.Link={Reader:Ky(),Writer:Ey()};L21.Proxy={Reader:Vy(),Writer:vy()};L21.Reader.Dir=L21.DirReader=L21.Dir.Reader;L21.Reader.File=L21.FileReader=L21.File.Reader;L21.Reader.Link=L21.LinkReader=L21.Link.Reader;L21.Reader.Proxy=L21.ProxyReader=L21.Proxy.Reader;L21.Writer.Dir=L21.DirWriter=L21.Dir.Writer;L21.Writer.File=L21.FileWriter=L21.File.Writer;L21.Writer.Link=L21.LinkWriter=L21.Link.Writer;L21.Writer.Proxy=L21.ProxyWriter=L21.Proxy.Writer;L21.collect=iD()});var SH0=L((oC1,hH0)=>{hH0.exports=E21;var M21=MD(),A21=yy().Writer,uy=o("path"),g21=o("stream"),P21=Yy(),T21=J7();function E21($){$.path=uy.resolve(uy.normalize($.path));var I=new M21($),q=new g21.Writable({objectMode:!0});q._write=function(Y,J,Q){if(Y.type=="Directory")return Q();var K=uy.join($.path,Y.path);if(K.indexOf($.path)!=0)return Q();let w=$.getWriter?$.getWriter({path:K}):A21({path:K});Y.pipe(w).on("error",Q).on("close",Q)};var U=P21(I,q);return I.once("crx-header",function(Y){U.crxHeader=Y}),I.pipe(q).on("finish",function(){U.emit("close")}),U.promise=function(){return new T21(function(Y,J){U.on("close",Y),U.on("error",J)})},U}});var yH0=L((rC1,cD)=>{var y4=function($){var I=1e7,q=7,U=9007199254740992,Y=V(U),J="0123456789abcdefghijklmnopqrstuvwxyz",Q=typeof BigInt==="function";function K(F,M,v,y){if(typeof F>"u")return K[0];if(typeof M<"u")return+M===10&&!v?g0(F):y$(F,M,v,y);return g0(F)}function w(F,M){this.value=F,this.sign=M,this.isSmall=!1}w.prototype=Object.create(K.prototype);function z(F){this.value=F,this.sign=F<0,this.isSmall=!0}z.prototype=Object.create(K.prototype);function G(F){th Line truncated
actual: `+$._bytesWritten);yL.prototype._finish.call($)}});var oy=F((Z_1,_W0)=>{_W0.exports=D7;var ly=zJ(),JQ1=lq(),QQ1=c0(),KQ1=SL(),qQ1=a("fs");QQ1(D7,ly);function D7($){var I=this;if(!(I instanceof D7))throw Error("ProxyWriter must be called as constructor.");I.props=$,I._needDrain=!1,ly.call(I,$)}D7.prototype._stat=function(){var $=this,I=$.props,U=I.follow?"stat":"lstat";qQ1[U](I.path,function(Y,J){var Q;if(Y||!J)Q="File";else Q=JQ1(J);I[Q]=!0,I.type=$.type=Q,$._old=J,$._addProxy(ly(I,J))})};D7.prototype._addProxy=function($){var I=this;if(I._proxy)return I.error("proxy already set");I._proxy=$,["ready","error","close","pipe","drain","warn"].forEach(function(Y){$.on(Y,I.emit.bind(I,Y))}),I.emit("proxy",$);var U=I._buffer;if(U.forEach(function(Y){$[Y[0]].apply($,Y[1])}),I._buffer.length=0,I._needsDrain)I.emit("drain")};D7.prototype.add=function($){if(KQ1($),!this._proxy)return this._buffer.push(["add",[$]]),this._needDrain=!0,!1;return this._proxy.add($)};D7.prototype.write=function($){if(!this._proxy)return this._buffer.push(["write",[$]]),this._needDrain=!0,!1;return this._proxy.write($)};D7.prototype.end=function($){if(!this._proxy)return this._buffer.push(["end",[$]]),!1;return this._proxy.end($)}});var zJ=F((z_1,iW0)=>{iW0.exports=k$;var x$=s6(),HQ1=c0(),GQ1=xy(),WQ1=ny(),eq=a("path"),gW0=process.platform==="win32"?0:process.umask(),yW0=lq(),hW0=ML();HQ1(k$,hW0);k$.dirmode=parseInt("0777",8)&~gW0;k$.filemode=parseInt("0666",8)&~gW0;var wQ1=cy(),VQ1=dy(),ZQ1=my(),zQ1=oy();function k$($,I){var U=this;if(typeof $==="string")$={path:$};var Y=yW0($),J=k$;switch(Y){case"Directory":J=wQ1;break;case"File":J=ZQ1;break;case"Link":case"SymbolicLink":J=VQ1;break;case null:default:J=zQ1;break}if(!(U instanceof J))return new J($);if(hW0.call(U),!$.path)U.error("Must provide a path",null,!0);if(U.type=$.type,U.props=$,U.depth=$.depth||0,U.clobber=$.clobber===!1?$.clobber:!0,U.parent=$.parent||null,U.root=$.root||$.parent&&$.parent.root||U,U._path=U.path=eq.resolve($.path),process.platform==="win32"){if(U.path=U._path=U.path.replace(/\?/g,"_"),U._path.length>=260)U._swallowErrors=!0,U._path="\\\\?\\"+U.path.replace(/\//g,"\\")}if(U.basename=eq.basename($.path),U.dirname=eq.dirname($.path),U.linkpath=$.linkpath||null,$.parent=$.root=null,U.size=$.size,typeof $.mode==="string")$.mode=parseInt($.mode,8);U.readable=!1,U.writable=!0,U._buffer=[],U.ready=!1,U.filter=typeof $.filter==="function"?$.filter:null,U._stat(I)}k$.prototype._create=function(){var $=this;x$[$.props.follow?"stat":"lstat"]($._path,function(I){if(I)return $.warn("Cannot create "+$._path+`
Unsupported type: `+$.type,"ENOTSUP");$._finish()})};k$.prototype._stat=function($){var I=this,U=I.props,Y=U.follow?"stat":"lstat",J=I._proxy||I;if($)Q(null,$);else x$[Y](I._path,Q);function Q(K,q){if(I.filter&&!I.filter.call(J,J,q)){I._aborted=!0,I.emit("end"),I.emit("close");return}if(K||!q)return ry(I);I._old=q;var H=yW0(q);if(H!==I.type||I.type==="File"&&q.nlink>1)return GQ1(I._path,function(G){if(G)return I.error(G);I._old=null,ry(I)});ry(I)}};function ry($){WQ1(eq.dirname($._path),k$.dirmode,function(I,U){if(I)return $.error(I);return $._madeDir=U,$._create()})}function uW0($,I,U,Y,J){var Q=I.mode,K=I.follow||$.type!=="SymbolicLink"?"chmod":"lchmod";if(!x$[K])return J();if(typeof Q!=="number")return J();var q=U.mode&parseInt("0777",8);if(Q=Q&parseInt("0777",8),Q===q)return J();x$[K](Y,Q,J)}function xW0($,I,U,Y,J){if(process.platform==="win32")return J();if(!process.getuid||process.getuid()!==0)return J();if(typeof I.uid!=="number"&&typeof I.gid!=="number")return J();if(U.uid===I.uid&&U.gid===I.gid)return J();var Q=$.props.follow||$.type!=="SymbolicLink"?"chown":"lchown";if(!x$[Q])return J();if(typeof I.uid!=="number")I.uid=U.uid;if(typeof I.gid!=="number")I.gid=U.gid;x$[Q](Y,I.uid,I.gid,J)}function kW0($,I,U,Y,J){if(!x$.utimes||process.platform==="win32")return J();var Q=I.follow||$.type!=="SymbolicLink"?"utimes":"lutimes";if(Q==="lutimes"&&!x$[Q])Q="utimes";if(!x$[Q])return J();var{atime:K,mtime:q}=U,H=I.atime,G=I.mtime;if(H===void 0)H=K;if(G===void 0)G=q;if(!SW0(H))H=new Date(H);if(!SW0(G))H=new Date(G);if(H.getTime()===K.getTime()&&G.getTime()===q.getTime())return J();x$[Q](Y,H,G,J)}k$.prototype._finish=function(){var $=this;if($._finishing)return;$._finishing=!0;var I=0,U=null,Y=!1;if($._old)$._old.atime=new Date(0),$._old.mtime=new Date(0),Q($._old);else{var J=$.props.follow?"stat":"lstat";x$[J]($._path,function(q,H){if(q)if(q.code==="ENOENT"&&($.type==="Link"||$.type==="SymbolicLink")&&process.platform==="win32"){$.ready=!0,$.emit("ready"),$.emit("end"),$.emit("close"),$.end=$._finish=function(){};return}else return $.error(q);Q($._old=H)})}return;function Q(q){I+=3,uW0($,$.props,q,$._path,K("chmod")),xW0($,$.props,q,$._path,K("chown")),kW0($,$.props,q,$._path,K("utimes"))}function K(q){return function(H){if(U)return;if(H)return H.fstream_finish_call=q,$.error(U=H);if(--I>0)return;if(Y)return;if(Y=!0,!$._madeDir)return G();else fW0($,$._path,G);function G(W){if(W)return W.fstream_finish_call="setupMadeDir",$.error(W);$.emit("end"),$.emit("close")}}}};function fW0($,I,U){var Y=$._madeDir,J=eq.dirname(I);XQ1($,J,function(Q){if(Q)return U(Q);if(J===Y)return U();fW0($,J,U)})}function XQ1($,I,U){var Y={};Object.keys($.props).forEach(function(q){if(Y[q]=$.props[q],q==="mode"&&$.type!=="Directory")Y[q]=Y[q]|parseInt("0111",8)});var J=3,Q=null;x$.stat(I,function(q,H){if(q)return U(Q=q);uW0($,Y,H,I,K),xW0($,Y,H,I,K),kW0($,Y,H,I,K)});function K(q){if(Q)return;if(q)return U(Q=q);if(--J===0)return U()}}k$.prototype.pipe=function(){this.error("Can't pipe from writable stream")};k$.prototype.add=function(){this.error("Can't add to non-Directory type")};k$.prototype.write=function(){return!0};function LQ1($){return Object.prototype.toString.call($)}function SW0($){return typeof $==="object"&&LQ1($)==="[object Date]"}});var $h=F((DQ1)=>{DQ1.Abstract=ML();DQ1.Reader=s3();DQ1.Writer=zJ();DQ1.File={Reader:Cy(),Writer:my()};DQ1.Dir={Reader:Ry(),Writer:cy()};DQ1.Link={Reader:By(),Writer:dy()};DQ1.Proxy={Reader:_y(),Writer:oy()};DQ1.Reader.Dir=DQ1.DirReader=DQ1.Dir.Reader;DQ1.Reader.File=DQ1.FileReader=DQ1.File.Reader;DQ1.Reader.Link=DQ1.LinkReader=DQ1.Link.Reader;DQ1.Reader.Proxy=DQ1.ProxyReader=DQ1.Proxy.Reader;DQ1.Writer.Dir=DQ1.DirWriter=DQ1.Dir.Writer;DQ1.Writer.File=DQ1.FileWriter=DQ1.File.Writer;DQ1.Writer.Link=DQ1.LinkWriter=DQ1.Link.Writer;DQ1.Writer.Proxy=DQ1.ProxyWriter=DQ1.Proxy.Writer;DQ1.collect=SL()});var nW0=F((T_1,bW0)=>{bW0.exports=EQ1;var NQ1=VL(),MQ1=$h().Writer,Ih=a("path"),AQ1=a("stream"),PQ1=Py(),TQ1=W7();function EQ1($){$.path=Ih.resolve(Ih.normalize($.path));var I=new NQ1($),U=new AQ1.Writable({objectMode:!0});U._write=function(J,Q,K){if(J.type=="Directory")return K();var q=Ih.join($.path,J.path);if(q.indexOf($.path)!=0)return K();let H=$.getWriter?$.getWriter({path:q}):MQ1({path:q});J.pipe(H).on("error",K).on("close",K)};var Y=PQ1(I,U);return I.once("crx-header",function(J){Y.crxHeader=J}),I.pipe(U).on("finish",function(){Y.emit("close")}),Y.promise=function(){return new TQ1(function(J,Q){Y.on("close",J),Y.on("error",Q)})},Y}});var pW0=F((E_1,hL)=>{var u4=function($){var I=1e7,U=7,Y=9007199254740992,J=V(Y),Q="0123456789abcdefghijklmnopqrstuvwxyz",K=typeof BigInt==="function";function q(N,M,j,u){if(typeof N>"u")return q[0];if(typeof M<"u")return+M===10&&!j?v0(N):i6(N,M,j,u);return v0(N)}function H(N,M){this.value=N,this.sign=M,this.isSmall=!1}H.prototype=Object.create(q.prototype);function G(N){this.value=N,this.sign=N<0,this.isSmall=!0}G.prototype=Object.create(q.prototype);function W(N){th Line truncated
* Tmp
*
* Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>
*
* MIT Licensed
*/var u1=o("fs"),tD=o("os"),u4=o("path"),oH0=o("crypto"),b8={fs:u1.constants,os:tD.constants},sH0=/XXXXXX/,eH0=(b8.O_CREAT||b8.fs.O_CREAT)|(b8.O_EXCL||b8.fs.O_EXCL)|(b8.O_RDWR||b8.fs.O_RDWR),t21=tD.platform()==="win32",a21=b8.EBADF||b8.os.errno.EBADF,s21=b8.ENOENT||b8.os.errno.ENOENT,ZY=[],$V0=u1.rmdirSync.bind(u1),IV0=!1;function e21($,I){return u1.rm($,{recursive:!0},I)}function qV0($){return u1.rmSync($,{recursive:!0})}function iy($,I){let q=XY($,I),U=q[0],Y=q[1];zK1(U,function(J,Q){if(J)return Y(J);let K=Q.tries;(function w(){try{let z=YV0(Q);u1.stat(z,function(G){if(!G){if(K-- >0)return w();return Y(Error("Could not get a unique tmp filename, max tries reached "+z))}Y(null,z)})}catch(z){Y(z)}})()})}function by($){let I=XY($),q=I[0],U=GK1(q),Y=U.tries;do{let J=YV0(U);try{u1.statSync(J)}catch(Q){return J}}while(Y-- >0);throw Error("Could not get a unique tmp filename, max tries reached")}function $K1($,I){let q=XY($,I),U=q[0],Y=q[1];iy(U,function(Q,K){if(Q)return Y(Q);u1.open(K,eH0,U.mode||384,function(z,G){if(z)return Y(z);if(U.discardDescriptor)return u1.close(G,function(V){return Y(V,K,void 0,fy(K,-1,U,!1))});else{let H=U.discardDescriptor||U.detachDescriptor;Y(null,K,G,fy(K,H?-1:G,U,!1))}})})}function IK1($){let I=XY($),q=I[0],U=q.discardDescriptor||q.detachDescriptor,Y=by(q),J=u1.openSync(Y,eH0,q.mode||384);if(q.discardDescriptor)u1.closeSync(J),J=void 0;return{name:Y,fd:J,removeCallback:fy(Y,U?-1:J,q,!0)}}function qK1($,I){let q=XY($,I),U=q[0],Y=q[1];iy(U,function(Q,K){if(Q)return Y(Q);u1.mkdir(K,U.mode||448,function(z){if(z)return Y(z);Y(null,K,UV0(K,U,!1))})})}function UK1($){let I=XY($),q=I[0],U=by(q);return u1.mkdirSync(U,q.mode||448),{name:U,removeCallback:UV0(U,q,!0)}}function YK1($,I){let q=function(U){if(U&&!ny(U))return I(U);I()};if(0<=$[0])u1.close($[0],function(){u1.unlink($[1],q)});else u1.unlink($[1],q)}function JK1($){let I=null;try{if(0<=$[0])u1.closeSync($[0])}catch(q){if(!HK1(q)&&!ny(q))throw q}finally{try{u1.unlinkSync($[1])}catch(q){if(!ny(q))I=q}}if(I!==null)throw I}function fy($,I,q,U){let Y=rD(JK1,[I,$],U),J=rD(YK1,[I,$],U,Y);if(!q.keep)ZY.unshift(Y);return U?Y:J}function UV0($,I,q){let U=I.unsafeCleanup?e21:u1.rmdir.bind(u1),Y=I.unsafeCleanup?qV0:$V0,J=rD(Y,$,q),Q=rD(U,$,q,J);if(!I.keep)ZY.unshift(J);return q?J:Q}function rD($,I,q,U){let Y=!1;return function J(Q){if(!Y){let K=U||J,w=ZY.indexOf(K);if(w>=0)ZY.splice(w,1);if(Y=!0,q||$===$V0||$===qV0)return $(I);else return $(I,Q||function(){})}}}function QK1(){if(!IV0)return;while(ZY.length)try{ZY[0]()}catch($){}}function rH0($){let I=[],q=null;try{q=oH0.randomBytes($)}catch(U){q=oH0.pseudoRandomBytes($)}for(let U=0;U<$;U++)I.push("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[q[U]%62]);return I.join("")}function r6($){return typeof $>"u"}function XY($,I){if(typeof $==="function")return[{},$];if(r6($))return[{},I];let q={};for(let U of Object.getOwnPropertyNames($))q[U]=$[U];return[q,I]}function KK1($,I,q){let U=u4.isAbsolute($)?$:u4.join(I,$);u1.stat(U,function(Y){if(Y)u1.realpath(u4.dirname(U),function(J,Q){if(J)return q(J);q(null,u4.join(Q,u4.basename(U)))});else u1.realpath(U,q)})}function wK1($,I){let q=u4.isAbsolute($)?$:u4.join(I,$);try{return u1.statSync(q),u1.realpathSync(q)}catch(U){let Y=u1.realpathSync(u4.dirname(q));return u4.join(Y,u4.basename(q))}}function YV0($){let I=$.tmpdir;if(!r6($.name))return u4.join(I,$.dir,$.name);if(!r6($.template))return u4.join(I,$.dir,$.template).replace(sH0,rH0(6));let q=[$.prefix?$.prefix:"tmp","-",process.pid,"-",rH0(12),$.postfix?"-"+$.postfix:""].join("");return u4.join(I,$.dir,q)}function ky($,I){if(typeof I!=="string")throw Error(`${$} option must be a string, got "${typeof I}".`);if(I.includes(".."))throw Error("Relative value not allowed");return I}function JV0($){if(!r6($.name)){let I=$.name;if(u4.isAbsolute(I))throw Error(`name option must not contain an absolute path, found "${I}".`);let q=u4.basename(I);if(q===".."||q==="."||q!==I)throw Error(`name option must not contain a path, found "${I}".`)}if(!r6($.template)){if(typeof $.template!=="string")throw Error(`template option must be a string, got "${typeof $.template}".`);if(!$.template.match(sH0))throw Error(`Invalid template, found "${$.template}".`)}if(!r6($.tries)&&isNaN($.tries)||$.tries<0)throw Error(`Invalid tries, found "${$.tries}".`);$.tries=r6($.name)?$.tries||3:1,$.keep=!!$.keep,$.detachDescriptor=!!$.detachDescriptor,$.discardDescriptor=!!$.discardDescriptor,$.unsafeCleanup=!!$.unsafeCleanup,$.prefix=r6($.prefix)?"":ky("prefix",$.prefix),$.postfix=r6($.postfix)?"":ky("postfix",$.postfix),$.template=r6($.template)?void 0:ky("template",$.template)}function tH0($,I,q,U){if(r6(I))return U(null);KK1(I,q,function(Y,J){if(Y)return U(Y);let Q=u4.relative(q,J);if(Q.startsWith("..")||u4.isAbsolute(Q))return U(Error(`${$} option must be relative to "${q}", found "${Q}".`));U(null,Q)})}function aH0($,I,q){if(r6(I))return;let U=wK1(I,q),Y=u4.relative(q,U);if(Y.startsWith("..")||u4.isAbsolute(Y))throw ELine truncated
`)}var zI=($)=>(I,q,U,Y)=>{let J=U?{...U,async:!1}:{async:!1},Q=I._zod.run({value:q,issues:[]},J);if(Q instanceof Promise)throw new Y8;if(Q.issues.length){let K=new(Y?.Err??$)(Q.issues.map((w)=>A6(w,J,W4())));throw cw(K,Y?.callee),K}return Q.value},nY=zI(y6),GI=($)=>async(I,q,U,Y)=>{let J=U?{...U,async:!0}:{async:!0},Q=I._zod.run({value:q,issues:[]},J);if(Q instanceof Promise)Q=await Q;if(Q.issues.length){let K=new(Y?.Err??$)(Q.issues.map((w)=>A6(w,J,W4())));throw cw(K,Y?.callee),K}return Q.value},iY=GI(y6),HI=($)=>(I,q,U)=>{let Y=U?{...U,async:!1}:{async:!1},J=I._zod.run({value:q,issues:[]},Y);if(J instanceof Promise)throw new Y8;return J.issues.length?{success:!1,error:new($??xY)(J.issues.map((Q)=>A6(Q,Y,W4())))}:{success:!0,data:J.value}},VI=HI(y6),WI=($)=>async(I,q,U)=>{let Y=U?{...U,async:!0}:{async:!0},J=I._zod.run({value:q,issues:[]},Y);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((Q)=>A6(Q,Y,W4())))}:{success:!0,data:J.value}},bY=WI(y6),dw=($)=>(I,q,U)=>{let Y=U?{...U,direction:"backward"}:{direction:"backward"};return zI($)(I,q,Y)},Ax=dw(y6),lw=($)=>(I,q,U)=>{return zI($)(I,q,U)},gx=lw(y6),mw=($)=>async(I,q,U)=>{let Y=U?{...U,direction:"backward"}:{direction:"backward"};return GI($)(I,q,Y)},Px=mw(y6),ow=($)=>async(I,q,U)=>{return GI($)(I,q,U)},Tx=ow(y6),rw=($)=>(I,q,U)=>{let Y=U?{...U,direction:"backward"}:{direction:"backward"};return HI($)(I,q,Y)},Ex=rw(y6),tw=($)=>(I,q,U)=>{return HI($)(I,q,U)},jx=tw(y6),aw=($)=>async(I,q,U)=>{let Y=U?{...U,direction:"backward"}:{direction:"backward"};return WI($)(I,q,Y)},Bx=aw(y6),sw=($)=>async(I,q,U)=>{return WI($)(I,q,U)},vx=sw(y6);var e6={};m8(e6,{xid:()=>aO,uuid7:()=>mD0,uuid6:()=>lD0,uuid4:()=>dD0,uuid:()=>g7,uppercase:()=>AL,unicodeEmail:()=>Rx,undefined:()=>FL,ulid:()=>tO,time:()=>WL,string:()=>XL,sha512_hex:()=>ZO0,sha512_base64url:()=>DO0,sha512_base64:()=>XO0,sha384_hex:()=>HO0,sha384_base64url:()=>WO0,sha384_base64:()=>VO0,sha256_hex:()=>wO0,sha256_base64url:()=>GO0,sha256_base64:()=>zO0,sha1_hex:()=>JO0,sha1_base64url:()=>KO0,sha1_base64:()=>QO0,rfc5322Email:()=>rD0,number:()=>pY,null:()=>NL,nanoid:()=>eO,md5_hex:()=>qO0,md5_base64url:()=>YO0,md5_base64:()=>UO0,mac:()=>QL,lowercase:()=>ML,ksuid:()=>sO,ipv6:()=>JL,ipv4:()=>YL,integer:()=>OL,idnEmail:()=>tD0,httpProtocol:()=>GL,html5Email:()=>oD0,hostname:()=>eD0,hex:()=>IO0,guid:()=>IL,extendedDuration:()=>cD0,emoji:()=>UL,email:()=>qL,e164:()=>HL,duration:()=>$L,domain:()=>$O0,datetime:()=>ZL,date:()=>VL,cuid2:()=>rO,cuid:()=>oO,cidrv6:()=>wL,cidrv4:()=>KL,browserEmail:()=>aD0,boolean:()=>LL,bigint:()=>DL,base64url:()=>ew,base64:()=>zL});var oO=/^[cC][0-9a-z]{6,}$/,rO=/^[0-9a-z]+$/,tO=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,aO=/^[0-9a-vA-V]{20}$/,sO=/^[A-Za-z0-9]{27}$/,eO=/^[a-zA-Z0-9_-]{21}$/,$L=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,cD0=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,IL=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,g7=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},dD0=g7(4),lD0=g7(6),mD0=g7(7),qL=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,oD0=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,rD0=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Rx=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,tD0=Rx,aD0=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,sD0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function UL(){return new RegExp(sD0,"u")}var YL=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,JL=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,QL=($)=>{let I=Z$($??":");return new RegExp(`^(?:[0-9A-F]{2}${I}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${I}){5}[0-9a-f]{2}$`)},KL=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0Line truncated
`).filter((J)=>J),U=Math.min(...q.map((J)=>J.length-J.trimStart().length)),Y=q.map((J)=>J.slice(U)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of Y)this.content.push(J)}compile(){let $=Function,I=this?.args,U=[...(this?.content??[""]).map((Y)=>` ${Y}`)];return new $(...I,U.join(`
`))}}var iL={major:4,minor:4,patch:3};var k0=m("$ZodType",($,I)=>{var q;$??($={}),$._zod.def=I,$._zod.bag=$._zod.bag||{},$._zod.version=iL;let U=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))U.unshift($);for(let Y of U)for(let J of Y._zod.onattach)J($);if(U.length===0)(q=$._zod).deferred??(q.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let Y=(Q,K,w)=>{let z=t5(Q),G;for(let H of K){if(H._zod.def.when){if(dO(Q))continue;if(!H._zod.def.when(Q))continue}else if(z)continue;let V=Q.issues.length,W=H._zod.check(Q);if(W instanceof Promise&&w?.async===!1)throw new Y8;if(G||W instanceof Promise)G=(G??Promise.resolve()).then(async()=>{if(await W,Q.issues.length===V)return;if(!z)z=t5(Q,V)});else{if(Q.issues.length===V)continue;if(!z)z=t5(Q,V)}}if(G)return G.then(()=>{return Q});return Q},J=(Q,K,w)=>{if(t5(Q))return Q.aborted=!0,Q;let z=Y(K,U,w);if(z instanceof Promise){if(w.async===!1)throw new Y8;return z.then((G)=>$._zod.parse(G,w))}return $._zod.parse(z,w)};$._zod.run=(Q,K)=>{if(K.skipChecks)return $._zod.parse(Q,K);if(K.direction==="backward"){let z=$._zod.parse({value:Q.value,issues:[]},{...K,skipChecks:!0});if(z instanceof Promise)return z.then((G)=>{return J(G,Q,K)});return J(z,Q,K)}let w=$._zod.parse(Q,K);if(w instanceof Promise){if(K.async===!1)throw new Y8;return w.then((z)=>Y(z,U,K))}return Y(w,U,K)}}o0($,"~standard",()=>({validate:(Y)=>{try{let J=VI($,Y);return J.success?{value:J.data}:{issues:J.error?.issues}}catch(J){return bY($,Y).then((Q)=>Q.success?{value:Q.data}:{issues:Q.error?.issues})}},vendor:"zod",version:1}))}),P7=m("$ZodString",($,I)=>{k0.init($,I),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??XL($._zod.bag),$._zod.parse=(q,U)=>{if(I.coerce)try{q.value=String(q.value)}catch(Y){}if(typeof q.value==="string")return q;return q.issues.push({expected:"string",code:"invalid_type",input:q.value,inst:$}),q}}),_1=m("$ZodStringFormat",($,I)=>{ZI.init($,I),P7.init($,I)}),pL=m("$ZodGUID",($,I)=>{I.pattern??(I.pattern=IL),_1.init($,I)}),cL=m("$ZodUUID",($,I)=>{if(I.version){let U={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[I.version];if(U===void 0)throw Error(`Invalid UUID version: "${I.version}"`);I.pattern??(I.pattern=g7(U))}else I.pattern??(I.pattern=g7());_1.init($,I)}),dL=m("$ZodEmail",($,I)=>{I.pattern??(I.pattern=qL),_1.init($,I)}),lL=m("$ZodURL",($,I)=>{_1.init($,I),$._zod.check=(q)=>{try{let U=q.value.trim();if(!I.normalize&&I.protocol?.source===GL.source){if(!/^https?:\/\//i.test(U)){q.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:q.value,inst:$,continue:!I.abort});return}}let Y=new URL(U);if(I.hostname){if(I.hostname.lastIndex=0,!I.hostname.test(Y.hostname))q.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:I.hostname.source,input:q.value,inst:$,continue:!I.abort})}if(I.protocol){if(I.protocol.lastIndex=0,!I.protocol.test(Y.protocol.endsWith(":")?Y.protocol.slice(0,-1):Y.protocol))q.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:I.protocol.source,input:q.value,inst:$,continue:!I.abort})}if(I.normalize)q.value=Y.href;else q.value=U;return}catch(U){q.issues.push({code:"invalid_format",format:"url",input:q.value,inst:$,continue:!I.abort})}}}),mL=m("$ZodEmoji",($,I)=>{I.pattern??(I.pattern=UL()),_1.init($,I)}),oL=m("$ZodNanoID",($,I)=>{I.pattern??(I.pattern=eO),_1.init($,I)}),rL=m("$ZodCUID",($,I)=>{I.pattern??(I.pattern=oO),_1.init($,I)}),tL=m("$ZodCUID2",($,I)=>{I.pattern??(I.pattern=rO),_1.init($,I)}),aL=m("$ZodULID",($,I)=>{I.pattern??(I.pattern=tO),_1.init($,I)}),sL=m("$ZodXID",($,I)=>{I.pattern??(I.pattern=aO),_1.init($,I)}),eL=m("$ZodKSUID",($,I)=>{I.pattern??(I.pattern=sO),_1.init($,I)}),$N=m("$ZodISODateTime",($,I)=>{I.pattern??(I.pattern=ZL(I)),_1.init($,I)}),IN=m("$ZodISODate",($,I)=>{I.pattern??(I.pattern=VL),_1.init($,I)}),qN=m("$ZodISOTime",($,I)=>{I.pattern??(I.pattern=WL(I)),_1.init($,I)}),UN=m("$ZodISODuration",($,I)=>{I.pattern??(I.pattern=$L),_1.init($,I)}),YN=m("$ZodIPv4",($,I)=>{I.pattern??(I.pattern=YL),_1.init($,I),$._zod.bag.format="ipv4"}),JN=m("$ZodIPv6",($,I)=>{I.pattern??(I.pattern=JL),_1.init($,I),$._zod.bag.format="ipv6",$._zod.check=(q)=>{try{new URL(`http://[${q.value}]`)}catch{q.issues.push({code:"invalid_format",format:"ipv6",input:q.value,inst:$,continue:!I.abort})}}}),QN=m("$ZodMAC",($,I)=>{I.pattern??(I.pattern=QL(I.delimiter)),_1.init($,I),$._zod.bag.format="mac"}),KN=m("$ZodCIDRv4",($,I)=>{I.pattern??(I.pattern=KL),_1.init($,I)}),wN=m("$ZodCIDRv6",($,I)=>{I.pattern??(I.pattern=wL),_1.init($,I),$._zod.check=(q)=>{let U=q.value.split("/");try{if(U.length!==2)throw Error();let[Y,J]=U;if(!J)throw Error();let Q=Number(J);if(`${Q}`!==J)throw Error();if(Q<0||Q>128)throw Error();new URL(`http://[${Y}]`)}catch{q.issues.push({code:"invalid_format",format:"cidrv6",input:q.value,inst:$,continue:!I.abort})}}});function zN($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}} Line truncated
if (${g}.issues.length) {
if (${B} in input) {
payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
*/var k1=a("fs"),bL=a("os"),x4=a("path"),Uw0=a("crypto"),p8={fs:k1.constants,os:bL.constants},Kw0=/XXXXXX/,qw0=(p8.O_CREAT||p8.fs.O_CREAT)|(p8.O_EXCL||p8.fs.O_EXCL)|(p8.O_RDWR||p8.fs.O_RDWR),rQ1=bL.platform()==="win32",tQ1=p8.EBADF||p8.os.errno.EBADF,aQ1=p8.ENOENT||p8.os.errno.ENOENT,LJ=[],Hw0=k1.rmdirSync.bind(k1),Gw0=!1;function sQ1($,I){return k1.rm($,{recursive:!0},I)}function Ww0($){return k1.rmSync($,{recursive:!0})}function Kh($,I){let U=DJ($,I),Y=U[0],J=U[1];H21(Y,function(Q,K){if(Q)return J(Q);let q=K.tries;(function H(){try{let G=Vw0(K);k1.stat(G,function(W){if(!W){if(q-- >0)return H();return J(Error("Could not get a unique tmp filename, max tries reached "+G))}J(null,G)})}catch(G){J(G)}})()})}function qh($){let I=DJ($),U=I[0],Y=G21(U),J=Y.tries;do{let Q=Vw0(Y);try{k1.statSync(Q)}catch(K){return Q}}while(J-- >0);throw Error("Could not get a unique tmp filename, max tries reached")}function eQ1($,I){let U=DJ($,I),Y=U[0],J=U[1];Kh(Y,function(K,q){if(K)return J(K);k1.open(q,qw0,Y.mode||384,function(G,W){if(G)return J(G);if(Y.discardDescriptor)return k1.close(W,function(V){return J(V,q,void 0,Jh(q,-1,Y,!1))});else{let w=Y.discardDescriptor||Y.detachDescriptor;J(null,q,W,Jh(q,w?-1:W,Y,!1))}})})}function $21($){let I=DJ($),U=I[0],Y=U.discardDescriptor||U.detachDescriptor,J=qh(U),Q=k1.openSync(J,qw0,U.mode||384);if(U.discardDescriptor)k1.closeSync(Q),Q=void 0;return{name:J,fd:Q,removeCallback:Jh(J,Y?-1:Q,U,!0)}}function I21($,I){let U=DJ($,I),Y=U[0],J=U[1];Kh(Y,function(K,q){if(K)return J(K);k1.mkdir(q,Y.mode||448,function(G){if(G)return J(G);J(null,q,ww0(q,Y,!1))})})}function U21($){let I=DJ($),U=I[0],Y=qh(U);return k1.mkdirSync(Y,U.mode||448),{name:Y,removeCallback:ww0(Y,U,!0)}}function Y21($,I){let U=function(Y){if(Y&&!Qh(Y))return I(Y);I()};if(0<=$[0])k1.close($[0],function(){k1.unlink($[1],U)});else k1.unlink($[1],U)}function J21($){let I=null;try{if(0<=$[0])k1.closeSync($[0])}catch(U){if(!W21(U)&&!Qh(U))throw U}finally{try{k1.unlinkSync($[1])}catch(U){if(!Qh(U))I=U}}if(I!==null)throw I}function Jh($,I,U,Y){let J=iL(J21,[I,$],Y),Q=iL(Y21,[I,$],Y,J);if(!U.keep)LJ.unshift(J);return Y?J:Q}function ww0($,I,U){let Y=I.unsafeCleanup?sQ1:k1.rmdir.bind(k1),J=I.unsafeCleanup?Ww0:Hw0,Q=iL(J,$,U),K=iL(Y,$,U,Q);if(!I.keep)LJ.unshift(Q);return U?Q:K}function iL($,I,U,Y){let J=!1;return function Q(K){if(!J){let q=Y||Q,H=LJ.indexOf(q);if(H>=0)LJ.splice(H,1);if(J=!0,U||$===Hw0||$===Ww0)return $(I);else return $(I,K||function(){})}}}function Q21(){if(!Gw0)return;while(LJ.length)try{LJ[0]()}catch($){}}function Yw0($){let I=[],U=null;try{U=Uw0.randomBytes($)}catch(Y){U=Uw0.pseudoRandomBytes($)}for(let Y=0;Y<$;Y++)I.push("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[U[Y]%62]);return I.join("")}function $$($){return typeof $>"u"}function DJ($,I){if(typeof $==="function")return[{},$];if($$($))return[{},I];let U={};for(let Y of Object.getOwnPropertyNames($))U[Y]=$[Y];return[U,I]}function K21($,I,U){let Y=x4.isAbsolute($)?$:x4.join(I,$);k1.stat(Y,function(J){if(J)k1.realpath(x4.dirname(Y),function(Q,K){if(Q)return U(Q);U(null,x4.join(K,x4.basename(Y)))});else k1.realpath(Y,U)})}function q21($,I){let U=x4.isAbsolute($)?$:x4.join(I,$);try{return k1.statSync(U),k1.realpathSync(U)}catch(Y){let J=k1.realpathSync(x4.dirname(U));return x4.join(J,x4.basename(U))}}function Vw0($){let I=$.tmpdir;if(!$$($.name))return x4.join(I,$.dir,$.name);if(!$$($.template))return x4.join(I,$.dir,$.template).replace(Kw0,Yw0(6));let U=[$.prefix?$.prefix:"tmp","-",process.pid,"-",Yw0(12),$.postfix?"-"+$.postfix:""].join("");return x4.join(I,$.dir,U)}function Yh($,I){if(typeof I!=="string")throw Error(`${$} option must be a string, got "${typeof I}".`);if(I.includes(".."))throw Error("Relative value not allowed");return I}function Zw0($){if(!$$($.name)){let I=$.name;if(x4.isAbsolute(I))throw Error(`name option must not contain an absolute path, found "${I}".`);let U=x4.basename(I);if(U===".."||U==="."||U!==I)throw Error(`name option must not contain a path, found "${I}".`)}if(!$$($.template)){if(typeof $.template!=="string")throw Error(`template option must be a string, got "${typeof $.template}".`);if(!$.template.match(Kw0))throw Error(`Invalid template, found "${$.template}".`)}if(!$$($.tries)&&isNaN($.tries)||$.tries<0)throw Error(`Invalid tries, found "${$.tries}".`);$.tries=$$($.name)?$.tries||3:1,$.keep=!!$.keep,$.detachDescriptor=!!$.detachDescriptor,$.discardDescriptor=!!$.discardDescriptor,$.unsafeCleanup=!!$.unsafeCleanup,$.prefix=$$($.prefix)?"":Yh("prefix",$.prefix),$.postfix=$$($.postfix)?"":Yh("postfix",$.postfix),$.template=$$($.template)?void 0:Yh("template",$.template)}function Jw0($,I,U,Y){if($$(I))return Y(null);K21(I,U,function(J,Q){if(J)return Y(J);let K=x4.relative(U,Q);if(K.startsWith("..")||x4.isAbsolute(K))return Y(Error(`${$} option must be relative to "${U}", found "${K}".`));Y(null,K)})}function Qw0($,I,U){if($$(I))return;let Y=q21(I,U),J=x4.relative(U,Y);if(J.startsWith("..")||x4.isAbsolute(J))throw ELine truncated
\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�`},ibm864:"cp864",csibm864:"cp864",cp865:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm865:"cp865",csibm865:"cp865",cp866:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "},ibm866:"cp866",csibm866:"cp866",cp869:{type:"_sbcs",chars:"������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ "},ibm869:"cp869",csibm869:"cp869",cp922:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"},ibm922:"cp922",csibm922:"cp922",cp1046:{type:"_sbcs",chars:"ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"},ibm1046:"cp1046",csibm1046:"cp1046",cp1124:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"},ibm1124:"cp1124",csibm1124:"cp1124",cp1125:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "},ibm1125:"cp1125",csibm1125:"cp1125",cp1129:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},ibm1129:"cp1129",csibm1129:"cp1129",cp1133:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"},ibm1133:"cp1133",csibm1133:"cp1133",cp1161:{type:"_sbcs",chars:"��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "},ibm1161:"cp1161",csibm1161:"cp1161",cp1162:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"},ibm1162:"cp1162",csibm1162:"cp1162",cp1163:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},ibm1163:"cp1163",csiLine truncated
\v\f\r\x0E\x0F\x10ỨỰỲỶỸÝỴ\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ`},georgianacademy:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},georgianps:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},pt154:{type:"_sbcs",chars:"ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"},viscii:{type:"_sbcs",chars:`\x00\x01Ẳ\x03\x04ẴẪ\x07\b
\v\f\r\x0E\x0F\x10\x11\x12\x13Ỷ\x15\x16\x17\x18Ỹ\x1A\x1B\x1C\x1DỴ\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ`},iso646cn:{type:"_sbcs",chars:`\x00\x01\x02\x03\x04\x05\x06\x07\b
\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������`},iso646jp:{type:"_sbcs",chars:`\x00\x01\x02\x03\x04\x05\x06\x07\b
\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_\`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������`},hproman8:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¾—¼½ªº«■»±�"},macintosh:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"},ascii:{type:"_sbcs",chars:"��������������������������������������������������������������������������������������������������������������������������������"},tis620:{type:"_sbcs",chars:"���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"}}});var rV0=F((pq1)=>{var Hu=c5().Buffer;pq1._dbcs=m5;var W6=-1,oV0=-2,n$=-10,x6=-1000,CJ=Array(256),wH=-1;for(WH=0;WH<256;WH++)CJ[WH]=W6;var WH;function m5($,I){if(this.encodingName=$.encodingName,!$)throw Error("DBCS codec is called without the data.");if(!$.table)throw Error("Encoding '"+this.encodingName+"' has no data.");var U=$.table();this.decodeTables=[],this.decodeTables[0]=CJ.slice(0),this.decodeTableSeq=[];for(var Y=0;Y<U.length;Y++)this._addDecodeChunk(U[Y]);if(typeof $.gb18030==="function"){this.gb18030=$.gb18030();var J=this.decodeTables.length;this.decodeTables.push(CJ.slice(0));var Q=this.decodeTables.length;this.decodeTables.push(CJ.slice(0));var K=this.decodeTables[0];for(var Y=129;Y<=254;Y++){var q=this.decodeTables[x6-K[Y]];for(var H=48;H<=57;H++){if(q[H]===W6)q[H]=x6-J;else if(q[H]>x6)throw Error("gb18030 decode tables conflict at byte 2");var G=this.decodeTables[x6-q[H]];for(var W=129;W<=254;W++){if(G[W]===W6)G[W]=x6-Q;else if(G[W]===x6-Q)continue;else if(G[W]>x6)throw Error("gb18030 decode tables conflict at byte 3");var w=this.decodeTables[x6-G[W]];for(var V=48;V<=57;V++)if(w[V]===W6)w[V]=oV0}}}}this.defaultCharUnicode=I.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var Z={};if($.encodeSkipVals)for(var Y=0;Y<$.encodeSkipVals.length;Y++){var X=$.encodeSkipVals[Y];if(typeof X==="number")Z[X]=!0;else for(var H=X.from;H<=X.to;H++)Z[H]=!0}if(this._fillEncodeTable(0,0,Z),$.encodeAdd){for(var L in $.encodeAdd)if(Object.prototype.hasOwnProperty.call($.encodeAdd,L))this._setEncodeChar(L.charCodeAt(0),$.encodeAdd[L])}if(this.defCharSB=this.encodeTable[0][I.defaultCharSingleByte.charCodeAt(0)],this.defCharSB===W6)this.defCharSB=this.encodeTable[0]["?"];if(this.defCharSB===W6)this.defCharSB=63}m5.prototype.encoder=ZD;m5.prototype.decoder=Gu;m5.prototype._getDecodeTrieNode=function($){var I=[];for(;$>0;$>>>=8)I.push($&255);if(I.length==0)I.push(0);var U=this.decodeTables[0];for(var Y=I.length-1;Y>0;Y--){var J=U[I[Y]];if(J==W6)U[I[Y]]=x6-this.decodeTables.length,this.decodeTables.push(U=CJ.slice(0));else if(J<=x6)U=this.decodeTables[x6-J];else throw Error("Overwrite byte in "+this.encodingName+", addr: "+$.toString(16))}return U};m5.prototype._addDecodeChunk=function($){var I=parseInt($[0],16),U=this._getDecodeTrieNode(I);I=I&255;for(var Y=1;Y<$.length;Y++){var J=$[Y];if(typeof J==="string")for(var Q=0;Q<J.length;){var K=J.charCodeAt(Q++);if(K>=55296&&K<56320){var q=J.charCodeAt(Q++);if(q>=56320&&q<57344)U[I++]=65536+(K-55296)*1024+(q-56320);else throw Error("Incorrect surrogate pair in "+this.encodingName+" at chunk "+$[0])}else if(K>4080&&K<=4095){var H=4095-K+2,G=[];for(var W=0;W<H;W++)G.push(J.charCodeAt(Q++));U[I++]=n$-this.decodeTableSeq.length,this.decodeTableSeq.push(G)}else U[I++]=K}else if(typeof J==="number"){var w=U[I-1]+1;for(var Q=0;Q<J;Q++)U[I++]=w++}else throw Error("Incorrect type '"+typeof J+"' given in "+this.encodingName+" at chunk "+$[0])}if(I>255)throw Error("Incorrect chunk in "+this.encoLine truncated
`)}var PI=($)=>(I,U,Y,J)=>{let Q=Y?{...Y,async:!1}:{async:!1},K=I._zod.run({value:U,issues:[]},Q);if(K instanceof Promise)throw new W8;if(K.issues.length){let q=new(J?.Err??$)(K.issues.map((H)=>E6(H,Q,z4())));throw aH(q,J?.callee),q}return K.value},tJ=PI(n6),TI=($)=>async(I,U,Y,J)=>{let Q=Y?{...Y,async:!0}:{async:!0},K=I._zod.run({value:U,issues:[]},Q);if(K instanceof Promise)K=await K;if(K.issues.length){let q=new(J?.Err??$)(K.issues.map((H)=>E6(H,Q,z4())));throw aH(q,J?.callee),q}return K.value},aJ=TI(n6),EI=($)=>(I,U,Y)=>{let J=Y?{...Y,async:!1}:{async:!1},Q=I._zod.run({value:U,issues:[]},J);if(Q instanceof Promise)throw new W8;return Q.issues.length?{success:!1,error:new($??lJ)(Q.issues.map((K)=>E6(K,J,z4())))}:{success:!0,data:Q.value}},BI=EI(n6),vI=($)=>async(I,U,Y)=>{let J=Y?{...Y,async:!0}:{async:!0},Q=I._zod.run({value:U,issues:[]},J);if(Q instanceof Promise)Q=await Q;return Q.issues.length?{success:!1,error:new $(Q.issues.map((K)=>E6(K,J,z4())))}:{success:!0,data:Q.value}},sJ=vI(n6),sH=($)=>(I,U,Y)=>{let J=Y?{...Y,direction:"backward"}:{direction:"backward"};return PI($)(I,U,J)},ix=sH(n6),eH=($)=>(I,U,Y)=>{return PI($)(I,U,Y)},bx=eH(n6),$G=($)=>async(I,U,Y)=>{let J=Y?{...Y,direction:"backward"}:{direction:"backward"};return TI($)(I,U,J)},nx=$G(n6),IG=($)=>async(I,U,Y)=>{return TI($)(I,U,Y)},px=IG(n6),UG=($)=>(I,U,Y)=>{let J=Y?{...Y,direction:"backward"}:{direction:"backward"};return EI($)(I,U,J)},cx=UG(n6),YG=($)=>(I,U,Y)=>{return EI($)(I,U,Y)},dx=YG(n6),JG=($)=>async(I,U,Y)=>{let J=Y?{...Y,direction:"backward"}:{direction:"backward"};return vI($)(I,U,J)},mx=JG(n6),QG=($)=>async(I,U,Y)=>{return vI($)(I,U,Y)},lx=QG(n6);var Q$={};e8(Q$,{xid:()=>DF,uuid7:()=>ID0,uuid6:()=>$D0,uuid4:()=>eL0,uuid:()=>j7,uppercase:()=>nF,unicodeEmail:()=>ox,undefined:()=>iF,ulid:()=>LF,time:()=>gF,string:()=>hF,sha512_hex:()=>AD0,sha512_base64url:()=>TD0,sha512_base64:()=>PD0,sha384_hex:()=>OD0,sha384_base64url:()=>MD0,sha384_base64:()=>ND0,sha256_hex:()=>LD0,sha256_base64url:()=>FD0,sha256_base64:()=>DD0,sha1_hex:()=>ZD0,sha1_base64url:()=>XD0,sha1_base64:()=>zD0,rfc5322Email:()=>YD0,number:()=>eJ,null:()=>fF,nanoid:()=>OF,md5_hex:()=>WD0,md5_base64url:()=>VD0,md5_base64:()=>wD0,mac:()=>BF,lowercase:()=>bF,ksuid:()=>FF,ipv6:()=>EF,ipv4:()=>TF,integer:()=>xF,idnEmail:()=>JD0,httpProtocol:()=>jF,html5Email:()=>UD0,hostname:()=>qD0,hex:()=>GD0,guid:()=>MF,extendedDuration:()=>sL0,emoji:()=>PF,email:()=>AF,e164:()=>_F,duration:()=>NF,domain:()=>HD0,datetime:()=>yF,date:()=>SF,cuid2:()=>XF,cuid:()=>zF,cidrv6:()=>RF,cidrv4:()=>vF,browserEmail:()=>QD0,boolean:()=>kF,bigint:()=>uF,base64url:()=>KG,base64:()=>CF});var zF=/^[cC][0-9a-z]{6,}$/,XF=/^[0-9a-z]+$/,LF=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,DF=/^[0-9a-vA-V]{20}$/,FF=/^[A-Za-z0-9]{27}$/,OF=/^[a-zA-Z0-9_-]{21}$/,NF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,sL0=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,MF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,j7=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},eL0=j7(4),$D0=j7(6),ID0=j7(7),AF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,UD0=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,YD0=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,ox=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,JD0=ox,QD0=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,KD0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function PF(){return new RegExp(KD0,"u")}var TF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,EF=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,BF=($)=>{let I=M$($??":");return new RegExp(`^(?:[0-9A-F]{2}${I}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${I}){5}[0-9a-f]{2}$`)},vF=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0Line truncated
`).filter((Q)=>Q),Y=Math.min(...U.map((Q)=>Q.length-Q.trimStart().length)),J=U.map((Q)=>Q.slice(Y)).map((Q)=>" ".repeat(this.indent*2)+Q);for(let Q of J)this.content.push(Q)}compile(){let $=Function,I=this?.args,Y=[...(this?.content??[""]).map((J)=>` ${J}`)];return new $(...I,Y.join(`
`))}}var qO={major:4,minor:4,patch:3};var n0=o("$ZodType",($,I)=>{var U;$??($={}),$._zod.def=I,$._zod.bag=$._zod.bag||{},$._zod.version=qO;let Y=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))Y.unshift($);for(let J of Y)for(let Q of J._zod.onattach)Q($);if(Y.length===0)(U=$._zod).deferred??(U.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let J=(K,q,H)=>{let G=I9(K),W;for(let w of q){if(w._zod.def.when){if(wF(K))continue;if(!w._zod.def.when(K))continue}else if(G)continue;let V=K.issues.length,Z=w._zod.check(K);if(Z instanceof Promise&&H?.async===!1)throw new W8;if(W||Z instanceof Promise)W=(W??Promise.resolve()).then(async()=>{if(await Z,K.issues.length===V)return;if(!G)G=I9(K,V)});else{if(K.issues.length===V)continue;if(!G)G=I9(K,V)}}if(W)return W.then(()=>{return K});return K},Q=(K,q,H)=>{if(I9(K))return K.aborted=!0,K;let G=J(q,Y,H);if(G instanceof Promise){if(H.async===!1)throw new W8;return G.then((W)=>$._zod.parse(W,H))}return $._zod.parse(G,H)};$._zod.run=(K,q)=>{if(q.skipChecks)return $._zod.parse(K,q);if(q.direction==="backward"){let G=$._zod.parse({value:K.value,issues:[]},{...q,skipChecks:!0});if(G instanceof Promise)return G.then((W)=>{return Q(W,K,q)});return Q(G,K,q)}let H=$._zod.parse(K,q);if(H instanceof Promise){if(q.async===!1)throw new W8;return H.then((G)=>J(G,Y,q))}return J(H,Y,q)}}e0($,"~standard",()=>({validate:(J)=>{try{let Q=BI($,J);return Q.success?{value:Q.data}:{issues:Q.error?.issues}}catch(Q){return sJ($,J).then((K)=>K.success?{value:K.data}:{issues:K.error?.issues})}},vendor:"zod",version:1}))}),_7=o("$ZodString",($,I)=>{n0.init($,I),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??hF($._zod.bag),$._zod.parse=(U,Y)=>{if(I.coerce)try{U.value=String(U.value)}catch(J){}if(typeof U.value==="string")return U;return U.issues.push({expected:"string",code:"invalid_type",input:U.value,inst:$}),U}}),y1=o("$ZodStringFormat",($,I)=>{RI.init($,I),_7.init($,I)}),GO=o("$ZodGUID",($,I)=>{I.pattern??(I.pattern=MF),y1.init($,I)}),WO=o("$ZodUUID",($,I)=>{if(I.version){let Y={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[I.version];if(Y===void 0)throw Error(`Invalid UUID version: "${I.version}"`);I.pattern??(I.pattern=j7(Y))}else I.pattern??(I.pattern=j7());y1.init($,I)}),wO=o("$ZodEmail",($,I)=>{I.pattern??(I.pattern=AF),y1.init($,I)}),VO=o("$ZodURL",($,I)=>{y1.init($,I),$._zod.check=(U)=>{try{let Y=U.value.trim();if(!I.normalize&&I.protocol?.source===jF.source){if(!/^https?:\/\//i.test(Y)){U.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:U.value,inst:$,continue:!I.abort});return}}let J=new URL(Y);if(I.hostname){if(I.hostname.lastIndex=0,!I.hostname.test(J.hostname))U.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:I.hostname.source,input:U.value,inst:$,continue:!I.abort})}if(I.protocol){if(I.protocol.lastIndex=0,!I.protocol.test(J.protocol.endsWith(":")?J.protocol.slice(0,-1):J.protocol))U.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:I.protocol.source,input:U.value,inst:$,continue:!I.abort})}if(I.normalize)U.value=J.href;else U.value=Y;return}catch(Y){U.issues.push({code:"invalid_format",format:"url",input:U.value,inst:$,continue:!I.abort})}}}),ZO=o("$ZodEmoji",($,I)=>{I.pattern??(I.pattern=PF()),y1.init($,I)}),zO=o("$ZodNanoID",($,I)=>{I.pattern??(I.pattern=OF),y1.init($,I)}),XO=o("$ZodCUID",($,I)=>{I.pattern??(I.pattern=zF),y1.init($,I)}),LO=o("$ZodCUID2",($,I)=>{I.pattern??(I.pattern=XF),y1.init($,I)}),DO=o("$ZodULID",($,I)=>{I.pattern??(I.pattern=LF),y1.init($,I)}),FO=o("$ZodXID",($,I)=>{I.pattern??(I.pattern=DF),y1.init($,I)}),OO=o("$ZodKSUID",($,I)=>{I.pattern??(I.pattern=FF),y1.init($,I)}),NO=o("$ZodISODateTime",($,I)=>{I.pattern??(I.pattern=yF(I)),y1.init($,I)}),MO=o("$ZodISODate",($,I)=>{I.pattern??(I.pattern=SF),y1.init($,I)}),AO=o("$ZodISOTime",($,I)=>{I.pattern??(I.pattern=gF(I)),y1.init($,I)}),PO=o("$ZodISODuration",($,I)=>{I.pattern??(I.pattern=NF),y1.init($,I)}),TO=o("$ZodIPv4",($,I)=>{I.pattern??(I.pattern=TF),y1.init($,I),$._zod.bag.format="ipv4"}),EO=o("$ZodIPv6",($,I)=>{I.pattern??(I.pattern=EF),y1.init($,I),$._zod.bag.format="ipv6",$._zod.check=(U)=>{try{new URL(`http://[${U.value}]`)}catch{U.issues.push({code:"invalid_format",format:"ipv6",input:U.value,inst:$,continue:!I.abort})}}}),BO=o("$ZodMAC",($,I)=>{I.pattern??(I.pattern=BF(I.delimiter)),y1.init($,I),$._zod.bag.format="mac"}),vO=o("$ZodCIDRv4",($,I)=>{I.pattern??(I.pattern=vF),y1.init($,I)}),RO=o("$ZodCIDRv6",($,I)=>{I.pattern??(I.pattern=RF),y1.init($,I),$._zod.check=(U)=>{let Y=U.value.split("/");try{if(Y.length!==2)throw Error();let[J,Q]=Y;if(!Q)throw Error();let K=Number(Q);if(`${K}`!==Q)throw Error();if(K<0||K>128)throw Error();new URL(`http://[${J}]`)}catch{U.issues.push({code:"invalid_format",format:"cidrv6",input:U.value,inst:$,continue:!I.abort})}}});function CO($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}} Line truncated
if (${A}.issues.length) {
if (${R} in input) {
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
...iss,
path: iss.path ? [${B}, ...iss.path] : [${B}]
path: iss.path ? [${R}, ...iss.path] : [${R}]
})));
}
}
if (${g}.value === undefined) {
if (${B} in input) {
newResult[${B}] = undefined;
if (${A}.value === undefined) {
if (${R} in input) {
newResult[${R}] = undefined;
}
} else {
newResult[${B}] = ${g}.value;
newResult[${R}] = ${A}.value;
}
`);else if(!h)W.write(`
const ${g}_present = ${B} in input;
if (${g}.issues.length) {
payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
`);else if(!g)Z.write(`
const ${A}_present = ${R} in input;
if (${A}.issues.length) {
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
...iss,
path: iss.path ? [${B}, ...iss.path] : [${B}]
path: iss.path ? [${R}, ...iss.path] : [${R}]
})));
}
if (!${g}_present && !${g}.issues.length) {
if (!${A}_present && !${A}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${B}]
path: [${R}]
});
}
if (${g}_present) {
if (${g}.value === undefined) {
newResult[${B}] = undefined;
if (${A}_present) {
if (${A}.value === undefined) {
newResult[${R}] = undefined;
} else {
newResult[${B}] = ${g}.value;
newResult[${R}] = ${A}.value;
}
}
`);else W.write(`
if (${g}.issues.length) {
payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
`);else Z.write(`
if (${A}.issues.length) {
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
...iss,
path: iss.path ? [${B}, ...iss.path] : [${B}]
path: iss.path ? [${R}, ...iss.path] : [${R}]
})));
}
if (${g}.value === undefined) {
if (${B} in input) {
newResult[${B}] = undefined;
if (${A}.value === undefined) {
if (${R} in input) {
newResult[${R}] = undefined;
}
} else {
newResult[${B}] = ${g}.value;
newResult[${R}] = ${A}.value;
}
`)}W.write("payload.value = newResult;"),W.write("return payload;");let T=W.compile();return(P,g)=>T(V,P,g)},J,Q=A7,K=!F7.jitless,z=K&&fO.value,G=I.catchall,H;$._zod.parse=(V,W)=>{H??(H=U.value);let X=V.value;if(!Q(X))return V.issues.push({expected:"object",code:"invalid_type",input:X,inst:$}),V;if(K&&z&&W?.async===!1&&W.jitless!==!0){if(!J)J=Y(I.shape);if(V=J(V,W),!G)return V;return ex([],X,V,W,H,$)}return q(V,W)}});function xx($,I,q,U){for(let J of $)if(J.issues.length===0)return I.value=J.value,I;let Y=$.filter((J)=>!t5(J));if(Y.length===1)return I.value=Y[0].value,Y[0];return I.issues.push({code:"invalid_union",input:I.value,inst:q,errors:$.map((J)=>J.issues.map((Q)=>A6(Q,U,W4())))}),I}var mY=m("$ZodUnion",($,I)=>{k0.init($,I),o0($._zod,"optin",()=>I.options.some((U)=>U._zod.optin==="optional")?"optional":void 0),o0($._zod,"optout",()=>I.options.some((U)=>U._zod.optout==="optional")?"optional":void 0),o0($._zod,"values",()=>{if(I.options.every((U)=>U._zod.values))return new Set(I.options.flatMap((U)=>Array.from(U._zod.values)));return}),o0($._zod,"pattern",()=>{if(I.options.every((U)=>U._zod.pattern)){let U=I.options.map((Y)=>Y._zod.pattern);return new RegExp(`^(${U.map((Y)=>hY(Y.source)).join("|")})$`)}return});let q=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(U,Y)=>{if(q)return q(U,Y);let J=!1,Q=[];for(let K of I.options){let w=K._zod.run({value:U.value,issues:[]},Y);if(w instanceof Promise)Q.push(w),J=!0;else{if(w.issues.length===0)return w;Q.push(w)}}if(!J)return xx(Q,U,$,Y);return Promise.all(Q).then((K)=>{return xx(K,U,$,Y)})}});function kx($,I,q,U){let Y=$.filter((J)=>J.issues.length===0);if(Y.length===1)return I.value=Y[0].value,I;if(Y.length===0)I.issues.push({code:"invalid_union",input:I.value,inst:q,errors:$.map((J)=>J.issues.map((Q)=>A6(Q,U,W4())))});else I.issues.push({code:"invalid_union",input:I.value,inst:q,errors:[],inclusive:!1});return I}var jN=m("$ZodXor",($,I)=>{mY.init($,I),I.inclusive=!1;let q=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(U,Y)=>{if(q)return q(U,Y);let J=!1,Q=[];for(let K of I.options){let w=K._zod.run({value:U.value,issues:[]},Y);if(w instanceof Promise)Q.push(w),J=!0;else Q.push(w)}if(!J)return kx(Q,U,$,Y);return Promise.all(Q).then((K)=>{return kx(K,U,$,Y)})}}),BN=m("$ZodDiscriminatedUnion",($,I)=>{I.inclusive=!1,mY.init($,I);let q=$._zod.parse;o0($._zod,"propValues",()=>{let Y={};for(let J of I.options){let Q=J._zod.propValues;if(!Q||Object.keys(Q).length===0)throw Error(`Invalid discriminated union option at index "${I.options.indexOf(J)}"`);for(let[K,w]of Object.entries(Q)){if(!Y[K])Y[K]=new Set;for(let z of w)Y[K].add(z)}}return Y});let U=KI(()=>{let Y=I.options,J=new Map;for(let Q of Y){let K=Q._zod.propValues?.[I.discriminator];if(!K||K.size===0)throw Error(`Invalid discriminated union option at index "${I.options.indexOf(Q)}"`);for(let w of K){if(J.has(w))throw Error(`Duplicate discriminator value "${String(w)}"`);J.set(w,Q)}}return J});$._zod.parse=(Y,J)=>{let Q=Y.value;if(!A7(Q))return Y.issues.push({code:"invalid_type",expected:"object",input:Q,inst:$}),Y;let K=U.value.get(Q?.[I.discriminator]);if(K)return K._zod.run(Y,J);if(I.unionFallback||J.direction==="backward")return q(Y,J);return Y.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:I.discriminator,options:Array.from(U.value.keys()),input:Q,path:[I.discriminator],inst:$}),Y}}),vN=m("$ZodIntersection",($,I)=>{k0.init($,I),$._zod.parse=(q,U)=>{let Y=q.value,J=I.left._zod.run({value:Y,issues:[]},U),Q=I.right._zod.run({value:Y,issues:[]},U);if(J instanceof Promise||Q instanceof Promise)return Promise.all([J,Q]).then(([w,z])=>{return fx(q,w,z)});return fx(q,J,Q)}});function bL($,I){if($===I)return{valid:!0,data:$};if($ instanceof Date&&I instanceof Date&&+$===+I)return{valid:!0,data:$};if(r5($)&&r5(I)){let q=Object.keys(I),U=Object.keys($).filter((J)=>q.indexOf(J)!==-1),Y={...$,...I};for(let J of U){let Q=bL($[J],I[J]);if(!Q.valid)return{valid:!1,mergeErrorPath:[J,...Q.mergeErrorPath]};Y[J]=Q.data}return{valid:!0,data:Y}}if(Array.isArray($)&&Array.isArray(I)){if($.length!==I.length)return{valid:!1,mergeErrorPath:[]};let q=[];for(let U=0;U<$.length;U++){let Y=$[U],J=I[U],Q=bL(Y,J);if(!Q.valid)return{valid:!1,mergeErrorPath:[U,...Q.mergeErrorPath]};q.push(Q.data)}return{valid:!0,data:q}}return{valid:!1,mergeErrorPath:[]}}function fx($,I,q){let U=new Map,Y;for(let K of I.issues)if(K.code==="unrecognized_keys"){Y??(Y=K);for(let w of K.keys){if(!U.has(w))U.set(w,{});U.get(w).l=!0}}else $.issues.push(K);for(let K of q.issues)if(K.code==="unrecognized_keys")for(let w of K.keys){if(!U.has(w))U.set(w,{});U.get(w).r=!0}else $.issues.push(K);let J=[...U].filter(([,K])=>K.l&&K.r).map(([K])=>K);if(J.length&&Y)$.issues.push({...Y,keys:J});if(t5($))return $;let Q=bL(I.value,q.value);if(!Q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);return $.value=Q.data,$}var zz=m("$ZodTuple",($,I)=>{k0. Line truncated
`)}Z.write("payload.value = newResult;"),Z.write("return payload;");let E=Z.compile();return(T,A)=>E(V,T,A)},Q,K=C7,q=!v7.jitless,G=q&&QF.value,W=I.catchall,w;$._zod.parse=(V,Z)=>{w??(w=Y.value);let X=V.value;if(!K(X))return V.issues.push({expected:"object",code:"invalid_type",input:X,inst:$}),V;if(q&&G&&Z?.async===!1&&Z.jitless!==!0){if(!Q)Q=J(I.shape);if(V=Q(V,Z),!W)return V;return Dk([],X,V,Z,w,$)}return U(V,Z)}});function Ik($,I,U,Y){for(let Q of $)if(Q.issues.length===0)return I.value=Q.value,I;let J=$.filter((Q)=>!I9(Q));if(J.length===1)return I.value=J[0].value,J[0];return I.issues.push({code:"invalid_union",input:I.value,inst:U,errors:$.map((Q)=>Q.issues.map((K)=>E6(K,Y,z4())))}),I}var YQ=o("$ZodUnion",($,I)=>{n0.init($,I),e0($._zod,"optin",()=>I.options.some((Y)=>Y._zod.optin==="optional")?"optional":void 0),e0($._zod,"optout",()=>I.options.some((Y)=>Y._zod.optout==="optional")?"optional":void 0),e0($._zod,"values",()=>{if(I.options.every((Y)=>Y._zod.values))return new Set(I.options.flatMap((Y)=>Array.from(Y._zod.values)));return}),e0($._zod,"pattern",()=>{if(I.options.every((Y)=>Y._zod.pattern)){let Y=I.options.map((J)=>J._zod.pattern);return new RegExp(`^(${Y.map((J)=>pJ(J.source)).join("|")})$`)}return});let U=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(Y,J)=>{if(U)return U(Y,J);let Q=!1,K=[];for(let q of I.options){let H=q._zod.run({value:Y.value,issues:[]},J);if(H instanceof Promise)K.push(H),Q=!0;else{if(H.issues.length===0)return H;K.push(H)}}if(!Q)return Ik(K,Y,$,J);return Promise.all(K).then((q)=>{return Ik(q,Y,$,J)})}});function Uk($,I,U,Y){let J=$.filter((Q)=>Q.issues.length===0);if(J.length===1)return I.value=J[0].value,I;if(J.length===0)I.issues.push({code:"invalid_union",input:I.value,inst:U,errors:$.map((Q)=>Q.issues.map((K)=>E6(K,Y,z4())))});else I.issues.push({code:"invalid_union",input:I.value,inst:U,errors:[],inclusive:!1});return I}var lO=o("$ZodXor",($,I)=>{YQ.init($,I),I.inclusive=!1;let U=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(Y,J)=>{if(U)return U(Y,J);let Q=!1,K=[];for(let q of I.options){let H=q._zod.run({value:Y.value,issues:[]},J);if(H instanceof Promise)K.push(H),Q=!0;else K.push(H)}if(!Q)return Uk(K,Y,$,J);return Promise.all(K).then((q)=>{return Uk(q,Y,$,J)})}}),oO=o("$ZodDiscriminatedUnion",($,I)=>{I.inclusive=!1,YQ.init($,I);let U=$._zod.parse;e0($._zod,"propValues",()=>{let J={};for(let Q of I.options){let K=Q._zod.propValues;if(!K||Object.keys(K).length===0)throw Error(`Invalid discriminated union option at index "${I.options.indexOf(Q)}"`);for(let[q,H]of Object.entries(K)){if(!J[q])J[q]=new Set;for(let G of H)J[q].add(G)}}return J});let Y=MI(()=>{let J=I.options,Q=new Map;for(let K of J){let q=K._zod.propValues?.[I.discriminator];if(!q||q.size===0)throw Error(`Invalid discriminated union option at index "${I.options.indexOf(K)}"`);for(let H of q){if(Q.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);Q.set(H,K)}}return Q});$._zod.parse=(J,Q)=>{let K=J.value;if(!C7(K))return J.issues.push({code:"invalid_type",expected:"object",input:K,inst:$}),J;let q=Y.value.get(K?.[I.discriminator]);if(q)return q._zod.run(J,Q);if(I.unionFallback||Q.direction==="backward")return U(J,Q);return J.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:I.discriminator,options:Array.from(Y.value.keys()),input:K,path:[I.discriminator],inst:$}),J}}),rO=o("$ZodIntersection",($,I)=>{n0.init($,I),$._zod.parse=(U,Y)=>{let J=U.value,Q=I.left._zod.run({value:J,issues:[]},Y),K=I.right._zod.run({value:J,issues:[]},Y);if(Q instanceof Promise||K instanceof Promise)return Promise.all([Q,K]).then(([H,G])=>{return Yk(U,H,G)});return Yk(U,Q,K)}});function HO($,I){if($===I)return{valid:!0,data:$};if($ instanceof Date&&I instanceof Date&&+$===+I)return{valid:!0,data:$};if($9($)&&$9(I)){let U=Object.keys(I),Y=Object.keys($).filter((Q)=>U.indexOf(Q)!==-1),J={...$,...I};for(let Q of Y){let K=HO($[Q],I[Q]);if(!K.valid)return{valid:!1,mergeErrorPath:[Q,...K.mergeErrorPath]};J[Q]=K.data}return{valid:!0,data:J}}if(Array.isArray($)&&Array.isArray(I)){if($.length!==I.length)return{valid:!1,mergeErrorPath:[]};let U=[];for(let Y=0;Y<$.length;Y++){let J=$[Y],Q=I[Y],K=HO(J,Q);if(!K.valid)return{valid:!1,mergeErrorPath:[Y,...K.mergeErrorPath]};U.push(K.data)}return{valid:!0,data:U}}return{valid:!1,mergeErrorPath:[]}}function Yk($,I,U){let Y=new Map,J;for(let q of I.issues)if(q.code==="unrecognized_keys"){J??(J=q);for(let H of q.keys){if(!Y.has(H))Y.set(H,{});Y.get(H).l=!0}}else $.issues.push(q);for(let q of U.issues)if(q.code==="unrecognized_keys")for(let H of q.keys){if(!Y.has(H))Y.set(H,{});Y.get(H).r=!0}else $.issues.push(q);let Q=[...Y].filter(([,q])=>q.l&&q.r).map(([q])=>q);if(Q.length&&J)$.issues.push({...J,keys:Q});if(I9($))return $;let K=HO(I.value,U.value);if(!K.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(K.mergeErrorPath)}`);return $.value=K.data,$}var LG=o("$ZodTuple",($,I)=>{n0. Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let Q of $.seen.entries()){let K=Q[1];if(I===Q[0]){J(Q);continue}if($.external){let z=$.external.registry.get(Q[0])?.id;if(I!==Q[0]&&z){J(Q);continue}}if($.metadataRegistry.get(Q[0])?.id){J(Q);continue}if(K.cycle){J(Q);continue}if(K.count>1){if($.reused==="ref"){J(Q);continue}}}}function I9($,I){let q=$.seen.get(I);if(!q)throw Error("Unprocessed schema. This is a bug in Zod.");let U=(K)=>{let w=$.seen.get(K);if(w.ref===null)return;let z=w.def??w.schema,G={...z},H=w.ref;if(w.ref=null,H){U(H);let W=$.seen.get(H),X=W.schema;if(X.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))z.allOf=z.allOf??[],z.allOf.push(X);else Object.assign(z,X);if(Object.assign(z,G),K._zod.parent===H)for(let O in z){if(O==="$ref"||O==="allOf")continue;if(!(O in G))delete z[O]}if(X.$ref&&W.def)for(let O in z){if(O==="$ref"||O==="allOf")continue;if(O in W.def&&JSON.stringify(z[O])===JSON.stringify(W.def[O]))delete z[O]}}let V=K._zod.parent;if(V&&V!==H){U(V);let W=$.seen.get(V);if(W?.schema.$ref){if(z.$ref=W.schema.$ref,W.def)for(let X in z){if(X==="$ref"||X==="allOf")continue;if(X in W.def&&JSON.stringify(z[X])===JSON.stringify(W.def[X]))delete z[X]}}}$.override({zodSchema:K,jsonSchema:z,path:w.path??[]})};for(let K of[...$.seen.entries()].reverse())U(K[0]);let Y={};if($.target==="draft-2020-12")Y.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")Y.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")Y.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let K=$.external.registry.get(I)?.id;if(!K)throw Error("Schema is missing an `id` property");Y.$id=$.external.uri(K)}Object.assign(Y,q.def??q.schema);let J=$.metadataRegistry.get(I)?.id;if(J!==void 0&&Y.id===J)delete Y.id;let Q=$.external?.defs??{};for(let K of $.seen.entries()){let w=K[1];if(w.def&&w.defId){if(w.def.id===w.defId)delete w.def.id;Q[w.defId]=w.def}}if($.external);else if(Object.keys(Q).length>0)if($.target==="draft-2020-12")Y.$defs=Q;else Y.definitions=Q;try{let K=JSON.parse(JSON.stringify(Y));return Object.defineProperty(K,"~standard",{value:{...I["~standard"],jsonSchema:{input:vI(I,"input",$.processors),output:vI(I,"output",$.processors)}},enumerable:!1,writable:!1}),K}catch(K){throw Error("Error converting schema to JSON.")}}function P6($,I){let q=I??{seen:new Set};if(q.seen.has($))return!1;q.seen.add($);let U=$._zod.def;if(U.type==="transform")return!0;if(U.type==="array")return P6(U.element,q);if(U.type==="set")return P6(U.valueType,q);if(U.type==="lazy")return P6(U.getter(),q);if(U.type==="promise"||U.type==="optional"||U.type==="nonoptional"||U.type==="nullable"||U.type==="readonly"||U.type==="default"||U.type==="prefault")return P6(U.innerType,q);if(U.type==="intersection")return P6(U.left,q)||P6(U.right,q);if(U.type==="record"||U.type==="map")return P6(U.keyType,q)||P6(U.valueType,q);if(U.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return P6(U.in,q)||P6(U.out,q)}if(U.type==="object"){for(let Y in U.shape)if(P6(U.shape[Y],q))return!0;return!1}if(U.type==="union"){for(let Y of U.options)if(P6(Y,q))return!0;return!1}if(U.type==="tuple"){for(let Y of U.items)if(P6(Y,q))return!0;if(U.rest&&P6(U.rest,q))return!0;return!1}return!1}var yM=($,I={})=>(q)=>{let U=e5({...q,processors:I});return j1($,U),$9(U,$),I9(U,$)},vI=($,I,q={})=>(U)=>{let{libraryOptions:Y,target:J}=U??{},Q=e5({...Y??{},target:J,io:I,processors:q});return j1($,Q),$9(Q,$),I9(Q,$)};var kL0={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},uM=($,I,q,U)=>{let Y=q;Y.type="string";let{minimum:J,maximum:Q,format:K,patterns:w,contentEncoding:z}=$._zod.bag;if(typeof J==="number")Y.minLength=J;if(typeof Q==="number")Y.maxLength=Q;if(K){if(Y.format=kL0[K]??K,Y.format==="")delete Y.format;if(K==="time")delete Y.format}if(z)Y.contentEncoding=z;if(w&&w.size>0){let G=[...w];if(G.length===1)Y.pattern=G[0].source;else if(G.length>1)Y.allOf=[...G.map((H)=>({...I.target==="draft-07"||I.target==="draft-04"||I.target==="openapi-3.0"?{type:"string"}:{},pattern:H.source}))]}},xM=($,I,q,U)=>{let Y=q,{minimum:J,maximum:Q,format:K,multipleOf:w,exclusiveMaximum:z,exclusiveMinimum:G}=$._zod.bag;if(typeof K==="string"&&K.includes("int"))Y.type="integer";else Y.type="number";let H=typeof G==="number"&&G>=(J??Number.NEGATIVE_INFINITY),V=typeof z==="number"&&z<=(Q??Number.POSITIVE_INFINITY),W=I.target==="draft-04"||I.target==="openapi-3.0";if(H)if(W)Y.minimum=G,Y.exclusiveMinimum=!0;else Y.exclusiveMinimum=G;else if(typeof J==="number")Y.minimum=J;if(V)if(W)Y.maximum=z,Y.exclusiveMaximum=!0;else Y.exclusiveMaximum=z;else if(typeof Q==="number")Y.maximum=Q;if(typeof w==="number")Y.multipleOf=w},kM=($,I,q,U)=>{q.type="boolean"},fM=($,I,q,U)=>{if(I.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},nM=($,I,q,U)=>{if(I.unrepresentable==Line truncated
`);if($===-1)return null;let I=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),Qv0(I)}clear(){this._buffer=void 0}}function Qv0($){return Rf.parse(JSON.parse($))}function Bc($){return JSON.stringify($)+`
`}class eP{constructor($=vc.stdin,I=vc.stdout){this._stdin=$,this._stdout=I,this._readBuffer=new sP,this._started=!1,this._ondata=(q)=>{this._readBuffer.append(q),this.processReadBuffer()},this._onerror=(q)=>{this.onerror?.(q)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((I)=>{let q=Bc($);if(this._stdout.write(q))I();else this._stdout.once("drain",I)})}}import{dirname as _u,join as dz1}from"node:path";import{fileURLToPath as lz1}from"node:url";class q5 extends Error{name="KyError";get isKyError(){return!0}}class i6 extends q5{name="HTTPError";response;request;options;data;constructor($,I,q){let U=$.status||$.status===0?$.status:"",Y=$.statusText??"",J=`${U} ${Y}`.trim(),Q=J?`status code ${J}`:"an unknown error";super(`Request failed with ${Q}: ${I.method} ${I.url}`);this.response=$,this.request=I,this.options=q}}class aJ extends q5{name="NetworkError";request;constructor($,I){super(`Request failed due to a network error: ${$.method} ${$.url}`,I);this.request=$}}class sJ extends Error{name="NonError";value;constructor($){let I="Non-error value was thrown";try{if(typeof $==="string")I=$;else if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string")I=$.message}catch{}super(I);this.value=$}}class qq extends q5{name="ForceRetryError";customDelay;code;customRequest;constructor($){let I=$?.cause?$.cause instanceof Error?$.cause:new sJ($.cause):void 0;super($?.code?`Forced retry: ${$.code}`:"Forced retry",I?{cause:I}:void 0);this.customDelay=$?.delay,this.code=$?.code,this.customRequest=$?.request}}class $T extends Error{name="SchemaValidationError";issues;constructor($){super("Response schema validation failed");this.issues=$}}class p$ extends q5{name="TimeoutError";request;constructor($){super(`Request timed out: ${$.method} ${$.url}`);this.request=$}}var IT=(()=>{let $=!1,I=!1,q=typeof globalThis.ReadableStream==="function",U=typeof globalThis.Request==="function";if(q&&U)try{I=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return $=!0,"half"}}).headers.has("Content-Type")}catch(Y){if(Y instanceof Error&&Y.message==="unsupported BodyInit type")return!1;throw Y}return $&&!I})(),Rc=typeof globalThis.AbortController==="function",XH=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",Cc=typeof globalThis.ReadableStream==="function",_c=typeof globalThis.FormData==="function",DH=["get","post","put","patch","head","delete"],Kv0=()=>{return};Kv0();var hc={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Uq=2147483647,Sc=40,OH=Symbol("stop");class LH{options;constructor($){this.options=$}}var yc=($)=>new LH($),uc={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},xc={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var NH=new TextEncoder,wv0=($)=>{if(!$)return 0;if($ instanceof FormData){let I=0;for(let[q,U]of $)I+=Sc,I+=NH.encode(`Content-Disposition: form-data; name="${q}"`).byteLength,I+=typeof U==="string"?NH.encode(U).byteLength:U.size;return I}if($ instanceof Blob)return $.size;if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return $.byteLength;if(typeof $==="string")return NH.encode($).byteLength;if($ instanceof URLSearchParams)return NH.encode($.toString()).byteLength;return 0},kc=($,I,q)=>{let U,Y=0;return $.pipeThrough(new TransformStream({transform(J,Q){if(Q.enqueue(J),U){Y+=U.byteLength;let K=I===0?0:Y/I;if(K>=1)K=1-Number.EPSILON;q?.({percent:K,totalBytes:Math.max(I,Y),transferredBytes:Y},U)}U=J},flush(){if(U)Y+=U.byteLength,q?.({percent:1,totalBytes:Math.max(I,Y),transferredBytes:Y},U)}}))},fc=($,I)=>{if(!$.body)return $;let q={status:$.status,statusText:$.statusText,headers:$.headers};if($.status===204)return new Response(null,q);let U=Math.max(0,Number($.headers.get("content-length"))||0);return new Response(kc($.body,U,I),q)},nc=($,I,q)=>{if(!$.body)return $;let U=wv0(q??$.body);return new Request($,{duplex:"half",body:kc($.body,U,I)})};var H8=($)=>$!==null&&typeof $==="object";var zv0=Symbol("replaceOption"),qT=($)=>H8($)&&$[zv0]===!0?{isReplace:!0,value:$.value}:{isReplace:!1,value:$};var $Q=(...$)=>{for(let I of $)if( Line truncated
`,{mode:384}),I}function Gq($,I,q=[]){let U=I.corpId?.trim()||void 0,Y=I.stateful?I.defaultCorpId?.trim()||void 0:void 0,J=U??Y;if(J){let K=$.find((w)=>w.id===J);if(K)return K;throw Error(`No enterprise config found for ${J}`)}if(!I.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-home config mode stateful` to enable a default enterprise.");let Q=$[0];if(Q)return Q;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(q.length?q.join(", "):"the configured enterprise directories"))}import{readFileSync as Zw1}from"node:fs";import{randomBytes as Xw1}from"node:crypto";import{randomBytes as ed}from"node:crypto";var YR0=Z.object({staffId:Z.string(),name:Z.string().optional(),code:Z.string().default(""),bindTime:Z.number().optional()}),JR0=Z.object({id:Z.string(),tenantId:Z.string(),name:Z.string(),isAdmin:Z.boolean().default(!1),permissions:Z.array(Z.string()).default([]),providerUserId:Z.string().optional(),hosecloudStaff:YR0.optional()}),QR0=Z.object({apiKey:Z.string().optional(),corporationId:Z.string().optional(),corporationName:Z.string().optional()}),KR0=Z.object({id:Z.string(),name:Z.string(),tenantSlug:Z.string().optional(),isDemo:Z.boolean().default(!1),logoUrl:Z.string().nullable().optional(),hoseCorpConfig:QR0.optional()}),Cd=Z.object({user:JR0,tenant:KR0}),wR0=Z.object({id:Z.string(),name:Z.string(),email:Z.string().nullable().optional(),emailVerified:Z.boolean().optional(),image:Z.string().nullable().optional(),tenantId:Z.string().optional(),provider:Z.string().optional(),providerUserId:Z.string().optional(),mobile:Z.string().nullable().optional(),status:Z.string().optional(),permissions:Z.array(Z.string()).default([]),isAdmin:Z.boolean().default(!1),hosecloudStaff:Z.unknown().optional()}).passthrough(),zR0=Z.object({id:Z.string(),token:Z.string().optional(),expiresAt:Z.string(),createdAt:Z.string().optional(),updatedAt:Z.string().optional(),ipAddress:Z.string().optional(),userAgent:Z.string().optional(),userId:Z.string(),delegationId:Z.string().nullable().optional()}).passthrough(),_d=Z.object({user:wR0,session:zR0}),yH=Z.object({id:Z.string(),tenantId:Z.string().optional(),code:Z.number().optional(),description:Z.string(),scope:Z.string(),strictness:Z.string(),status:Z.string().optional(),createdAt:Z.number().optional(),updatedAt:Z.number().optional()}),hd=Z.object({rules:Z.array(yH),hasPendingDeletes:Z.boolean().default(!1)}),GR0=Z.object({code:Z.string().optional(),description:Z.string(),scope:Z.string(),strictness:Z.string()}),uH=Z.object({id:Z.string(),tenantId:Z.string().optional(),versionNumber:Z.number(),versionName:Z.string().nullable().optional(),publishedBy:Z.string().nullable().optional(),publishedByName:Z.string().nullable().optional(),rules:Z.array(GR0).default([]),publishedAt:Z.number().optional(),createdAt:Z.number().optional()}),Sd=Z.object({version:uH,rulesCount:Z.number()}),wQ=Z.object({id:Z.string(),tenantId:Z.string().optional(),title:Z.string(),purpose:Z.string().default(""),contentType:Z.string().default("policy"),content:Z.string(),status:Z.string().default("published"),enabled:Z.boolean().default(!0),scenarios:Z.array(Z.string()).default([]),tags:Z.array(Z.string()).default([]),category:Z.string().nullable().optional(),categoryTags:Z.array(Z.string()).default([]),createdBy:Z.string().nullable().optional(),createdByName:Z.string().nullable().optional(),createdAt:Z.number().optional(),updatedAt:Z.number().optional(),updatedBy:Z.string().nullable().optional(),updatedByName:Z.string().nullable().optional(),isDeleted:Z.boolean().default(!1)}),yd=Z.object({articles:Z.array(wQ),total:Z.number().optional()}),HR0=Z.object({explicitApprove:Z.string().default(""),explicitReject:Z.string().default(""),exemptApprove:Z.string().default(""),review:Z.string().default("")}).passthrough(),VR0=Z.object({type:Z.string(),signKey:Z.string().optional(),outboundName:Z.string().optional(),mode:Z.string().optional(),autoApprovalRate:Z.number().optional(),apiKey:Z.string().optional(),apiSecret:Z.string().optional(),apiOrigin:Z.string().optional(),corporationId:Z.string().optional(),ebotSignKey:Z.string().optional(),completionSignKey:Z.string().optional(),outboundMessageId:Z.string().optional(),completionMessageId:Z.string().optional()}).passthrough(),WR0=Z.enum(["assisted","semi_automatic","fully_automatic"]),Rd=Z.object({id:Z.string(),url:Z.string().url()}).passthrough(),zQ=Z.object({type:Z.literal("webhook"),id:Z.string(),name:Z.string(),mode:WR0,incomingDocumentWebhook:Rd,outgoingResultWebhook:Z.string().url(),incomingManualResultWebhook:Rd,secret:Z.string().min(1),autoApprovalRate:Z.number().int().min(0).max(100).optional()}).passthrough(),FT=Z.object({id:Z.string().optional(),tenantId:Z.string().optional(),tone:Z.string().optional(),language:Z.string().optional(),detailLevel:Z.string().optional(),outputFormat:Z.string().optional(),examples:Z.array(Z.string()).default([]),prohibitedPhrases:Z.array(Z.strin Line truncated
`,"utf8"),q}function ll($){return $.map((I,q)=>{let U;if(typeof I.code==="number")U=`#${String(I.code).padStart(4,"0")}`;else if(typeof I.code==="string")U=I.code.startsWith("#")?I.code:`#${I.code}`;else U=`#${String(q+1).padStart(4,"0")}`;return{id:I.id,code:U,name:I.name,description:I.description,scope:I.scope,strictness:I.strictness}})}class f7 extends Error{errors;warnings;constructor($,I=[]){super(`材料包校验失败:${$.length} 个错误`);this.errors=$;this.warnings=I;this.name="MaterialPackValidationError"}}import{createHmac as $C0,randomBytes as IC0}from"node:crypto";function qC0($,I,q,U){return $C0("sha256",U).update(`${$}.${I}.${JSON.stringify(q)}`).digest("hex")}function pT($,I){let q=Math.floor(Date.now()/1000),U=IC0(16).toString("hex");return{Authorization:`Bearer ${I}`,"x-webhook-signature":qC0(q,U,$,I),"x-webhook-timestamp":String(q),"x-webhook-nonce":U}}var hE=RY(Vm(),1),Io=RY($o(),1);var wV={maxEntries:1000,maxTotalSize:524288000,maxCompressionRatio:150};async function qo($){return new Promise((I,q)=>{hE.default.fromBuffer(Buffer.from($),{lazyEntries:!0,autoClose:!0},(U,Y)=>{if(U||!Y)return q(U??Error("无法打开 ZIP"));let J=[];Y.readEntry(),Y.on("entry",(Q)=>{let K=Uo(Q);if(!K.endsWith("/")&&!C_0(K))J.push({fileName:K,uncompressedSize:Q.uncompressedSize,compressedSize:Q.compressedSize,raw:Q});Y.readEntry()}),Y.on("end",()=>I(J)),Y.on("error",q)})})}function Uo($){if($.fileNameUTF8||$.generalPurposeBitFlag&2048)return $.fileNameUTF8??$.fileName;let I=Buffer.from(String($.fileName),"binary"),q=I.toString("utf8");if(q.includes("�")||/[\u0080-\u00FF]/.test(q)){let U=Io.default.decode(I,"gbk");if(!U.includes("�"))return U}return q}function C_0($){let I=$.split("/").pop()??"";return $.split("/").includes("__MACOSX")||I===".DS_Store"||I.startsWith("._")||I.startsWith(".~")||I.startsWith("~$")}function Yo($){let I=[];if($.length>wV.maxEntries)I.push(`文件数超过 ${wV.maxEntries}`);if($.reduce((Y,J)=>Y+J.uncompressedSize,0)>wV.maxTotalSize)I.push("解压后总大小超过 500MB");for(let Y of $){if(Y.fileName.startsWith("/")||Y.fileName.split("/").includes(".."))I.push(`存在不安全路径: ${Y.fileName}`);if(Y.compressedSize>0&&Y.uncompressedSize/Y.compressedSize>wV.maxCompressionRatio)I.push(`压缩比超过 150: ${Y.fileName}`)}if(!$.find((Y)=>Y.fileName==="信息表.xlsx"))I.push("ZIP 根目录缺少精确名为「信息表.xlsx」的文件");if($.some((Y)=>Y.fileName.toLowerCase().endsWith(".zip")))I.push("不允许嵌套 ZIP");if(I.length)throw new f7(I)}function SE($,I){return new Promise((q,U)=>{hE.default.fromBuffer(Buffer.from($),{lazyEntries:!0,autoClose:!0},(Y,J)=>{if(Y||!J)return U(Y??Error("无法打开 ZIP"));J.readEntry(),J.on("entry",(Q)=>{if(Uo(Q)!==I.fileName)return J.readEntry();J.openReadStream(Q,(K,w)=>{if(K||!w)return U(K??Error(`无法读取 ${I.fileName}`));let z=[];w.on("data",(G)=>z.push(G)),w.on("end",()=>q(Buffer.concat(z))),w.on("error",U)})}),J.on("error",U)})})}var vV0=RY(jV0(),1);function sD($,I,q,U){return{key:$,label:I,type:q,value:U}}function RV0($,I,q){return sD($,I,"TEXT",q==null?"":String(q))}function CV0($,I,q){return sD($,I,"AMOUNT",typeof q==="number"?{amount:q,currency:"CNY"}:null)}function _V0($){if($ instanceof Date)return $.toISOString();if(typeof $==="string"&&$.trim())return $.trim();return null}function bK1($){if($ instanceof Date)return Math.floor($.getTime()/1000);if(typeof $==="string"&&$.trim()){let I=Date.parse($.trim().replace(" ","T"));if(Number.isFinite(I))return Math.floor(I/1000)}return null}function DY($){let I=new Map;return $.getRow(1).eachCell((q,U)=>I.set(String(q.value??"").trim(),U)),I}function OY($,I,q){let U=I.get(q);return U?$.getCell(U).value:void 0}function pK1($,I){return[["会议编号","meeting_id","TEXT"],["会议名称","meeting_name","TEXT"],["状态","status","TEXT"],["总金额","total_amount","AMOUNT"],["税前劳务总额","pretax_labor_total","AMOUNT"],["报销事由","reimbursement_reason","TEXT"],["po码","po_code","TEXT"],["快递单号","tracking_number","TEXT"],["申请日期","application_date","DATE"],["更新日期","updated_date","DATE"]].flatMap(([U,Y,J])=>{let Q=OY($,I,U);if(Q==null||Q==="")return[];return[J==="TEXT"?RV0(Y,U,Q):J==="AMOUNT"?CV0(Y,U,Q):sD(Y,U,J,_V0(Q))]})}function BV0($,I,q){return q.flatMap(([U,Y,J])=>{let Q=OY($,I,U);if(Q==null||Q==="")return[];return[J==="TEXT"?RV0(Y,U,Q):J==="AMOUNT"?CV0(Y,U,Q):sD(Y,U,J,_V0(Q))]})}var cK1=[["姓名","name","TEXT"],["身份证号码","id_number","TEXT"],["手机号","phone","TEXT"],["劳务费用","labor_fee","AMOUNT"],["税前费用","pretax_fee","AMOUNT"],["开户行","bank","TEXT"],["支行名称","branch_name","TEXT"],["联行号","bank_code","TEXT"],["银行卡号","bank_card_number","TEXT"]],dK1=[["报销金额","reimbursement_amount","AMOUNT"],["费用类型","expense_type","TEXT"],["发生时间","occurrence_time","DATE"],["收款人","payee","TEXT"],["开户行","bank","TEXT"],["支行名称","branch_name","TEXT"],["支行行 Line truncated
`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:NY({id:I?.id,sn:I?.sn??I?.sourceDocumentSN??$.sourceDocumentSN,title:I?.title??I?.name,template:zO(I,["template.name","templateName","form.name","formName","formTitle"]),amount:KO(q,["金额","报销金额","付款金额","合计","价税合计"])??zO(I,["amount","totalAmount","expenseAmount"]),expenseType:KO(q,["费用类型","费用类别","报销类型"]),costCompany:KO(q,["费用承担公司","承担公司","成本中心","费用归属"]),payee:KO(q,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:q.slice(0,30)}),invoices:Cw1($),attachments:JO($,{summary:!0}).attachments,aiResult:HO($),manualResult:II($)?.value,hints:NY({amountMentions:kW0(U,["金额","合计","税率"],8),partyMentions:kW0(U,["买方","卖方","甲方","乙方","收款"],8)})}}function jw1($){let I=[["result.citedRules",b5($,"result.citedRules")],["result.matchedRules",b5($,"result.matchedRules")],["result.ruleResults",b5($,"result.ruleResults")],["result.rules",b5($,"result.rules")],["pipelineData.citedRules",b5($,"pipelineData.citedRules")],["pipelineData.matchedRules",b5($,"pipelineData.matchedRules")]],q=[],U=new Set;for(let[Y,J]of I)(Array.isArray(J)?J:J&&typeof J==="object"?Object.values(J):[]).forEach((K,w)=>{let z=Hw(K);if(!z)return;let G=$4(z.runtimeRuleId)??$4(z.runtimeId)??$4(z.id)??$4(z.ruleId),H=$4(z.ruleCode)??$4(z.code)??(G?Sw1(G):void 0),V=NY({runtimeRuleId:G,ruleCode:H,versionNumber:vw1(z.versionNumber)??$.ruleSetVersionNumber,scope:$4(z.scope),strictness:$4(z.strictness),appliedAnalysis:z.appliedAnalysis??z.analysis??z.reasoning,checkResult:z.checkResult??z.result??z.decision,findings:z.findings??z.riskPoints??z.evidence,sourcePath:`${Y}.${w}`}),W=JSON.stringify(V);if(!U.has(W))U.add(W),q.push(V)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:q.length,rules:q}}function zO($,I){if(!$)return;for(let q of I){let U=b5($,q);if(U!==void 0)return U}return}function xW0($,I){if(!$)return 0;for(let q of I){let U=b5($,q);if(Array.isArray(U))return U.length;if(U&&typeof U==="object")return Object.keys(U).length;if(typeof U==="number")return U}return 0}function b5($,I){return I.split(".").reduce((q,U)=>{if(q===void 0||q===null)return;if(Array.isArray(q)){let Y=Number(U);return Number.isInteger(Y)?q[Y]:void 0}if(typeof q==="object")return q[U];return},$)}function Bw1($,I,q){let U=I.split("."),Y=$;for(let J of U.slice(0,-1)){let Q=Y[J];if(!Q||typeof Q!=="object"||Array.isArray(Q))Y[J]={};Y=Y[J]}Y[U[U.length-1]??I]=q}function NY($){return Object.fromEntries(Object.entries($).filter(([,I])=>I!==void 0))}function Hw($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function vw1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Rw1($){let I=[];return Uu($,"document",I),I}function Uu($,I,q){if(Array.isArray($)){$.forEach((Q,K)=>Uu(Q,`${I}.${K}`,q));return}let U=Hw($);if(!U)return;let Y=$4(U.label)??$4(U.name)??$4(U.title)??$4(U.fieldName),J=U.value??U.displayValue??U.text??U.content;if(Y&&J!==void 0&&typeof J!=="object")q.push(NY({path:I,label:Y,value:J,type:$4(U.type)??$4(U.fieldType)}));for(let[Q,K]of Object.entries(U)){if(Q==="attachments")continue;Uu(K,`${I}.${Q}`,q)}}function KO($,I){return $.find((U)=>{let Y=$4(U.label)??"";return I.some((J)=>Y.includes(J))})?.value}function Cw1($){let I=[];return GO($.result,"result",I),GO($.document,"document",I),I.slice(0,20)}function GO($,I,q){if(Array.isArray($)){$.forEach((Y,J)=>GO(Y,`${I}.${J}`,q));return}let U=Hw($);if(!U)return;if(/invoice|发票/i.test(I))q.push(NY({path:I,fileName:$4(U.fileName)??$4(U.filename)??$4(U.name),buyer:U.buyer??U.buyerName??U.purchaserName,seller:U.seller??U.sellerName,amount:U.amount??U.totalAmount??U.total,taxRate:U.taxRate,category:U.category??U.type}));for(let[Y,J]of Object.entries(U))GO(J,`${I}.${Y}`,q)}function kW0($,I,q){return $.split(/\r?\n/).filter((U)=>I.some((Y)=>U.includes(Y))).slice(0,q)}function wO($){return $.map((I)=>{let q=$I(I);return{recordId:q.id,tenantId:q.tenantId,agentId:q.agentId,sourceDocumentSN:q.sourceDocumentSN,sourceDocumentId:q.sourceDocumentId,simulationBatchId:q.simulationBatchId,langfuseTraceId:q.langfuseTraceId,langfuseSessionFallback:q.langfuseSessionFallback,ruleSetVersionNumber:q.ruleSetVersionNumber,ruleSetPublishedAt:q.ruleSetPublishedAt,ruleSetPublishedByName:q.ruleSetPublishedByName,resolution:q.langfuseTraceId?"trace":q.langfuseSessionFallback?"session-fallback":"unresolved"}})}function Iu($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function _w1($,I){if(I.recordId&&!I.versionId&&!I.versionNumber&&!I.latest){let q=await N$($,I.recordId);if(!q.ruleSetVersionNumber)throw Er Line truncated
`)}
`}function Zw($){return $.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function v0($,I={}){mw1($,I);let q=`${JSON.stringify($,null,2)}
`;if(I.outputFile){pw1(I.outputFile,q),console.log(JSON.stringify({outputFile:I.outputFile,bytes:Buffer.byteLength(q,"utf-8")},null,2));return}console.log(q.trimEnd())}function mw1($,I={}){if(I.allowFull||I.outputFile)return;let q=Buffer.byteLength(JSON.stringify($),"utf-8");if(q>lw1)throw Error(`Output is large (${q} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function wZ0($,I){if(I)return;let q=$&&typeof $==="object"?$:{},U=typeof q.count==="number"?q.count:void 0,Y=Array.isArray(q.rules)?q.rules.length:void 0,J=Buffer.byteLength(JSON.stringify($),"utf-8"),Q=U??Y??0;if(Q>cw1||J>dw1)throw Error(`Rule list is large (${Q} rules, ${J} bytes). Use "seal-use rules list --summary" or "seal-use rules count"; pass --full only when you really need full descriptions.`)}function O0($){return{allowFull:C0($.full)===!0,outputFile:x($.outputFile)??x($["output-file"])}}function zZ0(){console.log(`seal-use CLI
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let K of $.seen.entries()){let q=K[1];if(I===K[0]){Q(K);continue}if($.external){let G=$.external.registry.get(K[0])?.id;if(I!==K[0]&&G){Q(K);continue}}if($.metadataRegistry.get(K[0])?.id){Q(K);continue}if(q.cycle){Q(K);continue}if(q.count>1){if($.reused==="ref"){Q(K);continue}}}}function K9($,I){let U=$.seen.get(I);if(!U)throw Error("Unprocessed schema. This is a bug in Zod.");let Y=(q)=>{let H=$.seen.get(q);if(H.ref===null)return;let G=H.def??H.schema,W={...G},w=H.ref;if(H.ref=null,w){Y(w);let Z=$.seen.get(w),X=Z.schema;if(X.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))G.allOf=G.allOf??[],G.allOf.push(X);else Object.assign(G,X);if(Object.assign(G,W),q._zod.parent===w)for(let D in G){if(D==="$ref"||D==="allOf")continue;if(!(D in W))delete G[D]}if(X.$ref&&Z.def)for(let D in G){if(D==="$ref"||D==="allOf")continue;if(D in Z.def&&JSON.stringify(G[D])===JSON.stringify(Z.def[D]))delete G[D]}}let V=q._zod.parent;if(V&&V!==w){Y(V);let Z=$.seen.get(V);if(Z?.schema.$ref){if(G.$ref=Z.schema.$ref,Z.def)for(let X in G){if(X==="$ref"||X==="allOf")continue;if(X in Z.def&&JSON.stringify(G[X])===JSON.stringify(Z.def[X]))delete G[X]}}}$.override({zodSchema:q,jsonSchema:G,path:H.path??[]})};for(let q of[...$.seen.entries()].reverse())Y(q[0]);let J={};if($.target==="draft-2020-12")J.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")J.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")J.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let q=$.external.registry.get(I)?.id;if(!q)throw Error("Schema is missing an `id` property");J.$id=$.external.uri(q)}Object.assign(J,U.def??U.schema);let Q=$.metadataRegistry.get(I)?.id;if(Q!==void 0&&J.id===Q)delete J.id;let K=$.external?.defs??{};for(let q of $.seen.entries()){let H=q[1];if(H.def&&H.defId){if(H.def.id===H.defId)delete H.def.id;K[H.defId]=H.def}}if($.external);else if(Object.keys(K).length>0)if($.target==="draft-2020-12")J.$defs=K;else J.definitions=K;try{let q=JSON.parse(JSON.stringify(J));return Object.defineProperty(q,"~standard",{value:{...I["~standard"],jsonSchema:{input:pI(I,"input",$.processors),output:pI(I,"output",$.processors)}},enumerable:!1,writable:!1}),q}catch(q){throw Error("Error converting schema to JSON.")}}function v6($,I){let U=I??{seen:new Set};if(U.seen.has($))return!1;U.seen.add($);let Y=$._zod.def;if(Y.type==="transform")return!0;if(Y.type==="array")return v6(Y.element,U);if(Y.type==="set")return v6(Y.valueType,U);if(Y.type==="lazy")return v6(Y.getter(),U);if(Y.type==="promise"||Y.type==="optional"||Y.type==="nonoptional"||Y.type==="nullable"||Y.type==="readonly"||Y.type==="default"||Y.type==="prefault")return v6(Y.innerType,U);if(Y.type==="intersection")return v6(Y.left,U)||v6(Y.right,U);if(Y.type==="record"||Y.type==="map")return v6(Y.keyType,U)||v6(Y.valueType,U);if(Y.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return v6(Y.in,U)||v6(Y.out,U)}if(Y.type==="object"){for(let J in Y.shape)if(v6(Y.shape[J],U))return!0;return!1}if(Y.type==="union"){for(let J of Y.options)if(v6(J,U))return!0;return!1}if(Y.type==="tuple"){for(let J of Y.items)if(v6(J,U))return!0;if(Y.rest&&v6(Y.rest,U))return!0;return!1}return!1}var IA=($,I={})=>(U)=>{let Y=J9({...U,processors:I});return C1($,Y),Q9(Y,$),K9(Y,$)},pI=($,I,U={})=>(Y)=>{let{libraryOptions:J,target:Q}=Y??{},K=J9({...J??{},target:Q,io:I,processors:U});return C1($,K),Q9(K,$),K9(K,$)};var mF0={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},UA=($,I,U,Y)=>{let J=U;J.type="string";let{minimum:Q,maximum:K,format:q,patterns:H,contentEncoding:G}=$._zod.bag;if(typeof Q==="number")J.minLength=Q;if(typeof K==="number")J.maxLength=K;if(q){if(J.format=mF0[q]??q,J.format==="")delete J.format;if(q==="time")delete J.format}if(G)J.contentEncoding=G;if(H&&H.size>0){let W=[...H];if(W.length===1)J.pattern=W[0].source;else if(W.length>1)J.allOf=[...W.map((w)=>({...I.target==="draft-07"||I.target==="draft-04"||I.target==="openapi-3.0"?{type:"string"}:{},pattern:w.source}))]}},YA=($,I,U,Y)=>{let J=U,{minimum:Q,maximum:K,format:q,multipleOf:H,exclusiveMaximum:G,exclusiveMinimum:W}=$._zod.bag;if(typeof q==="string"&&q.includes("int"))J.type="integer";else J.type="number";let w=typeof W==="number"&&W>=(Q??Number.NEGATIVE_INFINITY),V=typeof G==="number"&&G<=(K??Number.POSITIVE_INFINITY),Z=I.target==="draft-04"||I.target==="openapi-3.0";if(w)if(Z)J.minimum=W,J.exclusiveMinimum=!0;else J.exclusiveMinimum=W;else if(typeof Q==="number")J.minimum=Q;if(V)if(Z)J.maximum=G,J.exclusiveMaximum=!0;else J.exclusiveMaximum=G;else if(typeof K==="number")J.maximum=K;if(typeof H==="number")J.multipleOf=H},JA=($,I,U,Y)=>{U.type="boolean"},QA=($,I,U,Y)=>{if(I.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},KA=($,I,U,Y)=>{if(I.unrepresentable==Line truncated
`);if($===-1)return null;let I=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),zC0(I)}clear(){this._buffer=void 0}}function zC0($){return rf.parse(JSON.parse($))}function mc($){return JSON.stringify($)+`
`}class OE{constructor($=lc.stdin,I=lc.stdout){this._stdin=$,this._stdout=I,this._readBuffer=new FE,this._started=!1,this._ondata=(U)=>{this._readBuffer.append(U),this.processReadBuffer()},this._onerror=(U)=>{this.onerror?.(U)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((I)=>{let U=mc($);if(this._stdout.write(U))I();else this._stdout.once("drain",I)})}}import{dirname as tu,join as XW1}from"node:path";import{fileURLToPath as LW1}from"node:url";class H5 extends Error{name="KyError";get isKyError(){return!0}}class H$ extends H5{name="HTTPError";response;request;options;data;constructor($,I,U){let Y=$.status||$.status===0?$.status:"",J=$.statusText??"",Q=`${Y} ${J}`.trim(),K=Q?`status code ${Q}`:"an unknown error";super(`Request failed with ${K}: ${I.method} ${I.url}`);this.response=$,this.request=I,this.options=U}}class q2 extends H5{name="NetworkError";request;constructor($,I){super(`Request failed due to a network error: ${$.method} ${$.url}`,I);this.request=$}}class H2 extends Error{name="NonError";value;constructor($){let I="Non-error value was thrown";try{if(typeof $==="string")I=$;else if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string")I=$.message}catch{}super(I);this.value=$}}class LU extends H5{name="ForceRetryError";customDelay;code;customRequest;constructor($){let I=$?.cause?$.cause instanceof Error?$.cause:new H2($.cause):void 0;super($?.code?`Forced retry: ${$.code}`:"Forced retry",I?{cause:I}:void 0);this.customDelay=$?.delay,this.code=$?.code,this.customRequest=$?.request}}class NE extends Error{name="SchemaValidationError";issues;constructor($){super("Response schema validation failed");this.issues=$}}class t$ extends H5{name="TimeoutError";request;constructor($){super(`Request timed out: ${$.method} ${$.url}`);this.request=$}}var ME=(()=>{let $=!1,I=!1,U=typeof globalThis.ReadableStream==="function",Y=typeof globalThis.Request==="function";if(U&&Y)try{I=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return $=!0,"half"}}).headers.has("Content-Type")}catch(J){if(J instanceof Error&&J.message==="unsupported BodyInit type")return!1;throw J}return $&&!I})(),oc=typeof globalThis.AbortController==="function",Aw=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",rc=typeof globalThis.ReadableStream==="function",tc=typeof globalThis.FormData==="function",Pw=["get","post","put","patch","head","delete"],XC0=()=>{return};XC0();var ac={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},DU=2147483647,sc=40,Tw=Symbol("stop");class Ew{options;constructor($){this.options=$}}var ec=($)=>new Ew($),$d={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},Id={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var Bw=new TextEncoder,LC0=($)=>{if(!$)return 0;if($ instanceof FormData){let I=0;for(let[U,Y]of $)I+=sc,I+=Bw.encode(`Content-Disposition: form-data; name="${U}"`).byteLength,I+=typeof Y==="string"?Bw.encode(Y).byteLength:Y.size;return I}if($ instanceof Blob)return $.size;if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return $.byteLength;if(typeof $==="string")return Bw.encode($).byteLength;if($ instanceof URLSearchParams)return Bw.encode($.toString()).byteLength;return 0},Ud=($,I,U)=>{let Y,J=0;return $.pipeThrough(new TransformStream({transform(Q,K){if(K.enqueue(Q),Y){J+=Y.byteLength;let q=I===0?0:J/I;if(q>=1)q=1-Number.EPSILON;U?.({percent:q,totalBytes:Math.max(I,J),transferredBytes:J},Y)}Y=Q},flush(){if(Y)J+=Y.byteLength,U?.({percent:1,totalBytes:Math.max(I,J),transferredBytes:J},Y)}}))},Yd=($,I)=>{if(!$.body)return $;let U={status:$.status,statusText:$.statusText,headers:$.headers};if($.status===204)return new Response(null,U);let Y=Math.max(0,Number($.headers.get("content-length"))||0);return new Response(Ud($.body,Y,I),U)},Jd=($,I,U)=>{if(!$.body)return $;let Y=LC0(U??$.body);return new Request($,{duplex:"half",body:Ud($.body,Y,I)})};var D8=($)=>$!==null&&typeof $==="object";var DC0=Symbol("replaceOption"),AE=($)=>D8($)&&$[DC0]===!0?{isReplace:!0,value:$.value}:{isReplace:!1,value:$};var W2=(...$)=>{for(let I of $)if( Line truncated
`,{mode:384}),I}function WK1($){let I=sw0();for(let U of I){if(!D$(U))continue;for(let Y of oL(U).filter((J)=>J.endsWith(".json")).filter((J)=>!J.startsWith("example."))){let J=c8(U,Y);try{let Q=tL(J,"utf-8"),K=JSON.parse(Q);if(K&&typeof K==="object"&&K.id===$)return J}catch{}}}return}function O7($,I){let U=WK1($);if(!U)throw Error(`Enterprise config not found: ${$}`);let J={...JSON.parse(tL(U,"utf-8")),...I};for(let K of Object.keys(I))if(I[K]===void 0)delete J[K];let Q=Xh.parse(J);return mw0(U,`${JSON.stringify(Q,null,2)}
`,"utf-8"),Q}function NJ($,I,U=[]){let Y=I.corpId?.trim()||void 0,J=I.stateful?I.defaultCorpId?.trim()||void 0:void 0,Q=Y??J;if(Q){let q=$.find((H)=>H.id===Q);if(q)return q;throw Error(`No enterprise config found for ${Q}`)}if(!I.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-home config mode stateful` to enable a default enterprise.");let K=$[0];if(K)return K;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(U.length?U.join(", "):"the configured enterprise directories"))}import{readFileSync as CH1}from"node:fs";import{randomBytes as jH1}from"node:crypto";var IV0=300000,ew0=new Map;function wK1($,I){return $.map((U)=>U.trim()).filter(Boolean).map((U)=>I?U:U.toLowerCase())}function VK1($,I){return I?$:$.toLowerCase()}function ZK1($,I,U,Y){let J=VK1($,Y),Q=I.filter((K)=>J.includes(K));if(U==="all"&&Q.length!==I.length)return[];return Q}function zK1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function XK1($,I){if(I.fields&&!I.fields.has($.field))return[];let U=zK1($.value),Y=[];return U.forEach((J,Q)=>{let K=ZK1(J,I.keywords,I.matchMode,I.caseSensitive);if(K.length===0)return;let q=Math.max(0,Q-I.contextLines),H=Math.min(U.length,Q+I.contextLines+1),G={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:Q+1,matchedKeywords:K,matchedText:sL(J,I.maxChars),context:{before:I.snippetOnly?[]:U.slice(q,Q).map((W)=>sL(W,I.maxChars)),line:sL(J,I.maxChars),after:I.snippetOnly?[]:U.slice(Q+1,H).map((W)=>sL(W,I.maxChars))},metadata:$.metadata};if(I.snippetOnly)G.context={before:[],line:G.context.line,after:[]};Y.push(G)}),Y}function sL($,I){if(!I||$.length<=I)return $;return`${$.slice(0,Math.max(0,I))}...`}function LK1($){return[{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"description",value:$.description,metadata:{scope:$.scope,strictness:$.strictness,status:$.status}},{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"scope",value:$.scope,metadata:{strictness:$.strictness,status:$.status}}]}function $V0($){return $.rules.flatMap((I,U)=>{let Y=`${$.id}:${I.description.slice(0,32)}`,J={versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedByName:$.publishedByName,publishedAt:$.publishedAt,scope:I.scope,strictness:I.strictness,code:"code"in I?I.code:void 0,index:U};return[{area:"rules",entityType:"rule",entityId:Y,title:`${$.versionName} / ${I.scope}`,field:"history.description",value:I.description,metadata:J},{area:"rules",entityType:"rule",entityId:Y,title:`${$.versionName} / ${I.scope}`,field:"history.scope",value:I.scope,metadata:J}]})}function DK1($){return[{area:"documents",entityType:"document",entityId:$.id,title:$.title,field:"title",value:$.title,metadata:{status:$.status,scenarios:$.scenarios,tags:$.tags}},{area:"documents",entityType:"document",entityId:$.id,title:$.title,field:"purpose",value:$.purpose,metadata:{status:$.status,scenarios:$.scenarios,tags:$.tags}},{area:"documents",entityType:"document",entityId:$.id,title:$.title,field:"content",value:$.content,metadata:{status:$.status,scenarios:$.scenarios,tags:$.tags}}]}function FK1($){let I=[];if($.decisionPreferences)for(let[U,Y]of Object.entries($.decisionPreferences))I.push({area:"preferences",entityType:"preference",field:`decisionPreferences.${U}`,value:Y,metadata:{integrationSystem:$.integrationSystem}});return $.integrations.forEach((U,Y)=>{I.push({area:"preferences",entityType:"integration",title:U.outboundName,field:`integrations[${Y}]`,value:U,metadata:{type:U.type,outboundName:U.outboundName,mode:U.mode,corporationId:U.corporationId}})}),I}async function OK1($,I,U){let Y=U.ruleVersionScope??"current",J=[I.id,`ruleVersionScope=${Y}`,`ruleVersionId=${U.ruleVersionId??""}`,`ruleVersionNumber=${U.ruleVersionNumber??""}`,`latestRuleVersion=${U.latestRuleVersion??!1}`,`documentLimit=${U.documentLimit??100}`].join("|"),Q=ew0.get(J);if(!U.refresh&&Q&&Date.now()<Q.expiresAt)return Q;let[K,q,H]=await Promise.all([NK1($,{scope:Y,versionId:U.ruleVersionId,versionNumber:U.ruleVersionNumber,latest:U.latestRuleVersion}),O9($,{limit:U.documentLimit??100}),j1($,I.seal.endpoints.approvalStylePreferences)]),G=Date.now(),W={entries:[...K,...q.articles.flatMap(DK1),...FK1(H)],fetchedAt:G,expiresAt:G+IV0};return ew0.set(J,W),W}async function NK1($,I){if(I.scope==="current")return(await _6($)).rules.flatMap(LK1);if(I.scope==="version"){let Y=await MK1($,I);return $V0(Y)}return(await v$($)).flatMap($V0)}async function MK1($,I){if(I.versionId)return P2($,I.versionId);let U=await v$($),Y=I.versionNumber?U.find((J)=>J.versionNumber===I.versionNumber):U[0];if(!Y)throw Error(I.versionNumber?`Rule version not found: ${I.versionNumber}`:"No rule versions found");return Y}async function UV0($,I,U){let Y=U.matchMode??"any",J=U.caseSensitive??!1,Q=U.contextLines??3,K=new Set(U.areas??["rules","documents","preferences"]),q=U Line truncated
`,"utf8"),U}function HV0($){return $.map((I,U)=>{let Y;if(typeof I.code==="number")Y=`#${String(I.code).padStart(4,"0")}`;else if(typeof I.code==="string")Y=I.code.startsWith("#")?I.code:`#${I.code}`;else Y=`#${String(U+1).padStart(4,"0")}`;return{id:I.id,code:Y,name:I.name,description:I.description,scope:I.scope,strictness:I.strictness}})}class f$ extends Error{errors;warnings;constructor($,I=[]){super([`材料包校验失败:${$.length} 个错误`,...$.map((U)=>`- ${U}`)].join(`
`));this.errors=$;this.warnings=I;this.name="MaterialPackValidationError"}}import{createHmac as xK1,randomBytes as kK1}from"node:crypto";function fK1($,I,U,Y){return xK1("sha256",Y).update(`${$}.${I}.${JSON.stringify(U)}`).digest("hex")}function Th($,I){let U=Math.floor(Date.now()/1000),Y=kK1(16).toString("hex");return{Authorization:`Bearer ${I}`,"x-webhook-signature":fK1(U,Y,$,I),"x-webhook-timestamp":String(U),"x-webhook-nonce":Y}}var zu=OI(RV0(),1),DZ0=OI(LZ0(),1);var DD={maxEntries:1000,maxTotalSize:524288000,maxCompressionRatio:150};async function FZ0($){return new Promise((I,U)=>{zu.default.fromBuffer(Buffer.from($),{lazyEntries:!0,autoClose:!0,decodeStrings:!1},(Y,J)=>{if(Y||!J)return U(Y??Error("无法打开 ZIP"));let Q=[];J.readEntry(),J.on("entry",(K)=>{let q=OZ0(K);if(!q.endsWith("/")&&!zH1(q))Q.push({fileName:q,uncompressedSize:K.uncompressedSize,compressedSize:K.compressedSize,raw:K});J.readEntry()}),J.on("end",()=>I(Q)),J.on("error",U)})})}function OZ0($){let I=Buffer.isBuffer($.fileName)?$.fileName:Buffer.from(String($.fileName),"binary"),U=I.toString("utf8");if(!U.includes("�"))return U;let Y=DZ0.default.decode(I,"gbk");if(!Y.includes("�"))return Y;return U}function zH1($){let I=$.split("/").pop()??"";return $.split("/").includes("__MACOSX")||I===".DS_Store"||I.startsWith("._")||I.startsWith(".~")||I.startsWith("~$")}function NZ0($,I){let U=[],Y=AU(I);if($.length>DD.maxEntries)U.push(`文件数超过 ${DD.maxEntries}`);if($.reduce((K,q)=>K+q.uncompressedSize,0)>DD.maxTotalSize)U.push("解压后总大小超过 500MB");for(let K of $){if(K.fileName.startsWith("/")||K.fileName.split("/").includes(".."))U.push(`存在不安全路径: ${K.fileName}`);if(K.compressedSize>0&&K.uncompressedSize/K.compressedSize>DD.maxCompressionRatio)U.push(`压缩比超过 150: ${K.fileName}`);if(K.fileName==="信息表.xlsx")continue;XH1(K,Y,U)}if(!$.find((K)=>K.fileName==="信息表.xlsx"))U.push("ZIP 根目录缺少精确名为「信息表.xlsx」的文件");if($.some((K)=>K.fileName.toLowerCase().endsWith(".zip")))U.push("不允许嵌套 ZIP");if(U.length)throw new f$(U)}function XH1($,I,U){let Y=LH1($.fileName);if(!Y||!I.allowedExtensions.includes(Y))U.push(`附件后缀不在白名单中: ${$.fileName}(允许: ${I.allowedExtensions.join(", ")})`);if($.uncompressedSize<I.minFileSizeBytes)U.push(`附件文件过小: ${$.fileName}(${$.uncompressedSize} B,小于最小值 ${I.minFileSizeBytes} B)`);if(I.maxFileSizeBytes!==void 0&&I.maxFileSizeBytes!==null&&$.uncompressedSize>I.maxFileSizeBytes)U.push(`附件文件过大: ${$.fileName}(${$.uncompressedSize} B,大于最大值 ${I.maxFileSizeBytes} B)`)}function LH1($){let I=$.split("/").pop()??$,U=I.lastIndexOf(".");return U>0?I.slice(U).toLowerCase():""}function Xu($,I){return new Promise((U,Y)=>{zu.default.fromBuffer(Buffer.from($),{lazyEntries:!0,autoClose:!0,decodeStrings:!1},(J,Q)=>{if(J||!Q)return Y(J??Error("无法打开 ZIP"));Q.readEntry(),Q.on("entry",(K)=>{if(OZ0(K)!==I.fileName)return Q.readEntry();Q.openReadStream(K,(q,H)=>{if(q||!H)return Y(q??Error(`无法读取 ${I.fileName}`));let G=[];H.on("data",(W)=>G.push(W)),H.on("end",()=>U(Buffer.concat(G))),H.on("error",Y)})}),Q.on("error",Y)})})}var AZ0=OI(Wh(),1);function DH1($){return $.startsWith("[附件]")}function PZ0($){return $.startsWith("[附件]")?$.slice(4):$}function FH1($){return PZ0($).toLowerCase().replace(/\s+/g,"_")||"attachment"}function OH1($){if($==null||$==="")return[];return String($).split(/[\n,;,;]/).map((I)=>I.trim()).filter(Boolean)}function Lu($,I){let U=[];for(let[Y,J]of I.entries()){if(!DH1(Y))continue;let Q=$.getCell(J).value,K=OH1(Q);if(!K.length)continue;U.push({key:FH1(Y),label:PZ0(Y),paths:K})}return U}function Du($){let I=new Map;return $.map((U)=>{let Y=(I.get(U.key)??0)+1;return I.set(U.key,Y),Y===1?U:{...U,key:`${U.key}-${Y}`}})}function FD($,I,U,Y){return{key:$,label:I,type:U,value:Y}}function TZ0($,I,U){return FD($,I,"TEXT",U==null?"":String(U))}function EZ0($,I,U){return FD($,I,"AMOUNT",typeof U==="number"?{amount:U,currency:"CNY"}:null)}function BZ0($){if($ instanceof Date)return $.toISOString();if(typeof $==="string"&&$.trim())return $.trim();return null}function NH1($){if($ instanceof Date)return Math.floor($.getTime()/1000);if(typeof $==="string"&&$.trim()){let I=Date.parse($.trim().replace(" ","T"));if(Number.isFinite(I))return Math.floor(I/1000)}return null}function XH($){let I=new Map;return $.getRow(1).eachCell((U,Y)=>I.set(String(U.value??"").trim(),Y)),I}function HI($,I,U){let Y=I.get(U);return Y?$.getCell(Y).value:void 0}function MH1($,I){return[["会议编号","meeting_id","TEXT"],["会议名称","meeting_name","TEXT"],["状态","status","TEXT"],["总金额","total_amount","AMOUNT"],["税前劳务总额","pretax_labor_total","AMOUNT"],["报销事由","reimbursement_reason","TEXT"],["po码","po_code","TEXT"],["快递单号","tracking_number","TEXT"],["申请日期","application_date","DATE"],["更新日期","updated_date","DATE"] Line truncated
`);let O=new FormData,E=await Xu(Y.fileBuffer,D),T=L.split("/").pop()??L;O.append("files",new File([new Uint8Array(E)],T));let A=await fetch(`${J}/api/v1/integrations/webhook/${encodeURIComponent(Q)}/attachments`,{method:"POST",headers:Th({},U.secret),body:O});if(!A.ok)throw Error(`附件上传失败 ${A.status}: ${await A.text()}`);let R=await A.json();W.set(L,R.attachments?.map((k)=>k.data)??(R.data===void 0?[]:[R.data])),process.stderr.write(`✓ 附件上传成功: ${L}
`)}process.stderr.write(`\uD83D\uDCE4 推送单据: ${H.document.documentId}
`);let V=Fu(H.document,G,W),Z=await fetch(`${J}/api/v1/integrations/webhook/${encodeURIComponent(Q)}/document`,{method:"POST",headers:{"Content-Type":"application/json",...Th({webhookId:Q,...V},U.secret)},body:JSON.stringify(V)});if(!Z.ok)throw Error(`Webhook 单据推送失败 ${Z.status}: ${await Z.text()}`);K.push({documentId:V.documentId,document:V,pushResult:await Z.json()}),process.stderr.write(`✓ 单据推送成功: ${V.documentId}
`)}return{warnings:[],results:K}}function WI($){return{fileBuffer:TH1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}import{existsSync as RH1}from"node:fs";async function ND($,I,U={}){let J=F4().stateful?"stateful":"stateless",Q="ok",K,q,H;try{let A=await B$($);H={id:A.user.id,name:A.user.name,isAdmin:A.user.isAdmin},q={id:A.tenant.id,name:A.tenant.name,tenantSlug:A.tenant.tenantSlug,corporationName:A.tenant.hoseCorpConfig?.corporationName}}catch(A){Q="error",K=A instanceof Error?A.message:String(A)}let G=[];if(Q==="ok")try{G=await N9($,I.seal.endpoints.approvalStylePreferences)}catch(A){Q="error",K=`读取 Webhook 配置失败: ${A instanceof Error?A.message:String(A)}`}let W=G.length===1,w=G.map((A)=>({id:A.id,name:A.name,mode:A.mode,incomingDocumentWebhookUrl:A.incomingDocumentWebhook.url,outgoingResultWebhookUrl:A.outgoingResultWebhook,autoApprovalRate:A.autoApprovalRate,...W?{isDefault:!0}:{}})),V=W?{id:G[0].id,name:G[0].name,mode:G[0].mode}:null,Z=U.webhook?M9(G,U.webhook):W?G[0]:void 0,X;if(U.filePath)if(!RH1(U.filePath))X={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[`文件不存在: ${U.filePath}`]};else try{let A=WI(U.filePath),R=await GI(A.fileBuffer,A.fileName,Z?.materialPackFilePolicy);X={valid:!0,filePath:U.filePath,fileName:A.fileName,documentCount:R.documents.length,warnings:R.warnings}}catch(A){X={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[A instanceof Error?A.message:String(A)]}}let L=X?X.valid:!0,D=Q==="ok"&&w.length>0&&L,O=J==="stateful"?"":` --corp ${I.id}`,E="",T="";if(Q!=="ok")T=`凭证鉴权异常: ${K}`,E=`seal-use auth diagnose${O}`;else if(w.length===0)T="当前企业尚未配置任何 Webhook 集成通道",E=`seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${O}`;else if(X&&!X.valid)T=`材料包预检失败: ${X.errors?.join("; ")}`,E=`seal-use webhook material-pack preview ${X.filePath}${O}`;else{T=W?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到 ${w.length} 个 Webhook 通道,等待载入`;let A=X?.filePath??"<材料包.zip>",R=W?"":` --webhook ${V?V.id:"<webhookIdOrName>"}`;E=`seal-use webhook material-pack push ${A}${R}${O}`}return{ready:D,corp:{id:I.id,name:I.name,sourceType:I.source.type,tenant:q,user:H},stateMode:J,authStatus:Q,authError:K,activeWebhooks:w,defaultWebhook:V,materialPack:X,statusMessage:T,nextAction:E}}var DH=[{name:"seal_whoami",description:"查询当前 Seal 用户身份及租户信息",parameters:z.object({}),handler:async($)=>B$($)},{name:"seal_session_get",description:"查询当前 Seal Bearer session、用户和过期时间",parameters:z.object({}),handler:async($)=>Am($)},{name:"seal_delegation_list",description:"查询当前 Seal 租户下的授权链接 (Delegation) 列表",parameters:z.object({}),handler:async($)=>dm($)},{name:"seal_delegation_create",description:"创建新的 Seal 授权链接 (Delegation)",parameters:z.object({note:z.string().optional().describe("授权链接的备注或说明信息")}),handler:async($,I)=>PU($,I)},{name:"seal_delegation_revoke",description:"撤销/废除指定的 Seal 授权链接 (Delegation)",parameters:z.object({tokenId:z.string().describe("授权链接 ID (delegation record ID)")}),handler:async($,I)=>mm($,I.tokenId)},{name:"seal_user_create",description:"创建本地 Seal 用户,生成并返回初始随机密码",parameters:z.object({name:z.string().describe("用户姓名"),phone:z.string().describe("手机号码 (例如 13300001111 或 +8613300001111)"),permissions:z.array(z.string()).optional().describe("权限列表,默认为 []"),departmentIds:z.array(z.string()).optional().describe("关联部门 ID 数组")}),handler:async($,I)=>lm($,I)},{name:"seal_user_reset_password",description:"重置指定 Seal 用户的默认/随机密码,并返回生成的新密码",parameters:z.object({userId:z.string().describe("用户 ID (_id)")}),handler:async($,I)=>sE($,I.userId)},{name:"seal_user_get",description:"获取指定 Seal 用户的详细信息",parameters:z.object({userId:z.string().describe("用户 ID (_id)")}),handler:async($,I)=>pw($,I.userId)},{name:"seal_user_search",description:"按姓名、手机号或邮箱搜索 Seal 成员用户列表",parameters:z.object({keyword:z.string().optional().describe("搜索关键词(姓名、手机号、邮箱等),不传或传空字符串可列出租户成员")}),handler:async($,I)=>cw($,I.keyword??"")},{name:"seal_user_delete",description:"删除指定 Seal 本地用户",parameters:z.object({userId:z.string().describe("用户 ID (_id)")}),handler:async($,I)=>Jl($,I.userId)},{name:"seal_user_activate",description:"启用/激活已离职的 Seal 用户账号",parameters:z.object({userId:z.string().describe("用户 ID (_id)")}),handler:async($,I)=>eE($,I.userId)},{name:"seal_user_delegation_create",description:"为指定 S Line truncated
`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:jJ({id:I?.id,sn:I?.sn??I?.sourceDocumentSN??$.sourceDocumentSN,title:I?.title??I?.name,template:BD(I,["template.name","templateName","form.name","formName","formTitle"]),amount:AD(U,["金额","报销金额","付款金额","合计","价税合计"])??BD(I,["amount","totalAmount","expenseAmount"]),expenseType:AD(U,["费用类型","费用类别","报销类型"]),costCompany:AD(U,["费用承担公司","承担公司","成本中心","费用归属"]),payee:AD(U,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:U.slice(0,30)}),invoices:dH1($),attachments:FJ($,{summary:!0}).attachments,aiResult:RD($),manualResult:VI($)?.value,hints:jJ({amountMentions:gZ0(Y,["金额","合计","税率"],8),partyMentions:gZ0(Y,["买方","卖方","甲方","乙方","收款"],8)})}}function bH1($){let I=[["result.citedRules",l5($,"result.citedRules")],["result.matchedRules",l5($,"result.matchedRules")],["result.ruleResults",l5($,"result.ruleResults")],["result.rules",l5($,"result.rules")],["pipelineData.citedRules",l5($,"pipelineData.citedRules")],["pipelineData.matchedRules",l5($,"pipelineData.matchedRules")]],U=[],Y=new Set;for(let[J,Q]of I)(Array.isArray(Q)?Q:Q&&typeof Q==="object"?Object.values(Q):[]).forEach((q,H)=>{let G=FH(q);if(!G)return;let W=J4(G.runtimeRuleId)??J4(G.runtimeId)??J4(G.id)??J4(G.ruleId),w=J4(G.ruleCode)??J4(G.code)??(W?oH1(W):void 0),V=jJ({runtimeRuleId:W,ruleCode:w,versionNumber:pH1(G.versionNumber)??$.ruleSetVersionNumber,scope:J4(G.scope),strictness:J4(G.strictness),appliedAnalysis:G.appliedAnalysis??G.analysis??G.reasoning,checkResult:G.checkResult??G.result??G.decision,findings:G.findings??G.riskPoints??G.evidence,sourcePath:`${J}.${H}`}),Z=JSON.stringify(V);if(!Y.has(Z))Y.add(Z),U.push(V)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:U.length,rules:U}}function BD($,I){if(!$)return;for(let U of I){let Y=l5($,U);if(Y!==void 0)return Y}return}function SZ0($,I){if(!$)return 0;for(let U of I){let Y=l5($,U);if(Array.isArray(Y))return Y.length;if(Y&&typeof Y==="object")return Object.keys(Y).length;if(typeof Y==="number")return Y}return 0}function l5($,I){return I.split(".").reduce((U,Y)=>{if(U===void 0||U===null)return;if(Array.isArray(U)){let J=Number(Y);return Number.isInteger(J)?U[J]:void 0}if(typeof U==="object")return U[Y];return},$)}function nH1($,I,U){let Y=I.split("."),J=$;for(let Q of Y.slice(0,-1)){let K=J[Q];if(!K||typeof K!=="object"||Array.isArray(K))J[Q]={};J=J[Q]}J[Y[Y.length-1]??I]=U}function jJ($){return Object.fromEntries(Object.entries($).filter(([,I])=>I!==void 0))}function FH($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function pH1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function cH1($){let I=[];return Mu($,"document",I),I}function Mu($,I,U){if(Array.isArray($)){$.forEach((K,q)=>Mu(K,`${I}.${q}`,U));return}let Y=FH($);if(!Y)return;let J=J4(Y.label)??J4(Y.name)??J4(Y.title)??J4(Y.fieldName),Q=Y.value??Y.displayValue??Y.text??Y.content;if(J&&Q!==void 0&&typeof Q!=="object")U.push(jJ({path:I,label:J,value:Q,type:J4(Y.type)??J4(Y.fieldType)}));for(let[K,q]of Object.entries(Y)){if(K==="attachments")continue;Mu(q,`${I}.${K}`,U)}}function AD($,I){return $.find((Y)=>{let J=J4(Y.label)??"";return I.some((Q)=>J.includes(Q))})?.value}function dH1($){let I=[];return vD($.result,"result",I),vD($.document,"document",I),I.slice(0,20)}function vD($,I,U){if(Array.isArray($)){$.forEach((J,Q)=>vD(J,`${I}.${Q}`,U));return}let Y=FH($);if(!Y)return;if(/invoice|发票/i.test(I))U.push(jJ({path:I,fileName:J4(Y.fileName)??J4(Y.filename)??J4(Y.name),buyer:Y.buyer??Y.buyerName??Y.purchaserName,seller:Y.seller??Y.sellerName,amount:Y.amount??Y.totalAmount??Y.total,taxRate:Y.taxRate,category:Y.category??Y.type}));for(let[J,Q]of Object.entries(Y))vD(Q,`${I}.${J}`,U)}function gZ0($,I,U){return $.split(/\r?\n/).filter((Y)=>I.some((J)=>Y.includes(J))).slice(0,U)}function PD($){return $.map((I)=>{let U=wI(I);return{recordId:U.id,tenantId:U.tenantId,agentId:U.agentId,sourceDocumentSN:U.sourceDocumentSN,sourceDocumentId:U.sourceDocumentId,simulationBatchId:U.simulationBatchId,langfuseTraceId:U.langfuseTraceId,langfuseSessionFallback:U.langfuseSessionFallback,ruleSetVersionNumber:U.ruleSetVersionNumber,ruleSetPublishedAt:U.ruleSetPublishedAt,ruleSetPublishedByName:U.ruleSetPublishedByName,resolution:U.langfuseTraceId?"trace":U.langfuseSessionFallback?"session-fallback":"unresolved"}})}function Ou($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function mH1($,I){if(I.recordId&&!I.versionId&&!I.versionNumber&&!I.latest){let U=await i4($,I.recordId);if(!U.ruleSetVersionNumber)throw Er Line truncated
`)}function HG1($){let I=[];if(I.push(`seal-use ${$.area} - ${$.title}`),$.description)I.push($.description);I.push(""),I.push("Usage:");for(let U of $.commands)for(let Y of U.usage)I.push(` ${Y}`);return I.push(""),I.push(`Run 'seal-use ${$.area} <command> --help' for details on a specific command.`),I.join(`
`)}function Iz0(){return`seal-use CLI
Usage:
seal-use version
@@ -330,6 +335,8 @@ Usage:
seal-use config paths
seal-use config get
seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use config test-dir [<path>|--clear]
seal-use config lint [status|enable|disable] [--linter <name|path>] [--min-score <score>]
seal-use update [--check] [--force] [--version <v>]
seal-use update check
seal-use update changelog [--limit <n>]
@@ -338,6 +345,10 @@ Usage:
seal-use corps list [--corp <corpId>]
seal-use corps current [--corp <corpId>]
seal-use corps switch <corpId>
seal-use corps mark <corpId> --env <production|test> [--confirm]
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
seal-use corps unbind-test [<corpId>] [--confirm]
seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]
@@ -352,6 +363,12 @@ Usage:
seal-use users reset-password <userId> [--corp <corpId>]
seal-use users get <userId> [--corp <corpId>]
seal-use users delete <userId> [--corp <corpId>]
seal-use contacts departments [<departmentId>] [--corp <corpId>]
seal-use contacts children <departmentId> [--corp <corpId>]
seal-use contacts users <departmentId> [--corp <corpId>]
seal-use contacts sync-time [--corp <corpId>]
seal-use data expenses [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]
seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]
seal-use llm config [--corp <corpId>]
seal-use llm providers [--corp <corpId>]
seal-use permissions available [--corp <corpId>]
@@ -359,25 +376,27 @@ Usage:
seal-use billing status [--corp <corpId>]
seal-use billing plans [--corp <corpId>]
seal-use billing features [--corp <corpId>]
seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] [--corp <corpId>]
seal-use webhook status [<材料包.zip>] [--corp <corpId>]
seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]
seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]
seal-use webhook delete <idOrName> --yes [--corp <corpId>]
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--corp <corpId>]
seal-use webhook material-pack push <材料包.zip|信息表.xlsx> --webhook <idOrName> [--corp <corpId>]
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size 500] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp <corpId>]
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp <corpId>]
seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]
seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]
seal-use deploy hosecloud requirements [--corp <corpId>]
seal-use deploy hosecloud list [--corp <corpId>]
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
seal-use deploy hosecloud status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]
seal-use deploy hosecloud sync <sign-key> [--corp <corpId>]
seal-use preference get [--corp <corpId>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--corp <corpId>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth policies list [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--dry-run] [--corp <corpId>]
seal-use source config [--corp <corpId>]
seal-use tool <toolName> [--corp <corpId>] [--json '{"key":"value"}']
seal-use rules count [--corp <corpId>]
@@ -392,6 +411,7 @@ Usage:
seal-use approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] [--corp <corpId>]
seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] [--corp <corpId>]
seal-use approval-runs count [--status APPROVED] [--corp <corpId>]
seal-use approval-runs export [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--limit <n>] [--downloads] [--out <file>] [--corp <corpId>]
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]
seal-use approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]
@@ -400,28 +420,36 @@ Usage:
seal-use approval-runs attachments <recordId> [--summary] [--corp <corpId>]
seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] [--corp <corpId>]
seal-use approval-runs result <recordId> [--summary] [--corp <corpId>]
seal-use analytics insight [--start-date <ISO>] [--end-date <ISO>] [--limit <n>] [--corp <corpId>]
seal-use approval-runs url [--corp <corpId>]
seal-use approval-runs url <recordId> [--corp <corpId>]
seal-use approval-runs url --sourceDocumentSN B26022501 [--corp <corpId>]
seal-use approval-runs bridge [--sourceDocumentSN B26001887] [--corp <corpId>]
seal-use simulation batch-records <batchId> [--corp <corpId>]
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--corp <corpId>]
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--corp <corpId>]
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" [--corp <corpId>]
seal-use simulation status <batchId> [--corp <corpId>]
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] [--corp <corpId>]
seal-use simulation clean <batchId> [--corp <corpId>]
seal-use simulation specifications [--integration <sign-key>] [--corp <corpId>]
seal-use simulation approval-definitions [--corp <corpId>]
seal-use simulation list [--limit 50] [--corp <corpId>]
seal-use simulation get <batchId> [--corp <corpId>]
seal-use simulation templates [--corp <corpId>]
seal-use simulation integrations [--corp <corpId>]
seal-use simulation package-upload <材料包.zip> [--corp <corpId>]
`)}function O4($){let I=V8(),q=V6();return Gq(I,{stateful:q.stateful,defaultCorpId:q.defaultCorpId,corpId:$},u7())}function Xw($=V6()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},lint:$.lint,configFile:zq()}}async function L0($,I,q,U,Y={}){v0(await p8($,I,q,U),Y)}async function p8($,I,q,U){let Y=Gw.find((K)=>K.name===$);if(!Y)throw Error(`Unknown Seal tool: ${$}`);let J=Object.fromEntries(Object.entries(U).filter(([,K])=>K!==void 0)),Q=Y.handler;return Q(I,J,{corp:q})}async function GZ0($,I,q,U,Y){if($==="summary"){let J=await p8("seal_approval_runs_summary",q,U,{date:x(Y.options.date),timezone:x(Y.options.timezone),limit:e0(Y.options.limit),startDate:x(Y.options.startDate),endDate:x(Y.options.endDate),status:x(Y.options.status),taskMode:x(Y.options.taskMode),manualApprovalStatus:x(Y.options.manualApprovalStatus),sourceDocumentSN:x(Y.options.sourceDocumentSN),sourceDocumentId:x(Y.options.sourceDocumentId),humanResult:x(Y.options.humanResult),query:x(Y.options.query)});if(J?.matched===0&&J?.total>0)console.error(`提示:在 ${J.date} 未匹配到记录(该企业共有 ${J.total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-use approval-runs list --limit 10 查看最近记录。`);v0(J,O0(Y.options));return}if($==="stats"){await L0("seal_approval_runs_stats",q,U,{since:x(Y.options.since),dedupeBy:x(Y.options.dedupeBy)??x(Y.options["dedupe-by"]),status:x(Y.options.status),sourceSystem:x(Y.options.sourceSystem)??x(Y.options["source-system"]),taskMode:x(Y.options.taskMode)??x(Y.options["task-mode"])},O0(Y.options));return}if($==="count"){await L0("seal_approval_runs_count",q,U,{status:x(Y.options.status),sourceSystem:x(Y.options.sourceSystem)??x(Y.options["source-system"]),taskMode:x(Y.options.taskMode)??x(Y.options["task-mode"]),search:x(Y.options.search)??x(Y.options.query)},O0(Y.options));return}if($==="search"||$==="list"){await L0("seal_approval_runs_search",q,U,{limit:e0(Y.options.limit),offset:e0(Y.options.offset),startDate:x(Y.options.startDate),endDate:x(Y.options.endDate),status:x(Y.options.status),taskMode:x(Y.options.taskMode),manualApprovalStatus:x(Y.options.manualApprovalStatus),sourceDocumentSN:x(Y.options.sourceDocumentSN),sourceDocumentId:x(Y.options.sourceDocumentId),humanResult:x(Y.options.humanResult),query:x(Y.options.query),includeBridge:C0(Y.options.includeBridge)},O0(Y.options));return}if($==="bridge"){await L0("seal_approval_run_langfuse_bridge_get",q,U,{recordId:x(Y.options.recordId),sourceDocumentSN:x(Y.options.sourceDocumentSN),sourceDocumentId:x(Y.options.sourceDocumentId),simulationBatchId:x(Y.options.simulationBatchId),limit:e0(Y.options.limit)},O0(Y.options));return}if($==="pick"){let J=I??x(Y.options.query)??x(Y.options.sn);if(!J)throw Error("Usage: seal-use approval-runs pick --sn <documentSN>");await L0("seal_approval_run_pick",q,U,{query:J,sn:x(Y.options.sn),batchId:x(Y.options.batch)??x(Y.options.batchId),latest:C0(Y.options.latest),fields:x(Y.options.fields),limit:e0(Y.options.limit),includeBridge:C0(Y.options.includeBridge)},O0(Y.options));return}if($==="get"){let J=Y.command[2];if(!J)throw Error("Missing approval run recordId");await L0("seal_approval_run_get",q,U,{recordId:J,fields:x(Y.options.fields),summary:C0(Y.options.summary)},O0(Y.options));return}if($==="cited-rules"){let J=Y.command[2];if(!J)throw Error("Usage: seal-use approval-runs cited-rules <recordId>");await L0("seal_approval_run_cited_rules_get",q,U,{recordId:J},O0(Y.options));return}if($==="document-summary"){let J=Y.command[2];if(!J)throw Error("Usage: seal-use approval-runs document-summary <recordId>");await L0("seal_approval_run_document_summary_get",q,U,{recordId:J},O0(Y.options));return}if($==="attachments"){if(Y.command[2]==="download"){let K=Y.command[3];if(!K)throw Error("Usage: seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>]");let w=await p8("seal_approval_run_attachments_download",q,U,{recordId:K,all:C0(Y.options.all),name:x(Y.options.name),outDir:x(Y.options["out-dir"])??x(Y.options.outDir)??x(Y.options.dir)});if(v0(w,O0(Y.options)),w?.total>0&&w?.downloaded===0)throw Error(`所有 ${w.total} 个附件下载均失败。`);return}let Q=Y.command[2];if(!Q)throw Error("Usage: seal-use approval-runs attachments <recordId> | seal-use approval-runs attachments download <recordId>");if(C0(Y.options.download)){let K=await p8("seal_approval_run_attachments_download",q,U,{recordId:Q,all:C0(Y.options.all)??!0,name:x(Y.options.name),outDir:x(Y.options["out-dir"])??x(Y.options.outDir)??x(Y.options.dir)});if(v0(K,O0(Y.options)),K?.total>0&&K?.downloaded===0)throw Error(`所有 ${K.total} 个附件下载均失败。`);return}await L0("seal_approval_run_attachments_get",q,U,{recordId:Q,summary:C0(Y.options.summary)},O0(Y.options));return}if($==="download"){let J=Y.command[2];if(!J)throw Error("Usage: seal-use approval-runs download <reco Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${S.length} candidate administrators:
- ${t}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!D)if(!G&&J)D=J;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-use corps hose-staffs' to discover available administrators.");let O=i1($,"id")??V,N=W??V,T=i1($,"sealUrl")??`https://${V.toLowerCase()}.sealai.cc`,P={id:O,name:N,seal:{url:T,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:H,appKey:q,appSecurity:U,corpId:V,staffId:D},auth:{refreshTtl:300}};if(G)PH(O),await FY(P);let g=NT();FZ0(g,{recursive:!0,mode:448});let B=AZ0(g,`${Gu(O)}.json`);if(NZ0(B)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${B}. Pass "overwrite": true to replace it.`);MZ0(B,`${JSON.stringify(P,null,2)}
`,{mode:384}),v0({id:O,name:N,corpId:V,domain:H,staffId:D,verified:G,path:B})}async function $z1($){let I=X7($,"token"),q=(i1($,"sealUrl")??i1($,"url")??"").replace(/\/+$/,"");if(!q)throw Error("Missing required JSON field: sealUrl");let U=qZ0($,"expiresIn")??2592000,Y=$.force===!0||$.verify===!1?!1:!0,J=Y?await qz1(q,I):void 0;PZ0($,{token:I,sealUrl:q,expiresIn:U,verify:Y,remote:J})}async function Iz1($,I,q){let U=await TH($),Y=JQ(U.sealUrl,U.token),J=await Z8(Y),Q={user:J.user,tenant:J.tenant};EH(U.corpId,Q.tenant),PZ0({id:U.corpId,corpId:U.corpId,name:I,provider:"hosecloud",overwrite:q},{token:U.token,sealUrl:U.sealUrl,expiresIn:U.expiresIn,verify:!0,remote:Q})}function PZ0($,I){let{token:q,sealUrl:U,expiresIn:Y,verify:J,remote:Q}=I,K=Q?.user,w=Q?.tenant,z=i1($,"tenantSlug")??D7(w?.tenantSlug),G=i1($,"tenantId")??D7(w?.id),H=i1($,"tenantName")??D7(w?.name),V=i1($,"id")??z??G;if(!V)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let W=i1($,"staffId")??D7(K?.providerUserId)??D7(K?.id)??"seal",X=i1($,"provider")??D7(K?.provider)??D7(w?.providerConfig?.provider),D=i1($,"corpId")??z??G??V,O={id:V,name:i1($,"name")??H??V,seal:{url:U,tenantSlug:z,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:q,sealUrl:U,expiresIn:Y,staffId:W,corpId:D,tenantId:G,tenantSlug:z,tenantName:H,providerUserId:D7(K?.providerUserId),provider:X},auth:{refreshTtl:300}},N=NT();FZ0(N,{recursive:!0,mode:448});let T=AZ0(N,`${Gu(V)}.json`);if(NZ0(T)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${T}. Pass "overwrite": true to replace it.`);MZ0(T,`${JSON.stringify(O,null,2)}
`,{mode:384}),v0({id:V,name:O.name,tenantId:G,tenantSlug:z,verified:J,path:T})}async function qz1($,I){let q=await Uz1(`${$}/api/v1/auth/me`,{authorization:`Bearer ${I}`}),U=WO(q.data);return{user:WO(U.user??q.user),tenant:WO(U.tenant??q.tenant)}}async function Uz1($,I={}){let q=await fetch($,{headers:I}),U=await q.text();if(!q.ok)throw Error(`${q.status} ${U}`);let Y=JSON.parse(U);return WO(Y)}function WO($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function D7($){return typeof $==="string"&&$?$:void 0}async function TZ0($,I){let q=await TH($),U=JQ(q.sealUrl,q.token),Y=await Z8(U);EH(q.corpId,Y.tenant);let J=await Hq(U,{note:I});v0({tenant:{id:Y.tenant.id,name:Y.tenant.name,tenantSlug:Y.tenant.tenantSlug,corpId:q.corpId},user:{id:Y.user.id,name:Y.user.name,providerUserId:Y.user.providerUserId,isAdmin:Y.user.isAdmin},delegation:J,expiresIn:q.expiresIn})}async function EZ0($,I,q,U,Y){if($==="list"){await L0("seal_delegation_list",q,U,{},O0(Y.options));return}if($==="create"){let J=x(Y.options.note)??(I?[I,...Y.command.slice(2)].join(" "):void 0);await L0("seal_delegation_create",q,U,{note:J},O0(Y.options));return}if($==="revoke"){let J=I??x(Y.options.tokenId);if(!J)throw Error("Usage: seal-use delegation revoke <tokenId>");await L0("seal_delegation_revoke",q,U,{tokenId:J},O0(Y.options));return}throw Error(`Unknown delegation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as Yz1}from"node:fs";async function jZ0($,I,q,U,Y,J){if(!$||$==="help")throw Error(`Usage: seal-use deploy <system> <action> [options]
`}var WG1=100,wG1=120000,Jz0=["id","code","status","strictness","scope","createdAt","updatedAt"],VG1=200000;function Su($){return $.map((I)=>typeof I==="string"?I:String(I)).join(" ")}function MH($){if(!$.length)return"";return`${$.join(`
`)}
`}function AH($){return $.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function B0($,I={}){ZG1($,I);let U=`${JSON.stringify($,null,2)}
`;if(I.outputFile){GG1(I.outputFile,U),console.log(JSON.stringify({outputFile:I.outputFile,bytes:Buffer.byteLength(U,"utf-8")},null,2));return}console.log(U.trimEnd())}function ZG1($,I={}){if(I.allowFull||I.outputFile)return;let U=Buffer.byteLength(JSON.stringify($),"utf-8");if(U>VG1)throw new CD(`Output is large (${U} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function Qz0($,I){if(I)return;let U=$&&typeof $==="object"?$:{},Y=typeof U.count==="number"?U.count:void 0,J=Array.isArray(U.rules)?U.rules.length:void 0,Q=Buffer.byteLength(JSON.stringify($),"utf-8"),K=Y??J??0;if(K>WG1||Q>wG1)throw new CD(`Rule list is large (${K} rules, ${Q} bytes). Use "seal-use rules list --summary" or "seal-use rules count"; pass --full only when you really need full descriptions.`,"seal-use rules list --summary")}function V0($){return{allowFull:N0($.full)===!0,outputFile:h($.outputFile)??h($["output-file"])}}function Kz0($=[]){console.log(Yz0($))}function f1($){let I=d8(),U=F4();return NJ(I,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$},YI())}function ZI($=F4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:JI()}}async function F0($,I,U,Y,J={}){B0(await zI($,I,U,Y),J)}async function zI($,I,U,Y){let J=DH.find((q)=>q.name===$);if(!J)throw Error(`Unknown Seal tool: ${$}`);let Q=Object.fromEntries(Object.entries(Y).filter(([,q])=>q!==void 0)),K=J.handler;return K(I,Q,{corp:U})}async function qz0($,I,U,Y,J){if($==="summary"){let Q=await zI("seal_approval_runs_summary",U,Y,{date:h(J.options.date),timezone:h(J.options.timezone),limit:m0(J.options.limit),startDate:h(J.options.startDate),endDate:h(J.options.endDate),status:h(J.options.status),taskMode:h(J.options.taskMode),manualApprovalStatus:h(J.options.manualApprovalStatus),sourceDocumentSN:h(J.options.sourceDocumentSN),sourceDocumentId:h(J.options.sourceDocumentId),humanResult:h(J.options.humanResult),query:h(J.options.query)});if(Q?.matched===0&&Q?.total>0)console.error(`提示:在 ${Q.date} 未匹配到记录(该企业共有 ${Q.total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-use approval-runs list --limit 10 查看最近记录。`);B0(Q,V0(J.options));return}if($==="stats"){await F0("seal_approval_runs_stats",U,Y,{since:h(J.options.since),dedupeBy:h(J.options.dedupeBy)??h(J.options["dedupe-by"]),status:h(J.options.status),sourceSystem:h(J.options.sourceSystem)??h(J.options["source-system"]),taskMode:h(J.options.taskMode)??h(J.options["task-mode"])},V0(J.options));return}if($==="count"){await F0("seal_approval_runs_count",U,Y,{status:h(J.options.status),sourceSystem:h(J.options.sourceSystem)??h(J.options["source-system"]),taskMode:h(J.options.taskMode)??h(J.options["task-mode"]),search:h(J.options.search)??h(J.options.query)},V0(J.options));return}if($==="search"||$==="list"){await F0("seal_approval_runs_search",U,Y,{limit:m0(J.options.limit),offset:m0(J.options.offset),startDate:h(J.options.startDate),endDate:h(J.options.endDate),status:h(J.options.status),taskMode:h(J.options.taskMode),manualApprovalStatus:h(J.options.manualApprovalStatus),sourceDocumentSN:h(J.options.sourceDocumentSN),sourceDocumentId:h(J.options.sourceDocumentId),humanResult:h(J.options.humanResult),query:h(J.options.query),includeBridge:N0(J.options.includeBridge)},V0(J.options));return}if($==="bridge"){await F0("seal_approval_run_langfuse_bridge_get",U,Y,{recordId:h(J.options.recordId),sourceDocumentSN:h(J.options.sourceDocumentSN),sourceDocumentId:h(J.options.sourceDocumentId),simulationBatchId:h(J.options.simulationBatchId),limit:m0(J.options.limit)},V0(J.options));return}if($==="pick"){let Q=I??h(J.options.query)??h(J.options.sn);if(!Q)throw Error("Usage: seal-use approval-runs pick --sn <documentSN>");await F0("seal_approval_run_pick",U,Y,{query:Q,sn:h(J.options.sn),batchId:h(J.options.batch)??h(J.options.batchId),latest:N0(J.options.latest),fields:h(J.options.fields),limit:m0(J.options.limit),includeBridge:N0(J.options.includeBridge)},V0(J.options));return}if($==="get"){let Q=J.command[2];if(!Q)throw Error("Missing approval run recordId");await F0("seal_approval_run_get",U,Y,{recordId:Q,fields:h(J.options.fields),summary:N0(J.options.summary)},V0(J.options));return}if($==="cited-rules"){let Q=J.command[2];if(!Q)throw Error("Usage: seal-use approval-runs cited-rules <recordId>");await F0("seal_approval_run_cited_rules_get",U,Y,{recordId:Q},V0(J.options));return}if($==="document-summary"){let Q=J.command[2];if(!Q)throw Error("Usage: seal-use approval-runs document-summary <recordId>");await F0("seal_approval_run_document_summary_get",U,Y,{recordId:Q},V0(J.options));return}if($==="attachments"){if(J.command[2]==="download"){let G=J.command[3];if(!G)throw Error("Usage: seal-use approval-runs attachment Line truncated
or: seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]`);let Q=f1(Y),K=f1(J);if(Q.id===K.id)throw _4(`Cannot bind enterprise '${Q.id}' to itself.`);if(Q.prodCorpId&&Q.prodCorpId!==K.id)throw _4(`Cannot use '${Q.id}' as a production enterprise because it is already registered as a test enterprise for '${Q.prodCorpId}'. Multi-tier chaining is not permitted.`);if(K.testCorpId&&K.testCorpId!==Q.id)throw _4(`Cannot bind '${K.id}' as a test enterprise because it already has a bound test enterprise '${K.testCorpId}'. Multi-tier chaining is not permitted.`);let q=N0(U.options.force)===!0;if(Q.testCorpId&&Q.testCorpId!==K.id||K.prodCorpId&&K.prodCorpId!==Q.id){if(!q)throw t8(`Enterprise binding conflict: production enterprise '${Q.id}' is bound to '${Q.testCorpId??"none"}', and test enterprise '${K.id}' is bound to '${K.prodCorpId??"none"}'. Overwriting an existing binding requires --force and --confirm.`,`seal-use corps bind-test ${Q.id} ${K.id} --confirm --force`)}if(!(N0(U.options.confirm)===!0||N0(U.options.yes)===!0)){let w=q?" --force":"";throw t8(`Refusing to bind test enterprise '${K.name}' (${K.id}) to production enterprise '${Q.name}' (${Q.id}) without --confirm. Enterprise binding establishes 1-to-1 sync pairing and marks '${K.id}' as a test environment.`,`seal-use corps bind-test ${Q.id} ${K.id} --confirm${w}`)}if(Q.testCorpId&&Q.testCorpId!==K.id)try{O7(Q.testCorpId,{prodCorpId:void 0})}catch{}if(K.prodCorpId&&K.prodCorpId!==Q.id)try{O7(K.prodCorpId,{testCorpId:void 0})}catch{}let G=O7(Q.id,{environment:"production",testCorpId:K.id}),W=O7(K.id,{environment:"test",prodCorpId:Q.id});B0({success:!0,productionEnterprise:{id:G.id,name:G.name,environment:G.environment,testCorpId:G.testCorpId},testEnterprise:{id:W.id,name:W.name,environment:W.environment,prodCorpId:W.prodCorpId}});return}if($==="unbind-test"){let Y=I??h(U.options.corp),J=f1(Y);if(!J.testCorpId&&!J.prodCorpId){B0({unbound:!1,message:`Enterprise '${J.name}' (${J.id}) does not have an active test enterprise binding.`});return}let Q=J.testCorpId?J.id:J.prodCorpId,K=J.testCorpId?J.testCorpId:J.id;if(!(N0(U.options.confirm)===!0||N0(U.options.yes)===!0))throw t8(`Refusing to unbind production enterprise '${Q}' and test enterprise '${K}' without --confirm.`,`seal-use corps unbind-test ${J.id} --confirm`);O7(Q,{testCorpId:void 0});try{O7(K,{prodCorpId:void 0})}catch{}B0({success:!0,unboundProduction:Q,unboundTest:K});return}if($==="sync-test"){let Y=I??h(U.options.corp),J=f1(Y);if(!J.testCorpId)throw _4(`Production enterprise '${J.name}' (${J.id}) has no bound test enterprise.
Run 'seal-use corps bind-test ${J.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`);let Q=f1(J.testCorpId);if(Q.environment!=="test")throw Error(`Target enterprise '${Q.name}' (${Q.id}) is marked as '${Q.environment}', NOT 'test'. Aborting sync to protect non-test environments.`);let K=await p1(J),q=await p1(Q),[H,G,W,w,V,Z,X,L]=await Promise.all([j1(K,J.seal.endpoints.approvalStylePreferences).catch(()=>({})),j1(q,Q.seal.endpoints.approvalStylePreferences).catch(()=>({})),_6(K),_6(q),v$(K).catch(()=>[]),v$(q).catch(()=>[]),O9(K,{limit:100}).catch(()=>({articles:[]})),O9(q,{limit:100}).catch(()=>({articles:[]}))]),D=(X.articles||[]).filter((t)=>!t.isDeleted),O=(L.articles||[]).filter((t)=>!t.isDeleted),E=new Map(O.map((t)=>[t.title.trim(),t])),T=[],A=[],R=new Set(D.map((t)=>t.title.trim()));for(let t of D){let T0=t.title.trim(),y0=E.get(T0);if(!y0)T.push(t);else{let g1=y0.content!==t.content,Z4=(y0.purpose??"")!==(t.purpose??""),A6=y0.enabled!==t.enabled,f6=y0.contentType!==t.contentType,F$=(y0.status??"")!==(t.status??""),i6=JSON.stringify([...y0.scenarios??[]].sort())!==JSON.stringify([...t.scenarios??[]].sort()),P6=JSON.stringify([...y0.tags??[]].sort())!==JSON.stringify([...t.tags??[]].sort());if(g1||Z4||A6||f6||F$||i6||P6)A.push({testId:y0.id,prodDoc:t,reasons:[...g1?["content"]:[],...Z4?["purpose"]:[],...A6?["enabled"]:[],...f6?["contentType"]:[],...F$?["status"]:[],...i6?["scenarios"]:[],...P6?["tags"]:[]]})}}let k=O.filter((t)=>!R.has(t.title.trim())),f=[...V].sort((t,T0)=>T0.versionNumber-t.versionNumber)[0],C=f?.versionNumber,n=([...Z].sort((t,T0)=>T0.versionNumber-t.versionNumber)[0]?.versionNumber??0)+1,S=Tz0(J.name,C,Z),b=h(U.options["version-name"])??h(U.options.versionName)??Ez0(J.name,C,S,n),Y0={...G,tone:H.tone,language:H.language,detailLevel:H.detailLevel,outputFormat:H.outputFormat,examples:H.examples??[],prohibitedPhrases:H.prohibitedPhrases??[],customInstructions:H.customInstructions,decisionPreferences:H.decisionPreferences,thinkingDepthPreference:H.thinkingDepthPreference};if(N0(U.options["dry-run"])===!0||N0(U.options.dryRun)===!0){B0({dryRun:!0,source:{id:J.id,name:J.name,environment:J.environment,latestPublishedVersion:f?{versionNumber:f.versionNumber,versionName:f.versionName}:null,documentsCount:D.length},target:{id:Q.id,name:Q.name,environment:Q.environment},versionMappingPlan:{sourceProdVersionNumber:C??null,sourceProdVersionName:f?.versionName??null,targetTestExpectedVersionNumber:n,targetTestPublishVersionName:b,iteration:S},preferencesDiff:{decisionPreferences:{before:G.decisionPreferences,after:H.decisionPreferences},thinkingDepthPreference:{before:G.thinkingDepthPreference,after:H.thinkingDepthPreference}},rulesPlan:{sourceDraftRuleCount:W.rules.length,targetExistingDraftRuleCount:w.rules.length,toDeleteCount:w.rules.length,toCreateCount:W.rules.length,rulesToSync:W.rules.map((t,T0)=>({index:T0+1,sourceRuleId:t.id,sourceRuleCode:t.code??T0+1,expectedTargetCode:`rule-${T0+1}`,description:t.description,scope:t.scope,strictness:t.strictness}))},documentsPlan:{sourceDocumentCount:D.length,targetExistingDocumentCount:O.length,toCreateCount:T.length,toCreate:T.map((t)=>({title:t.title,purpose:t.purpose,contentType:t.contentType,scenarios:t.scenarios})),toUpdateCount:A.length,toUpdate:A.map((t)=>({targetDocumentId:t.testId,title:t.prodDoc.title,reasons:t.reasons})),toDeleteCount:k.length,toDelete:k.map((t)=>({targetDocumentId:t.id,title:t.title}))},publishingPlan:{targetCorpId:Q.id,publishVersionName:b,publishTarget:"test"},productionGuarantees:{prodRulesStayDraft:!0,prodVersionPublished:!1}});return}if(!(N0(U.options.yes)===!0||N0(U.options.confirm)===!0))throw t8(`Refusing to overwrite test enterprise '${Q.name}' (${Q.id}) with preferences, ${W.rules.length} draft rules, and ${D.length} knowledge documents from production enterprise '${J.name}' (${J.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,`seal-use corps sync-test ${J.id} --yes`);await W5(q,Y0,Q.seal.endpoints.approvalStylePreferences);let c=[];for(let t of k)await rw(q,t.id),c.push({id:t.id,title:t.title});let r=[];for(let t of A)await ow(q,t.testId,{title:t.prodDoc.title,purpose:t.prodDoc.purpose,content:t.prodDoc.content,contentType:t.prodDoc.contentType,status:t.prodDoc.status,enabled:t.prodDoc.enabled,scenarios:t.prodDoc.scenarios&&t.prodDoc.scenarios.length>0?t.prodDoc.scenarios:["audit"],tags:t.prodDoc.tags}),r.push({id:t.testId,title:t.prodDoc.title,reasons:t.reasons});let Q0=[];for(let t of T){let T0=await lw(q,{title:t.title,purpose:t.purpose,content:t.content,contentType:t.contentType,status:t.status,enabled:t.enabled,scenarios:t.scenarios&&t.scenarios.length>0?t.scenarios:["audit"],tags:t.tags});Q0.push({id:T0.id,title:T0.title})}for(let t of w.rules)await TU(q,t.id);let w0=[];for(let t of W.rules){let T0=await A2(q,{description:t.description,scope:t.scope,strictness:t.strictness});w0.pu Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${C.length} candidate administrators:
- ${p}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!L)if(!W&&Q)L=Q;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-use corps hose-staffs' to discover available administrators.");let D=d1($,"id")??V,O=Z??V,E=d1($,"sealUrl")??`https://${V.toLowerCase()}.sealai.cc`,T={id:D,name:O,environment:"production",seal:{url:E,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:w,appKey:U,appSecurity:Y,corpId:V,staffId:L},auth:{refreshTtl:300}};if(W)_w(D),await _J(T);let A=Dh();vz0(A,{recursive:!0,mode:448});let R=Cz0(A,`${Ru(D)}.json`);if(Bz0(R)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${R}. Pass "overwrite": true to replace it.`);Rz0(R,`${JSON.stringify(T,null,2)}
`,{mode:384}),B0({id:D,name:O,corpId:V,domain:w,staffId:L,verified:W,path:R})}async function TG1($){let I=A7($,"token"),U=(d1($,"sealUrl")??d1($,"url")??"").replace(/\/+$/,"");if(!U)throw Error("Missing required JSON field: sealUrl");let Y=tZ0($,"expiresIn")??2592000,J=$.force===!0||$.verify===!1?!1:!0,Q=_z0($),K=J?await BG1(U,I,X2(Q)):void 0;Sz0($,{token:I,sealUrl:U,expiresIn:Y,verify:J,remote:K,custom:Q})}function _z0($){return{headers:Zh.parse($.headers),cookies:zh.parse($.cookies)}}async function EG1($,I,U){let Y=await Sw($),J=L2(Y.sealUrl,Y.token),Q=await B$(J),K={user:Q.user,tenant:Q.tenant};gw(Y.corpId,K.tenant),Sz0({id:Y.corpId,corpId:Y.corpId,name:I,provider:"hosecloud",overwrite:U},{token:Y.token,sealUrl:Y.sealUrl,expiresIn:Y.expiresIn,verify:!0,remote:K})}function Sz0($,I){let{token:U,sealUrl:Y,expiresIn:J,verify:Q,remote:K}=I,q=I.custom??_z0($),H=K?.user,G=K?.tenant,W=d1($,"tenantSlug")??P7(G?.tenantSlug),w=d1($,"tenantId")??P7(G?.id),V=d1($,"tenantName")??P7(G?.name),Z=d1($,"id")??W??w;if(!Z)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let X=d1($,"staffId")??P7(H?.providerUserId)??P7(H?.id)??"seal",L=d1($,"provider")??P7(H?.provider)??P7(G?.providerConfig?.provider),D=d1($,"corpId")??W??w??Z,O={id:Z,name:d1($,"name")??V??Z,environment:"production",seal:{url:Y,tenantSlug:W,headers:q.headers,cookies:q.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:U,sealUrl:Y,expiresIn:J,staffId:X,corpId:D,tenantId:w,tenantSlug:W,tenantName:V,providerUserId:P7(H?.providerUserId),provider:L},auth:{refreshTtl:300}},E=Dh();vz0(E,{recursive:!0,mode:448});let T=Cz0(E,`${Ru(Z)}.json`);if(Bz0(T)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${T}. Pass "overwrite": true to replace it.`);Rz0(T,`${JSON.stringify(O,null,2)}
`,{mode:384}),B0({id:Z,name:O.name,tenantId:w,tenantSlug:W,verified:Q,path:T})}async function BG1($,I,U={}){let Y=await vG1(`${$}/api/v1/auth/me`,{...U,authorization:`Bearer ${I}`}),J=gD(Y.data);return{user:gD(J.user??Y.user),tenant:gD(J.tenant??Y.tenant)}}async function vG1($,I={}){let U=await fetch($,{headers:I}),Y=await U.text();if(!U.ok)throw Error(`${U.status} ${Y}`);let J=JSON.parse(Y);return gD(J)}function gD($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function P7($){return typeof $==="string"&&$?$:void 0}async function gz0($,I){let U=await Sw($),Y=L2(U.sealUrl,U.token),J=await B$(Y);gw(U.corpId,J.tenant);let Q=await PU(Y,{note:I});B0({tenant:{id:J.tenant.id,name:J.tenant.name,tenantSlug:J.tenant.tenantSlug,corpId:U.corpId},user:{id:J.user.id,name:J.user.name,providerUserId:J.user.providerUserId,isAdmin:J.user.isAdmin},delegation:Q,expiresIn:U.expiresIn})}async function yz0($,I,U,Y,J){if($==="list"){await F0("seal_delegation_list",U,Y,{},V0(J.options));return}if($==="create"){let Q=h(J.options.note)??(I?[I,...J.command.slice(2)].join(" "):void 0);await F0("seal_delegation_create",U,Y,{note:Q},V0(J.options));return}if($==="revoke"){let Q=I??h(J.options.tokenId);if(!Q)throw Error("Usage: seal-use delegation revoke <tokenId>");await F0("seal_delegation_revoke",U,Y,{tokenId:Q},V0(J.options));return}throw Error(`Unknown delegation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as RG1}from"node:fs";async function hz0($,I,U,Y,J,Q){if(!$||$==="help")throw Error(`Usage: seal-use deploy <system> <action> [options]
`+`支持的审批系统与发布目标:
`+` • hosecloud (合思费控): seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>
@@ -429,25 +457,25 @@ Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an a
`+` • feishu (飞书审批): 建议使用 Webhook 模式对接
`+` • weaver (泛微 OA): 建议使用 Webhook 模式对接
`+` • helios (汇联易): 建议使用 Webhook 模式对接
`+" • maycur (每刻报销): 建议使用 Webhook 模式对接");if($==="webhook"||$==="webhooks")throw Error("Webhook 审批流发布请直接使用专有命令:seal-use webhook <list|get|add|update|delete> --corp <corpId>");if($==="feishu"||$==="lark")throw Error("飞书审批发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '飞书审批' --result-url <url> --corp <corpId>");if($==="weaver")throw Error("泛微 OA 发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '泛微OA' --result-url <url> --corp <corpId>");if($==="maycur"||$==="helios"){let z=$==="maycur"?"每刻报销":"汇联易";throw Error(`${z}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${z}' --result-url <url> --corp <corpId>`)}let Q=$==="hosecloud",K=$==="hosecloud"?I:$,w=$==="hosecloud"?q:I;if(!Q)throw Error(`未知的发布目标系统: ${$}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);if(K==="requirements"){await L0("seal_deploy_hosecloud_requirements",U,Y,{},O0(J.options));return}if(K==="list"){await L0("seal_deploy_hosecloud_list",U,Y,{},O0(J.options));return}if(K==="get"){let z=w??x(J.options.signKey)??x(J.options["sign-key"]);if(!z){let H=((await K4(U)).integrations??[]).filter((V)=>V.type==="hosecloud");if(H.length===0)throw Error(`当前企业 (${Y.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${Y.id}`);console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${Y.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of H){let W=V.outboundName??"SealAI 审批",X=V.signKey,D=V.apiOrigin??"production";console.error(` • "${W}" (signKey: ${X}, 环境: ${D})`),console.error(` \uD83D\uDC49 查看命令: seal-use deploy hosecloud get ${X} --corp ${Y.id}
`)}throw Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。")}await L0("seal_deploy_hosecloud_get",U,Y,{signKey:z},O0(J.options));return}if(K==="status"){await L0("seal_deploy_hosecloud_status",U,Y,{},O0(J.options));return}if(K==="configure"){let z=x(J.options.input),G=z?JSON.parse(Yz1(z,"utf8")):t6(J.json);if(!G||Object.keys(G).length===0)throw Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");await L0("seal_deploy_hosecloud_configure",U,Y,G,O0(J.options));return}if(K==="sync"){let z=w??x(J.options.signKey)??x(J.options["sign-key"]),G=C0(J.options.auto)??C0(J.options.yes);if(!z){let V=((await K4(U)).integrations??[]).filter((X)=>X.type==="hosecloud");if(V.length===0)throw Error(`当前企业 (${Y.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${Y.id}`);let W=V[0];if(W&&V.length===1&&G){let X=W.signKey;console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${X})`),await L0("seal_deploy_hosecloud_sync",U,Y,{signKey:X},O0(J.options));return}console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${Y.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let X of V){let D=X.outboundName??"SealAI 审批",O=X.signKey,N=X.apiOrigin??"production";console.error(` • "${D}" (signKey: ${O}, 环境: ${N})`),console.error(` \uD83D\uDC49 同步命令: seal-use deploy hosecloud sync ${O} --corp ${Y.id}
`)}if(V.length===1)console.error(`\uD83D\uDCA1 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${Y.id}
`);throw Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。")}await L0("seal_deploy_hosecloud_sync",U,Y,{signKey:z},O0(J.options));return}throw Error(`Unknown deploy hosecloud action: ${K??""}. Available: requirements, list, get, status, configure, sync.`)}import{createServer as zz1}from"node:http";import{URL as Qz1}from"node:url";var BZ0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.8",description:`Planned HTTP contract for the seal-use wrapped backend API.
`+" • maycur (每刻报销): 建议使用 Webhook 模式对接");if($==="webhook"||$==="webhooks")throw Error("Webhook 审批流发布请直接使用专有命令:seal-use webhook <list|get|add|update|delete> --corp <corpId>");if($==="feishu"||$==="lark")throw Error("飞书审批发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '飞书审批' --result-url <url> --corp <corpId>");if($==="weaver")throw Error("泛微 OA 发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '泛微OA' --result-url <url> --corp <corpId>");if($==="maycur"||$==="helios"){let G=$==="maycur"?"每刻报销":"汇联易";throw Error(`${G}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${G}' --result-url <url> --corp <corpId>`)}let K=$==="hosecloud",q=$==="hosecloud"?I:$,H=$==="hosecloud"?U:I;if(!K)throw Error(`未知的发布目标系统: ${$}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);if(q==="requirements"){await F0("seal_deploy_hosecloud_requirements",Y,J,{},V0(Q.options));return}if(q==="list"){await F0("seal_deploy_hosecloud_list",Y,J,{},V0(Q.options));return}if(q==="get"){let G=H??h(Q.options.signKey)??h(Q.options["sign-key"]);if(!G){let w=((await j1(Y)).integrations??[]).filter((V)=>V.type==="hosecloud");if(w.length===0)throw Error(`当前企业 (${J.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${J.id}`);console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${J.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of w){let Z=V.outboundName??"SealAI 审批",X=V.signKey,L=V.apiOrigin??"production";console.error(` • "${Z}" (signKey: ${X}, 环境: ${L})`),console.error(` \uD83D\uDC49 查看命令: seal-use deploy hosecloud get ${X} --corp ${J.id}
`)}throw new r8("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。",2,w.length===1?`seal-use deploy hosecloud get ${w[0].signKey} --corp ${J.id}`:void 0)}await F0("seal_deploy_hosecloud_get",Y,J,{signKey:G},V0(Q.options));return}if(q==="status"){await F0("seal_deploy_hosecloud_status",Y,J,{},V0(Q.options));return}if(q==="configure"){let G=h(Q.options.input),W=G?JSON.parse(RG1(G,"utf8")):U$(Q.json);if(!W||Object.keys(W).length===0)throw Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");await F0("seal_deploy_hosecloud_configure",Y,J,{...W,dryRun:N0(Q.options.dryRun)??N0(Q.options["dry-run"])},V0(Q.options));return}if(q==="sync"){let G=H??h(Q.options.signKey)??h(Q.options["sign-key"]),W=N0(Q.options.auto)??N0(Q.options.yes);if(!G){let V=((await j1(Y)).integrations??[]).filter((X)=>X.type==="hosecloud");if(V.length===0)throw Error(`当前企业 (${J.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${J.id}`);let Z=V[0];if(Z&&V.length===1&&W){let X=Z.signKey;console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${X})`),await F0("seal_deploy_hosecloud_sync",Y,J,{signKey:X},V0(Q.options));return}console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${J.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let X of V){let L=X.outboundName??"SealAI 审批",D=X.signKey,O=X.apiOrigin??"production";console.error(` • "${L}" (signKey: ${D}, 环境: ${O})`),console.error(` \uD83D\uDC49 同步命令: seal-use deploy hosecloud sync ${D} --corp ${J.id}
`)}if(V.length===1)console.error(`\uD83D\uDCA1 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${J.id}
`);throw new r8("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,V.length===1?`seal-use deploy hosecloud sync ${V[0].signKey} --corp ${J.id}`:void 0)}await F0("seal_deploy_hosecloud_sync",Y,J,{signKey:G},V0(Q.options));return}throw Error(`Unknown deploy hosecloud action: ${q??""}. Available: requirements, list, get, status, configure, sync.`)}import{createServer as gG1}from"node:http";import{URL as jG1}from"node:url";var uz0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.16",description:`Planned HTTP contract for the seal-use wrapped backend API.
These endpoints describe the intended stable API for frontend developers and agents once
the HTTP adapter is implemented.
They are not the raw downstream Seal endpoints. seal-use is responsible for enterprise
selection, source authentication, response compaction, and diagnostics-friendly fields.
`},servers:[{url:"http://localhost:8787",description:"Reserved for a future local HTTP adapter; the current service uses MCP stdio."}],security:[{localSession:[]}],tags:[{name:"Corps",description:"Local enterprise configuration selection."},{name:"Source",description:"Source-derived Seal enterprise configuration."},{name:"Auth",description:"Wrapped authentication diagnostics and current identity."},{name:"Approval Runs",description:"Wrapped approval run history, summaries, document URLs, and trace bridge helpers."},{name:"Approval Knowledge",description:"Wrapped approval rules, documents, preferences, and search."},{name:"Simulation",description:"Wrapped simulation batch record access."}],paths:{"/v1/corps":{get:{tags:["Corps"],operationId:"listCorps",summary:"List configured enterprises",responses:{"200":{description:"Configured enterprises.",content:{"application/json":{schema:{type:"array",items:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp",summary:"Get current enterprise",description:"Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",responses:{"200":{description:"Current enterprise.",content:{"application/json":{schema:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp",summary:"Switch current enterprise",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}}}}},responses:{"200":{description:"Switched enterprise.",content:{"application/json":{schema:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}}}}},"404":{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/source/config":{get:{tags:["Source"],operationId:"getSourceConfig",summary:"Resolve source-derived Seal enterprise config",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Redacted Seal enterprise config.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/auth/diagnose":{get:{tags:["Auth"],operationId:"diagnoseAuth",summary:"Diagnose wrapped source-to-Seal authentication",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Authentication stage diagnosis.",content:{"application/json":{schema:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}}}}}}}},"/v1/whoami":{get:{tags:["Auth"],operationId:"whoami",summary:"Get current wrapped Seal identity",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Current Seal user and tenant.",content:{"application/json":{schema:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/session":{get:{tags:["Auth"],operationId:"getSession",summary:"Get current wrapped Seal session metadata",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"2 Line truncated
`},servers:[{url:"http://localhost:8787",description:"Reserved for a future local HTTP adapter; the current service uses MCP stdio."}],security:[{localSession:[]}],tags:[{name:"Corps",description:"Local enterprise configuration selection."},{name:"Source",description:"Source-derived Seal enterprise configuration."},{name:"Auth",description:"Wrapped authentication diagnostics and current identity."},{name:"Approval Runs",description:"Wrapped approval run history, summaries, document URLs, and trace bridge helpers."},{name:"Approval Knowledge",description:"Wrapped approval rules, documents, preferences, and search."},{name:"Simulation",description:"Wrapped simulation batch record access."}],paths:{"/v1/corps":{get:{tags:["Corps"],operationId:"listCorps",summary:"List configured enterprises",responses:{"200":{description:"Configured enterprises.",content:{"application/json":{schema:{type:"array",items:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp",summary:"Get current enterprise",description:"Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",responses:{"200":{description:"Current enterprise.",content:{"application/json":{schema:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp",summary:"Switch current enterprise",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}}}}},responses:{"200":{description:"Switched enterprise.",content:{"application/json":{schema:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}}}}},"404":{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/source/config":{get:{tags:["Source"],operationId:"getSourceConfig",summary:"Resolve source-derived Seal enterprise config",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Redacted Seal enterprise config.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/auth/diagnose":{get:{tags:["Auth"],operationId:"diagnoseAuth",summary:"Diagnose wrapped source-to-Seal authentication",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Authentication stage diagnosis.",content:{"application/json":{schema:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}}}}}}}},"/v1/whoami":{get:{tags:["Auth"],operationId:"whoami",summary:"Get current wrapped Seal identity",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Current Seal user and tenant.",content:{"application/json":{schema:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/session":{get:{tags:["Auth"],operationId:"getSession",summary:"Get current wrapped Seal session metadata",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"2 Line truncated
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>Seal Home API Docs (v${t0})</title>
<title>Seal Home API Docs (v${U1})</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>\uD83E\uDDAD</text></svg>" />
<style>
body {
@@ -466,21 +494,21 @@ selection, source authentication, response compaction, and diagnostics-friendly
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
></script>
</body>
</html>`}async function x4($,I,q,U){let Y=$.handler;return Y(I,q,{corp:U})}async function RZ0($,I){if(I.setHeader("Access-Control-Allow-Origin","*"),I.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),I.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),$.method==="OPTIONS"){I.writeHead(204),I.end();return}let q=$.headers.host||"localhost",U=$.headers["x-forwarded-proto"]||"http",Y=new Qz1($.url||"/",`${U}://${q}`),J=Y.pathname.replace(/\/+$/,"")||"/",Q=($.method||"GET").toUpperCase();try{if(Q==="GET"&&J==="/"){d1(I,200,{name:"seal-use",version:t0,description:"Seal tenant operations and approval automation HTTP API",docs:"/docs",openapi:"/openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",tools:"GET /api/tools",toolInvoke:"POST /api/tool/:name",restV1:"GET/POST /v1/*"}});return}if(Q==="GET"&&J==="/docs"){wz1(I,200,vZ0());return}if(Q==="GET"&&J==="/openapi.json"){d1(I,200,ZO());return}if(Q==="GET"&&J==="/health"){d1(I,200,{status:"ok",version:t0,name:"seal-use",timestamp:new Date().toISOString()});return}if(Q==="POST"&&(J==="/shutdown"||J==="/api/shutdown")){d1(I,200,{success:!0,message:"Shutting down seal-use background daemon",pid:process.pid}),setTimeout(()=>{process.kill(process.pid,"SIGTERM")},50);return}if(Q==="POST"&&J==="/api/cli"){let K=await DO($),w=(typeof K?.command==="string"?K.command:"").trim();if(!w){XO(I,400,"Missing 'command' property in request body");return}let z=Du(w),G=z[0]==="seal-use"||z[0]==="seal-home"||z[0]?.endsWith("/seal-use")||z[0]?.endsWith("/seal-home")?z.slice(1):z,H=await Ow(G),V=void 0;try{if(H.stdout.trim().startsWith("{")||H.stdout.trim().startsWith("["))V=JSON.parse(H.stdout)}catch{}d1(I,H.isError?400:200,{success:!H.isError,stdout:H.stdout,stderr:H.stderr,exitCode:H.exitCode,data:V});return}if(Q==="POST"&&J.startsWith("/api/tool/")){let K=J.slice(10).trim(),w=v4(K,{includeMcpAliases:!0});if(!w){XO(I,404,`Tool not found: '${K}'`);return}let z=await DO($)||{},G=h6($,Y,z),H=O4(G),V=await q4(H),W={...z};delete W.corp;let X=await x4(w,V,W,H);d1(I,200,X);return}if(J.startsWith("/v1/")){if(await Kz1($,I,Q,J,Y))return}XO(I,404,`Cannot ${Q} ${J}. Visit /docs for available endpoints.`)}catch(K){let w=K instanceof Error?K.message:String(K);XO(I,500,w)}}async function Kz1($,I,q,U,Y){let J=Object.fromEntries(Y.searchParams.entries());if(q==="GET"&&U==="/v1/corps"){let Q=V8(),K=V6();return d1(I,200,{count:Q.length,mode:K.stateful?"stateful":"stateless",defaultCorpId:K.defaultCorpId,corps:Q.map((w)=>({id:w.id,name:w.name,sourceType:w.source.type,sealUrl:w.seal?.url}))}),!0}if(q==="GET"&&U==="/v1/whoami"){let Q=h6($,Y,J),K=O4(Q),w=await q4(K),z=v4("seal_whoami"),G=await x4(z,w,{},K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/session"){let Q=h6($,Y,J),K=O4(Q),w=await q4(K),z=v4("seal_session_get"),G=await x4(z,w,{},K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/approval-runs/summary"){let Q=h6($,Y,J),K=O4(Q),w=await q4(K),z=v4("seal_approval_runs_summary"),G=await x4(z,w,J,K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/approval-runs/stats"){let Q=h6($,Y,J),K=O4(Q),w=await q4(K),z=v4("seal_approval_runs_stats"),G=await x4(z,w,J,K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/approval-runs/pick"){let Q=h6($,Y,J),K=O4(Q),w=await q4(K),z=v4("seal_approval_run_pick"),G=await x4(z,w,J,K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/approval-runs/url"){let Q=h6($,Y,J),K=O4(Q),w=await q4(K),z=v4("seal_approval_run_url_get"),G=await x4(z,w,J,K);return d1(I,200,G),!0}if(U.startsWith("/v1/approval-runs/")){let Q=U.slice(18).split("/"),K=Q[0],w=Q[1];if(K&&!["summary","pick","stats","url","bridge"].includes(K)){let z=h6($,Y,J),G=O4(z),H=await q4(G);if(!w){let V=v4("seal_approval_run_get"),W=await x4(V,H,{recordId:K,...J},G);return d1(I,200,W),!0}if(w==="attachments"){let V=v4("seal_approval_run_attachments_get"),W=await x4(V,H,{recordId:K,...J},G);return d1(I,200,W),!0}if(w==="cited-rules"){let V=v4("seal_approval_run_cited_rules_get"),W=await x4(V,H,{recordId:K,...J},G);return d1(I,200,W),!0}if(w==="document-summary"){let V=v4("seal_approval_run_document_summary_get"),W=await x4(V,H,{recordId:K,...J},G);return d1(I,200,W),!0}if(w==="result"){let V=v4("seal_approval_run_result_get"),W=await x4(V,H,{recordId:K,...J},G);return d1(I,200,W),!0}}}if(q==="GET"&&U==="/v1/approval-runs"){let Q=h6($,Y,J),K=O4(Q),w=await q4(K),z=v4("seal_approval_runs_search"),G=await x4(z,w,{...J,limit:J.limit?Number(J.limit):void 0,offset:J.offset?Number(J.offset):void 0,includeBridge:J.includeBridge==="true"},K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/approval/rules"){let Q=h6($,Y,J),K=O4(Q),w=await q4(K),z=v4("seal_approval_rules_list"),G=await x4(z,w,J,K);return d1(I,200,G),!0}if(q==="GET"&&U==="/v1/simulation/batches"){let Q=h6($,Y,J),K=O4(Q),w=await q4(K),z=v4("seal_simulation_batches_list"),G=await x4(z,w,J,K);return d1(I,200,G),!0}if(q==="POST"&&U==="/v1/simulation/create-batch"){let Q=await DO($)||{},K=h6($,Line truncated
\uD83D\uDE80 seal-use HTTP Server (v${t0}) started`),console.error(` URL: http://${q}:${I}`),console.error(` Docs: http://${q}:${I}/docs`),console.error(` OpenAPI: http://${q}:${I}/openapi.json`),console.error(` CLI Exec: POST http://${q}:${I}/api/cli`),console.error(` REST API: http://${q}:${I}/v1/...
`);Y(U)})})}async function CZ0($){let I=e0($.options.port)??e0($.options.p),q=x($.options.host)??x($.options.h),U=await NO({port:I,host:q}),Y=()=>{U.close(()=>{process.exit(0)})};process.on("SIGINT",Y),process.on("SIGTERM",Y),await new Promise(()=>{})}async function _Z0($,I,q,U){if($==="config"||$==="get"){await L0("seal_llm_config_get",I,q,{},O0(U.options));return}if($==="providers"||$==="list"){await L0("seal_llm_providers_list",I,q,{},O0(U.options));return}throw Error(`Unknown llm command: ${$??""}. Run 'seal-use help' for available commands.`)}async function hZ0($,I){if($==="config"||$==="json"){Ou();return}await Lu()}function Ou(){v0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}function SZ0($){let I=ZO();v0(I,{...O0($.options),allowFull:!0})}async function yZ0($,I,q,U){if($==="available"){await L0("seal_permissions_available_list",I,q,{},O0(U.options));return}if($==="configs"||$==="list"){await L0("seal_permissions_configs_list",I,q,{},O0(U.options));return}throw Error(`Unknown permissions command: ${$??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as uZ0}from"node:fs";async function xZ0($,I,q,U,Y,J,Q){if(!$||$==="get"){await L0("seal_preference_get",Y,J,{},O0(Q.options));return}if($==="decision"){if(I==="update"||!I){let K=x(Q.options.input),w=K?JSON.parse(uZ0(K,"utf8")):t6(Q.json);if(!w||Object.keys(w).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await L0("seal_preference_decision_update",Y,J,w,O0(Q.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(I==="set"){let K=x(Q.options.default)??x(Q.options.level)??U;if(K!=="medium"&&K!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await L0("seal_preference_thinking_depth_set",Y,J,{defaultLevel:K},O0(Q.options));return}if(I==="policies"){if(q==="list"||!q){await L0("seal_preference_thinking_depth_policies_list",Y,J,{},O0(Q.options));return}if(q==="upsert"){let K=x(Q.options.input),w=K?JSON.parse(uZ0(K,"utf8")):t6(Q.json);if(!w||!w.id||!w.name)throw Error(`Usage: seal-use preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await L0("seal_preference_thinking_depth_policies_upsert",Y,J,w,O0(Q.options));return}if(q==="remove"||q==="delete"){let K=U??x(Q.options.id)??x(Q.options.policyId);if(!K)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await L0("seal_preference_thinking_depth_policies_remove",Y,J,{policyId:K},O0(Q.options));return}}}throw Error(`Unknown preference action: ${$??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}async function kZ0($={}){let I=V8(),q=V6(),U=Gq(I,{stateful:q.stateful,defaultCorpId:q.defaultCorpId,corpId:$.corpId},u7());console.log(`[probe] corp=${U.id} source=${U.source.type}`);let Y=await FY(U);console.log("[probe] seal enterprise"),console.log(JSON.stringify(Y,null,2));let J=await q4(U),Q=await bH(J,{documentLimit:20,stylePreferencesEndpoint:U.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:Q.rules.rules.length,hasPendingRuleDeletes:Q.rules.hasPendingDeletes,documents:Q.documents.articles.length,documentsTotal:Q.documents.total,stylePreferences:Q.stylePreferences.ok?"ok":`error: ${Q.stylePreferences.error}`},null,2))}async function fZ0($,I,q){let U=I??x(q.options.corp)??($&&$!=="--corp"?$:void 0);await kZ0({corpId:U})}async function Nu($,I,q,U,Y){if($==="count"){await L0("seal_approval_rules_list",q,U,{countOnly:!0},O0(Y.options));return}if($==="list"){if(C0(Y.options.count)){await L0("seal_approval_rules_list",q,U,{countOnly:!0},O0(Y.options));return}let J=e0(Y.options.limit),Q=e0(Y.options.offset);if(C0(Y.options.summary)){await L0("seal_approval_rules_list",q,U,{fields:KZ0,limit:J,offset:Q},O0(Y.options));return}let K=await p8("seal_approval_rules_list",q,U,{limit:J,offset:Q});wZ0(K,C0(Y.options.full)===!0),v0(K);return}if($==="clear"){let J=C0(Y.options.yes)===!0,Q=C0(Y.options.dryRun)??C0(Y.options["dry-run"])??!J;if(!J&&!Q)throw Error("Refusing to clear rules without --yes. Use --dry-run to preview.");let K=await p8("seal_approval_rules_clear",q,U,{dryRun:Q,recode:C0(Y.options.recode)});if(!J&&Q&&K&&typeof K==="object"){v0({...K,nextCommand:`seal-use rules clear --corp ${U.id} --yes`},O0(Y.options));return}v0(K,O0(Y.options));return}if($==="versions"){await L0("seal_approval_rule_versions_list",q,U,{},O0(Y.options));return}if($==="version"){let J=I??x(Y.options.version);if(!J)throw Error("Usage: seal-use rules version <versionId|versionNumber|latest>");await L0("seal_approval_rule_version_get",q,U,Vw(J),O0(Y.options));return}if($==="get"){await L0("seal_approval_rule_get",q,U,{...QZ0(x(Y.options.version)),code:x(Y.options.code),runtimeId:x(Y.options.runtimeId)??x(Y.options["runtime-id"]),recordId:x(Y.options.r Line truncated
`).filter(Boolean),J=Y.slice(-I);return{logFile:q,lines:J,totalLines:Y.length}}async function Zz1($){let I=gO($),q=Au($),U=Lw($);pZ0($.stateDir);let Y=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):OO),J=$.host??(process.env.HOST?process.env.HOST:LO);MO(I,`${process.pid}
`,{mode:384}),MO(q,JSON.stringify({pid:process.pid,port:Y,host:J,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),MY(U,`service starting on http://${J}:${Y} pid=${process.pid}`);let Q=null;try{Q=await NO({port:Y,host:J,silent:!0}),MY(U,`service listening pid=${process.pid}`)}catch(w){if(MY(U,`service failed to bind port ${Y}: ${w instanceof Error?w.message:String(w)}`),AO(I)===process.pid)c8(I,{force:!0}),c8(q,{force:!0});throw w}let K=()=>{if(Q)Q.close(),Q=null;if(AO(I)===process.pid)c8(I,{force:!0}),c8(q,{force:!0});MY(U,`stopped pid=${process.pid}`)};await new Promise((w)=>{let z=!1,G=()=>{if(z)return;z=!0,K(),process.off("SIGTERM",G),process.off("SIGINT",G),w()};process.once("SIGTERM",G),process.once("SIGINT",G)})}function nZ0($){pZ0($.stateDir);let I=AY($);if(I.running)return I;let q=$.launcher??{command:process.execPath,args:[$.entryFile]},U=[...q.args??[],"service","run"];if($.port)U.push("--port",String($.port));if($.host)U.push("--host",String($.host));let Y=Gz1(q.command,U,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});Y.unref();let J=gO($);return MO(J,`${Y.pid}
`,{mode:384}),MY(Lw($),`started pid=${Y.pid}`),{started:!0,...AY($)}}function iZ0($,I={}){let q=gO($),U=Au($),Y=AO(q);if(!Y||!bZ0(Y,$.appRoot))return c8(q,{force:!0}),c8(U,{force:!0}),I.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(Y,"SIGTERM"),c8(q,{force:!0}),c8(U,{force:!0}),MY(Lw($),`stop requested pid=${Y}`),I.quiet?void 0:{stopped:!0,pid:Y}}function bZ0($,I){if(!Xz1($))return!1;try{let q=Hz1("ps",["-p",String($),"-o","command="],{encoding:"utf8"});return(q.includes(I)||q.includes("seal-use")||q.includes("src/cli.ts"))&&q.includes("service")&&q.includes("run")}catch{return!1}}function Xz1($){try{return process.kill($,0),!0}catch{return!1}}function gO($){return Mu($.stateDir,"service.pid")}function Au($){return Mu($.stateDir,"service.json")}function Lw($){return Mu($.stateDir,"service.log")}function AO($){if(!FO($))return;let I=Number(Fu($,"utf8").trim());return Number.isInteger(I)&&I>0?I:void 0}function pZ0($){Vz1($,{recursive:!0,mode:448})}function MY($,I){MO($,`${new Date().toISOString()} ${I}
`,{flag:"a",mode:384})}var gu=Oz1(Dz1(),".config","seal-use");async function Pu($,I,q){let U=q?e0(q.options.port)??e0(q.options.p):void 0,Y=q?x(q.options.host)??x(q.options.h):void 0,J=q?e0(q.options.lines)??e0(q.options.n):void 0,Q=await qI($,{appRoot:I.appRoot,entryFile:I.entryFile,stateDir:gu,version:t0,launcher:I.launcher,port:U,host:Y},{maxLines:J});if(Q!==void 0)v0(Q)}import{existsSync as Lz1,readFileSync as cZ0}from"node:fs";async function dZ0($,I,q,U,Y){if($==="batch-records"||$==="records"){let J=I??x(Y.options.batchId)??x(Y.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation batch-records <batchId>");await L0("seal_simulation_batch_records_get",q,U,{batchId:J,query:x(Y.options.query)},O0(Y.options));return}if($==="create"||$==="run"){let J=x(Y.options.mode)??x(Y.options.sourceSystem)??x(Y.options["source-system"])??"hosecloud",Q=J==="material-pack"?"material_pack":J,K=x(Y.options.schemaConfig)??x(Y.options["schema-config"]),w=K?JSON.parse(cZ0(K,"utf8")):void 0,z=x(Y.options.input),G=z?JSON.parse(cZ0(z,"utf8")):t6(Y.json),H=x(Y.options.packageId)??x(Y.options["package-id"]),V=F6(Y.options.packageIds)??F6(Y.options["package-ids"])??(H?[H]:void 0),W=F6(Y.options.flowIds)??F6(Y.options["flow-ids"])??F6(Y.options.documentSn)??F6(Y.options["document-sn"]),X=x(Y.options.signKey)??x(Y.options["sign-key"])??x(Y.options.integration);await L0("seal_simulation_batch_create",q,U,{mode:Q,sourceSystem:Q,flowIds:W,documentSn:W,rejectNodeName:x(Y.options.rejectNode)??x(Y.options["reject-node"])??null,thinkingDepthOverride:x(Y.options.thinkingDepth)??x(Y.options["thinking-depth"]),skipInvoiceGeneration:C0(Y.options.skipInvoiceGeneration)??C0(Y.options["skip-invoice-generation"]),skipExpenseExtraction:C0(Y.options.skipExpenseExtraction)??C0(Y.options["skip-expense-extraction"]),disableAttachmentCache:C0(Y.options.disableAttachmentCache)??C0(Y.options["disable-attachment-cache"]),signKey:X,packageIds:V,packageId:H,templateId:x(Y.options.templateId)??x(Y.options["template-id"]),schemaConfig:w,requestIds:F6(Y.options.requestIds)??F6(Y.options["request-ids"]),workflowTypeId:x(Y.options.workflowTypeId)??x(Y.options["workflow-type-id"]),flowStatusList:F6(Y.options.flowStatusList)?.map(Number)??F6(Y.options["flow-status-list"])?.map(Number),businessCodes:F6(Y.options.businessCodes)??F6(Y.options["business-codes"]),documentType:x(Y.options.documentType)??x(Y.options["document-type"]),startTime:e0(Y.options.startTime)??e0(Y.options["start-time"]),endTime:e0(Y.options.endTime)??e0(Y.options["end-time"]),status:F6(Y.options.status),limit:e0(Y.options.limit),rawParams:G},O0(Y.options));return}if($==="wait"){let J=I??x(Y.options.batchId)??x(Y.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await L0("seal_simulation_batch_wait",q,U,{batchId:J,timeout:x(Y.options.timeout),pollInterval:x(Y.options.pollInterval)??x(Y.options["poll-interval"])},O0(Y.options));return}if($==="clean"||$==="delete"){let J=I??x(Y.options.batchId)??x(Y.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation clean <batchId>");await L0("seal_simulation_batch_clean",q,U,{batchId:J},O0(Y.options));return}if($==="specifications"){let J=I??x(Y.options.integration)??x(Y.options.signKey)??x(Y.options["sign-key"]);await L0("seal_simulation_specifications_list",q,U,{signKey:J},O0(Y.options));return}if($==="list"){await L0("seal_simulation_batches_list",q,U,{limit:e0(Y.options.limit)},O0(Y.options));return}if($==="get"){let J=I??x(Y.options.batchId)??x(Y.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation get <batchId>");await L0("seal_simulation_batch_get",q,U,{batchId:J},O0(Y.options));return}if($==="templates"){await L0("seal_simulation_templates_get",q,U,{},O0(Y.options));return}if($==="integrations"){await L0("seal_simulation_integrations_get",q,U,{},O0(Y.options));return}if($==="package-upload"){let J=I??x(Y.options.file);if(!J)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!Lz1(J))throw Error(`File not found: ${J}`);await L0("seal_simulation_material_package_upload",q,U,{filePath:J},O0(Y.options));return}throw Error(`Unknown simulation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as zX0}from"node:fs";import{join as PO}from"node:path";import{existsSync as Tu,mkdirSync as UX0,rmSync as Rz1,writeFileSync as Cz1}from"node:fs";import{homedir as YX0}from"node:os";import{dirname as _z1,join as Eu}from"node:path";var lZ0=`---
</html>`}async function k4($,I,U,Y){let J=$.handler;return J(I,U,{corp:Y})}async function kz0($,I){if(I.setHeader("Access-Control-Allow-Origin","*"),I.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),I.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),$.method==="OPTIONS"){I.writeHead(204),I.end();return}let U=$.headers.host||"localhost",Y=$.headers["x-forwarded-proto"]||"http",J=new jG1($.url||"/",`${Y}://${U}`),Q=J.pathname.replace(/\/+$/,"")||"/",K=($.method||"GET").toUpperCase();try{if(K==="GET"&&Q==="/"){r1(I,200,{name:"seal-use",version:U1,description:"Seal tenant operations and approval automation HTTP API",docs:"/docs",openapi:"/openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",tools:"GET /api/tools",toolInvoke:"POST /api/tool/:name",restV1:"GET/POST /v1/*"}});return}if(K==="GET"&&Q==="/docs"){SG1(I,200,xz0());return}if(K==="GET"&&Q==="/openapi.json"){r1(I,200,yD());return}if(K==="GET"&&Q==="/health"){r1(I,200,{status:"ok",version:U1,name:"seal-use",timestamp:new Date().toISOString()});return}if(K==="POST"&&(Q==="/shutdown"||Q==="/api/shutdown")){r1(I,200,{success:!0,message:"Shutting down seal-use background daemon",pid:process.pid}),setTimeout(()=>{process.kill(process.pid,"SIGTERM")},50);return}if(K==="POST"&&Q==="/api/cli"){let q=await uD($),H=(typeof q?.command==="string"?q.command:"").trim();if(!H){hD(I,400,"Missing 'command' property in request body");return}let G=yu(H),W=G[0]==="seal-use"||G[0]==="seal-home"||G[0]?.endsWith("/seal-use")||G[0]?.endsWith("/seal-home")?G.slice(1):G,w=await TH(W),V=void 0;try{if(w.stdout.trim().startsWith("{")||w.stdout.trim().startsWith("["))V=JSON.parse(w.stdout)}catch{}r1(I,w.isError?400:200,{success:!w.isError,stdout:w.stdout,stderr:w.stderr,exitCode:w.exitCode,data:V});return}if(K==="POST"&&Q.startsWith("/api/tool/")){let q=Q.slice(10).trim(),H=j4(q);if(!H){hD(I,404,`Tool not found: '${q}'`);return}let G=await uD($)||{},W=k6($,J,G),w=f1(W),V=await p1(w),Z={...G};delete Z.corp;let X=await k4(H,V,Z,w);r1(I,200,X);return}if(Q.startsWith("/v1/")){if(await _G1($,I,K,Q,J))return}hD(I,404,`Cannot ${K} ${Q}. Visit /docs for available endpoints.`)}catch(q){let H=q instanceof Error?q.message:String(q);hD(I,500,H)}}async function _G1($,I,U,Y,J){let Q=Object.fromEntries(J.searchParams.entries());if(U==="GET"&&Y==="/v1/corps"){let K=d8(),q=F4();return r1(I,200,{count:K.length,mode:q.stateful?"stateful":"stateless",defaultCorpId:q.defaultCorpId,corps:K.map((H)=>({id:H.id,name:H.name,sourceType:H.source.type,sealUrl:H.seal?.url}))}),!0}if(U==="GET"&&Y==="/v1/whoami"){let K=k6($,J,Q),q=f1(K),H=await p1(q),G=j4("seal_whoami"),W=await k4(G,H,{},q);return r1(I,200,W),!0}if(U==="GET"&&Y==="/v1/session"){let K=k6($,J,Q),q=f1(K),H=await p1(q),G=j4("seal_session_get"),W=await k4(G,H,{},q);return r1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval-runs/summary"){let K=k6($,J,Q),q=f1(K),H=await p1(q),G=j4("seal_approval_runs_summary"),W=await k4(G,H,Q,q);return r1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval-runs/stats"){let K=k6($,J,Q),q=f1(K),H=await p1(q),G=j4("seal_approval_runs_stats"),W=await k4(G,H,Q,q);return r1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval-runs/pick"){let K=k6($,J,Q),q=f1(K),H=await p1(q),G=j4("seal_approval_run_pick"),W=await k4(G,H,Q,q);return r1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval-runs/url"){let K=k6($,J,Q),q=f1(K),H=await p1(q),G=j4("seal_approval_run_url_get"),W=await k4(G,H,Q,q);return r1(I,200,W),!0}if(Y.startsWith("/v1/approval-runs/")){let K=Y.slice(18).split("/"),q=K[0],H=K[1];if(q&&!["summary","pick","stats","url","bridge"].includes(q)){let G=k6($,J,Q),W=f1(G),w=await p1(W);if(!H){let V=j4("seal_approval_run_get"),Z=await k4(V,w,{recordId:q,...Q},W);return r1(I,200,Z),!0}if(H==="attachments"){let V=j4("seal_approval_run_attachments_get"),Z=await k4(V,w,{recordId:q,...Q},W);return r1(I,200,Z),!0}if(H==="cited-rules"){let V=j4("seal_approval_run_cited_rules_get"),Z=await k4(V,w,{recordId:q,...Q},W);return r1(I,200,Z),!0}if(H==="document-summary"){let V=j4("seal_approval_run_document_summary_get"),Z=await k4(V,w,{recordId:q,...Q},W);return r1(I,200,Z),!0}if(H==="result"){let V=j4("seal_approval_run_result_get"),Z=await k4(V,w,{recordId:q,...Q},W);return r1(I,200,Z),!0}}}if(U==="GET"&&Y==="/v1/approval-runs"){let K=k6($,J,Q),q=f1(K),H=await p1(q),G=j4("seal_approval_runs_search"),W=await k4(G,H,{...Q,limit:Q.limit?Number(Q.limit):void 0,offset:Q.offset?Number(Q.offset):void 0,includeBridge:Q.includeBridge==="true"},q);return r1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval/rules"){let K=k6($,J,Q),q=f1(K),H=await p1(q),G=j4("seal_approval_rules_list"),W=await k4(G,H,Q,q);return r1(I,200,W),!0}if(U==="GET"&&Y==="/v1/simulation/batches"){let K=k6($,J,Q),q=f1(K),H=await p1(q),G=j4("seal_simulation_batches_list"),W=await k4(G,H,Q,q);return r1(I,200,W),!0}if(U==="POST"&&Y==="/v1/simulation/create-batch"){let K=await uD($)||{},q=k6($,J,K),H=f1(q),G=await p1Line truncated
\uD83D\uDE80 seal-use HTTP Server (v${U1}) started`),console.error(` URL: http://${U}:${I}`),console.error(` Docs: http://${U}:${I}/docs`),console.error(` OpenAPI: http://${U}:${I}/openapi.json`),console.error(` CLI Exec: POST http://${U}:${I}/api/cli`),console.error(` REST API: http://${U}:${I}/v1/...
`);J(Y)})})}async function fz0($){let I=m0($.options.port)??m0($.options.p),U=h($.options.host)??h($.options.h),Y=await fD({port:I,host:U}),J=()=>{Y.close(()=>{process.exit(0)})};process.on("SIGINT",J),process.on("SIGTERM",J),await new Promise(()=>{})}async function iz0($,I,U,Y){if($==="config"||$==="get"){await F0("seal_llm_config_get",I,U,{},V0(Y.options));return}if($==="providers"||$==="list"){await F0("seal_llm_providers_list",I,U,{},V0(Y.options));return}throw Error(`Unknown llm command: ${$??""}. Run 'seal-use help' for available commands.`)}async function bz0($,I){if($==="config"||$==="json"){hu();return}await uu()}function hu(){B0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}function nz0($){let I=yD();B0(I,{...V0($.options),allowFull:!0})}async function pz0($,I,U,Y){if($==="available"){await F0("seal_permissions_available_list",I,U,{},V0(Y.options));return}if($==="configs"||$==="list"){await F0("seal_permissions_configs_list",I,U,{},V0(Y.options));return}throw Error(`Unknown permissions command: ${$??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as cz0}from"node:fs";async function dz0($,I,U,Y,J,Q,K){if(!$||$==="get"){await F0("seal_preference_get",J,Q,{},V0(K.options));return}if($==="decision"){if(I==="update"||!I){let q=h(K.options.input),H=q?JSON.parse(cz0(q,"utf8")):U$(K.json);if(!H||Object.keys(H).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await F0("seal_preference_decision_update",J,Q,{...H,dryRun:N0(K.options.dryRun)??N0(K.options["dry-run"])},V0(K.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(I==="set"){let q=h(K.options.default)??h(K.options.level)??Y;if(q!=="medium"&&q!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await F0("seal_preference_thinking_depth_set",J,Q,{defaultLevel:q,dryRun:N0(K.options.dryRun)??N0(K.options["dry-run"])},V0(K.options));return}if(I==="policies"){if(U==="list"||!U){await F0("seal_preference_thinking_depth_policies_list",J,Q,{},V0(K.options));return}if(U==="upsert"){let q=h(K.options.input),H=q?JSON.parse(cz0(q,"utf8")):U$(K.json);if(!H||!H.id||!H.name)throw Error(`Usage: seal-use preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await F0("seal_preference_thinking_depth_policies_upsert",J,Q,{...H,dryRun:N0(K.options.dryRun)??N0(K.options["dry-run"])},V0(K.options));return}if(U==="remove"||U==="delete"){let q=Y??h(K.options.id)??h(K.options.policyId);if(!q)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await F0("seal_preference_thinking_depth_policies_remove",J,Q,{policyId:q,dryRun:N0(K.options.dryRun)??N0(K.options["dry-run"])},V0(K.options));return}}}throw Error(`Unknown preference action: ${$??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}async function mz0($={}){let I=d8(),U=F4(),Y=NJ(I,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$.corpId},YI());console.log(`[probe] corp=${Y.id} source=${Y.source.type}`);let J=await _J(Y);console.log("[probe] seal enterprise"),console.log(JSON.stringify(J,null,2));let Q=await p1(Y),K=await sw(Q,{documentLimit:20,stylePreferencesEndpoint:Y.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:K.rules.rules.length,hasPendingRuleDeletes:K.rules.hasPendingDeletes,documents:K.documents.articles.length,documentsTotal:K.documents.total,stylePreferences:K.stylePreferences.ok?"ok":`error: ${K.stylePreferences.error}`},null,2))}async function lz0($,I,U){let Y=I??h(U.options.corp)??($&&$!=="--corp"?$:void 0);await mz0({corpId:Y})}async function xu($,I,U,Y,J){if($==="count"){await F0("seal_approval_rules_list",U,Y,{countOnly:!0},V0(J.options));return}if($==="list"){if(N0(J.options.count)){await F0("seal_approval_rules_list",U,Y,{countOnly:!0},V0(J.options));return}let Q=m0(J.options.limit),K=m0(J.options.offset);if(N0(J.options.summary)){await F0("seal_approval_rules_list",U,Y,{fields:Jz0,limit:Q,offset:K},V0(J.options));return}let q=await zI("seal_approval_rules_list",U,Y,{limit:Q,offset:K});Qz0(q,N0(J.options.full)===!0),B0(q);return}if($==="clear"){let Q=N0(J.options.yes)===!0,K=N0(J.options.dryRun)??N0(J.options["dry-run"])??!Q;if(!Q&&!K)throw t8("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-use rules clear --corp ${Y.id} --dry-run`);let q=await zI("seal_approval_rules_clear",U,Y,{dryRun:K,recode:N0(J.options.recode)});if(!Q&&K&&q&&typeof q==="object"){B0({...q,nextCommand:`seal-use rules clear --corp ${Y.id} --yes`},V0(J.options));return}B0(q,V0(J.options));return}if($==="versions"){await F0("seal_approval_rule_versions_list",U,Y,{},V0(J.options));return}if($==="version"){let Q=I??h(J.options.version);if(!Q)throw Error("Usage: seal-use rules version <versionId|versionNumber|l Line truncated
`).filter(Boolean),Q=J.slice(-I);return{logFile:U,lines:Q,totalLines:J.length}}async function kG1($){let I=pD($),U=iu($),Y=EH($);az0($.stateDir);let J=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):xD),Q=$.host??(process.env.HOST?process.env.HOST:kD);bD(I,`${process.pid}
`,{mode:384}),bD(U,JSON.stringify({pid:process.pid,port:J,host:Q,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),SJ(Y,`service starting on http://${Q}:${J} pid=${process.pid}`);let K=null;try{K=await fD({port:J,host:Q,silent:!0}),SJ(Y,`service listening pid=${process.pid}`)}catch(H){if(SJ(Y,`service failed to bind port ${J}: ${H instanceof Error?H.message:String(H)}`),nD(I)===process.pid)a8(I,{force:!0}),a8(U,{force:!0});throw H}let q=()=>{if(K)K.close(),K=null;if(nD(I)===process.pid)a8(I,{force:!0}),a8(U,{force:!0});SJ(Y,`stopped pid=${process.pid}`)};await new Promise((H)=>{let G=!1,W=()=>{if(G)return;G=!0,q(),process.off("SIGTERM",W),process.off("SIGINT",W),H()};process.once("SIGTERM",W),process.once("SIGINT",W)})}function oz0($){az0($.stateDir);let I=gJ($);if(I.running)return I;let U=$.launcher??{command:process.execPath,args:[$.entryFile]},Y=[...U.args??[],"service","run"];if($.port)Y.push("--port",String($.port));if($.host)Y.push("--host",String($.host));let J=yG1(U.command,Y,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});J.unref();let Q=pD($);return bD(Q,`${J.pid}
`,{mode:384}),SJ(EH($),`started pid=${J.pid}`),{started:!0,...gJ($)}}function rz0($,I={}){let U=pD($),Y=iu($),J=nD(U);if(!J||!tz0(J,$.appRoot))return a8(U,{force:!0}),a8(Y,{force:!0}),I.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(J,"SIGTERM"),a8(U,{force:!0}),a8(Y,{force:!0}),SJ(EH($),`stop requested pid=${J}`),I.quiet?void 0:{stopped:!0,pid:J}}function tz0($,I){if(!fG1($))return!1;try{let U=hG1("ps",["-p",String($),"-o","command="],{encoding:"utf8"});return(U.includes(I)||U.includes("seal-use")||U.includes("src/cli.ts"))&&U.includes("service")&&U.includes("run")}catch{return!1}}function fG1($){try{return process.kill($,0),!0}catch{return!1}}function pD($){return fu($.stateDir,"service.pid")}function iu($){return fu($.stateDir,"service.json")}function EH($){return fu($.stateDir,"service.log")}function nD($){if(!iD($))return;let I=Number(ku($,"utf8").trim());return Number.isInteger(I)&&I>0?I:void 0}function az0($){uG1($,{recursive:!0,mode:448})}function SJ($,I){bD($,`${new Date().toISOString()} ${I}
`,{flag:"a",mode:384})}var bu=bG1(iG1(),".config","seal-use");async function nu($,I,U){let Y=U?m0(U.options.port)??m0(U.options.p):void 0,J=U?h(U.options.host)??h(U.options.h):void 0,Q=U?m0(U.options.lines)??m0(U.options.n):void 0,K=await XI($,{appRoot:I.appRoot,entryFile:I.entryFile,stateDir:bu,version:U1,launcher:I.launcher,port:Y,host:J},{maxLines:Q});if(K!==void 0)B0(K)}import{existsSync as nG1,readFileSync as sz0}from"node:fs";async function ez0($,I,U,Y,J){if($==="batch-records"||$==="records"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation batch-records <batchId>");await F0("seal_simulation_batch_records_get",U,Y,{batchId:Q,query:h(J.options.query)},V0(J.options));return}if($==="create"||$==="run"){let Q=h(J.options.mode)??h(J.options.sourceSystem)??h(J.options["source-system"])??"hosecloud",K=Q==="material-pack"?"material_pack":Q,q=h(J.options.schemaConfig)??h(J.options["schema-config"]),H=q?JSON.parse(sz0(q,"utf8")):void 0,G=h(J.options.input),W=G?JSON.parse(sz0(G,"utf8")):U$(J.json),w=h(J.options.packageId)??h(J.options["package-id"]),V=w6(J.options.packageIds)??w6(J.options["package-ids"])??(w?[w]:void 0),Z=w6(J.options.flowIds)??w6(J.options["flow-ids"])??w6(J.options.documentSn)??w6(J.options["document-sn"]),X=h(J.options.signKey)??h(J.options["sign-key"])??h(J.options.integration),L=N0(J.options.noWait)??N0(J.options["no-wait"]);await F0("seal_simulation_batch_create",U,Y,{mode:K,sourceSystem:K,flowIds:Z,documentSn:Z,rejectNodeName:h(J.options.rejectNode)??h(J.options["reject-node"])??null,thinkingDepthOverride:h(J.options.thinkingDepth)??h(J.options["thinking-depth"]),skipInvoiceGeneration:N0(J.options.skipInvoiceGeneration)??N0(J.options["skip-invoice-generation"]),skipExpenseExtraction:N0(J.options.skipExpenseExtraction)??N0(J.options["skip-expense-extraction"]),disableAttachmentCache:N0(J.options.disableAttachmentCache)??N0(J.options["disable-attachment-cache"]),signKey:X,packageIds:V,packageId:w,templateId:h(J.options.templateId)??h(J.options["template-id"]),schemaConfig:H,requestIds:w6(J.options.requestIds)??w6(J.options["request-ids"]),workflowTypeId:h(J.options.workflowTypeId)??h(J.options["workflow-type-id"]),flowStatusList:w6(J.options.flowStatusList)?.map(Number)??w6(J.options["flow-status-list"])?.map(Number),businessCodes:w6(J.options.businessCodes)??w6(J.options["business-codes"]),documentType:h(J.options.documentType)??h(J.options["document-type"]),startTime:m0(J.options.startTime)??m0(J.options["start-time"]),endTime:m0(J.options.endTime)??m0(J.options["end-time"]),status:w6(J.options.status),limit:m0(J.options.limit),noWait:L,rawParams:W},V0(J.options));return}if($==="wait"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await F0("seal_simulation_batch_wait",U,Y,{batchId:Q,timeout:h(J.options.timeout),pollInterval:h(J.options.pollInterval)??h(J.options["poll-interval"])},V0(J.options));return}if($==="status"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation status <batchId>");await F0("seal_simulation_batch_status",U,Y,{batchId:Q},V0(J.options));return}if($==="clean"||$==="delete"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation clean <batchId>");await F0("seal_simulation_batch_clean",U,Y,{batchId:Q},V0(J.options));return}if($==="specifications"){let Q=I??h(J.options.integration)??h(J.options.signKey)??h(J.options["sign-key"]);await F0("seal_simulation_specifications_list",U,Y,{signKey:Q},V0(J.options));return}if($==="approval-definitions"||$==="definitions"){await F0("seal_simulation_feishu_approval_definitions_list",U,Y,{},V0(J.options));return}if($==="list"){await F0("seal_simulation_batches_list",U,Y,{limit:m0(J.options.limit)},V0(J.options));return}if($==="get"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation get <batchId>");await F0("seal_simulation_batch_get",U,Y,{batchId:Q},V0(J.options));return}if($==="templates"){await F0("seal_simulation_templates_get",U,Y,{},V0(J.options));return}if($==="integrations"){await F0("seal_simulation_integrations_get",U,Y,{},V0(J.options));return}if($==="package-upload"){let Q=I??h(J.options.file);if(!Q)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!nG1(Q))throw Error(`File not found: ${Q}`);await F0("seal_simulation_material_package_upload",U,Y,{filePath:Q},V0(J.options));return}throw Error(`Unknown simulation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as DX0}from"node:fs";import{join as cD}from"node:path";import{existsSync as pu,mkdirSync as wX0,rmSync as $W1,writeFileSync as IW1}from"node:fs";import{homedir as VX0}from"node:os";import{dirname as UW1,join as cu}from"node:path";var $X0=`---
name: seal-use
description: "v0.10.8: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.10.16: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.10.8
short-description: Seal tenant and Hose approval automation (v0.10.8)
version: 0.10.16
short-description: Seal tenant and Hose approval automation (v0.10.16)
---
# Seal Use (v0.10.8)
# Seal Use (v0.10.16)
Use the \`seal_cli\` MCP tool when it is available; pass the command string as its \`command\` argument. If MCP is unavailable, fall back to the global \`seal-use\` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
@@ -513,7 +541,8 @@ seal-use corps list
- Prefer compact commands first: \`pick\`, \`--summary\`, \`--fields\`, \`attachments --summary\`, \`rules count\`, and \`rules list --summary\`.
- Parse JSON stdout. Do not scrape human text.
- Do not hand-edit enterprise configs for normal setup. Use \`seal-use corps ...\`.
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For repeat test-environment rule resets, prefer \`rules clear --dry-run\` followed by \`rules clear --yes\`.
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For supported configuration writes, prefer the universal \`--dry-run\` preview first (rules clear/push, preferences, thinking-depth policies, HoseCloud configure, and Webhook add/update/delete), then use \`--yes\` only after reviewing its redacted \`changesDiff\`.
- Knowledge document creation is currently irreversible: the upstream API exposes no delete operation. Validate \`contentType\` and \`scenarios\` before creating, and use \`enabled: false\` when the document should be withdrawn.
- For customer-feedback rule remediation, show an exact field-level diff and obtain explicit approval before updating. Default to changing only the narrowest necessary part of \`description\`; preserve \`scope\`, \`strictness\`, and unrelated clauses unless the user explicitly approves otherwise.
- Resolve and lock the target enterprise \`corpId\` before diagnosis or mutation. Never assume the current tenant is the customer tenant. Re-fetch the target rule immediately before updating, then verify the draft and newly published version after writing.
- For date questions, use explicit dates and \`--timezone Asia/Shanghai\`.
@@ -529,7 +558,8 @@ seal-use corps list
- First install / zero configuration / “how do I connect my enterprise?” / user supplies app credentials, an assistance link, or F12/Network cURL: read \`references/enterprise-onboarding.md\`. Ask what material the user already has in plain language, then discover all remaining identifiers automatically.
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run \`seal-use delegation create --corp <corpId> --note '<enterprise>'\`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (\` \`\`\`text ... \`\`\` \`) AND a hyperlink.
- Packaged customer feedback → approval-rule remediation: read \`references/customer-feedback-rule-remediation.md\`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version.
- 模拟测试发布闭环: \`seal-use simulation create --mode hosecloud --flow-ids ... --corp <corpId>\` (合思指定单号) 或 \`--mode material_pack --package-ids ... --schema-config file.json\` (材料包导入), 支持多源系统 \`--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>\`, \`simulation wait <batchId>\` 轮询等待完成, \`simulation clean <batchId>\` 清理数据, \`simulation specifications\` 列出单据模板, \`simulation list\`/\`get\`/\`batch-records\` 查看批次与记录。创建前确认目标环境为测试环境。
- 模拟测试发布闭环: \`seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp <corpId>\` (合思指定单号) 或 \`--mode material_pack --package-ids ... --schema-config file.json\` (材料包导入), 支持多源系统 \`--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>\`, \`simulation status <batchId>\` 单次查询状态, \`simulation wait <batchId>\` 轮询等待完成, \`simulation clean <batchId>\` 清理数据, \`simulation specifications\` 列出单据模板, \`simulation list\`/\`get\`/\`batch-records\` 查看批次与记录。创建前确认目标环境为测试环境。
- 测试企业标记、关联与配置规则同步: \`seal-use corps mark <corpId> --env <production|test> --confirm\` (严格标记环境), \`seal-use corps bind-test <prodCorpId> <testCorpId> --confirm\` (严格1对1下挂,禁止多层级串联), \`seal-use corps unbind-test <corpId> --confirm\`, \`seal-use corps sync-test <prodCorpId> [--dry-run|--yes] [--version-name <name>]\` (将正式企业的偏好和草稿规则覆盖同步到测试企业并自动发布语义版本 \`[Prod vN · #M]\`,输出并本地缓存 \`ruleMapping\`,正式企业规则保持草稿态不发布), \`seal-use rules map [--corp <corpId>] [--version <v|latest>] [--code <code>]\` (离线毫秒级速查测试与生产规则对照映射)。
- Seal AI 智能审核发布到合思费控: \`seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>\`; read \`references/hose-enterprise-deploy.md\`.
- 审核决策偏好与思考深度: \`seal-use preference get --corp <corpId>\`, \`preference decision update --json '...' --corp <corpId>\`, \`preference thinking-depth set --default <medium|high> --corp <corpId>\`, \`preference thinking-depth policies <list|upsert|remove> --corp <corpId>\`.
- 审核大盘统计与去重分析: \`seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|id] --corp <corpId>\`, \`seal-use approval-runs count --corp <corpId>\`.
@@ -539,12 +569,28 @@ seal-use corps list
- LLM Model Config & Providers: \`seal-use llm config --corp <corpId>\`, \`seal-use llm providers --corp <corpId>\`.
- System Permissions Config: \`seal-use permissions available --corp <corpId>\`, \`seal-use permissions configs --corp <corpId>\`.
- Billing & Feature Quotas: \`seal-use billing status --corp <corpId>\`, \`seal-use billing plans --corp <corpId>\`, \`seal-use billing features --corp <corpId>\`.
- Webhook 审批回调管理: \`seal-use webhook <list|get|add|update|delete> --corp <corpId>\`.
- Webhook 材料包导入: \`seal-use webhook material-pack preview <材料包.zip> --corp <corpId>\` 只做本地校验和解析;\`... push <材料包.zip> --webhook <idOrName> --corp <corpId>\` 上传附件并通过入站 Webhook 触发 AI 审批。它与 \`simulation material_pack\` 的官方服务端导入流程相互独立。
- Webhook 准备看板与审批回调管理: \`seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] --corp <corpId>\` (别名 \`status\`) 检查企业环境、租户连通性、已激活通道与材料包预检;\`seal-use webhook <list|get|add|update|delete> --corp <corpId>\`.
- Webhook 材料包导入: \`seal-use webhook material-pack preview <材料包.zip> --corp <corpId>\` 只做本地校验和解析(无网络请求);\`... push <材料包.zip> [--webhook <idOrName>] --corp <corpId>\` 上传附件并通过入站 Webhook 触发 AI 审批(租户仅有 1 个通道时自动锁定无需指定 \`--webhook\`)。每个 Webhook 可配置材料包附件的最小字节数、可选最大字节数和文件后缀白名单;这是可修改的持久化策略,不是不可绕过的硬编码。校验不通过时不会上传附件或推送单据。材料包格式:ZIP 根目录名 = \`documentId\`(或 \`documentId@annotation\`),Excel 附件列以 \`[附件]\` 为前缀(如 \`[附件]合同协议\`),单元格值为 ZIP 相对路径(支持多行/逗号/分号分隔);系统执行严格双向验证(Excel 声明的路径必须在 ZIP 中存在,ZIP 中的文件必须在某个 \`[附件]\` 列中声明)。详见 \`references/cli.md\` 中 "Material Pack Workflow" 一节。它与 \`simulation material_pack\` 的官方服务端导入流程相互独立。
- HTTP REST API & Docs Server: \`seal-use http [--port 8787] [--host 127.0.0.1]\` (提供 \`/docs\` 交互文档、\`/openapi.json\`、\`POST /api/cli\` 与 \`/v1/*\` REST API)。
- 审批规则质量校验 (Linter): \`seal-use rules lint [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary] --corp <corpId>\`; read \`references/rule-lint.md\`. 全局配置默认关闭 (\`config lint <enable|disable>\`)。
- Full CLI inventory: read \`references/cli.md\`.
## Material-pack Webhook policy and recovery
材料包附件策略保存在目标入站 Webhook 的 \`materialPackFilePolicy\` 下,按 Webhook 生效。新建 Webhook 的默认策略是:最小文件大小 \`500\` 字节、最大文件大小不限制、后缀白名单为常见 PDF/Office/文本/邮件/图片格式。\`信息表.xlsx\` 是材料包根清单,不属于普通附件,不受这三个附件策略限制。完整默认后缀和边界规则见 \`references/cli.md\`。
这套策略允许人工或助手修改。错误处理有两条通道:先通过错误通道明确告诉助手是哪一个文件、哪一条规则失败;再通过配置或文件处置通道完成恢复。遇到附件被拦截时按以下闭环处理:
1. 从错误中识别被拦截的文件、实际大小、失败规则和目标 Webhook。
2. 向用户说明可选处置:替换/压缩文件,或在确认允许该格式/大小后修改 Webhook 策略。
3. 用户或业务负责人明确确认放宽策略后,读取目标 Webhook 当前配置(CLI 使用 \`webhook get\`/\`webhook list\`,MCP 使用 \`seal_webhook_get\`/\`seal_webhook_list\`)。
4. 调用 \`seal_webhook_update\` 或 \`seal-use webhook update\` 修改最小值、最大值或完整后缀白名单,写入后重新读取核对,再重试原来的材料包 push。
push 会重新读取最新 Webhook 配置;校验通过后才会开始上传附件。CLI 以非零退出码和 \`stderr\` 返回可恢复的业务错误,MCP 以工具错误返回。没有用户授权或没有修改权限时,不能擅自放宽策略,也不能绕过校验。
注意:直接执行本地 \`material-pack preview\` 只使用默认策略或命令行临时覆盖,不会自动读取某个 Webhook 的持久化策略;\`webhook ready --file\`(指定 Webhook 时)和 \`material-pack push\` 才使用保存的 Webhook 策略。需要验证实际入站通道策略时,优先使用 \`ready --file --webhook ...\`,或直接重试 push。
## High-Value Commands
\`\`\`bash
@@ -600,14 +646,20 @@ seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅"
## Safety
Rule, document, style preference, and publish actions mutate Seal configuration. Make the target enterprise explicit, show the intended payload, and verify after the write. Never send real \`enterprises/*.json\` files, tokens, signed URLs, or full raw documents to GitHub, tickets, logs, or chat unless the user explicitly requests a safe export.
`;var mZ0=`interface:
`;var IX0=`interface:
display_name: "Seal Use"
short_description: "Diagnose approval feedback and publish minimal rule fixes"
default_prompt: "Use $seal-use to resolve a customer feedback package to the correct tenant, diagnose the approval run, propose a minimal rule diff, and publish only after explicit confirmation."
`;var oZ0=`# Rule Lightweight Queries
`;var UX0=`# Rule Lightweight Queries
Use this reference when the user wants rule counts, compact rule lists, one rule from a historical version, or approval knowledge search without dumping hundreds of rule descriptions.
## Draft and Published Rule Codes
\`rules list\` and \`rules pull\` operate on the current draft and therefore return draft \`code\` values. A published version stores a separate snapshot and may recode the same rules; publishing, deleting, or reordering rules can make those published codes differ or drift again. A code such as \`#0038\` is only meaningful together with its version context.
Use the draft \`id\` for current edits and use the approval run's recorded version plus rule text or runtime rule ID for historical investigations. Do not copy a draft code into a report or command that will be interpreted against a published version.
## Count Rules
Use count when only scale or existence matters.
@@ -709,7 +761,7 @@ Use current search only when the question is about current draft/current knowled
## Output Discipline
If a rule command would return many descriptions or more than about 20 rules, use \`rules count\`, \`rules list --summary\`, \`fields\`, \`snippetOnly\`, or \`--output-file\`. Use \`--full\` only for deliberate exports.
`;var rZ0=`# Approval Bad Case Catalog
`;var YX0=`# Approval Bad Case Catalog
Use this file only as a comparison catalog after inspecting the current trace. Do not treat any case below as a default diagnosis.
@@ -759,7 +811,7 @@ Important nuance:
- This is a bad-case pattern, not a general rule that every amount-total dispute is caused by \`pre_analysis\`.
- Use it when the current trace shows recognized amounts being excluded downstream or duplicate attachments producing inconsistent conclusions.
`;var tZ0="# Seal Use CLI Reference\n\nRun from any directory after installing the global CLI:\n\n```bash\nseal-use <command>\n```\n\nEnterprise config lookup:\n\n- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.\n- Otherwise `./enterprises` and `~/.config/seal-use/enterprises` are merged.\n- User-level configs override same-ID local configs.\n\nEnterprise selection is stateless by default. Commands that access an enterprise require\n`--corp <corpId>` unless stateful mode is explicitly enabled:\n\n```bash\nseal-use config mode stateful --corp <corpId>\nseal-use corps switch <corpId>\nseal-use config mode stateless\n```\n\nThe global mode is stored in `~/.config/seal-use/config.json`; set `SEAL_USE_CONFIG_FILE` to\noverride that path. The legacy `current-corp` file is not read.\n\n## Stream & Exit Code Contract\n\n- **`stdout`**: Pure, deterministic JSON for machine/Agent parsing.\n- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** (e.g. `👉 Next action: ...`).\n- **`Exit Code`**: `0` on success, non-zero (e.g. `1`) on failure to trigger Agent error self-remediation.\n\n## Top-Level Commands\n\n```bash\nseal-use version\nseal-use config paths\nseal-use config get\nseal-use config mode <stateful|stateless> [--corp <corpId>]\nseal-use config lint <enable|disable|status> [--linter <name>] [--min-score <score>]\nseal-use rules pull [--corp <corpId>] [--version <id|num|latest>] [--out <file>]\nseal-use rules lint [--file <path>] [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]\nseal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]\nseal-use service <start|stop|restart|status|logs> [--port 8787] [--host 127.0.0.1] [--lines 50]\nseal-use http [--port 8787] [--host 127.0.0.1]\nseal-use serve [--port 8787]\nseal-use update\nseal-use tools list\nseal-use corps list [--corp <corpId>]\nseal-use corps current [--corp <corpId>]\nseal-use corps switch <corpId>\nseal-use corps add-hose --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-use corps add-seal --json '{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'\nseal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]\nseal-use auth diagnose [--corp <corpId>]\nseal-use auth hose-link [--corp <corpId>] [--expire 7200]\nseal-use delegation list [--corp <corpId>]\nseal-use delegation create [--note <note>] [--from-link <url>] [--corp <corpId>]\nseal-use delegation revoke <tokenId> [--corp <corpId>]\nseal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]\nseal-use users reset-password <userId> [--corp <corpId>]\nseal-use users get <userId> [--corp <corpId>]\nseal-use users delete <userId> [--corp <corpId>]\nseal-use llm config [--corp <corpId>]\nseal-use llm providers [--corp <corpId>]\nseal-use permissions available [--corp <corpId>]\nseal-use permissions configs [--corp <corpId>]\nseal-use billing status [--corp <corpId>]\nseal-use billing plans [--corp <corpId>]\nseal-use billing features [--corp <corpId>]\nseal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]\nseal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]\nseal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]\nseal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]\nseal-use webhook delete <idOrName> --yes [--corp <corpId>]\nseal-use deploy hosecloud requirements [--corp <corpId>]\nseal-use deploy hosecloud list [--corp <corpId>]\nseal-use deploy hosecloud get [<sign-key>] [--corp <corpId>]\nseal-use deploy hosecloud status [--corp <corpId>]\nseal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]\nseal-use deploy hosecloud sync [<sign-key>] [--auto] [--corp <corpId>]\nseal-use preference get [--corp <corpId>]\nseal-use preference decision update --json '{\"explicitApprove\":\"...\"}' [--corp <corpId>]\nseal-use preference thinking-depth set --default <medium|high> [--corp <corpId>]\nseal-use preference thinking-depth policies list [--corp <corpId>]\nseal-use preference thinking-depth policies upsert --json '{...}' [--corp <corpId>]\nseal-use preference thinking-depth policies remove <policyId> [--corp <corpId>]\nseal-use source config [--corp <corpId>]\nseal-use tool <toolName> [--corp <corpId>] [--json '{\"key\":\"value\"}']\nseal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]\nseal-use approval-runs stats --corp <corpId> [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id]\nseal-uLine truncated
`;var JX0="# Seal Use CLI Reference\n\nRun from any directory after installing the global CLI:\n\n```bash\nseal-use <command>\n```\n\nEnterprise config lookup:\n\n- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.\n- Otherwise `./enterprises` and `~/.config/seal-use/enterprises` are merged.\n- User-level configs override same-ID local configs.\n\nEnterprise selection is stateless by default. Commands that access an enterprise require\n`--corp <corpId>` unless stateful mode is explicitly enabled:\n\n```bash\nseal-use config mode stateful --corp <corpId>\nseal-use corps switch <corpId>\nseal-use config mode stateless\n```\n\nThe global mode is stored in `~/.config/seal-use/config.json`; set `SEAL_USE_CONFIG_FILE` to\noverride that path. The legacy `current-corp` file is not read.\n\n## Stream & Exit Code Contract\n\n- **`stdout`**: Pure, deterministic JSON for machine/Agent parsing.\n- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** with the stable prefix `👉 Next action: seal-use ...`.\n- **`Exit Code`**: `0` on success; `1` runtime/upstream failure, `2` usage/argument error, `10` explicit destructive-operation confirmation required, `11` missing/invalid authentication, and `12` output protection requiring a compact/file/query alternative.\n\n## Top-Level Commands\n\n```bash\nseal-use version\nseal-use config paths\nseal-use config get\nseal-use config mode <stateful|stateless> [--corp <corpId>]\nseal-use config test-dir [<path>|--clear]\nseal-use config lint <enable|disable|status> [--linter <name>] [--min-score <score>]\nseal-use rules pull [--corp <corpId>] [--version <id|num|latest>] [--out <file>]\nseal-use rules lint [--file <path>] [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]\nseal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]\nseal-use service <start|stop|restart|status|logs> [--port 8787] [--host 127.0.0.1] [--lines 50]\nseal-use http [--port 8787] [--host 127.0.0.1]\nseal-use serve [--port 8787]\nseal-use update\nseal-use tools list\nseal-use corps list [--corp <corpId>]\nseal-use corps current [--corp <corpId>]\nseal-use corps switch <corpId>\nseal-use corps mark <corpId> --env <production|test> [--confirm]\nseal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]\nseal-use corps unbind-test [<corpId>] [--confirm]\nseal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]\nseal-use corps add-hose --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-use corps add-seal --json '{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'\nseal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]\nseal-use auth diagnose [--corp <corpId>]\nseal-use auth hose-link [--corp <corpId>] [--expire 7200]\nseal-use delegation list [--corp <corpId>]\nseal-use delegation create [--note <note>] [--from-link <url>] [--corp <corpId>]\nseal-use delegation revoke <tokenId> [--corp <corpId>]\nseal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]\nseal-use users reset-password <userId> [--corp <corpId>]\nseal-use users get <userId> [--corp <corpId>]\nseal-use users delete <userId> [--corp <corpId>]\nseal-use contacts departments [<departmentId>] [--corp <corpId>]\nseal-use contacts children <departmentId> [--corp <corpId>]\nseal-use contacts users <departmentId> [--corp <corpId>]\nseal-use contacts sync-time [--corp <corpId>]\nseal-use data expenses --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]\nseal-use data invoices --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]\nseal-use llm config [--corp <corpId>]\nseal-use llm providers [--corp <corpId>]\nseal-use permissions available [--corp <corpId>]\nseal-use permissions configs [--corp <corpId>]\nseal-use billing status [--corp <corpId>]\nseal-use billing plans [--corp <corpId>]\nseal-use billing features [--corp <corpId>]\nseal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]\nseal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]\nseal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp <corpId>]\nseal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--cLine truncated
Use this workflow when a customer disputes an AI approval finding about an attachment, invoice, receipt, OCR result, or a UI-highlighted audit result.
@@ -980,7 +1032,7 @@ Manual image check:
- The customer's objection that they were receipts rather than invoices was reasonable.
However, the final rejection also had an independent rule-37 reason: payment screenshots totaled 699.48 while reimbursement was 700.00.
`;var eZ0=`# Customer Feedback Rule Remediation
`;var qX0=`# Customer Feedback Rule Remediation
Use this low-freedom workflow when the user provides packaged customer feedback from WeChat, screenshots, rejection notifications, a document number, or expected business behavior and wants diagnosis or an approval-rule change.
@@ -1115,6 +1167,8 @@ seal-use tool seal_approval_rule_update --corp <corpId> \\
Do not send \`scope\` or \`strictness\` when they are unchanged. Fetch the draft again and verify the exact description, scope, strictness, and draft status before publishing.
For a complete local rule-set sync, \`rules push\` is incremental: it matches pulled rules by stable \`id\`, updates only changed fields, creates new entries, and removes entries omitted from the local file. It preserves matched rule IDs and does not recode the whole draft. Preview it with \`rules push --dry-run\` before applying.
## 9. Publish and verify
Publish only when explicitly authorized:
@@ -1144,7 +1198,7 @@ Return a compact report containing:
- New version number and version name, if published
- Verification result
- Whether a regression rerun was performed
`;var $X0="# Enterprise Onboarding\n\nRead this reference for first installation, zero configured enterprises, incoming credentials or assistance links, and browser-copied cURL. The goal is to identify the enterprise with the least user effort while keeping authentication material confidential.\n\n## Start With Discovery\n\nRun this before asking for setup parameters (if `seal-use` is not installed, first run `curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash`):\n\n```bash\nseal-use version\nseal-use corps list\n```\n\n- If `seal-use` is not installed on the system, run the curl install script above to install it.\n- If the target enterprise is listed, match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.\n- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.\n- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”\n\nDo not open with a JSON template or a list of internal fields.\n\nAll command examples in this reference are for the Agent to run. Do not hand them to the user as setup instructions. Communicate with the user in natural language and translate their answer into CLI/MCP parameters yourself.\n\n## Keep Two Concepts Separate\n\nClassify both the enterprise identity origin and how the current credential was acquired:\n\n| Enterprise identity origin | Credential material the user may have | Meaning |\n| --- | --- | --- |\n| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | Stable, refreshable standard integration |\n| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |\n| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |\n| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |\n| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |\n\nCredential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When `whoami` returns provider metadata, preserve it and use it to describe the tenant accurately.\n\n## Parameter Ownership\n\nAsk the user only for information that cannot be discovered safely:\n\n| Field | Owner and behavior |\n| --- | --- |\n| `appKey`, `appSecurity` | User supplies these for standard Hose OpenAPI onboarding. Explain that they come from the enterprise's 合思开放平台 application credentials. Treat both as secrets. |\n| `domain` | Probe the standard Hose SaaS domains automatically. Ask only when probing fails and the enterprise uses a private or dedicated deployment. |\n| Enterprise name and `corpId` | Discover from the credential response or Seal `whoami`. Do not ask the user to invent or locate them first. |\n| Administrator and `staffId` | Discover administrator candidates. If more than one is eligible, present name and masked phone for the user to choose; pass the selected ID internally. |\n| Seal URL, tenant ID, tenant slug | Discover from the assistance link, cURL host, and Seal `whoami`. |\n| Bearer token, cookies, signed query tokens | Extract only from user-supplied authentication material. Never print them back or include them in summaries. |\n\n## Route 1: Standard Hose Credentials\n\nThis is the preferred durable route for a Hose-sourced tenant. Read `hose-enterprise-init.md`, then use:\n\n```bash\nseal-use corps add-hose --json '{\"appKey\":\"...\",\"appSecurity\":\"...\"}'\n```\n\nThe CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with `staffName`, `staffPhone`, or the selected `staffId` internally. After creation, run:\n\n```bash\nseal-use auth diagnose --corp <discovered-id>\n```\n\nDo not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicated/private Hose deployment, add `domain` only after standard probing reports that it cannot find the enterprise.\n\n## Route 2: Incoming Assistance Link\n\nFirst distinguish the link by its host and purpose:\n\n- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.\n- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.\n- `seal-use auth hose-link` and `seal-use delegation create` generat Line truncated
`;var HX0="# Enterprise Onboarding\n\nRead this reference for first installation, zero configured enterprises, incoming credentials or assistance links, and browser-copied cURL. The goal is to identify the enterprise with the least user effort while keeping authentication material confidential.\n\n## Start With Discovery\n\nRun this before asking for setup parameters (if `seal-use` is not installed, first run `curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash`):\n\n```bash\nseal-use version\nseal-use corps list\n```\n\n- If `seal-use` is not installed on the system, run the curl install script above to install it.\n- If the target enterprise is listed, match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.\n- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.\n- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”\n\nDo not open with a JSON template or a list of internal fields.\n\nAll command examples in this reference are for the Agent to run. Do not hand them to the user as setup instructions. Communicate with the user in natural language and translate their answer into CLI/MCP parameters yourself.\n\n## Keep Two Concepts Separate\n\nClassify both the enterprise identity origin and how the current credential was acquired:\n\n| Enterprise identity origin | Credential material the user may have | Meaning |\n| --- | --- | --- |\n| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | Stable, refreshable standard integration |\n| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |\n| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |\n| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |\n| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |\n\nCredential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When `whoami` returns provider metadata, preserve it and use it to describe the tenant accurately.\n\n## Parameter Ownership\n\nAsk the user only for information that cannot be discovered safely:\n\n| Field | Owner and behavior |\n| --- | --- |\n| `appKey`, `appSecurity` | User supplies these for standard Hose OpenAPI onboarding. Explain that they come from the enterprise's 合思开放平台 application credentials. Treat both as secrets. |\n| `domain` | Probe the standard Hose SaaS domains automatically. Ask only when probing fails and the enterprise uses a private or dedicated deployment. |\n| Enterprise name and `corpId` | Discover from the credential response or Seal `whoami`. Do not ask the user to invent or locate them first. |\n| Administrator and `staffId` | Discover administrator candidates. If more than one is eligible, present name and masked phone for the user to choose; pass the selected ID internally. |\n| Seal URL, tenant ID, tenant slug | Discover from the assistance link, cURL host, and Seal `whoami`. |\n| Bearer token, cookies, signed query tokens | Extract only from user-supplied authentication material. Never print them back or include them in summaries. |\n\n## Route 1: Standard Hose Credentials\n\nThis is the preferred durable route for a Hose-sourced tenant. Read `hose-enterprise-init.md`, then use:\n\n```bash\nseal-use corps add-hose --json '{\"appKey\":\"...\",\"appSecurity\":\"...\"}'\n```\n\nThe CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with `staffName`, `staffPhone`, or the selected `staffId` internally. After creation, run:\n\n```bash\nseal-use auth diagnose --corp <discovered-id>\n```\n\nDo not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicated/private Hose deployment, add `domain` only after standard probing reports that it cannot find the enterprise.\n\n## Route 2: Incoming Assistance Link\n\nFirst distinguish the link by its host and purpose:\n\n- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.\n- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.\n- `seal-use auth hose-link` and `seal-use delegation create` generat Line truncated
Use this reference for Hose/合思 enterprise configuration and user-facing Hose authorization links.
@@ -1209,7 +1263,7 @@ Important:
- \`seal-use auth diagnose\` proves this stage works but redacts the token, so it is not enough when the user needs the actual clickable Hose link.
- **Formatting Requirement**: When returning a Hose authorization link to the user, ALWAYS provide BOTH a code block (\` \`\`\`text ... \`\`\` \`) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
- If the CLI later provides a dedicated command for this, prefer that command.
`;var qX0=`# Hose Enterprise Initialization & Automated Discovery
`;var WX0=`# Hose Enterprise Initialization & Automated Discovery
Use this reference for automated Hose/合思 enterprise onboarding, multi-domain probing (including dedicated private cloud domains like 美年大健康), OpenAPI role and staff discovery, and non-TUI safe administrator selection.
@@ -1315,12 +1369,12 @@ seal-use corps hose-staffs --json '{
}'
\`\`\`
* 直接使用指定 ID 完成接入并进行连通性验证。
`;var JX0={"SKILL.md":lZ0,"agents/openai.yaml":mZ0,"references/rule-lightweight.md":oZ0,"references/approval-bad-cases.md":rZ0,"references/cli.md":tZ0,"references/approval-run-lightweight.md":aZ0,"references/approval-attachment-trace.md":sZ0,"references/customer-feedback-rule-remediation.md":eZ0,"references/enterprise-onboarding.md":$X0,"references/hose-enterprise-auth.md":IX0,"references/hose-enterprise-init.md":qX0};function QX0(){return JX0["SKILL.md"]||""}function Nw(){return Eu(YX0(),".agents","skills","seal-use")}function KX0(){return Eu(YX0(),".agents","skills","seal-home")}function wX0(){let $=KX0();if(Tu($))try{return Rz1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function ju($=Nw()){wX0(),UX0($,{recursive:!0});let I=[];for(let[q,U]of Object.entries(JX0)){let Y=Eu($,q);UX0(_z1(Y),{recursive:!0}),Cz1(Y,U,"utf8"),I.push(q)}return{targetDir:$,files:I}}function Bu(){let $=KX0(),I=Nw(),q=Tu($),U=Tu(I);if(q||U)return wX0(),ju(I),{synced:!0,targetDir:I};return{synced:!1}}function GX0($,I,q){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${QX0()}
`);return}if($==="install"||$==="init"||$==="sync"){let U=C0(q.options.local)||C0(q.options.workspace),Y=x(q.options.dir)??x(q.options.target)??I,J=Y?Y:U?PO(process.cwd(),".agents","skills","seal-use"):Nw(),Q=ju(J);v0({installed:!0,targetDir:Q.targetDir,fileCount:Q.files.length,files:Q.files});return}if($==="status"||$==="get"||!$){let U=Nw(),Y=PO(process.cwd(),".agents","skills","seal-use");v0({global:{dir:U,installed:zX0(PO(U,"SKILL.md"))},local:{dir:Y,installed:zX0(PO(Y,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${$}. Run 'seal-use help' for available commands.`)}async function HX0($,I){if($==="config"){v0(await FY(I));return}throw Error(`Unknown source command: ${$??""}. Run 'seal-use help' for available commands.`)}async function VX0($,I,q,U){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await L0($,I,q,t6(U.json),O0(U.options))}function WX0(){v0(Gw.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as hz1,mkdirSync as Sz1,renameSync as vu,rmSync as yz1,unlinkSync as LX0,writeFileSync as ZX0}from"node:fs";import{dirname as uz1,join as XX0}from"node:path";import{spawnSync as UI}from"node:child_process";function TO($=process.execPath,I=import.meta.url){if(I.includes("/$bunfs/")||I.includes("\\$bunfs\\"))return!0;let q=$.toLowerCase().replace(/\\/g,"/");return!q.endsWith("/bun")&&!q.endsWith("/bun.exe")&&!q.endsWith("/node")&&!q.endsWith("/node.exe")}var NX0="yunyingk/seal-use",Mw="yunyingk/seal-home";var xz1="SEAL_USE_GITHUB_REPO",kz1="SEAL_HOME_GITHUB_REPO";async function FX0($,I={}){let q={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:gu,version:t0,launcher:$.launcher},U=I.repo||process.env[xz1]?.trim()||process.env[kz1]?.trim()||NX0,Y=I.targetVersion?.trim(),J=Y&&Y.toLowerCase()!=="latest"?Y:void 0;if(J){let g=J.replace(/^v/,""),B=MX0(g,t0);if(B<0){v0({updated:!1,currentVersion:t0,targetVersion:g,mode:TO()?"binary":"source",message:`Cannot downgrade seal-use from v${t0} to older version v${g}. Updates must be forward-only.`});return}if(B===0&&!I.force){v0({updated:!1,currentVersion:t0,targetVersion:g,mode:TO()?"binary":"source",message:`seal-use is already at version v${t0}. Use --force to reinstall.`});return}}if(I.changelogOnly){let g=await Ru(U,I.limit??10);v0({currentVersion:t0,totalQueried:g.length,releases:g.map((B)=>({version:B.version,tagName:B.tagName,publishedAt:B.publishedAt,author:B.author,releaseNotes:B.notes,releaseUrl:B.htmlUrl,isCurrent:B.version===t0,isNewer:Fw(B.version,t0)}))});return}if(!TO()){if(I.checkOnly){let B=await Ru(U,30),k=B[0],h=k?.version??t0,f=B.find((p)=>p.version===t0),S=Fw(h,t0),t=B.filter((p)=>Fw(p.version,t0));v0({updated:!1,updateAvailable:S,currentVersion:t0,currentVersionPublishedAt:f?.publishedAt,latestVersion:h,latestVersionPublishedAt:k?.publishedAt,behindCount:t.length,pendingReleases:t.map((p)=>({version:p.version,tagName:p.tagName,publishedAt:p.publishedAt,author:p.author,releaseNotes:p.notes,releaseUrl:p.htmlUrl})),releaseNotes:k?.notes??"",releaseUrl:k?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let g=AY(q).running;if(g)await qI("stop",q);try{OX0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(B){console.error(`git pull skipped: ${B instanceof Error?B.message:String(B)}`)}if(OX0("bun",["install"],{cwd:$.appRoot}),g)await qI("start",q);v0({updated:!0,serviceRestarted:g,version:t0,mode:"source"});return}let Q=fz1(),K=nz1(),w=await Ru(U,30),z=J?w.find((g)=>g.version===J||g.tagName===J||g.tagName===`v${J}`)??await DX0(U,J):w[0]??await DX0(U);if(!z){v0({updated:!1,currentVersion:t0,mode:"binary",message:`Failed to query releases from repository '${U}'`});return}let G=z.version,H=w.find((g)=>g.version===t0),V=Fw(G,t0),W=V||Boolean(I.force),X=w.filter((g)=>Fw(g.version,t0));if(I.checkOnly){v0({updated:!1,updateAvailable:V,currentVersion:t0,currentVersionPublishedAt:H?.publishedAt,latestVersion:G,latestVersionPublishedAt:z.publishedAt,behindCount:X.length,pendingReleases:X.map((g)=>({version:g.version,tagName:g.tagName,publishedAt:g.publishedAt,author:g.author,releaseNotes:g.notes,releaseUrl:g.htmlUrl})),releaseNotes:z.notes,releaseUrl:z.htmlUrl,mode:"binary"});return}if(!W){v0({updated:!1,currentVersion:t0,currentVersionPublishedAt:H?.publishedAt,latestVersion:G,latestVersionPublishedAt:z.publishedAt,mode:"binary",message:`seal-use is already up to date (v${t0})`});return}let D=iz1(z.assets,Q,K);if(!D)throw Error(`No compatible binary found for ${Q}-${K} in release v${G}. Available assets: ${z.assets.map((g)=>g.name).join(", ")}`);let O=AY(q).running;if(O)await qI("stop",q);let N=process.execPath,T=uz1(N),P=XX0(T,`.tmp-update-${Date.now()}`);Sz1(P,{recursive:!0});try{let g=XX0(P,D.name);await bz1(D.downloadUrl,g,z.tagName,D.name);let B=g;if(D.name.endsWith(".tar.gz")||D.name.endsWith(".tgz"))B=pz1(g,P,Q);else if(D.name.endsWith(".zip"))B=cz1(g,P,Q);if(hz1(B,493),process.platform==="darwin")try{UI("/usr/bin/codesig Line truncated
`)}catch{}}async function bz1($,I,q,U){let Y=Cu(),J=[],Q=q?q.startsWith("v")?q:`v${q}`:void 0,K=U||$.split("/").pop()||"";if(Y!=="github"){if(Q&&K)J.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${Q}/${K}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${Q}/${K}`);if($.startsWith("https://git.ying-qing.cn"))J.push($)}if(Y!=="gitea")if(Q&&K){let D=`https://github.com/${NX0}/releases/download/${Q}/${K}`;if(!process.env.CI)J.push(`https://ghfast.top/${D}`,`https://gh.ddlc.top/${D}`);J.push(D)}else if($.includes("github.com")){if(!process.env.CI)J.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);J.push($)}else J.push($);let w=Array.from(new Set(J)),z,G=6000,H=6000,V=307200,W=1e4,X=180000;for(let D=0;D<w.length;D++){let O=w[D],N=new AbortController,T="",P=(h)=>{T=h;try{N.abort()}catch{}},g=setTimeout(()=>{P("Connection timed out (no response headers within 6s)")},G),B,k;try{EO(`==> [${D+1}/${w.length}] Downloading via: ${O}`);let h=await fetch(O,{signal:N.signal});if(g)clearTimeout(g),g=void 0;if(!h.ok)throw Error(`HTTP ${h.status} ${h.statusText}`);B=setTimeout(()=>{P("Overall download time exceeded 3 minutes")},X);let f=Number(h.headers.get("content-length"))||0,S=h.body?.getReader();if(!S){let i=Buffer.from(await h.arrayBuffer());if(i.length<1000)throw Error(`Downloaded content is suspiciously small (${i.length} bytes)`);ZX0(I,i),EO(`✓ Download succeeded (${(i.length/1024/1024).toFixed(1)} MB)`);return}let t=[],p=0,C=0;k=setTimeout(()=>{if(p<V){let i=(p/1024).toFixed(1);P(`Initial transfer too slow (${i} KB < 300 KB in 6s), switching mirror...`)}},H);while(!0){let i=S.read(),J0,E=new Promise((K0,G0)=>{J0=setTimeout(()=>{G0(Error("Data transfer stalled (no chunk received for 10s)"))},W)}),u;try{u=await Promise.race([i,E])}finally{if(J0)clearTimeout(J0)}let{done:d,value:a}=u;if(d)break;if(a){if(t.push(a),p+=a.length,k&&p>=V)clearTimeout(k),k=void 0;let K0=Date.now();if(K0-C>200){C=K0;let G0=f?Math.round(p/f*100):0,M0=(p/1048576).toFixed(1),R0=f?(f/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${G0}% (${M0} / ${R0} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let n=Buffer.concat(t);if(n.length<1000)throw Error(`Downloaded content is suspiciously small (${n.length} bytes)`);ZX0(I,n),EO(`✓ Download completed successfully (${(n.length/1024/1024).toFixed(1)} MB)`);return}catch(h){if(g)clearTimeout(g);if(k)clearTimeout(k);if(B)clearTimeout(B);let f=T||(h instanceof Error?h.message:String(h));z=Error(f),EO(`
↳ Mirror failed: ${z.message}`)}finally{if(g)clearTimeout(g);if(k)clearTimeout(k);if(B)clearTimeout(B)}}throw Error(`Failed to download asset from all mirrors: ${z?.message}`)}function pz1($,I,q){let U=UI("tar",["-xzf",$,"-C",I],{stdio:"pipe"});if(U.status!==0)throw Error(`Failed to extract tar archive: ${U.stderr.toString()}`);LX0($);let Y=q==="windows"?"seal-use.exe":"seal-use",J=UI("find",[I,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),Q=J.find((K)=>K.endsWith(`/${Y}`)||K.endsWith(Y));if(Q)return Q;return J[0]||$}function cz1($,I,q){let U=UI("unzip",["-q","-o",$,"-d",I],{stdio:"pipe"});if(U.status!==0)throw Error(`Failed to extract zip archive: ${U.stderr.toString()}`);LX0($);let Y=q==="windows"?"seal-use.exe":"seal-use",J=UI("find",[I,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),Q=J.find((K)=>K.endsWith(`/${Y}`)||K.endsWith(Y));if(Q)return Q;return J[0]||$}function MX0($,I){let q=$.replace(/^v/,"").split(".").map((Y)=>Number.parseInt(Y,10)||0),U=I.replace(/^v/,"").split(".").map((Y)=>Number.parseInt(Y,10)||0);for(let Y=0;Y<Math.max(q.length,U.length);Y++){let J=q[Y]??0,Q=U[Y]??0;if(J>Q)return 1;if(J<Q)return-1}return 0}function Fw($,I){return MX0($,I)>0}function OX0($,I,q={}){let U=UI($,I,{cwd:q.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(U.stdout)console.error(U.stdout.trimEnd());if(U.stderr)console.error(U.stderr.trimEnd());if(U.status!==0)throw Error(`${$} ${I.join(" ")} failed with status ${U.status}`)}async function AX0($,I,q,U,Y){if($==="create"){let J=x(Y.options.name)??I,Q=x(Y.options.phone);if(!J||!Q)throw Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");let K=x(Y.options.dept)??x(Y.options.departmentId);await L0("seal_user_create",q,U,{name:J,phone:Q,departmentIds:K?[K]:void 0},O0(Y.options));return}if($==="reset-password"){let J=I??x(Y.options.userId);if(!J)throw Error("Usage: seal-use users reset-password <userId>");await L0("seal_user_reset_password",q,U,{userId:J},O0(Y.options));return}if($==="search"||$==="list"){let J=I??x(Y.options.keyword)??x(Y.options.query)??"";await L0("seal_user_search",q,U,{keyword:J},O0(Y.options));return}if($==="get"){let J=I??x(Y.options.userId);if(!J)throw Error("Usage: seal-use users get <userId>");await L0("seal_user_get",q,U,{userId:J},O0(Y.options));return}if($==="delete"){let J=I??x(Y.options.userId);if(!J)throw Error("Usage: seal-use users delete <userId>");await L0("seal_user_delete",q,U,{userId:J},O0(Y.options));return}if($==="activate"){let J=I??x(Y.options.userId);if(!J)throw Error("Usage: seal-use users activate <userId>");await L0("seal_user_activate",q,U,{userId:J},O0(Y.options));return}if($==="delegation"||$==="impersonate"){let J=I??x(Y.options.userId)??x(Y.options.phone);if(!J)throw Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");let Q=x(Y.options.note);await L0("seal_user_delegation_create",q,U,{userIdOrPhone:J,note:Q},O0(Y.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as gX0}from"node:fs";async function PX0($){if(!gX0($))throw Error(`File not found: ${$}`);let I=Kw($);console.log(JSON.stringify(await Qw(I.fileBuffer,I.fileName),null,2))}async function TX0($,I,q,U,Y){if($==="material-pack"||$==="material-pack-push"){let J=$==="material-pack-push"?"push":I,Q=$==="material-pack-push"?x(Y.options.file)??x(Y.options.input):Y.command[3]??x(Y.options.file)??x(Y.options.input);if(!Q)throw Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");if(!gX0(Q))throw Error(`File not found: ${Q}`);let K=Kw(Q);if(J==="preview"){console.log(JSON.stringify(await Qw(K.fileBuffer,K.fileName),null,2));return}if(J!=="push")throw Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");let w=x(Y.options.webhook)??x(Y.options.selector);if(!w)throw Error("Push requires --webhook <idOrName>");let z=Wq(await Vq(q),w),G=await YO(K.fileBuffer,K.fileName,{webhookUrl:z.incomingDocumentWebhook.url,secret:z.secret});console.log(JSON.stringify(G,null,2));return}if($==="list"){await L0("seal_webhook_list",q,U,{query:x(Y.options.query)??x(Y.options.keyword),includeSecret:Wu(Y.options)},O0(Y.options));return}if($==="get"||$==="find"){let J=I??x(Y.options.selector)??x(Y.options.id);if(!J)throw Error("Usage: seal-use webhook get <idOrName> [--show-secret]");await L0("seal_webhook_get",q,U,{selector:J,includeSecret:Wu(Y.options)},O0(Y.options));return}if($==="add"||$==="create"){let J=x(Y.options.name)??I,Q=x(Y.options.resultUrl)??x(Y.options["result-url"])??x(Y.options.outgoingResultWebhook)??x(Y.options["outgoing-result-webhook"]);if(!J||!Q)throw Error("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");let K=Vu(Y.options);await L0("seal_webhook_add",q,U,{name:J,mode:Hu(x(Y.options.mode)),outgoingResultWebhook:Q,autoApprovalRate:K,secret:x(Y.options.secret)},O0(Y.options));return}if($==="update"){let J=I??x(Y.options.selector)??x(Y.options.id);if(!J)throw Error("Usage: seal-use webhook update <idOrName> [options]");let Q=x(Y.options.secret),K=C0(Y.options.rotateSecret)??C0(Y.options["rotate-secret"]);if(Q!==void 0&&K)throw Error("Use either --secret or --rotate-secret, not both");let w=x(Y.options.name),z=Hu(x(Y.options.mode)),G=x(Y.options.resultUrl)??x(Y.options["result-url"])??x(Y.options.outgoingResultWebhook)??x(Y.options["outgoing-result-webhook"]),H=Vu(Y.options);if(w===void 0&&z===void 0&&G===void 0&&H===void 0&&Q===void 0&&!K)throw Error("Webhook update requires at least one field option");await L0("seal_webhook_update",q,U,{selector:J,name:w,mode:z,outgoingResultWebhook:G,autoApprovalRate:H,secret:Q,rotateSecret:K},O0(Y.options));return}if($==="delete"){let J=I??x(Y.options. Line truncated
`;var ZX0={"SKILL.md":$X0,"agents/openai.yaml":IX0,"references/rule-lightweight.md":UX0,"references/approval-bad-cases.md":YX0,"references/cli.md":JX0,"references/approval-run-lightweight.md":QX0,"references/approval-attachment-trace.md":KX0,"references/customer-feedback-rule-remediation.md":qX0,"references/enterprise-onboarding.md":HX0,"references/hose-enterprise-auth.md":GX0,"references/hose-enterprise-init.md":WX0};function zX0(){return ZX0["SKILL.md"]||""}function BH(){return cu(VX0(),".agents","skills","seal-use")}function XX0(){return cu(VX0(),".agents","skills","seal-home")}function LX0(){let $=XX0();if(pu($))try{return $W1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function du($=BH()){LX0(),wX0($,{recursive:!0});let I=[];for(let[U,Y]of Object.entries(ZX0)){let J=cu($,U);wX0(UW1(J),{recursive:!0}),IW1(J,Y,"utf8"),I.push(U)}return{targetDir:$,files:I}}function mu(){let $=XX0(),I=BH(),U=pu($),Y=pu(I);if(U||Y)return LX0(),du(I),{synced:!0,targetDir:I};return{synced:!1}}function FX0($,I,U){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${zX0()}
`);return}if($==="install"||$==="init"||$==="sync"){let Y=N0(U.options.local)||N0(U.options.workspace),J=h(U.options.dir)??h(U.options.target)??I,Q=J?J:Y?cD(process.cwd(),".agents","skills","seal-use"):BH(),K=du(Q);B0({installed:!0,targetDir:K.targetDir,fileCount:K.files.length,files:K.files});return}if($==="status"||$==="get"||!$){let Y=BH(),J=cD(process.cwd(),".agents","skills","seal-use");B0({global:{dir:Y,installed:DX0(cD(Y,"SKILL.md"))},local:{dir:J,installed:DX0(cD(J,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${$}. Run 'seal-use help' for available commands.`)}async function OX0($,I){if($==="config"){B0(await _J(I));return}throw Error(`Unknown source command: ${$??""}. Run 'seal-use help' for available commands.`)}async function NX0($,I,U,Y){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await F0($,I,U,U$(Y.json),V0(Y.options))}function MX0(){B0(DH.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as YW1,mkdirSync as JW1,renameSync as lu,rmSync as QW1,unlinkSync as BX0,writeFileSync as AX0}from"node:fs";import{dirname as KW1,join as PX0}from"node:path";import{spawnSync as LI}from"node:child_process";function dD($=process.execPath,I=import.meta.url){if(I.includes("/$bunfs/")||I.includes("\\$bunfs\\"))return!0;let U=$.toLowerCase().replace(/\\/g,"/");return!U.endsWith("/bun")&&!U.endsWith("/bun.exe")&&!U.endsWith("/node")&&!U.endsWith("/node.exe")}var vX0="yunyingk/seal-use",RH="yunyingk/seal-home";var qW1="SEAL_USE_GITHUB_REPO",HW1="SEAL_HOME_GITHUB_REPO";async function RX0($,I={}){let U={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:bu,version:U1,launcher:$.launcher},Y=I.repo||process.env[qW1]?.trim()||process.env[HW1]?.trim()||vX0,J=I.targetVersion?.trim(),Q=J&&J.toLowerCase()!=="latest"?J:void 0;if(Q){let A=Q.replace(/^v/,""),R=CX0(A,U1);if(R<0)if(!uE&&I.force);else{B0({updated:!1,currentVersion:U1,targetVersion:A,mode:dD()?"binary":"source",message:!uE?`Cannot downgrade seal-use from dev build v${U1} to release v${A}. Use --force to overwrite.`:`Cannot downgrade seal-use from v${U1} to older version v${A}. Updates must be forward-only.`});return}if(R===0&&!I.force){B0({updated:!1,currentVersion:U1,targetVersion:A,mode:dD()?"binary":"source",message:`seal-use is already at version v${U1}. Use --force to reinstall.`});return}}if(I.changelogOnly){let A=await ou(Y,I.limit??10);B0({currentVersion:U1,totalQueried:A.length,releases:A.map((R)=>({version:R.version,tagName:R.tagName,publishedAt:R.publishedAt,author:R.author,releaseNotes:R.notes,releaseUrl:R.htmlUrl,isCurrent:R.version===U1,isNewer:vH(R.version,U1)}))});return}if(!dD()){if(I.checkOnly){let R=await ou(Y,30),k=R[0],g=k?.version??U1,f=R.find((n)=>n.version===U1),C=vH(g,U1),p=R.filter((n)=>vH(n.version,U1));B0({updated:!1,updateAvailable:C,currentVersion:U1,currentVersionPublishedAt:f?.publishedAt,latestVersion:g,latestVersionPublishedAt:k?.publishedAt,behindCount:p.length,pendingReleases:p.map((n)=>({version:n.version,tagName:n.tagName,publishedAt:n.publishedAt,author:n.author,releaseNotes:n.notes,releaseUrl:n.htmlUrl})),releaseNotes:k?.notes??"",releaseUrl:k?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let A=gJ(U).running;if(A)await XI("stop",U);try{EX0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(R){console.error(`git pull skipped: ${R instanceof Error?R.message:String(R)}`)}if(EX0("bun",["install"],{cwd:$.appRoot}),A)await XI("start",U);B0({updated:!0,serviceRestarted:A,version:U1,mode:"source"});return}let K=GW1(),q=WW1(),H=await ou(Y,30),G=Q?H.find((A)=>A.version===Q||A.tagName===Q||A.tagName===`v${Q}`)??await TX0(Y,Q):H[0]??await TX0(Y);if(!G){B0({updated:!1,currentVersion:U1,mode:"binary",message:`Failed to query releases from repository '${Y}'`});return}let W=G.version,w=H.find((A)=>A.version===U1),V=vH(W,U1),Z=V||Boolean(I.force),X=H.filter((A)=>vH(A.version,U1));if(I.checkOnly){B0({updated:!1,updateAvailable:V,currentVersion:U1,currentVersionPublishedAt:w?.publishedAt,latestVersion:W,latestVersionPublishedAt:G.publishedAt,behindCount:X.length,pendingReleases:X.map((A)=>({version:A.version,tagName:A.tagName,publishedAt:A.publishedAt,author:A.author,releaseNotes:A.notes,releaseUrl:A.htmlUrl})),releaseNotes:G.notes,releaseUrl:G.htmlUrl,mode:"binary"});return}if(!Z){B0({updated:!1,currentVersion:U1,currentVersionPublishedAt:w?.publishedAt,latestVersion:W,latestVersionPublishedAt:G.publishedAt,mode:"binary",message:`seal-use is already up to date (v${U1})`});return}let L=wW1(G.assets,K,q);if(!L)throw Error(`No compatible binary found for ${K}-${q} in release v${W}. Available assets: ${G.assets.map((A)=>A.name).join(", ")}`);let D=gJ(U).running;if(D)await XI("stop",U);let O=process.execPath,E=KW1(O),T=PX0(E,`.tmp-update-${Date.now()}`);JW1(T,{recursive:!0});try{let A=PX0(T,L.name);await VW1(L.downloadUrl,A,G.tagName,L.name);let R=A;if(L.name.endsWith(".tar.gz")||L.name.endsWith(".tgz"))R=ZW1 Line truncated
`)}catch{}}async function VW1($,I,U,Y){let J=ru(),Q=[],K=U?U.startsWith("v")?U:`v${U}`:void 0,q=Y||$.split("/").pop()||"";if(J!=="github"){if(K&&q)Q.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${K}/${q}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${K}/${q}`);if($.startsWith("https://git.ying-qing.cn"))Q.push($)}if(J!=="gitea")if(K&&q){let L=`https://github.com/${vX0}/releases/download/${K}/${q}`;if(!process.env.CI)Q.push(`https://ghfast.top/${L}`,`https://gh.ddlc.top/${L}`);Q.push(L)}else if($.includes("github.com")){if(!process.env.CI)Q.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);Q.push($)}else Q.push($);let H=Array.from(new Set(Q)),G,W=6000,w=6000,V=307200,Z=1e4,X=180000;for(let L=0;L<H.length;L++){let D=H[L],O=new AbortController,E="",T=(g)=>{E=g;try{O.abort()}catch{}},A=setTimeout(()=>{T("Connection timed out (no response headers within 6s)")},W),R,k;try{mD(`==> [${L+1}/${H.length}] Downloading via: ${D}`);let g=await fetch(D,{signal:O.signal});if(A)clearTimeout(A),A=void 0;if(!g.ok)throw Error(`HTTP ${g.status} ${g.statusText}`);R=setTimeout(()=>{T("Overall download time exceeded 3 minutes")},X);let f=Number(g.headers.get("content-length"))||0,C=g.body?.getReader();if(!C){let b=Buffer.from(await g.arrayBuffer());if(b.length<1000)throw Error(`Downloaded content is suspiciously small (${b.length} bytes)`);AX0(I,b),mD(`✓ Download succeeded (${(b.length/1024/1024).toFixed(1)} MB)`);return}let p=[],n=0,S=0;k=setTimeout(()=>{if(n<V){let b=(n/1024).toFixed(1);T(`Initial transfer too slow (${b} KB < 300 KB in 6s), switching mirror...`)}},w);while(!0){let b=C.read(),Y0,B=new Promise((Q0,w0)=>{Y0=setTimeout(()=>{w0(Error("Data transfer stalled (no chunk received for 10s)"))},Z)}),x;try{x=await Promise.race([b,B])}finally{if(Y0)clearTimeout(Y0)}let{done:c,value:r}=x;if(c)break;if(r){if(p.push(r),n+=r.length,k&&n>=V)clearTimeout(k),k=void 0;let Q0=Date.now();if(Q0-S>200){S=Q0;let w0=f?Math.round(n/f*100):0,M0=(n/1048576).toFixed(1),R0=f?(f/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${w0}% (${M0} / ${R0} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let i=Buffer.concat(p);if(i.length<1000)throw Error(`Downloaded content is suspiciously small (${i.length} bytes)`);AX0(I,i),mD(`✓ Download completed successfully (${(i.length/1024/1024).toFixed(1)} MB)`);return}catch(g){if(A)clearTimeout(A);if(k)clearTimeout(k);if(R)clearTimeout(R);let f=E||(g instanceof Error?g.message:String(g));G=Error(f),mD(`
↳ Mirror failed: ${G.message}`)}finally{if(A)clearTimeout(A);if(k)clearTimeout(k);if(R)clearTimeout(R)}}throw Error(`Failed to download asset from all mirrors: ${G?.message}`)}function ZW1($,I,U){let Y=LI("tar",["-xzf",$,"-C",I],{stdio:"pipe"});if(Y.status!==0)throw Error(`Failed to extract tar archive: ${Y.stderr.toString()}`);BX0($);let J=U==="windows"?"seal-use.exe":"seal-use",Q=LI("find",[I,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),K=Q.find((q)=>q.endsWith(`/${J}`)||q.endsWith(J));if(K)return K;return Q[0]||$}function zW1($,I,U){let Y=LI("unzip",["-q","-o",$,"-d",I],{stdio:"pipe"});if(Y.status!==0)throw Error(`Failed to extract zip archive: ${Y.stderr.toString()}`);BX0($);let J=U==="windows"?"seal-use.exe":"seal-use",Q=LI("find",[I,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),K=Q.find((q)=>q.endsWith(`/${J}`)||q.endsWith(J));if(K)return K;return Q[0]||$}function CX0($,I){let U=$.replace(/^v/,"").split(".").map((J)=>Number.parseInt(J,10)||0),Y=I.replace(/^v/,"").split(".").map((J)=>Number.parseInt(J,10)||0);for(let J=0;J<Math.max(U.length,Y.length);J++){let Q=U[J]??0,K=Y[J]??0;if(Q>K)return 1;if(Q<K)return-1}return 0}function vH($,I){return CX0($,I)>0}function EX0($,I,U={}){let Y=LI($,I,{cwd:U.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(Y.stdout)console.error(Y.stdout.trimEnd());if(Y.stderr)console.error(Y.stderr.trimEnd());if(Y.status!==0)throw Error(`${$} ${I.join(" ")} failed with status ${Y.status}`)}async function jX0($,I,U,Y,J){if($==="create"){let Q=h(J.options.name)??I,K=h(J.options.phone);if(!Q||!K)throw Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");let q=h(J.options.dept)??h(J.options.departmentId);await F0("seal_user_create",U,Y,{name:Q,phone:K,departmentIds:q?[q]:void 0},V0(J.options));return}if($==="reset-password"){let Q=I??h(J.options.userId);if(!Q)throw Error("Usage: seal-use users reset-password <userId>");await F0("seal_user_reset_password",U,Y,{userId:Q},V0(J.options));return}if($==="search"||$==="list"){let Q=I??h(J.options.keyword)??h(J.options.query)??"";await F0("seal_user_search",U,Y,{keyword:Q},V0(J.options));return}if($==="get"){let Q=I??h(J.options.userId);if(!Q)throw Error("Usage: seal-use users get <userId>");await F0("seal_user_get",U,Y,{userId:Q},V0(J.options));return}if($==="delete"){let Q=I??h(J.options.userId);if(!Q)throw Error("Usage: seal-use users delete <userId>");await F0("seal_user_delete",U,Y,{userId:Q},V0(J.options));return}if($==="activate"){let Q=I??h(J.options.userId);if(!Q)throw Error("Usage: seal-use users activate <userId>");await F0("seal_user_activate",U,Y,{userId:Q},V0(J.options));return}if($==="delegation"||$==="impersonate"){let Q=I??h(J.options.userId)??h(J.options.phone);if(!Q)throw Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");let K=h(J.options.note);await F0("seal_user_delegation_create",U,Y,{userIdOrPhone:Q,note:K},V0(J.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as _X0}from"node:fs";async function SX0($,I){if(!_X0($))throw Error(`File not found: ${$}`);let U=WI($);console.log(JSON.stringify(await GI(U.fileBuffer,U.fileName,I),null,2))}async function gX0($,I,U,Y,J){if($==="ready"||$==="status"){let Q=I??h(J.options.file)??h(J.options.input),K=await ND(U,Y,{filePath:Q,webhook:h(J.options.webhook)??h(J.options.selector)});if(console.error(`[webhook-ready] 企业环境: ${K.corp.name} (${K.corp.id}) [${K.stateMode}]`),K.corp.tenant?.name)console.error(`[webhook-ready] 租户信息: ${K.corp.tenant.name} (${K.corp.tenant.id})`);console.error(`[webhook-ready] 凭证状态: ${K.authStatus==="ok"?"OK":`异常 (${K.authError})`}`),console.error(`[webhook-ready] Webhook 通道: ${K.activeWebhooks.length} 个可用`);for(let q of K.activeWebhooks){let H=q.isDefault?" [默认通道]":"";console.error(` - ${q.name} (${q.id}) mode=${q.mode}${H}`)}if(K.materialPack)console.error(`[webhook-ready] 材料包预检: ${K.materialPack.valid?`通过 (${K.materialPack.documentCount} 单)`:`失败 (${K.materialPack.errors?.join("; ")})`}`);if(K.ready)console.error(`\uD83D\uDFE2 ${K.statusMessage}`),console.error(`\uD83D\uDC49 Next action: ${K.nextAction}`);else console.error(`\uD83D\uDD34 准备阶段未通过: ${K.statusMessage}`),console.error(`\uD83D\uDC49 Next action: ${K.nextAction}`);console.log(JSON.stringify(K,null,2));return}if($==="material-pack"||$==="material-pack-push"){let Q=$==="material-pack-push"?"push":I,K=$==="material-pack-push"?h(J.options.file)??h(J.options.input):J.command[3]??h(J.options.file)??h(J.options.input);if(!K)throw Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");if(!_X0(K))throw Error(`File not found: ${K}`);let q=WI(K);if(Q==="preview"){console.log(JSON.stringify(await GI(q.fileBuffer,q.fileName),null,2));return}if(Q!=="push")throw Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");let H=h(J.options.webhook)??h(J.options.selector),G=await N9(U,Y.seal.endpoints.approvalStylePreferences),W;if(H)W=M9(G,H);else if(G.length===1)W=G[0],console.error(`\uD83D\uDC49 自动锁定唯一可用 Webhook 通道: ${W.name} (${W.id})`);else if(G.length>1){let V=G.map((Z)=>`"${Z.name}" (${Z.id})`).join(", ");throw Error(`当前租户存在多个 Webhook 通道 [${V}],请通过 --webhook <idOrName> 指定目标通道。`)}else throw new r8("当前租户未配置任何 Webhook 集成通道。",1,`seal-use webhook add --name <name> --result-url <url> --corp ${Y.id}`);let w=await OD(q.fileBuffer,q.fileName,{webhookUrl:W.incomingDocumentWebhook.url,secret:W.secret,materialPackFilePolicy:W.materialPackFilePolicy});console.log(JSON.stringify(w,null,2));return}if($==="list"){await F0("seal_webhook_ Line truncated
`)?"":`
`}`);process.exitCode=$.exitCode}var JG1=Boolean(o.main==o.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&vX0(process.argv[1])===vX0(c5));if(JG1)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await YG1();else Lu().catch(($)=>{console.error($),process.exitCode=1});export{Du as tokenizeCommand,Lu as startServer,IG1 as resolveMcpEnabled,qG1 as createServer,ez1 as SEAL_MCP_ENABLED_ENV,sz1 as SEAL_CLI_TOOL_NAME,$G1 as LEGACY_SEAL_MCP_ENABLED_ENV};
`}`);process.exitCode=$.exitCode}var CW1=Boolean(a.main==a.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&xX0(process.argv[1])===xX0(r5));if(CW1)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await RW1();else uu().catch(($)=>{console.error($),process.exitCode=1});export{yu as tokenizeCommand,uu as startServer,EW1 as resolveMcpEnabled,BW1 as createServer,PW1 as SEAL_MCP_ENABLED_ENV,AW1 as SEAL_CLI_TOOL_NAME,TW1 as LEGACY_SEAL_MCP_ENABLED_ENV};
+13 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "seal-use Wrapped API",
"version": "0.10.8",
"version": "0.10.16",
"description": "Planned HTTP contract for the seal-use wrapped backend API.\n\nThese endpoints describe the intended stable API for frontend developers and agents once\nthe HTTP adapter is implemented.\nThey are not the raw downstream Seal endpoints. seal-use is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n"
},
"servers": [
@@ -1369,6 +1369,18 @@
}
}
}
},
"delete": {
"tags": [
"Approval Knowledge"
],
"operationId": "deleteApprovalDocument",
"summary": "Delete approval knowledge document",
"responses": {
"200": {
"description": "Deleted document confirmation."
}
}
}
},
"/v1/approval/style-preferences": {
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: seal-use Wrapped API
version: 0.10.8
version: 0.10.16
description: |
Planned HTTP contract for the seal-use wrapped backend API.
+7
View File
@@ -265,6 +265,13 @@ paths:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalDocument
delete:
tags: [Approval Knowledge]
operationId: deleteApprovalDocument
summary: Delete approval knowledge document
responses:
"200":
description: Deleted document confirmation.
/v1/approval/style-preferences:
get:
tags: [Approval Knowledge]
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.8",
"version": "0.10.16",
"type": "module",
"module": "src/server.ts",
"bin": {
@@ -16,6 +16,8 @@
"build:binary": "node scripts/build-binary.mjs",
"build:plugin": "node scripts/build-plugin.mjs",
"bump": "bun run scripts/bump-version.ts",
"dev:override": "bun run scripts/dev-override.ts",
"dev:link": "bun run scripts/dev-override.ts",
"openapi:bundle": "bun run scripts/bundle-openapi.ts",
"openapi:raw": "bun run scripts/generate-raw-openapi.ts",
"test": "bun test"
+91 -9
View File
@@ -1,5 +1,5 @@
import { mkdirSync } from "node:fs";
import { spawn } from "node:child_process";
import { mkdirSync, readFileSync } from "node:fs";
import { spawn, spawnSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -18,14 +18,95 @@ const args = process.argv.slice(2);
const isAll = args.includes("--all") || args.includes("--matrix");
const targetArg = args.find((arg) => arg.startsWith("--target="))?.replace("--target=", "");
const shouldMinify = !args.includes("--no-minify");
const isRelease = args.includes("--release") ||
process.env.SEAL_BUILD_RELEASE === "1" ||
(Boolean(process.env.CI) && process.env.GITHUB_REF_TYPE === "tag");
function getBuildInfo(releaseMode) {
const pkg = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8"));
if (releaseMode) {
return {
version: pkg.version,
channel: "release",
isRelease: true
};
}
try {
const res = spawnSync("git", ["describe", "--tags", "--long", "--dirty", "--always"], {
cwd: root,
encoding: "utf8"
});
if (res.status === 0 && res.stdout) {
const trimmed = res.stdout.trim();
const dirty = trimmed.endsWith("-dirty");
const clean = dirty ? trimmed.slice(0, -6) : trimmed;
const longMatch = clean.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/);
let baseVersion = pkg.version;
let commitsAhead = 0;
let commit = "";
if (longMatch) {
baseVersion = longMatch[1];
commitsAhead = Number.parseInt(longMatch[2], 10);
commit = longMatch[3];
} else {
const rev = spawnSync("git", ["rev-parse", "--short", "HEAD"], { cwd: root, encoding: "utf8" });
if (rev.status === 0 && rev.stdout) commit = rev.stdout.trim();
}
const dirtySuffix = dirty ? ".dirty" : "";
const commitSuffix = commit ? `+g${commit}${dirtySuffix}` : dirty ? "+dirty" : "";
const version = `${baseVersion}-dev.${commitsAhead}${commitSuffix}`;
return {
version,
channel: "dev",
isRelease: false,
git: {
baseVersion,
commitsAhead,
commit,
dirty,
describe: trimmed
}
};
}
} catch {
// fallback
}
return {
version: `${pkg.version}-dev.0+local`,
channel: "dev",
isRelease: false
};
}
async function main() {
const startTime = Date.now();
const buildInfo = getBuildInfo(isRelease);
console.log(`[build:binary] version: ${buildInfo.version} (${buildInfo.channel}, isRelease: ${buildInfo.isRelease})`);
const buildEnv = {
...process.env,
SEAL_BUILD_VERSION: buildInfo.version,
SEAL_BUILD_CHANNEL: buildInfo.channel,
SEAL_BUILD_IS_RELEASE: String(buildInfo.isRelease),
...(buildInfo.git ? {
SEAL_BUILD_GIT_BASE: buildInfo.git.baseVersion,
SEAL_BUILD_GIT_COMMITS_AHEAD: String(buildInfo.git.commitsAhead),
SEAL_BUILD_GIT_COMMIT: buildInfo.git.commit,
SEAL_BUILD_GIT_DIRTY: String(buildInfo.git.dirty),
SEAL_BUILD_GIT_DESCRIBE: buildInfo.git.describe
} : {})
};
if (isAll) {
console.log(`[build:binary] compiling ${Object.keys(TARGET_MAP).length} targets in parallel (minify: ${shouldMinify})...`);
await Promise.all(
Object.entries(TARGET_MAP).map(([name, config]) =>
buildTarget(name, config.bunTarget, resolve(root, config.outfile), shouldMinify)
buildTarget(name, config.bunTarget, resolve(root, config.outfile), shouldMinify, buildEnv)
)
);
console.log(`[build:binary] all targets compiled in ${((Date.now() - startTime) / 1000).toFixed(2)}s`);
@@ -34,16 +115,16 @@ async function main() {
if (!config) {
throw new Error(`Unknown target: ${targetArg}. Available targets: ${Object.keys(TARGET_MAP).join(", ")}`);
}
await buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile), shouldMinify);
await buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile), shouldMinify, buildEnv);
} else {
const output = resolve(root, "dist/bin/seal-use");
await buildTarget("host", null, output, shouldMinify);
await buildTarget("host", null, output, shouldMinify, buildEnv);
}
}
async function buildTarget(name, bunTarget, output, minify = true) {
async function buildTarget(name, bunTarget, output, minify = true, buildEnv = process.env) {
mkdirSync(dirname(output), { recursive: true });
const buildArgs = ["build", "--compile"];
const buildArgs = ["build", "--compile", "--env=SEAL_BUILD_*"];
if (minify) {
buildArgs.push("--minify");
}
@@ -53,7 +134,7 @@ async function buildTarget(name, bunTarget, output, minify = true) {
buildArgs.push("--outfile", output, "src/cli.ts");
console.log(`[build:binary] start compiling: ${name} -> ${output}`);
await runAsync(bun, buildArgs);
await runAsync(bun, buildArgs, { env: buildEnv });
if (process.platform === "darwin" && (name.startsWith("darwin") || name === "host")) {
try {
@@ -74,7 +155,8 @@ function runAsync(command, args, options = {}) {
return new Promise((res, rej) => {
const child = spawn(command, args, {
cwd: root,
stdio: options.quiet ? ["ignore", "ignore", "ignore"] : "inherit"
stdio: options.quiet ? ["ignore", "ignore", "ignore"] : "inherit",
env: options.env ?? process.env
});
child.on("error", rej);
child.on("exit", (code) => {
+158
View File
@@ -0,0 +1,158 @@
#!/usr/bin/env bun
import { chmodSync, copyFileSync, existsSync, mkdirSync, rmSync, symlinkSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
function resolveTargetBinaryPath(): string {
// 1. Check which seal-use
try {
const whichRes = spawnSync("which", ["seal-use"], { encoding: "utf8" });
if (whichRes.status === 0 && whichRes.stdout) {
const p = whichRes.stdout.trim();
if (p && existsSync(p)) {
return p;
}
}
} catch {
// ignore
}
// 2. Fallback candidate paths in order of preference
const candidates = [
"/opt/homebrew/bin/seal-use",
"/usr/local/bin/seal-use",
join(homedir(), ".local", "bin", "seal-use"),
join(homedir(), "bin", "seal-use")
];
for (const candidate of candidates) {
const dir = dirname(candidate);
if (existsSync(dir)) {
return candidate;
}
}
const defaultDir = join(homedir(), ".local", "bin");
mkdirSync(defaultDir, { recursive: true });
return join(defaultDir, "seal-use");
}
async function main() {
console.error("==> [dev:override] Building latest host binary from local worktree...");
// 1. Compile host binary with dev metadata
const buildRes = spawnSync("node", ["scripts/build-binary.mjs"], {
cwd: root,
stdio: ["ignore", "inherit", "inherit"]
});
if (buildRes.status !== 0) {
console.error("❌ [dev:override] Build failed.");
process.exit(buildRes.status ?? 1);
}
const localBinary = join(root, "dist", "bin", "seal-use");
if (!existsSync(localBinary)) {
console.error(`❌ [dev:override] Expected binary at ${localBinary} not found.`);
process.exit(1);
}
const targetPath = resolveTargetBinaryPath();
const targetDir = dirname(targetPath);
mkdirSync(targetDir, { recursive: true });
console.error(`==> [dev:override] Installing to global path: ${targetPath}`);
// 2. Check and stop background service if running
let serviceWasRunning = false;
try {
const statusRes = spawnSync(targetPath, ["service", "status"], { encoding: "utf8" });
if (statusRes.status === 0 && statusRes.stdout) {
const parsed = JSON.parse(statusRes.stdout);
if (parsed.running) {
console.error("==> [dev:override] Stopping running background service daemon...");
spawnSync(targetPath, ["service", "stop"], { stdio: "ignore" });
serviceWasRunning = true;
}
}
} catch {
// ignore
}
// 3. Atomically overwrite target binary
const tmpTarget = `${targetPath}.tmp.${Date.now()}`;
copyFileSync(localBinary, tmpTarget);
chmodSync(tmpTarget, 0o755);
if (process.platform === "darwin") {
try {
spawnSync("/usr/bin/codesign", ["--remove-signature", tmpTarget], { stdio: "ignore" });
spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", tmpTarget], { stdio: "ignore" });
} catch {
// ignore
}
}
copyFileSync(tmpTarget, targetPath);
chmodSync(targetPath, 0o755);
try {
rmSync(tmpTarget, { force: true });
} catch {
// ignore
}
// 4. Ensure legacy seal-home symlink exists
const legacyLink = join(targetDir, "seal-home");
if (legacyLink !== targetPath) {
try {
if (existsSync(legacyLink)) rmSync(legacyLink, { force: true });
symlinkSync(targetPath, legacyLink);
} catch {
// ignore
}
}
// 5. Sync Agent Skill to ~/.agents/skills/seal-use
const skillSource = join(root, "skills", "seal-use");
const skillTarget = join(homedir(), ".agents", "skills", "seal-use");
const legacySkill = join(homedir(), ".agents", "skills", "seal-home");
if (existsSync(legacySkill)) {
try {
rmSync(legacySkill, { recursive: true, force: true });
} catch {}
}
if (existsSync(skillSource)) {
try {
const { cpSync } = await import("node:fs");
mkdirSync(dirname(skillTarget), { recursive: true });
cpSync(skillSource, skillTarget, { recursive: true });
console.error(`✓ [dev:override] Synced agent skill to ${skillTarget}`);
} catch (err) {
console.error(`⚠️ [dev:override] Failed to sync agent skill: ${err}`);
}
}
// 6. Restart service daemon if it was previously running
if (serviceWasRunning) {
console.error("==> [dev:override] Restarting background service daemon with new binary...");
spawnSync(targetPath, ["service", "start"], { stdio: "ignore" });
}
// 7. Verify and output
console.error("✨ [dev:override] Success! Active global seal-use binary is now updated:");
const testRes = spawnSync(targetPath, ["v"], { encoding: "utf8" });
if (testRes.status === 0 && testRes.stdout) {
process.stdout.write(testRes.stdout);
} else {
console.error(testRes.stderr || "Failed to verify updated binary");
}
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
+26 -8
View File
@@ -1,12 +1,12 @@
---
name: seal-use
description: "v0.10.8: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.10.16: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.10.8
short-description: Seal tenant and Hose approval automation (v0.10.8)
version: 0.10.16
short-description: Seal tenant and Hose approval automation (v0.10.16)
---
# Seal Use (v0.10.8)
# Seal Use (v0.10.16)
Use the `seal_cli` MCP tool when it is available; pass the command string as its `command` argument. If MCP is unavailable, fall back to the global `seal-use` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
@@ -39,7 +39,8 @@ seal-use corps list
- Prefer compact commands first: `pick`, `--summary`, `--fields`, `attachments --summary`, `rules count`, and `rules list --summary`.
- Parse JSON stdout. Do not scrape human text.
- Do not hand-edit enterprise configs for normal setup. Use `seal-use corps ...`.
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For repeat test-environment rule resets, prefer `rules clear --dry-run` followed by `rules clear --yes`.
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For supported configuration writes, prefer the universal `--dry-run` preview first (rules clear/push, preferences, thinking-depth policies, HoseCloud configure, and Webhook add/update/delete), then use `--yes` only after reviewing its redacted `changesDiff`.
- Knowledge document creation is currently irreversible: the upstream API exposes no delete operation. Validate `contentType` and `scenarios` before creating, and use `enabled: false` when the document should be withdrawn.
- For customer-feedback rule remediation, show an exact field-level diff and obtain explicit approval before updating. Default to changing only the narrowest necessary part of `description`; preserve `scope`, `strictness`, and unrelated clauses unless the user explicitly approves otherwise.
- Resolve and lock the target enterprise `corpId` before diagnosis or mutation. Never assume the current tenant is the customer tenant. Re-fetch the target rule immediately before updating, then verify the draft and newly published version after writing.
- For date questions, use explicit dates and `--timezone Asia/Shanghai`.
@@ -55,7 +56,8 @@ seal-use corps list
- First install / zero configuration / “how do I connect my enterprise?” / user supplies app credentials, an assistance link, or F12/Network cURL: read `references/enterprise-onboarding.md`. Ask what material the user already has in plain language, then discover all remaining identifiers automatically.
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-use delegation create --corp <corpId> --note '<enterprise>'`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
- Packaged customer feedback → approval-rule remediation: read `references/customer-feedback-rule-remediation.md`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version.
- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --corp <corpId>` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>`, `simulation wait <batchId>` 轮询等待完成, `simulation clean <batchId>` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。
- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp <corpId>` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>`, `simulation status <batchId>` 单次查询状态, `simulation wait <batchId>` 轮询等待完成, `simulation clean <batchId>` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。
- 测试企业标记、关联与配置规则同步: `seal-use corps mark <corpId> --env <production|test> --confirm` (严格标记环境), `seal-use corps bind-test <prodCorpId> <testCorpId> --confirm` (严格1对1下挂,禁止多层级串联), `seal-use corps unbind-test <corpId> --confirm`, `seal-use corps sync-test <prodCorpId> [--dry-run|--yes] [--version-name <name>]` (将正式企业的偏好和草稿规则覆盖同步到测试企业并自动发布语义版本 `[Prod vN · #M]`,输出并本地缓存 `ruleMapping`,正式企业规则保持草稿态不发布), `seal-use rules map [--corp <corpId>] [--version <v|latest>] [--code <code>]` (离线毫秒级速查测试与生产规则对照映射)。
- Seal AI 智能审核发布到合思费控: `seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>`; read `references/hose-enterprise-deploy.md`.
- 审核决策偏好与思考深度: `seal-use preference get --corp <corpId>`, `preference decision update --json '...' --corp <corpId>`, `preference thinking-depth set --default <medium|high> --corp <corpId>`, `preference thinking-depth policies <list|upsert|remove> --corp <corpId>`.
- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|id] --corp <corpId>`, `seal-use approval-runs count --corp <corpId>`.
@@ -65,12 +67,28 @@ seal-use corps list
- LLM Model Config & Providers: `seal-use llm config --corp <corpId>`, `seal-use llm providers --corp <corpId>`.
- System Permissions Config: `seal-use permissions available --corp <corpId>`, `seal-use permissions configs --corp <corpId>`.
- Billing & Feature Quotas: `seal-use billing status --corp <corpId>`, `seal-use billing plans --corp <corpId>`, `seal-use billing features --corp <corpId>`.
- Webhook 审批回调管理: `seal-use webhook <list|get|add|update|delete> --corp <corpId>`.
- Webhook 材料包导入: `seal-use webhook material-pack preview <材料包.zip> --corp <corpId>` 只做本地校验和解析;`... push <材料包.zip> --webhook <idOrName> --corp <corpId>` 上传附件并通过入站 Webhook 触发 AI 审批。它与 `simulation material_pack` 的官方服务端导入流程相互独立。
- Webhook 准备看板与审批回调管理: `seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] --corp <corpId>` (别名 `status`) 检查企业环境、租户连通性、已激活通道与材料包预检;`seal-use webhook <list|get|add|update|delete> --corp <corpId>`.
- Webhook 材料包导入: `seal-use webhook material-pack preview <材料包.zip> --corp <corpId>` 只做本地校验和解析(无网络请求);`... push <材料包.zip> [--webhook <idOrName>] --corp <corpId>` 上传附件并通过入站 Webhook 触发 AI 审批(租户仅有 1 个通道时自动锁定无需指定 `--webhook`)。每个 Webhook 可配置材料包附件的最小字节数、可选最大字节数和文件后缀白名单;这是可修改的持久化策略,不是不可绕过的硬编码。校验不通过时不会上传附件或推送单据。材料包格式:ZIP 根目录名 = `documentId`(或 `documentId@annotation`),Excel 附件列以 `[附件]` 为前缀(如 `[附件]合同协议`),单元格值为 ZIP 相对路径(支持多行/逗号/分号分隔);系统执行严格双向验证(Excel 声明的路径必须在 ZIP 中存在,ZIP 中的文件必须在某个 `[附件]` 列中声明)。详见 `references/cli.md` 中 "Material Pack Workflow" 一节。它与 `simulation material_pack` 的官方服务端导入流程相互独立。
- HTTP REST API & Docs Server: `seal-use http [--port 8787] [--host 127.0.0.1]` (提供 `/docs` 交互文档、`/openapi.json`、`POST /api/cli` 与 `/v1/*` REST API)。
- 审批规则质量校验 (Linter): `seal-use rules lint [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary] --corp <corpId>`; read `references/rule-lint.md`. 全局配置默认关闭 (`config lint <enable|disable>`)。
- Full CLI inventory: read `references/cli.md`.
## Material-pack Webhook policy and recovery
材料包附件策略保存在目标入站 Webhook 的 `materialPackFilePolicy` 下,按 Webhook 生效。新建 Webhook 的默认策略是:最小文件大小 `500` 字节、最大文件大小不限制、后缀白名单为常见 PDF/Office/文本/邮件/图片格式。`信息表.xlsx` 是材料包根清单,不属于普通附件,不受这三个附件策略限制。完整默认后缀和边界规则见 `references/cli.md`。
这套策略允许人工或助手修改。错误处理有两条通道:先通过错误通道明确告诉助手是哪一个文件、哪一条规则失败;再通过配置或文件处置通道完成恢复。遇到附件被拦截时按以下闭环处理:
1. 从错误中识别被拦截的文件、实际大小、失败规则和目标 Webhook。
2. 向用户说明可选处置:替换/压缩文件,或在确认允许该格式/大小后修改 Webhook 策略。
3. 用户或业务负责人明确确认放宽策略后,读取目标 Webhook 当前配置(CLI 使用 `webhook get`/`webhook list`,MCP 使用 `seal_webhook_get`/`seal_webhook_list`)。
4. 调用 `seal_webhook_update` 或 `seal-use webhook update` 修改最小值、最大值或完整后缀白名单,写入后重新读取核对,再重试原来的材料包 push。
push 会重新读取最新 Webhook 配置;校验通过后才会开始上传附件。CLI 以非零退出码和 `stderr` 返回可恢复的业务错误,MCP 以工具错误返回。没有用户授权或没有修改权限时,不能擅自放宽策略,也不能绕过校验。
注意:直接执行本地 `material-pack preview` 只使用默认策略或命令行临时覆盖,不会自动读取某个 Webhook 的持久化策略;`webhook ready --file`(指定 Webhook 时)和 `material-pack push` 才使用保存的 Webhook 策略。需要验证实际入站通道策略时,优先使用 `ready --file --webhook ...`,或直接重试 push。
## High-Value Commands
```bash
+223 -70
View File
@@ -27,8 +27,8 @@ override that path. The legacy `current-corp` file is not read.
## Stream & Exit Code Contract
- **`stdout`**: Pure, deterministic JSON for machine/Agent parsing.
- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** (e.g. `👉 Next action: ...`).
- **`Exit Code`**: `0` on success, non-zero (e.g. `1`) on failure to trigger Agent error self-remediation.
- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** with the stable prefix `👉 Next action: seal-use ...`.
- **`Exit Code`**: `0` on success; `1` runtime/upstream failure, `2` usage/argument error, `10` explicit destructive-operation confirmation required, `11` missing/invalid authentication, and `12` output protection requiring a compact/file/query alternative.
## Top-Level Commands
@@ -37,6 +37,7 @@ seal-use version
seal-use config paths
seal-use config get
seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use config test-dir [<path>|--clear]
seal-use config lint <enable|disable|status> [--linter <name>] [--min-score <score>]
seal-use rules pull [--corp <corpId>] [--version <id|num|latest>] [--out <file>]
seal-use rules lint [--file <path>] [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]
@@ -49,6 +50,10 @@ seal-use tools list
seal-use corps list [--corp <corpId>]
seal-use corps current [--corp <corpId>]
seal-use corps switch <corpId>
seal-use corps mark <corpId> --env <production|test> [--confirm]
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
seal-use corps unbind-test [<corpId>] [--confirm]
seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]
@@ -61,6 +66,12 @@ seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <c
seal-use users reset-password <userId> [--corp <corpId>]
seal-use users get <userId> [--corp <corpId>]
seal-use users delete <userId> [--corp <corpId>]
seal-use contacts departments [<departmentId>] [--corp <corpId>]
seal-use contacts children <departmentId> [--corp <corpId>]
seal-use contacts users <departmentId> [--corp <corpId>]
seal-use contacts sync-time [--corp <corpId>]
seal-use data expenses --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]
seal-use data invoices --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]
seal-use llm config [--corp <corpId>]
seal-use llm providers [--corp <corpId>]
seal-use permissions available [--corp <corpId>]
@@ -70,26 +81,28 @@ seal-use billing plans [--corp <corpId>]
seal-use billing features [--corp <corpId>]
seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]
seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]
seal-use webhook delete <idOrName> --yes [--corp <corpId>]
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp <corpId>]
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp <corpId>]
seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]
seal-use deploy hosecloud requirements [--corp <corpId>]
seal-use deploy hosecloud list [--corp <corpId>]
seal-use deploy hosecloud get [<sign-key>] [--corp <corpId>]
seal-use deploy hosecloud status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--corp <corpId>]
seal-use preference get [--corp <corpId>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--corp <corpId>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth policies list [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--dry-run] [--corp <corpId>]
seal-use source config [--corp <corpId>]
seal-use tool <toolName> [--corp <corpId>] [--json '{"key":"value"}']
seal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]
seal-use approval-runs stats --corp <corpId> [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id]
seal-use analytics insight --corp <corpId> [--start-date <ISO>] [--end-date <ISO>] [--limit <n>]
seal-use approval-runs count --corp <corpId> [--status APPROVED]
seal-use approval-runs export --corp <corpId> [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--limit <n>] [--downloads] [--out <file>]
seal-use approval-runs search --corp <corpId> [--query text] [--limit 20] [--includeBridge true]
seal-use approval-runs get <recordId> --corp <corpId> [--fields metadata|document.fields,result.summary] [--output-file file.json]
seal-use approval-runs attachments <recordId> --corp <corpId>
@@ -100,12 +113,14 @@ seal-use approval-runs url <recordId> --corp <corpId>
seal-use approval-runs url --sourceDocumentSN <sourceDocumentSN> --corp <corpId>
seal-use approval-runs bridge --corp <corpId> [--sourceDocumentSN <sourceDocumentSN>]
seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] --corp <corpId>
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] --corp <corpId>
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] --corp <corpId>
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" --corp <corpId>
seal-use simulation status <batchId> --corp <corpId>
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] --corp <corpId>
seal-use simulation clean <batchId> --corp <corpId>
seal-use simulation specifications [--integration <sign-key>] --corp <corpId>
seal-use simulation approval-definitions --corp <corpId>
seal-use simulation list [--limit 50] --corp <corpId>
seal-use simulation get <batchId> --corp <corpId>
seal-use simulation templates --corp <corpId>
@@ -113,7 +128,7 @@ seal-use simulation integrations --corp <corpId>
seal-use simulation package-upload <材料包.zip> --corp <corpId>
```
## Fine-Grained Tools
## CLI Command Overview
`seal-use version` returns:
@@ -131,27 +146,36 @@ seal-use simulation package-upload <材料包.zip> --corp <corpId>
Identity and session:
- `seal-use auth diagnose --corp <corpId>`
- `seal_whoami`
- `seal_session_get`
- `seal-use corps list`
- `seal-use corps current`
Test Enterprise Binding & Staging Synchronization:
- **1-to-1 Association**: One production enterprise can only bind at most one test enterprise (`corps bind-test <prodCorpId> <testCorpId>`). Multi-tier chaining is rejected.
- **Marking & Rigorous Confirmation**: Marking (`corps mark <corpId> --env <production|test>`) and binding require explicit `--confirm`. Without confirmation, the CLI blocks with exit code `10` (`confirmationRequired`). Overwriting existing bindings requires `--force`.
- **Production Safety Guarantee (`corps sync-test`)**:
- In the **Production Enterprise**: Rules remain strictly in **draft state** without publishing any live version.
- In the **Test Enterprise**: Style preferences (`decisionPreferences`, `thinkingDepthPreference`) are updated to match production, test draft rules are cleared and populated with production draft rules, recoded, and immediately **published as a new official version** in the test tenant (`--version-name <name>`).
- **Semantic Version Naming**: Defaults to `Sync from <ProdCorp> [Prod v<N> · #<Iteration>]` tracking production baseline version and test draft iteration without redundant date strings.
- **Rule Mapping & Local Snapshot**: Returns `versionMapping` and `ruleMapping` in CLI stdout and saves persistent snapshot to `~/.config/seal-use/mappings/<testCorpId>-v<N>.json` and `<testCorpId>-latest.json`.
- `--dry-run` previews the full preference diff, version mapping plan, and rule sync plan without sending mutations. Execution requires `--yes`.
Approval rule maintenance:
- `seal-use rules count [--corp <corpId>]`
- `seal-use rules list --summary [--corp <corpId>]`
- `seal-use rules map [--corp <corpId>] [--version <id|num|latest>] [--code <code>]` (reads local sync rule mapping snapshot)
- `seal-use rules pull [--corp <corpId>] [--version <id|num|latest>] [--out <file>]`
- `seal-use rules lint [--file <path>] [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]`
- `seal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]`
- `seal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred.
- `seal-use rules clear [--corp <corpId>] [--dry-run|--yes]`
- `seal_approval_rules_list`
- `seal_approval_rules_pull`
- `seal_approval_rules_push`
- `seal_approval_rules_lint`
- `seal_approval_rules_clear`
- `seal_approval_rule_create`
- `seal_approval_rule_update`
- `seal_approval_rule_delete`
- `seal_approval_rule_versions_list`
- `seal_approval_rule_version_publish`
Rule identity and versioning:
- `rules list` and `rules pull` read the current **draft** rule set. Their `code` values belong to the draft code space.
- A published version has its own snapshot and code space. Publishing can recode rules, so a published `code` may differ from the draft `code`, and codes can shift again after later edits and publishes.
- Do not use a draft `#NN` as a cross-version identifier. For current draft work, prefer the stable rule `id`; for historical behavior, select the published `version` and locate the rule by its text/context or runtime rule ID from the approval run.
- `rules get --version ... --code ...` interprets `code` inside that selected published version, while `rules get --record-id ... --runtime-id ...` resolves the version recorded on the run.
Approval run lightweight queries:
@@ -164,61 +188,42 @@ Approval run lightweight queries:
- `seal-use approval-runs attachments <recordId> --corp <corpId> --summary`
- `seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] --corp <corpId>`
- `seal-use approval-runs result <recordId> --corp <corpId> --summary`
- `seal_approval_run_get` with `fields`
- `seal_approval_run_pick`
- `seal_approval_run_cited_rules_get`
- `seal_approval_run_document_summary_get`
- `seal_approval_run_attachments_get`
- `seal_approval_run_attachments_download`
- `seal_approval_run_result_get` with `{"summary":true}`
Approval knowledge documents:
Approval knowledge documents & style:
- `seal_approval_documents_list`
- `seal_approval_document_get`
- `seal_approval_document_create`
- `seal_approval_document_update`
Approval search and context:
- `seal_approval_search`
- `seal_approval_context_get`
- `seal-use rules get --corp <corpId> --version <number> --code '#0038'`
- `seal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205`
Style preferences:
- `seal_approval_style_preferences_get`
- `seal_approval_style_preferences_update`
Webhook integrations:
- `seal-use webhook ready [<材料包.zip|信息表.xlsx>] [--webhook <idOrName>] [--corp <corpId>]`
- `seal-use webhook status [<材料包.zip|信息表.xlsx>] [--corp <corpId>]`
- `seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]`
- `seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]`
- `seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]`
- `seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]`
- `seal-use webhook delete <idOrName> --yes [--corp <corpId>]`
- `seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> --corp <corpId>`
- `seal-use webhook material-pack push <材料包.zip|信息表.xlsx> --webhook <idOrName> --corp <corpId>`
- `seal_webhook_list`
- `seal_webhook_get`
- `seal_webhook_add`
- `seal_webhook_update`
- `seal_webhook_delete`
- `seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp <corpId>]`
- `seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp <corpId>]`
- `seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]`
- `seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] --corp <corpId>`
- `seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] --corp <corpId>`
Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once.
Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once. Each Webhook can also store a mutable `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`. Update is a patch: omitted policy fields are retained; `allowedExtensions` replaces the complete list; `--clear-max-file-size` removes the upper bound.
All supported configuration writes accept `--dry-run`: rules clear/push, preference updates, thinking-depth policy changes, HoseCloud configure, and Webhook add/update/delete. Preview mode performs read-only discovery and returns JSON with `preview: true`, the exact `targetUrl`, a redacted `changesDiff` (`before`/`after`), and `impactCount`. It never sends the mutation request and does not require `--yes`; use the same command with `--yes` only after reviewing the preview.
Approval runs, simulations, and Langfuse bridge:
- `seal_approval_runs_search`
- `seal_approval_runs_summary`
- `seal_simulation_batch_records_get`
- `seal_simulation_batch_create`
- `seal_simulation_batches_list`
- `seal_simulation_batch_get`
- `seal_simulation_templates_get`
- `seal_simulation_integrations_get`
- `seal_approval_run_langfuse_bridge_get`
- `seal-use approval-runs search --corp <corpId> [--query <text>] [--limit 20]`
- `seal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]`
- `seal-use approval-runs bridge --corp <corpId> [--sourceDocumentSN <sn>]`
- `seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp <corpId>` returns immediately with an `asyncTicket` (creation is non-blocking by default for compatibility).
- `seal-use simulation status <batchId> --corp <corpId>` performs one non-blocking status check and returns `QUEUED`/`RUNNING`/`COMPLETED`/`FAILED`-style state plus counters.
- `seal-use simulation wait <batchId> --corp <corpId>`
- `seal-use simulation clean <batchId> --corp <corpId>`
- `seal-use simulation list --corp <corpId>`
- `seal-use simulation get <batchId> --corp <corpId>`
- `seal-use simulation batch-records <batchId> --corp <corpId>`
- `seal-use simulation templates --corp <corpId>`
- `seal-use simulation integrations --corp <corpId>`
## Common Examples
@@ -341,13 +346,17 @@ Create a document:
"title": "标题",
"purpose": "用途",
"content": "Markdown 内容",
"contentType": "text/markdown",
"status": "可选",
"scenarios": ["场景"],
"contentType": "policy",
"status": "published",
"scenarios": ["audit"],
"tags": ["标签"]
}
```
`contentType` 必须是 `document`、`video`、`pdf`、`feishu_doc` 或 `policy` 之一;`scenarios` 必填且至少包含一个 `fill`(智能填单)或 `audit`(智能审核)。这里的 `scenarios` 是产品能力开关,不是费用类别或业务场景名。
知识文档创建后当前 API 没有删除接口,创建操作不可逆;请在写入前确认标题、正文、内容类型和能力场景。需要撤下内容时,优先使用更新操作并设置 `enabled: false`(如果上游支持该字段),不要通过试探性创建来验证参数。规则支持删除,但知识文档与规则的生命周期能力并不对称。
Update a document:
```json
@@ -376,6 +385,150 @@ Update style preferences:
}
```
## Material Pack Workflow
A **material pack** (材料包) is a ZIP file that bundles an Excel information sheet (`信息表.xlsx`) with attachments organised by document ID. It is the primary input to the Webhook-based AI approval ingestion pipeline.
### ZIP structure convention
```
材料包.zip
├── 信息表.xlsx ← must exist at ZIP root
├── BX20260826003/ ← root dir name = documentId (or documentId@annotation)
│ ├── 合同协议/
│ │ └── 采购合同.pdf
│ └── 支付凭证/
│ └── 支付宝交易明细.pdf
└── BX20260826004@重新提交v2/ ← @annotation is stripped when matching documentId
└── 发票/
└── 增值税专用发票.pdf
```
- The root directory name **must equal** the `documentId` **OR** start with `documentId@` (the `@` separates an optional annotation ignored during matching).
- `信息表.xlsx` at the ZIP root is the only file not associated with any document directory.
### Excel column convention
| Column type | Naming | Purpose |
|---|---|---|
| Regular column | Any header (e.g. `会议编号`, `总金额`) | Standard document fields |
| Attachment column | Header starts with `[附件]` (e.g. `[附件]合同协议`) | Declares attached files for this row |
- The `[附件]` prefix is stripped to produce the field `label` sent to Seal.
- The cell value contains full ZIP-relative path(s) to the declared files (multiple paths separated by newline, comma, or semicolon).
- Example: column `[附件]合同协议`, cell value `BX20260826003/合同协议/采购合同.pdf`
### Sheet → document level mapping
| Excel sheet | Maps to |
|---|---|
| First sheet (main / 会议) | Root document `categoryFields` |
| 费用明细表 (has `报销金额` column) | Per-row entries in `mingxi_list` |
| 劳务明细 (has `姓名` column) | Per-person entries in `daoshi_list` |
### Strict bidirectional validation
Before pushing or previewing, the system enforces:
1. **Excel → ZIP**: Every path declared in an `[附件]` column cell **must** exist as a ZIP entry. Error: `Excel 声明的附件路径在 ZIP 中不存在: <path>`
2. **ZIP → Excel**: Every ZIP file (excluding `信息表.xlsx`) **must** be declared in exactly one `[附件]` column. Error: `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>`
3. **Document Directory Scope Isolation**: All attachments declared for a document `DOC_X` **must** reside in its own root directory (`DOC_X/` or `DOC_X@annotation/`). Cross-document references are strictly forbidden. Error: `单据「X」声明了跨单据或非本单据目录的附件路径: <path>。附件必须位于该单据自己的根目录...`
4. **Strict Declaration Uniqueness**: A given ZIP file path **cannot** be declared more than once across the entire material pack (even within the same document across multiple rows or fields). If the same logical document is needed in multiple places, separate files must be placed in distinct paths. Error: `附件路径「<path>」被重复声明了 N 次...`
5. **Attachment file policy**: Every attachment except the root `信息表.xlsx` must satisfy the selected Webhook's minimum size, optional maximum size, and extension whitelist. The default minimum is 500 bytes; the default maximum is unlimited; the default whitelist includes common PDF, Office, text, email, and image formats. Error: `附件文件过小...` / `附件文件过大...` / `附件后缀不在白名单中...`
6. **documentId ↔ ZIP root**: Every `documentId` in the Excel main sheet must have a matching ZIP root dir (exact match or `documentId@annotation`). Errors: `Excel 会议编号「X」在 ZIP 中找不到对应的根目录...` / `ZIP 根目录对应的编号「X」在信息表中找不到对应的会议编号`
All validation errors are collected and reported together in a single `MaterialPackValidationError`.
### CLI usage
```bash
# Check environment readiness and optionally pre-validate the material pack
seal-use webhook ready [--file <pack.zip>] [--corp <corpId>]
# Dry-run: local parse & validation only, no network calls, returns preview JSON
seal-use webhook material-pack preview <pack.zip> --corp <corpId>
# Preview with temporary local policy overrides (comma-separated extensions)
seal-use webhook material-pack preview <pack.zip> --min-file-size 500 --max-file-size 20971520 --allowed-extensions .pdf,.xlsx,.docx --corp <corpId>
# Upload attachments and push documents via inbound Webhook
seal-use webhook material-pack push <pack.zip> [--webhook <nameOrId>] --corp <corpId>
# When there is exactly one webhook channel, --webhook can be omitted (auto-locked)
```
### Attachment file policy configuration
The policy is stored per inbound Webhook integration and is applied before any attachment upload or document push. A failed check stops the entire material-pack flow. The policy is intentionally mutable: after an authorized configuration change, retrying the same push reads the saved policy again.
Default configuration:
```json
{
"minFileSizeBytes": 500,
"maxFileSizeBytes": null,
"allowedExtensions": [
".pdf", ".xls", ".xlsx", ".csv", ".doc", ".docx", ".ppt", ".pptx",
".txt", ".rtf", ".odt", ".ods", ".odp", ".jpg", ".jpeg", ".png",
".gif", ".bmp", ".webp", ".heic", ".eml", ".msg"
]
}
```
`null` or an omitted `maxFileSizeBytes` means no per-file upper bound. Values are bytes; a file smaller than the minimum or larger than the maximum fails. Extensions are normalized case-insensitively and may be written with or without the leading dot. The root `信息表.xlsx` remains exempt from attachment policy checks.
```bash
# New Webhook: use the default 500-byte minimum and default extension whitelist
seal-use webhook add --name "材料包入站" --result-url "https://your-domain.com/callback" --corp <corpId>
# Configure an existing Webhook; sizes are bytes and extensions are comma-separated
seal-use webhook update <webhookIdOrName> \
--min-file-size 500 \
--max-file-size 20971520 \
--allowed-extensions .pdf,.xlsx,.xls,.docx,.pptx,.jpg,.png \
--corp <corpId>
# Allow a newly confirmed format while retaining the rest of the policy:
# first read webhook get/list, then pass the complete desired whitelist.
seal-use webhook update <webhookIdOrName> \
--allowed-extensions .pdf,.xlsx,.xls,.docx,.pptx,.jpg,.png,.zip \
--corp <corpId>
# Remove only the maximum-size limit (minimum and whitelist are retained).
seal-use webhook update <webhookIdOrName> --clear-max-file-size --corp <corpId>
```
The saved configuration is returned by `webhook get`/`webhook list` under `materialPackFilePolicy`. The root `信息表.xlsx` is always allowed as the material-pack manifest and is not subject to the attachment policy.
### Failure recovery loop
When a push fails because of the attachment policy, the error is actionable and should be handled as a two-channel recovery loop:
1. Error channel: read `附件文件过小`, `附件文件过大`, or `附件后缀不在白名单中`, including the attachment path and the configured boundary.
2. Resolution channel: ask whether the user wants to replace/compress the file or explicitly allow the format/size by changing the target Webhook policy.
3. If configuration change is authorized, read the current policy with `webhook get`/`webhook list`, update only the necessary fields, and verify the returned configuration.
4. Retry the original `material-pack push`; it will load the latest saved policy before any upload begins.
The same loop is available through MCP: read with `seal_webhook_get`/`seal_webhook_list`, update with `seal_webhook_update` and its `materialPackFilePolicy` patch, then retry `seal_webhook_material_pack` in `push` mode. For MCP, set `maxFileSizeBytes` to `null` to clear the upper bound. `allowedExtensions` is a complete replacement list, so include existing allowed suffixes when adding one.
If the assistant lacks permission to update the Webhook or the user does not authorize relaxing the rule, report the block rather than bypassing validation. Since validation happens before the upload loop, a failed attempt does not leave a partially pushed material pack.
The direct local `material-pack preview` command and MCP preview use the default or temporary policy. They do not automatically read a selected Webhook's persisted policy. Use `webhook ready --file --webhook <idOrName>` or the actual push path when validating against the saved inbound policy.
### Error messages reference
| Error message | Meaning | Fix |
|---|---|---|
| `Excel 声明的附件路径在 ZIP 中不存在: <path>` | Cell value references a file not in ZIP | Add the file to ZIP at exactly that path |
| `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>` | ZIP contains a file not referenced by any `[附件]` column | Add an `[附件]` column entry or remove the file from ZIP |
| `单据「X」声明了跨单据或非本单据目录的附件路径: <path>` | Document X declared a path inside another document's folder | Move file into Document X's own folder and update Excel |
| `附件路径「<path>」被重复声明了 N 次` | The same file path was declared in multiple columns/rows/documents | Each declaration must point to a unique file path; duplicate file if needed |
| `Excel 会议编号「X」在 ZIP 中找不到对应的根目录` | No ZIP root dir matches documentId `X` | Rename the ZIP folder to match the documentId |
| `ZIP 根目录对应的编号「X」在信息表中找不到` | ZIP folder has no matching documentId in Excel | Remove the folder or add the document to Excel |
| `ZIP 根目录缺少信息表.xlsx` | No `信息表.xlsx` found at ZIP root | Add the Excel file to the ZIP root |
| `附件文件过小` | Attachment is below the configured minimum byte size | Replace the empty/truncated file or lower `--min-file-size` |
| `附件文件过大` | Attachment exceeds the configured maximum byte size | Replace/compress the file or raise `--max-file-size` |
| `附件后缀不在白名单中` | Attachment extension is not allowed by the Webhook policy | Add the extension with `--allowed-extensions` or convert the file |
| `附件上传失败 <status>` | Network/server error during file upload | Check webhook URL, secret, and server availability |
## Failure Handling
- CLI commands are short-lived processes. In-memory auth/search caches only live for that single process. Use `seal-use service restart` after updates so the optional local service picks up new code.
@@ -133,6 +133,8 @@ seal-use tool seal_approval_rule_update --corp <corpId> \
Do not send `scope` or `strictness` when they are unchanged. Fetch the draft again and verify the exact description, scope, strictness, and draft status before publishing.
For a complete local rule-set sync, `rules push` is incremental: it matches pulled rules by stable `id`, updates only changed fields, creates new entries, and removes entries omitted from the local file. It preserves matched rule IDs and does not recode the whole draft. Preview it with `rules push --dry-run` before applying.
## 9. Publish and verify
Publish only when explicitly authorized:
@@ -2,6 +2,12 @@
Use this reference when the user wants rule counts, compact rule lists, one rule from a historical version, or approval knowledge search without dumping hundreds of rule descriptions.
## Draft and Published Rule Codes
`rules list` and `rules pull` operate on the current draft and therefore return draft `code` values. A published version stores a separate snapshot and may recode the same rules; publishing, deleting, or reordering rules can make those published codes differ or drift again. A code such as `#0038` is only meaningful together with its version context.
Use the draft `id` for current edits and use the approval run's recorded version plus rule text or runtime rule ID for historical investigations. Do not copy a draft code into a report or command that will be interpreted against a published version.
## Count Rules
Use count when only scale or existence matters.
+20 -1
View File
@@ -37,6 +37,25 @@ describe("CLI version & help handling", () => {
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.name).toBe("seal-use");
expect(parsed.version).toBe(VERSION);
expect(parsed).toHaveProperty("channel");
expect(parsed).toHaveProperty("isRelease");
});
test("version output includes structured dev channel and git information", () => {
const result = runCli(["v"]);
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.name).toBe("seal-use");
expect(typeof parsed.channel).toBe("string");
expect(typeof parsed.isRelease).toBe("boolean");
if (!parsed.isRelease) {
expect(parsed.channel).toBe("dev");
if (parsed.git) {
expect(parsed.git).toHaveProperty("baseVersion");
expect(parsed.git).toHaveProperty("commitsAhead");
expect(parsed.git).toHaveProperty("commit");
}
}
});
test("help command prints standard help banner", () => {
@@ -57,7 +76,7 @@ describe("CLI version & help handling", () => {
test("invalid command displays unknown command error with help hint", () => {
const result = runCli(["invalid-command"]);
expect(result.status).toBe(1);
expect(result.status).toBe(2);
expect(result.stderr).toContain("Unknown command: invalid-command. Run 'seal-use help' for available commands.");
});
+30
View File
@@ -0,0 +1,30 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleAnalyticsCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "insight" || action === "insight-stats" || action === "stats") {
await runTool(
"seal_insight_stats_get",
client,
corp,
{
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
limit: numberOption(args.options.limit)
},
outputOptions(args.options)
);
return;
}
throw new Error(`Unknown analytics command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+69 -55
View File
@@ -1,5 +1,11 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import * as api from "../../domains/seal/api.js";
import { exportApprovalRunsToExcel } from "../../domains/seal/approval-runs-export.js";
import {
downloadApprovalRunAttachments,
extractApprovalRunAttachments
} from "../../domains/seal/attachments.js";
import { runTool, runToolResult } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
@@ -176,23 +182,19 @@ export async function handleApprovalRunsCommand(
"Usage: seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>]"
);
}
const downloadResult = (await runToolResult(
"seal_approval_run_attachments_download",
client,
corp,
{
recordId,
all: booleanOption(args.options.all),
name: stringOption(args.options.name),
outDir:
stringOption(args.options["out-dir"]) ??
stringOption(args.options.outDir) ??
stringOption(args.options.dir)
}
)) as any;
const record = await api.getApprovalRun(client, recordId);
const downloadResult = await downloadApprovalRunAttachments({
record,
all: booleanOption(args.options.all),
name: stringOption(args.options.name),
outDir:
stringOption(args.options["out-dir"]) ??
stringOption(args.options.outDir) ??
stringOption(args.options.dir)
});
printJson(downloadResult, outputOptions(args.options));
if (downloadResult?.total > 0 && downloadResult?.downloaded === 0) {
if (downloadResult.total > 0 && downloadResult.downloaded === 0) {
throw new Error(`所有 ${downloadResult.total} 个附件下载均失败。`);
}
return;
@@ -202,38 +204,29 @@ export async function handleApprovalRunsCommand(
if (!recordId) throw new Error("Usage: seal-use approval-runs attachments <recordId> | seal-use approval-runs attachments download <recordId>");
if (booleanOption(args.options.download)) {
const downloadResult = (await runToolResult(
"seal_approval_run_attachments_download",
client,
corp,
{
recordId,
all: booleanOption(args.options.all) ?? true,
name: stringOption(args.options.name),
outDir:
stringOption(args.options["out-dir"]) ??
stringOption(args.options.outDir) ??
stringOption(args.options.dir)
}
)) as any;
const record = await api.getApprovalRun(client, recordId);
const downloadResult = await downloadApprovalRunAttachments({
record,
all: booleanOption(args.options.all) ?? true,
name: stringOption(args.options.name),
outDir:
stringOption(args.options["out-dir"]) ??
stringOption(args.options.outDir) ??
stringOption(args.options.dir)
});
printJson(downloadResult, outputOptions(args.options));
if (downloadResult?.total > 0 && downloadResult?.downloaded === 0) {
if (downloadResult.total > 0 && downloadResult.downloaded === 0) {
throw new Error(`所有 ${downloadResult.total} 个附件下载均失败。`);
}
return;
}
await runTool(
"seal_approval_run_attachments_get",
client,
corp,
{
recordId,
summary: booleanOption(args.options.summary)
},
outputOptions(args.options)
);
const record = await api.getApprovalRun(client, recordId);
const result = extractApprovalRunAttachments(record, {
summary: booleanOption(args.options.summary)
});
printJson(result, outputOptions(args.options));
return;
}
@@ -244,23 +237,19 @@ export async function handleApprovalRunsCommand(
"Usage: seal-use approval-runs download <recordId> [--all] [--name <name>] [--out-dir <dir>]"
);
}
const downloadResult = (await runToolResult(
"seal_approval_run_attachments_download",
client,
corp,
{
recordId,
all: booleanOption(args.options.all),
name: stringOption(args.options.name),
outDir:
stringOption(args.options["out-dir"]) ??
stringOption(args.options.outDir) ??
stringOption(args.options.dir)
}
)) as any;
const record = await api.getApprovalRun(client, recordId);
const downloadResult = await downloadApprovalRunAttachments({
record,
all: booleanOption(args.options.all),
name: stringOption(args.options.name),
outDir:
stringOption(args.options["out-dir"]) ??
stringOption(args.options.outDir) ??
stringOption(args.options.dir)
});
printJson(downloadResult, outputOptions(args.options));
if (downloadResult?.total > 0 && downloadResult?.downloaded === 0) {
if (downloadResult.total > 0 && downloadResult.downloaded === 0) {
throw new Error(`所有 ${downloadResult.total} 个附件下载均失败。`);
}
return;
@@ -297,5 +286,30 @@ export async function handleApprovalRunsCommand(
return;
}
if (action === "export") {
const result = await exportApprovalRunsToExcel(client, corp, {
limit: numberOption(args.options.limit),
startDate:
stringOption(args.options.start) ??
stringOption(args.options.startDate) ??
stringOption(args.options.since),
endDate: stringOption(args.options.end) ?? stringOption(args.options.endDate),
status: stringOption(args.options.status),
manualApprovalStatus:
stringOption(args.options["manual-status"]) ??
stringOption(args.options.manualStatus) ??
stringOption(args.options.manualApprovalStatus),
includeCompletedOnly:
booleanOption(args.options["completed-only"]) ?? booleanOption(args.options.completedOnly),
outputFile:
stringOption(args.options.out) ??
stringOption(args.options.output) ??
stringOption(args.options.file),
toDownloads: booleanOption(args.options.downloads) ?? booleanOption(args.options.download)
});
printJson(result, outputOptions(args.options));
return;
}
throw new Error(`Unknown approval-runs command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+1 -1
View File
@@ -22,7 +22,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
throw new Error(`Unknown auth command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
export async function diagnoseAuth(corp: CorpConfig) {
async function diagnoseAuth(corp: CorpConfig) {
if (corp.source.type !== "hose") {
const client = await createSealClient(corp);
const me = await getMe(client);
+34 -1
View File
@@ -90,5 +90,38 @@ export function handleConfigCommand(action: string | undefined, maybeName: strin
return;
}
throw new Error(`Unknown config command: ${action ?? ""}. Available: paths, get, status, mode, lint. Run 'seal-use help' for available commands.`);
if (action === "test-dir" || action === "test-enterprises-dir") {
const isClear = args.options.clear === true || maybeName === "--clear" || maybeName === "clear";
const previousConfig = loadGlobalConfig();
if (isClear) {
const config = saveGlobalConfig({
...previousConfig,
testEnterprisesDir: undefined
});
printJson(globalConfigSummary(config));
return;
}
const newPath = maybeName && !maybeName.startsWith("-")
? maybeName
: stringOption(args.options.path) ?? stringOption(args.options.dir);
if (!newPath) {
printJson({
testEnterprisesDir: previousConfig.testEnterprisesDir ?? null,
configFile: resolveGlobalConfigFile()
});
return;
}
const config = saveGlobalConfig({
...previousConfig,
testEnterprisesDir: newPath
});
printJson(globalConfigSummary(config));
return;
}
throw new Error(`Unknown config command: ${action ?? ""}. Available: paths, get, status, mode, lint, test-dir. Run 'seal-use help' for available commands.`);
}
+42
View File
@@ -0,0 +1,42 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleContactsCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "sync-time" || action === "last-sync-time") {
await runTool("seal_contacts_last_sync_time_get", client, corp, {}, outputOptions(args.options));
return;
}
if (action === "departments" || action === "department") {
if (!maybeName) {
await runTool("seal_contacts_departments_root_list", client, corp, {}, outputOptions(args.options));
return;
}
await runTool("seal_contacts_department_get", client, corp, { departmentId: maybeName }, outputOptions(args.options));
return;
}
if (action === "children" || action === "department-children") {
if (!maybeName) throw new Error("Usage: seal-use contacts children <departmentId>");
await runTool("seal_contacts_department_children_list", client, corp, { departmentId: maybeName }, outputOptions(args.options));
return;
}
if (action === "users" || action === "department-users") {
if (!maybeName) throw new Error("Usage: seal-use contacts users <departmentId>");
await runTool("seal_contacts_department_users_list", client, corp, { departmentId: maybeName }, outputOptions(args.options));
return;
}
throw new Error(`Unknown contacts command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+685
View File
@@ -0,0 +1,685 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { CorpConfig } from "../../core/config/types.js";
import { runCli } from "../runner.js";
const ORIGINAL_ENV = {
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
config: process.env.SEAL_USE_CONFIG_FILE,
tokenStore: process.env.SEAL_USE_TOKEN_STORE,
mappings: process.env.SEAL_USE_MAPPINGS_DIR
};
const ORIGINAL_FETCH = globalThis.fetch;
const tempDirs: string[] = [];
afterEach(() => {
restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config);
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
restoreEnv("SEAL_USE_MAPPINGS_DIR", ORIGINAL_ENV.mappings);
globalThis.fetch = ORIGINAL_FETCH;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
function setupTestEnv() {
const root = mkdtempSync(join(tmpdir(), "seal-use-bind-test-"));
const enterprises = join(root, "enterprises");
const mappings = join(root, "mappings");
mkdirSync(enterprises, { recursive: true });
mkdirSync(mappings, { recursive: true });
tempDirs.push(root);
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
process.env.SEAL_USE_MAPPINGS_DIR = mappings;
const prodCorp: CorpConfig = {
id: "corp-prod",
name: "Acme Production",
environment: "production",
seal: {
url: "https://acme-prod.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "prod-token",
sealUrl: "https://acme-prod.sealai.cc",
expiresIn: 3600,
staffId: "seal"
},
auth: { refreshTtl: 300 }
};
const testCorp: CorpConfig = {
id: "corp-test",
name: "Acme Staging Test",
environment: "test",
seal: {
url: "https://acme-test.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "test-token",
sealUrl: "https://acme-test.sealai.cc",
expiresIn: 3600,
staffId: "seal"
},
auth: { refreshTtl: 300 }
};
writeFileSync(join(enterprises, "corp-prod.json"), JSON.stringify(prodCorp, null, 2));
writeFileSync(join(enterprises, "corp-test.json"), JSON.stringify(testCorp, null, 2));
return { root, enterprises, prodCorp, testCorp };
}
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
describe("corps mark", () => {
test("requires confirmation and exit code 10 without --confirm", async () => {
setupTestEnv();
const result = await runCli(["corps", "mark", "corp-prod", "--env", "test"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(10);
expect(result.stderr).toContain("without --confirm");
expect(result.stderr).toContain("seal-use corps mark corp-prod --env test --confirm");
});
test("successfully updates environment with --confirm", async () => {
const { enterprises } = setupTestEnv();
const result = await runCli(["corps", "mark", "corp-prod", "--env", "test", "--confirm"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.id).toBe("corp-prod");
expect(parsed.environment).toBe("test");
const saved = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
expect(saved.environment).toBe("test");
});
});
describe("corps bind-test & unbind-test", () => {
test("rejects self-binding with exit code 2", async () => {
setupTestEnv();
const result = await runCli(["corps", "bind-test", "corp-prod", "corp-prod", "--confirm"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("Cannot bind enterprise 'corp-prod' to itself");
});
test("requires confirmation and exit code 10 without --confirm", async () => {
setupTestEnv();
const result = await runCli(["corps", "bind-test", "corp-prod", "corp-test"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(10);
expect(result.stderr).toContain("without --confirm");
expect(result.stderr).toContain("seal-use corps bind-test corp-prod corp-test --confirm");
});
test("successfully binds 1-to-1 with --confirm and sets tags", async () => {
const { enterprises } = setupTestEnv();
const result = await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.success).toBe(true);
expect(parsed.productionEnterprise.id).toBe("corp-prod");
expect(parsed.productionEnterprise.testCorpId).toBe("corp-test");
expect(parsed.productionEnterprise.environment).toBe("production");
expect(parsed.testEnterprise.id).toBe("corp-test");
expect(parsed.testEnterprise.prodCorpId).toBe("corp-prod");
expect(parsed.testEnterprise.environment).toBe("test");
const savedProd = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
expect(savedProd.testCorpId).toBe("corp-test");
expect(savedProd.environment).toBe("production");
const savedTest = JSON.parse(readFileSync(join(enterprises, "corp-test.json"), "utf-8"));
expect(savedTest.prodCorpId).toBe("corp-prod");
expect(savedTest.environment).toBe("test");
});
test("prevents multi-tier chaining: test corp cannot be bound as prod parent", async () => {
const { enterprises } = setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const thirdCorp: CorpConfig = {
id: "corp-subtest",
name: "Acme Subtest",
environment: "test",
seal: { url: "https://sub.sealai.cc", endpoints: { approvalStylePreferences: "" } },
source: { type: "seal", token: "tok", sealUrl: "https://sub.sealai.cc", expiresIn: 3600, staffId: "seal" },
auth: { refreshTtl: 300 }
};
writeFileSync(join(enterprises, "corp-subtest.json"), JSON.stringify(thirdCorp, null, 2));
const result = await runCli(["corps", "bind-test", "corp-test", "corp-subtest", "--confirm"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("Multi-tier chaining is not permitted");
});
test("requires --force when re-binding an already bound corp", async () => {
const { enterprises } = setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const testCorp2: CorpConfig = {
id: "corp-test-2",
name: "Acme Staging 2",
environment: "test",
seal: { url: "https://test2.sealai.cc", endpoints: { approvalStylePreferences: "" } },
source: { type: "seal", token: "tok2", sealUrl: "https://test2.sealai.cc", expiresIn: 3600, staffId: "seal" },
auth: { refreshTtl: 300 }
};
writeFileSync(join(enterprises, "corp-test-2.json"), JSON.stringify(testCorp2, null, 2));
const conflictResult = await runCli(["corps", "bind-test", "corp-prod", "corp-test-2", "--confirm"]);
expect(conflictResult.isError).toBe(true);
expect(conflictResult.exitCode).toBe(10);
expect(conflictResult.stderr).toContain("requires --force");
const forceResult = await runCli(["corps", "bind-test", "corp-prod", "corp-test-2", "--confirm", "--force"]);
expect(forceResult.isError).toBe(false);
expect(forceResult.exitCode).toBe(0);
const savedProd = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
expect(savedProd.testCorpId).toBe("corp-test-2");
});
test("unbind-test requires confirmation then unlinks both sides", async () => {
const { enterprises } = setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const blockResult = await runCli(["corps", "unbind-test", "corp-prod"]);
expect(blockResult.isError).toBe(true);
expect(blockResult.exitCode).toBe(10);
expect(blockResult.stderr).toContain("without --confirm");
const successResult = await runCli(["corps", "unbind-test", "corp-prod", "--confirm"]);
expect(successResult.isError).toBe(false);
expect(successResult.exitCode).toBe(0);
const parsed = JSON.parse(successResult.stdout);
expect(parsed.success).toBe(true);
expect(parsed.unboundProduction).toBe("corp-prod");
expect(parsed.unboundTest).toBe("corp-test");
const savedProd = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
expect(savedProd.testCorpId).toBeUndefined();
const savedTest = JSON.parse(readFileSync(join(enterprises, "corp-test.json"), "utf-8"));
expect(savedTest.prodCorpId).toBeUndefined();
});
});
describe("corps sync-test", () => {
test("fails if production corp has no bound test corp", async () => {
setupTestEnv();
const result = await runCli(["corps", "sync-test", "corp-prod", "--dry-run"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("has no bound test enterprise");
});
test("dry-run produces preview diff without making network mutations", async () => {
setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const mockMutations: string[] = [];
mockSealSyncRequests({ onMutation: (method, path) => mockMutations.push(`${method} ${path}`) });
const result = await runCli(["corps", "sync-test", "corp-prod", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.dryRun).toBe(true);
expect(parsed.source.id).toBe("corp-prod");
expect(parsed.target.id).toBe("corp-test");
expect(parsed.rulesPlan.sourceDraftRuleCount).toBe(2);
expect(parsed.rulesPlan.targetExistingDraftRuleCount).toBe(1);
expect(parsed.rulesPlan.toDeleteCount).toBe(1);
expect(parsed.rulesPlan.toCreateCount).toBe(2);
expect(parsed.documentsPlan).toBeDefined();
expect(parsed.documentsPlan.sourceDocumentCount).toBe(2);
expect(parsed.documentsPlan.targetExistingDocumentCount).toBe(2);
expect(parsed.documentsPlan.toCreateCount).toBe(1);
expect(parsed.documentsPlan.toCreate[0].title).toBe("Doc Alpha");
expect(parsed.documentsPlan.toUpdateCount).toBe(1);
expect(parsed.documentsPlan.toUpdate[0].title).toBe("Doc Beta");
expect(parsed.documentsPlan.toDeleteCount).toBe(1);
expect(parsed.documentsPlan.toDelete[0].title).toBe("Doc Gamma Old");
expect(parsed.productionGuarantees.prodRulesStayDraft).toBe(true);
expect(parsed.productionGuarantees.prodVersionPublished).toBe(false);
expect(mockMutations).toEqual([]);
});
test("sync-test requires --yes and blocks with exit code 10", async () => {
setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
mockSealSyncRequests();
const result = await runCli(["corps", "sync-test", "corp-prod"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(10);
expect(result.stderr).toContain("without --yes");
expect(result.stderr).toContain("seal-use corps sync-test corp-prod --yes");
});
test("sync-test --yes overwrites test preferences, syncs rules, publishes new test version, and guarantees prod draft safety", async () => {
setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const requests: { method: string; path: string; body?: unknown }[] = [];
mockSealSyncRequests({
onMutation: (method, path, body) => requests.push({ method, path, body })
});
const result = await runCli([
"corps",
"sync-test",
"corp-prod",
"--yes",
"--version-name",
"v1.5-staging"
]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.success).toBe(true);
expect(parsed.source.id).toBe("corp-prod");
expect(parsed.source.draftRulesCount).toBe(2);
expect(parsed.target.id).toBe("corp-test");
expect(parsed.target.deletedDraftRulesCount).toBe(1);
expect(parsed.target.createdDraftRulesCount).toBe(2);
expect(parsed.target.publishedVersion.versionName).toBe("v1.5-staging");
expect(parsed.target.publishedVersion.versionNumber).toBe(3);
expect(parsed.documents).toBeDefined();
expect(parsed.documents.sourceCount).toBe(2);
expect(parsed.documents.targetExistingCount).toBe(2);
expect(parsed.documents.createdCount).toBe(1);
expect(parsed.documents.created[0].title).toBe("Doc Alpha");
expect(parsed.documents.updatedCount).toBe(1);
expect(parsed.documents.updated[0].title).toBe("Doc Beta");
expect(parsed.documents.deletedCount).toBe(1);
expect(parsed.documents.deleted[0].title).toBe("Doc Gamma Old");
expect(parsed.productionGuarantees.prodRulesStayDraft).toBe(true);
expect(parsed.productionGuarantees.prodVersionPublished).toBe(false);
expect(parsed.versionMapping).toBeDefined();
expect(parsed.versionMapping.sourceProdVersionNumber).toBe(22);
expect(parsed.versionMapping.targetTestVersionNumber).toBe(3);
expect(parsed.ruleMapping).toHaveLength(2);
expect(parsed.ruleMapping[0].sourceRuleId).toBe("prod-rule-1");
expect(parsed.ruleMapping[0].targetRuleCode).toBe("rule-1");
expect(parsed.mappingSavedTo).toBeDefined();
const postPref = requests.find((r) => (r.method === "POST" || r.method === "PATCH") && r.path.includes("config"));
expect(postPref).toBeDefined();
expect((postPref?.body as any).decisionPreferences?.explicitApprove).toBe("Prod approve note");
const deleteDoc = requests.find((r) => r.method === "DELETE" && r.path === "/api/v1/knowledge/articles/test-doc-old");
expect(deleteDoc).toBeDefined();
const patchDoc = requests.find((r) => r.method === "PATCH" && r.path === "/api/v1/knowledge/articles/test-doc-2");
expect(patchDoc).toBeDefined();
expect((patchDoc?.body as any).attributes?.content).toBe("Content Beta Updated");
const postDoc = requests.find((r) => r.method === "POST" && r.path === "/api/v1/knowledge/articles");
expect(postDoc).toBeDefined();
expect((postDoc?.body as any).title).toBe("Doc Alpha");
const deleteRule = requests.find((r) => r.method === "DELETE" && r.path === "/api/v1/rules/test-rule-old");
expect(deleteRule).toBeDefined();
const createdRules = requests.filter((r) => r.method === "POST" && r.path === "/api/v1/rules");
expect(createdRules.length).toBe(2);
expect((createdRules[0]?.body as any).description).toBe("Production Rule A");
expect((createdRules[1]?.body as any).description).toBe("Production Rule B");
const publishVersion = requests.find((r) => r.method === "POST" && r.path === "/api/v1/rule-set-versions/publish");
expect(publishVersion).toBeDefined();
expect((publishVersion?.body as any).versionName).toBe("v1.5-staging");
const allPublishCalls = requests.filter((r) => r.path === "/api/v1/rule-set-versions/publish");
expect(allPublishCalls.length).toBe(1);
});
test("sync-test formats semantic version name [Prod v22 · #1 -> Test v3] and rules map inspects local snapshot", async () => {
setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const requests: { method: string; path: string; body?: unknown }[] = [];
mockSealSyncRequests({
onMutation: (method, path, body) => requests.push({ method, path, body })
});
const syncResult = await runCli([
"corps",
"sync-test",
"corp-prod",
"--yes"
]);
expect(syncResult.isError).toBe(false);
const parsed = JSON.parse(syncResult.stdout);
expect(parsed.target.publishedVersion.versionName).toBe("Sync from Acme Production [Prod v22 · #1 -> Test v3]");
expect(parsed.versionMapping.sourceProdVersionNumber).toBe(22);
expect(parsed.ruleMapping).toHaveLength(2);
// Verify rules map command
const mapResult = await runCli(["rules", "map", "--corp", "corp-test"]);
expect(mapResult.isError).toBe(false);
const mapParsed = JSON.parse(mapResult.stdout);
expect(mapParsed.matchedRules).toBe(2);
expect(mapParsed.versionMapping.sourceProdVersionNumber).toBe(22);
// Verify filtering rules map by targetCode
const filteredResult = await runCli(["rules", "map", "--corp", "corp-test", "--code", "rule-1"]);
expect(filteredResult.isError).toBe(false);
const filteredParsed = JSON.parse(filteredResult.stdout);
expect(filteredParsed.matchedRules).toBe(1);
expect(filteredParsed.rules[0].targetRuleCode).toBe("rule-1");
});
});
describe("corps list & current", () => {
test("outputs environment, testCorpId, and prodCorpId", async () => {
setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const listResult = await runCli(["corps", "list"]);
expect(listResult.isError).toBe(false);
const list = JSON.parse(listResult.stdout);
const prodItem = list.find((item: any) => item.id === "corp-prod");
const testItem = list.find((item: any) => item.id === "corp-test");
expect(prodItem.environment).toBe("production");
expect(prodItem.testCorpId).toBe("corp-test");
expect(testItem.environment).toBe("test");
expect(testItem.prodCorpId).toBe("corp-prod");
const currentResult = await runCli(["corps", "current", "--corp", "corp-prod"]);
expect(currentResult.isError).toBe(false);
const current = JSON.parse(currentResult.stdout);
expect(current.id).toBe("corp-prod");
expect(current.environment).toBe("production");
expect(current.testCorpId).toBe("corp-test");
});
});
function mockSealSyncRequests(options: {
onMutation?: (method: string, path: string, body?: unknown) => void;
} = {}) {
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const requestUrl = typeof input === "string"
? input
: input instanceof URL
? input.toString()
: input.url;
const url = new URL(requestUrl);
const method = (
init?.method ??
(typeof input === "object" && "method" in input ? (input as Request).method : "GET")
).toUpperCase();
const isProd = url.host.includes("prod");
let rawBody = typeof init?.body === "string" ? init.body : undefined;
if (!rawBody && typeof input === "object" && "text" in input) {
rawBody = await (input as Request).clone().text().catch(() => "{}");
}
if (url.pathname === "/api/v1/auth/me") {
return jsonResponse({
data: {
user: { id: "user-1", name: isProd ? "Prod User" : "Test User" },
tenant: { id: isProd ? "tenant-prod" : "tenant-test", tenantSlug: isProd ? "acme-prod" : "acme-test" }
}
});
}
if (url.pathname === "/api/v1/agent/ai-approval/config" && method === "GET") {
return jsonResponse({
data: {
id: isProd ? "pref-prod" : "pref-test",
tenantId: isProd ? "tenant-prod" : "tenant-test",
tone: isProd ? "formal" : "casual",
language: "zh-CN",
decisionPreferences: {
explicitApprove: isProd ? "Prod approve note" : "Test approve note",
explicitReject: "Reject invalid expenses",
exemptApprove: "",
review: ""
},
thinkingDepthPreference: {
defaultLevel: isProd ? "high" : "medium",
routingPolicies: []
},
integrations: [
{ type: "hosecloud", signKey: isProd ? "prod-sign" : "test-sign" }
]
}
});
}
if (url.pathname === "/api/v1/agent/ai-approval/config" && (method === "POST" || method === "PATCH")) {
const body = JSON.parse(rawBody || "{}");
options.onMutation?.(method, url.pathname, body);
return jsonResponse({ data: { success: true } });
}
if (url.pathname === "/api/v1/knowledge/articles" && method === "GET") {
if (isProd) {
return jsonResponse({
data: {
articles: [
{
id: "prod-doc-1",
title: "Doc Alpha",
purpose: "Purpose Alpha",
content: "Content Alpha",
contentType: "policy",
status: "published",
enabled: true,
scenarios: ["audit"],
tags: []
},
{
id: "prod-doc-2",
title: "Doc Beta",
purpose: "Purpose Beta",
content: "Content Beta Updated",
contentType: "policy",
status: "published",
enabled: true,
scenarios: ["audit"],
tags: []
}
],
total: 2
}
});
} else {
return jsonResponse({
data: {
articles: [
{
id: "test-doc-2",
title: "Doc Beta",
purpose: "Purpose Beta",
content: "Content Beta Old",
contentType: "policy",
status: "published",
enabled: true,
scenarios: ["audit"],
tags: []
},
{
id: "test-doc-old",
title: "Doc Gamma Old",
purpose: "Redundant doc",
content: "To be deleted",
contentType: "policy",
status: "published",
enabled: true,
scenarios: ["audit"],
tags: []
}
],
total: 2
}
});
}
}
if (url.pathname.startsWith("/api/v1/knowledge/articles/") && method === "DELETE") {
options.onMutation?.("DELETE", url.pathname);
return jsonResponse({ data: { success: true } });
}
if (url.pathname.startsWith("/api/v1/knowledge/articles/") && method === "PATCH") {
const body = JSON.parse(rawBody || "{}");
options.onMutation?.("PATCH", url.pathname, body);
return jsonResponse({
data: {
id: url.pathname.split("/").pop(),
...body.attributes
}
});
}
if (url.pathname === "/api/v1/knowledge/articles" && method === "POST") {
const body = JSON.parse(rawBody || "{}");
options.onMutation?.("POST", url.pathname, body);
return jsonResponse({
data: {
id: `new-doc-${Date.now()}`,
...body
}
});
}
if (url.pathname === "/api/v1/rules" && method === "GET") {
if (isProd) {
return jsonResponse({
data: {
rules: [
{ id: "prod-rule-1", description: "Production Rule A", scope: "global", strictness: "strict" },
{ id: "prod-rule-2", description: "Production Rule B", scope: "invoice", strictness: "flexible" }
],
hasPendingDeletes: false
}
});
} else {
return jsonResponse({
data: {
rules: [
{ id: "test-rule-old", description: "Old test rule", scope: "global", strictness: "strict" }
],
hasPendingDeletes: false
}
});
}
}
if (url.pathname.startsWith("/api/v1/rules/") && method === "DELETE") {
options.onMutation?.("DELETE", url.pathname);
return jsonResponse({ data: { success: true } });
}
if (url.pathname === "/api/v1/rules" && method === "POST") {
const body = JSON.parse(rawBody || "{}");
options.onMutation?.("POST", url.pathname, body);
return jsonResponse({
data: {
id: `new-rule-${Date.now()}`,
...body
}
});
}
if (url.pathname === "/api/v1/rules/batch-recode" && method === "POST") {
options.onMutation?.("POST", url.pathname);
return jsonResponse({ data: { success: true } });
}
if (url.pathname === "/api/v1/rule-set-versions" && method === "GET") {
if (isProd) {
return jsonResponse({
data: [
{
id: "ver-prod-22",
versionNumber: 22,
versionName: "审核规则 版本22",
publishedByName: "周晚容",
rules: [],
publishedAt: 1786961644896,
createdAt: 1786961644896
}
]
});
} else {
return jsonResponse({
data: [
{
id: "ver-test-2",
versionNumber: 2,
versionName: "v1.0-old",
publishedByName: "管理员",
rules: [],
publishedAt: 1783495074421,
createdAt: 1783495074421
}
]
});
}
}
if (url.pathname === "/api/v1/rule-set-versions/publish" && method === "POST") {
const body = JSON.parse(rawBody || "{}");
options.onMutation?.("POST", url.pathname, body);
return jsonResponse({
data: {
version: {
id: "ver-3",
versionNumber: 3,
versionName: body.versionName ?? "v1.0",
rules: [
{ code: "rule-1", description: "Production Rule A", scope: "global", strictness: "strict" },
{ code: "rule-2", description: "Production Rule B", scope: "invoice", strictness: "flexible" }
]
},
rulesCount: 2
}
});
}
return jsonResponse({ error: `Unexpected request: ${method} ${url.pathname}` }, 404);
}) as typeof fetch;
}
function jsonResponse(value: unknown, status = 200) {
return new Response(JSON.stringify(value), {
status,
headers: { "content-type": "application/json" }
});
}
+580 -7
View File
@@ -9,17 +9,27 @@ import {
probeHoseDomain
} from "../../core/auth/hose.js";
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import { createSealClientForUrl } from "../../core/http/factory.js";
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import {
loadCorpConfigs,
loadGlobalConfig,
resolveWritableEnterprisesDir,
saveGlobalConfig
saveGlobalConfig,
updateCorpConfig
} from "../../core/config/loader.js";
import type { CorpConfig } from "../../core/config/types.js";
import { SealCookieMapSchema, SealHeaderMapSchema } from "../../core/config/types.js";
import type { CorpConfig, CorpEnvironment } from "../../core/config/types.js";
import * as api from "../../domains/seal/api.js";
import { getMe } from "../../domains/seal/api.js";
import {
computeNextSyncIteration,
formatSyncVersionName,
saveRuleMappingSnapshot
} from "../../domains/seal/rule-mapping.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
import { selectCorp } from "../helpers.js";
import { confirmationRequired, usageError } from "../errors.js";
import {
inferCorpIdFromStaffId,
booleanOption,
@@ -50,8 +60,11 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
printJson(corps.map((item) => ({
id: item.id,
name: item.name,
environment: item.environment ?? "production",
sourceType: item.source.type,
provider: (item.source as any).provider ?? item.source.type,
testCorpId: item.testCorpId,
prodCorpId: item.prodCorpId,
current: item.id === currentCorpId
})));
return;
@@ -62,8 +75,549 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
printJson({
id: corp.id,
name: corp.name,
environment: corp.environment ?? "production",
sourceType: corp.source.type,
provider: (corp.source as any).provider ?? corp.source.type
provider: (corp.source as any).provider ?? corp.source.type,
testCorpId: corp.testCorpId,
prodCorpId: corp.prodCorpId
});
return;
}
if (action === "mark" || action === "mark-test" || action === "mark-prod") {
const corpId = maybeName ?? stringOption(args.options.corp);
if (!corpId) {
throw usageError("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");
}
const corp = selectCorp(corpId);
const targetEnv = (
action === "mark-test"
? "test"
: action === "mark-prod"
? "production"
: (stringOption(args.options.env) ?? stringOption(args.options.environment))
) as CorpEnvironment | undefined;
if (targetEnv !== "production" && targetEnv !== "test") {
throw usageError("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");
}
const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to change environment tag of enterprise '${corp.name}' (${corp.id}) to '${targetEnv}' without --confirm. Marking alters synchronization safety guards.`,
`seal-use corps mark ${corp.id} --env ${targetEnv} --confirm`
);
}
const updated = updateCorpConfig(corp.id, { environment: targetEnv });
printJson({
id: updated.id,
name: updated.name,
environment: updated.environment,
testCorpId: updated.testCorpId,
prodCorpId: updated.prodCorpId
});
return;
}
if (action === "bind-test") {
let prodId: string | undefined;
let testId: string | undefined;
if (maybeName && args.command[3]) {
prodId = maybeName;
testId = args.command[3];
} else if (maybeName) {
const corpOption = stringOption(args.options.corp);
const testCorpOption = stringOption(args.options["test-corp"]) ?? stringOption(args.options.testCorp);
if (corpOption) {
prodId = corpOption;
testId = maybeName;
} else if (testCorpOption) {
prodId = maybeName;
testId = testCorpOption;
}
}
if (!prodId || !testId) {
throw usageError(
"Usage: seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]\n" +
" or: seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"
);
}
const prodCorp = selectCorp(prodId);
const testCorp = selectCorp(testId);
if (prodCorp.id === testCorp.id) {
throw usageError(`Cannot bind enterprise '${prodCorp.id}' to itself.`);
}
if (prodCorp.prodCorpId && prodCorp.prodCorpId !== testCorp.id) {
throw usageError(
`Cannot use '${prodCorp.id}' as a production enterprise because it is already registered as a test enterprise for '${prodCorp.prodCorpId}'. Multi-tier chaining is not permitted.`
);
}
if (testCorp.testCorpId && testCorp.testCorpId !== prodCorp.id) {
throw usageError(
`Cannot bind '${testCorp.id}' as a test enterprise because it already has a bound test enterprise '${testCorp.testCorpId}'. Multi-tier chaining is not permitted.`
);
}
const force = booleanOption(args.options.force) === true;
if (
(prodCorp.testCorpId && prodCorp.testCorpId !== testCorp.id) ||
(testCorp.prodCorpId && testCorp.prodCorpId !== prodCorp.id)
) {
if (!force) {
throw confirmationRequired(
`Enterprise binding conflict: production enterprise '${prodCorp.id}' is bound to '${prodCorp.testCorpId ?? "none"}', and test enterprise '${testCorp.id}' is bound to '${testCorp.prodCorpId ?? "none"}'. Overwriting an existing binding requires --force and --confirm.`,
`seal-use corps bind-test ${prodCorp.id} ${testCorp.id} --confirm --force`
);
}
}
const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true;
if (!confirmed) {
const forceFlag = force ? " --force" : "";
throw confirmationRequired(
`Refusing to bind test enterprise '${testCorp.name}' (${testCorp.id}) to production enterprise '${prodCorp.name}' (${prodCorp.id}) without --confirm. Enterprise binding establishes 1-to-1 sync pairing and marks '${testCorp.id}' as a test environment.`,
`seal-use corps bind-test ${prodCorp.id} ${testCorp.id} --confirm${forceFlag}`
);
}
if (prodCorp.testCorpId && prodCorp.testCorpId !== testCorp.id) {
try {
updateCorpConfig(prodCorp.testCorpId, { prodCorpId: undefined });
} catch {}
}
if (testCorp.prodCorpId && testCorp.prodCorpId !== prodCorp.id) {
try {
updateCorpConfig(testCorp.prodCorpId, { testCorpId: undefined });
} catch {}
}
const updatedProd = updateCorpConfig(prodCorp.id, {
environment: "production",
testCorpId: testCorp.id
});
const updatedTest = updateCorpConfig(testCorp.id, {
environment: "test",
prodCorpId: prodCorp.id
});
printJson({
success: true,
productionEnterprise: {
id: updatedProd.id,
name: updatedProd.name,
environment: updatedProd.environment,
testCorpId: updatedProd.testCorpId
},
testEnterprise: {
id: updatedTest.id,
name: updatedTest.name,
environment: updatedTest.environment,
prodCorpId: updatedTest.prodCorpId
}
});
return;
}
if (action === "unbind-test") {
const targetId = maybeName ?? stringOption(args.options.corp);
const corp = selectCorp(targetId);
if (!corp.testCorpId && !corp.prodCorpId) {
printJson({
unbound: false,
message: `Enterprise '${corp.name}' (${corp.id}) does not have an active test enterprise binding.`
});
return;
}
const prodId = corp.testCorpId ? corp.id : corp.prodCorpId!;
const testId = corp.testCorpId ? corp.testCorpId : corp.id;
const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to unbind production enterprise '${prodId}' and test enterprise '${testId}' without --confirm.`,
`seal-use corps unbind-test ${corp.id} --confirm`
);
}
updateCorpConfig(prodId, { testCorpId: undefined });
try {
updateCorpConfig(testId, { prodCorpId: undefined });
} catch {}
printJson({
success: true,
unboundProduction: prodId,
unboundTest: testId
});
return;
}
if (action === "sync-test") {
const targetCorpId = maybeName ?? stringOption(args.options.corp);
const prodCorp = selectCorp(targetCorpId);
if (!prodCorp.testCorpId) {
throw usageError(
`Production enterprise '${prodCorp.name}' (${prodCorp.id}) has no bound test enterprise.\n` +
`Run 'seal-use corps bind-test ${prodCorp.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`
);
}
const testCorp = selectCorp(prodCorp.testCorpId);
if (testCorp.environment !== "test") {
throw new Error(
`Target enterprise '${testCorp.name}' (${testCorp.id}) is marked as '${testCorp.environment}', NOT 'test'. Aborting sync to protect non-test environments.`
);
}
const prodClient = await createSealClient(prodCorp);
const testClient = await createSealClient(testCorp);
const [
prodPref,
testPref,
prodRules,
testRules,
prodVersions,
testVersions,
prodDocsRes,
testDocsRes
] = await Promise.all([
api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any)),
api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any)),
api.listApprovalRules(prodClient),
api.listApprovalRules(testClient),
api.listApprovalRuleVersions(prodClient).catch(() => []),
api.listApprovalRuleVersions(testClient).catch(() => []),
api.listApprovalDocuments(prodClient, { limit: 100 }).catch(() => ({ articles: [] })),
api.listApprovalDocuments(testClient, { limit: 100 }).catch(() => ({ articles: [] }))
]);
const prodDocs = (prodDocsRes.articles || []).filter((d) => !d.isDeleted);
const testDocs = (testDocsRes.articles || []).filter((d) => !d.isDeleted);
const testDocsByTitle = new Map(testDocs.map((d) => [d.title.trim(), d]));
const docsToCreate = [];
const docsToUpdate = [];
const prodTitles = new Set(prodDocs.map((d) => d.title.trim()));
for (const prodDoc of prodDocs) {
const title = prodDoc.title.trim();
const existing = testDocsByTitle.get(title);
if (!existing) {
docsToCreate.push(prodDoc);
} else {
const contentChanged = existing.content !== prodDoc.content;
const purposeChanged = (existing.purpose ?? "") !== (prodDoc.purpose ?? "");
const enabledChanged = existing.enabled !== prodDoc.enabled;
const contentTypeChanged = existing.contentType !== prodDoc.contentType;
const statusChanged = (existing.status ?? "") !== (prodDoc.status ?? "");
const scenariosChanged = JSON.stringify([...(existing.scenarios ?? [])].sort()) !==
JSON.stringify([...(prodDoc.scenarios ?? [])].sort());
const tagsChanged = JSON.stringify([...(existing.tags ?? [])].sort()) !==
JSON.stringify([...(prodDoc.tags ?? [])].sort());
if (contentChanged || purposeChanged || enabledChanged || contentTypeChanged || statusChanged || scenariosChanged || tagsChanged) {
docsToUpdate.push({
testId: existing.id,
prodDoc,
reasons: [
...(contentChanged ? ["content"] : []),
...(purposeChanged ? ["purpose"] : []),
...(enabledChanged ? ["enabled"] : []),
...(contentTypeChanged ? ["contentType"] : []),
...(statusChanged ? ["status"] : []),
...(scenariosChanged ? ["scenarios"] : []),
...(tagsChanged ? ["tags"] : [])
]
});
}
}
}
const docsToDelete = testDocs.filter(
(td) => !prodTitles.has(td.title.trim())
);
const sortedProdVersions = [...prodVersions].sort((a, b) => b.versionNumber - a.versionNumber);
const latestProd = sortedProdVersions[0];
const prodVersionNumber = latestProd?.versionNumber;
const sortedTestVersions = [...testVersions].sort((a, b) => b.versionNumber - a.versionNumber);
const targetTestExpectedVersionNumber = (sortedTestVersions[0]?.versionNumber ?? 0) + 1;
const nextIteration = computeNextSyncIteration(prodCorp.name, prodVersionNumber, testVersions);
const customVersionName = stringOption(args.options["version-name"]) ?? stringOption(args.options.versionName);
const versionName = customVersionName ?? formatSyncVersionName(prodCorp.name, prodVersionNumber, nextIteration, targetTestExpectedVersionNumber);
const updatedTestPref = {
...testPref,
tone: prodPref.tone,
language: prodPref.language,
detailLevel: prodPref.detailLevel,
outputFormat: prodPref.outputFormat,
examples: prodPref.examples ?? [],
prohibitedPhrases: prodPref.prohibitedPhrases ?? [],
customInstructions: prodPref.customInstructions,
decisionPreferences: prodPref.decisionPreferences,
thinkingDepthPreference: prodPref.thinkingDepthPreference
};
const dryRun = booleanOption(args.options["dry-run"]) === true || booleanOption(args.options.dryRun) === true;
if (dryRun) {
printJson({
dryRun: true,
source: {
id: prodCorp.id,
name: prodCorp.name,
environment: prodCorp.environment,
latestPublishedVersion: latestProd ? {
versionNumber: latestProd.versionNumber,
versionName: latestProd.versionName
} : null,
documentsCount: prodDocs.length
},
target: {
id: testCorp.id,
name: testCorp.name,
environment: testCorp.environment
},
versionMappingPlan: {
sourceProdVersionNumber: prodVersionNumber ?? null,
sourceProdVersionName: latestProd?.versionName ?? null,
targetTestExpectedVersionNumber,
targetTestPublishVersionName: versionName,
iteration: nextIteration
},
preferencesDiff: {
decisionPreferences: {
before: testPref.decisionPreferences,
after: prodPref.decisionPreferences
},
thinkingDepthPreference: {
before: testPref.thinkingDepthPreference,
after: prodPref.thinkingDepthPreference
}
},
rulesPlan: {
sourceDraftRuleCount: prodRules.rules.length,
targetExistingDraftRuleCount: testRules.rules.length,
toDeleteCount: testRules.rules.length,
toCreateCount: prodRules.rules.length,
rulesToSync: prodRules.rules.map((r, idx) => ({
index: idx + 1,
sourceRuleId: r.id,
sourceRuleCode: r.code ?? idx + 1,
expectedTargetCode: `rule-${idx + 1}`,
description: r.description,
scope: r.scope,
strictness: r.strictness
}))
},
documentsPlan: {
sourceDocumentCount: prodDocs.length,
targetExistingDocumentCount: testDocs.length,
toCreateCount: docsToCreate.length,
toCreate: docsToCreate.map((d) => ({
title: d.title,
purpose: d.purpose,
contentType: d.contentType,
scenarios: d.scenarios
})),
toUpdateCount: docsToUpdate.length,
toUpdate: docsToUpdate.map((d) => ({
targetDocumentId: d.testId,
title: d.prodDoc.title,
reasons: d.reasons
})),
toDeleteCount: docsToDelete.length,
toDelete: docsToDelete.map((d) => ({
targetDocumentId: d.id,
title: d.title
}))
},
publishingPlan: {
targetCorpId: testCorp.id,
publishVersionName: versionName,
publishTarget: "test"
},
productionGuarantees: {
prodRulesStayDraft: true,
prodVersionPublished: false
}
});
return;
}
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to overwrite test enterprise '${testCorp.name}' (${testCorp.id}) with preferences, ${prodRules.rules.length} draft rules, and ${prodDocs.length} knowledge documents from production enterprise '${prodCorp.name}' (${prodCorp.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,
`seal-use corps sync-test ${prodCorp.id} --yes`
);
}
// 1. Update style & decision preferences in test enterprise
await api.updateApprovalStylePreferences(testClient, updatedTestPref, testCorp.seal.endpoints.approvalStylePreferences);
// 2. Synchronize knowledge documents in test enterprise (full coverage, delete redundant test documents)
const deletedDocs: Array<{ id: string; title: string }> = [];
for (const doc of docsToDelete) {
await api.deleteApprovalDocument(testClient, doc.id);
deletedDocs.push({ id: doc.id, title: doc.title });
}
const updatedDocs: Array<{ id: string; title: string; reasons: string[] }> = [];
for (const item of docsToUpdate) {
await api.updateApprovalDocument(testClient, item.testId, {
title: item.prodDoc.title,
purpose: item.prodDoc.purpose,
content: item.prodDoc.content,
contentType: item.prodDoc.contentType,
status: item.prodDoc.status,
enabled: item.prodDoc.enabled,
scenarios: item.prodDoc.scenarios && item.prodDoc.scenarios.length > 0 ? item.prodDoc.scenarios : ["audit"],
tags: item.prodDoc.tags
});
updatedDocs.push({ id: item.testId, title: item.prodDoc.title, reasons: item.reasons });
}
const createdDocs: Array<{ id: string; title: string }> = [];
for (const doc of docsToCreate) {
const created = await api.createApprovalDocument(testClient, {
title: doc.title,
purpose: doc.purpose,
content: doc.content,
contentType: doc.contentType,
status: doc.status,
enabled: doc.enabled,
scenarios: doc.scenarios && doc.scenarios.length > 0 ? doc.scenarios : ["audit"],
tags: doc.tags
});
createdDocs.push({ id: created.id, title: created.title });
}
// 3. Clear old draft rules in test enterprise
for (const rule of testRules.rules) {
await api.deleteApprovalRule(testClient, rule.id);
}
// 4. Create new draft rules in test enterprise
const createdRules: any[] = [];
for (const rule of prodRules.rules) {
const created = await api.createApprovalRule(testClient, {
description: rule.description,
scope: rule.scope,
strictness: rule.strictness
});
createdRules.push(created);
}
// 5. Batch recode rules in test enterprise
await api.recodeApprovalRules(testClient).catch(() => undefined);
// 6. Publish new version in test enterprise
const published = await api.publishApprovalRuleVersion(testClient, versionName);
const publishedRules = published.version.rules ?? [];
const ruleMapping = prodRules.rules.map((prodRule, idx) => {
const testDraft = createdRules[idx];
const publishedRule = publishedRules[idx];
return {
index: idx + 1,
sourceRuleId: prodRule.id,
sourceRuleCode: prodRule.code ?? idx + 1,
targetRuleId: testDraft?.id ?? "",
targetRuleCode: publishedRule?.code ?? `rule-${idx + 1}`,
description: prodRule.description,
scope: prodRule.scope,
strictness: prodRule.strictness
};
});
const versionMapping = {
sourceProdVersionNumber: prodVersionNumber ?? null,
sourceProdVersionName: latestProd?.versionName ?? null,
targetTestVersionNumber: published.version.versionNumber,
targetTestVersionName: published.version.versionName ?? null
};
let mappingSavedTo: string | undefined;
try {
mappingSavedTo = saveRuleMappingSnapshot({
syncedAt: new Date().toISOString(),
source: {
id: prodCorp.id,
name: prodCorp.name,
latestPublishedVersionNumber: prodVersionNumber ?? null,
latestPublishedVersionName: latestProd?.versionName ?? null
},
target: {
id: testCorp.id,
name: testCorp.name,
publishedVersionNumber: published.version.versionNumber,
publishedVersionName: published.version.versionName,
rulesCount: published.rulesCount
},
versionMapping,
ruleMapping
});
} catch {}
printJson({
success: true,
syncedAt: new Date().toISOString(),
source: {
id: prodCorp.id,
name: prodCorp.name,
environment: prodCorp.environment,
latestPublishedVersion: latestProd ? {
versionNumber: latestProd.versionNumber,
versionName: latestProd.versionName
} : null,
draftRulesCount: prodRules.rules.length,
documentsCount: prodDocs.length
},
target: {
id: testCorp.id,
name: testCorp.name,
environment: testCorp.environment,
deletedDraftRulesCount: testRules.rules.length,
createdDraftRulesCount: createdRules.length,
publishedVersion: {
id: published.version.id,
versionNumber: published.version.versionNumber,
versionName: published.version.versionName,
rulesCount: published.rulesCount
}
},
documents: {
sourceCount: prodDocs.length,
targetExistingCount: testDocs.length,
createdCount: createdDocs.length,
created: createdDocs,
updatedCount: updatedDocs.length,
updated: updatedDocs,
deletedCount: deletedDocs.length,
deleted: deletedDocs
},
versionMapping,
ruleMapping,
...(mappingSavedTo ? { mappingSavedTo } : {}),
productionGuarantees: {
prodRulesStayDraft: true,
prodVersionPublished: false
}
});
return;
}
@@ -324,6 +878,7 @@ async function addHoseCorp(input: Record<string, unknown>) {
const config: CorpConfig = {
id,
name,
environment: "production",
seal: {
url: sealUrl,
endpoints: {
@@ -374,8 +929,20 @@ async function addSealCorp(input: Record<string, unknown>) {
const expiresIn = optionalNumber(input, "expiresIn") ?? 30 * 24 * 60 * 60;
const verify = input.force === true || input.verify === false ? false : true;
const remote = verify ? await resolveSealWhoami(sealUrl, token) : undefined;
writeSealCorpConfig(input, { token, sealUrl, expiresIn, verify, remote });
const custom = sealCustomHeadersFromInput(input);
const remote = verify
? await resolveSealWhoami(sealUrl, token, resolveSealCustomHeaders(custom))
: undefined;
writeSealCorpConfig(input, { token, sealUrl, expiresIn, verify, remote, custom });
}
// Validates extra headers/cookies up front so a malformed name fails here
// rather than on the next config load.
function sealCustomHeadersFromInput(input: Record<string, unknown>) {
return {
headers: SealHeaderMapSchema.parse(input.headers),
cookies: SealCookieMapSchema.parse(input.cookies)
};
}
async function addLinkCorp(link: string, name: string | undefined, overwrite: boolean) {
@@ -419,9 +986,11 @@ function writeSealCorpConfig(
expiresIn: number;
verify: boolean;
remote?: RemoteSealIdentity;
custom?: { headers?: Record<string, string>; cookies?: Record<string, string> };
}
) {
const { token, sealUrl, expiresIn, verify, remote } = auth;
const custom = auth.custom ?? sealCustomHeadersFromInput(input);
const remoteUser = remote?.user;
const remoteTenant = remote?.tenant;
const tenantSlug = optionalString(input, "tenantSlug") ?? stringValue(remoteTenant?.tenantSlug);
@@ -444,9 +1013,12 @@ function writeSealCorpConfig(
const config: CorpConfig = {
id,
name: optionalString(input, "name") ?? tenantName ?? id,
environment: "production",
seal: {
url: sealUrl,
tenantSlug,
headers: custom.headers,
cookies: custom.cookies,
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
@@ -522,8 +1094,9 @@ async function resolveHoseCorporation(domain: string, appKey: string, appSecurit
: undefined;
}
async function resolveSealWhoami(sealUrl: string, token: string) {
async function resolveSealWhoami(sealUrl: string, token: string, customHeaders: Record<string, string> = {}) {
const json = await getJson(`${sealUrl}/api/v1/auth/me`, {
...customHeaders,
authorization: `Bearer ${token}`
});
const data = objectValue(json.data);
+33
View File
@@ -0,0 +1,33 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleDataCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
const params = {
offset: numberOption(args.options.offset),
limit: numberOption(args.options.limit),
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
search: stringOption(args.options.search) ?? stringOption(args.options.query)
};
if (action === "expenses" || action === "expense") {
await runTool("seal_expenses_list", client, corp, params, outputOptions(args.options));
return;
}
if (action === "invoices" || action === "invoice") {
await runTool("seal_invoices_list", client, corp, params, outputOptions(args.options));
return;
}
throw new Error(`Unknown data command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+19 -3
View File
@@ -6,6 +6,7 @@ import { booleanOption, jsonObject, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import * as api from "../../domains/seal/api.js";
import { CliError } from "../errors.js";
export async function handleDeployCommand(
systemOrAction: string | undefined,
@@ -83,7 +84,13 @@ export async function handleDeployCommand(
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
console.error(` 👉 查看命令: seal-use deploy hosecloud get ${key} --corp ${corp.id}\n`);
}
throw new Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。");
throw new CliError(
"缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。",
2,
hoseConfigs.length === 1
? `seal-use deploy hosecloud get ${hoseConfigs[0]!.signKey} --corp ${corp.id}`
: undefined
);
}
await runTool("seal_deploy_hosecloud_get", client, corp, { signKey }, outputOptions(args.options));
return;
@@ -102,7 +109,10 @@ export async function handleDeployCommand(
if (!payload || Object.keys(payload).length === 0) {
throw new Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");
}
await runTool("seal_deploy_hosecloud_configure", client, corp, payload, outputOptions(args.options));
await runTool("seal_deploy_hosecloud_configure", client, corp, {
...payload,
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"])
}, outputOptions(args.options));
return;
}
@@ -143,7 +153,13 @@ export async function handleDeployCommand(
console.error(`💡 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${corp.id}\n`);
}
throw new Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。");
throw new CliError(
"缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",
2,
hoseConfigs.length === 1
? `seal-use deploy hosecloud sync ${hoseConfigs[0]!.signKey} --corp ${corp.id}`
: undefined
);
}
await runTool("seal_deploy_hosecloud_sync", client, corp, { signKey }, outputOptions(args.options));
+17 -5
View File
@@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { jsonObject, stringOption } from "../parser.js";
import { booleanOption, jsonObject, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
@@ -29,7 +29,10 @@ export async function handlePreferenceCommand(
if (!payload || Object.keys(payload).length === 0) {
throw new Error("Usage: seal-use preference decision update --json '{\"explicitApprove\":\"...\"}'");
}
await runTool("seal_preference_decision_update", client, corp, payload, outputOptions(args.options));
await runTool("seal_preference_decision_update", client, corp, {
...payload,
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"])
}, outputOptions(args.options));
return;
}
}
@@ -43,7 +46,10 @@ export async function handlePreferenceCommand(
if (defaultLevel !== "medium" && defaultLevel !== "high") {
throw new Error("Usage: seal-use preference thinking-depth set --default <medium|high>");
}
await runTool("seal_preference_thinking_depth_set", client, corp, { defaultLevel }, outputOptions(args.options));
await runTool("seal_preference_thinking_depth_set", client, corp, {
defaultLevel,
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"])
}, outputOptions(args.options));
return;
}
@@ -61,7 +67,10 @@ export async function handlePreferenceCommand(
if (!payload || !payload.id || !payload.name) {
throw new Error("Usage: seal-use preference thinking-depth policies upsert --json '{\"id\":\"...\",\"name\":\"...\",\"level\":\"high\"}'");
}
await runTool("seal_preference_thinking_depth_policies_upsert", client, corp, payload, outputOptions(args.options));
await runTool("seal_preference_thinking_depth_policies_upsert", client, corp, {
...payload,
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"])
}, outputOptions(args.options));
return;
}
@@ -70,7 +79,10 @@ export async function handlePreferenceCommand(
if (!policyId) {
throw new Error("Usage: seal-use preference thinking-depth policies remove <policyId>");
}
await runTool("seal_preference_thinking_depth_policies_remove", client, corp, { policyId }, outputOptions(args.options));
await runTool("seal_preference_thinking_depth_policies_remove", client, corp, {
policyId,
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"])
}, outputOptions(args.options));
return;
}
}
+35 -2
View File
@@ -1,6 +1,8 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { filterRuleMapping, loadRuleMappingSnapshot } from "../../domains/seal/rule-mapping.js";
import { runTool, runToolResult } from "../helpers.js";
import { confirmationRequired } from "../errors.js";
import {
booleanOption,
numberOption,
@@ -63,7 +65,10 @@ export async function handleRulesCommand(
const confirmed = booleanOption(args.options.yes) === true;
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed;
if (!confirmed && !dryRun) {
throw new Error("Refusing to clear rules without --yes. Use --dry-run to preview.");
throw confirmationRequired(
"Refusing to clear rules without --yes. Use --dry-run to preview.",
`seal-use rules clear --corp ${corp.id} --dry-run`
);
}
const result = await runToolResult("seal_approval_rules_clear", client, corp, {
dryRun,
@@ -210,5 +215,33 @@ export async function handleRulesCommand(
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, get, search, lint, pull, push. Run 'seal-use help' for available commands.`);
if (action === "map") {
const versionSelector = stringOption(args.options.version) ?? maybeName;
const code = stringOption(args.options.code) ?? stringOption(args.options.rule);
const snapshot = loadRuleMappingSnapshot(corp.id, versionSelector);
if (!snapshot) {
const vText = versionSelector ? `version '${versionSelector}'` : "latest version";
printJson({
error: `No local rule mapping found for enterprise '${corp.name}' (${corp.id}) ${vText}. Run 'seal-use corps sync-test <prodCorp> --yes' to synchronize and generate mapping snapshots.`,
corpId: corp.id,
version: versionSelector ?? "latest"
}, outputOptions(args.options));
return;
}
const filtered = filterRuleMapping(snapshot.ruleMapping, code);
printJson({
corpId: corp.id,
syncedAt: snapshot.syncedAt,
source: snapshot.source,
target: snapshot.target,
versionMapping: snapshot.versionMapping,
totalRules: snapshot.ruleMapping.length,
matchedRules: filtered.length,
rules: filtered
}, outputOptions(args.options));
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, get, search, lint, pull, push, map. Run 'seal-use help' for available commands.`);
}
+26
View File
@@ -62,6 +62,7 @@ export async function handleSimulationCommand(
stringOption(args.options.signKey) ??
stringOption(args.options["sign-key"]) ??
stringOption(args.options.integration);
const noWait = booleanOption(args.options.noWait) ?? booleanOption(args.options["no-wait"]);
await runTool(
"seal_simulation_batch_create",
@@ -91,6 +92,7 @@ export async function handleSimulationCommand(
endTime: numberOption(args.options.endTime) ?? numberOption(args.options["end-time"]),
status: splitOption(args.options.status),
limit: numberOption(args.options.limit),
noWait,
rawParams: inputPayload
},
outputOptions(args.options)
@@ -115,6 +117,19 @@ export async function handleSimulationCommand(
return;
}
if (action === "status") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation status <batchId>");
await runTool(
"seal_simulation_batch_status",
client,
corp,
{ batchId },
outputOptions(args.options)
);
return;
}
if (action === "clean" || action === "delete") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation clean <batchId>");
@@ -132,6 +147,17 @@ export async function handleSimulationCommand(
return;
}
if (action === "approval-definitions" || action === "definitions") {
await runTool(
"seal_simulation_feishu_approval_definitions_list",
client,
corp,
{},
outputOptions(args.options)
);
return;
}
if (action === "list") {
await runTool(
"seal_simulation_batches_list",
+15 -9
View File
@@ -3,7 +3,7 @@ import { dirname, join } from "node:path";
import { spawnSync } from "node:child_process";
import { isCompiledBinary } from "../../core/runtime.js";
import { syncGlobalSkillIfPresent } from "../../core/embedded-skill.js";
import { VERSION } from "../../version.js";
import { VERSION, IS_RELEASE } from "../../version.js";
import { runServiceCommand, serviceStatus } from "../service.js";
import { printJson } from "../printer.js";
import { STATE_DIR } from "./service.js";
@@ -46,14 +46,20 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
const cleanTarget = targetVersion.replace(/^v/, "");
const cmp = compareSemVer(cleanTarget, VERSION);
if (cmp < 0) {
printJson({
updated: false,
currentVersion: VERSION,
targetVersion: cleanTarget,
mode: isCompiledBinary() ? "binary" : "source",
message: `Cannot downgrade seal-use from v${VERSION} to older version v${cleanTarget}. Updates must be forward-only.`
});
return;
if (!IS_RELEASE && options.force) {
// Allow force reinstall/switch from dev build to target release
} else {
printJson({
updated: false,
currentVersion: VERSION,
targetVersion: cleanTarget,
mode: isCompiledBinary() ? "binary" : "source",
message: !IS_RELEASE
? `Cannot downgrade seal-use from dev build v${VERSION} to release v${cleanTarget}. Use --force to overwrite.`
: `Cannot downgrade seal-use from v${VERSION} to older version v${cleanTarget}. Updates must be forward-only.`
});
return;
}
}
if (cmp === 0 && !options.force) {
printJson({
+94 -15
View File
@@ -4,9 +4,16 @@ import { existsSync } from "node:fs";
import { runTool } from "../helpers.js";
import * as api from "../../domains/seal/api.js";
import { findWebhookIntegration } from "../../domains/seal/api.js";
import { previewMaterialPack, pushMaterialPack, readMaterialPackFile } from "../../domains/seal/material-pack/index.js";
import type { WebhookIntegration } from "../../domains/seal/types.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "../../domains/seal/material-pack/index.js";
import {
booleanOption,
materialPackFilePolicyOptions,
parseWebhookMode,
stringOption,
webhookRateOption,
@@ -14,11 +21,16 @@ import {
} from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js";
import { CliError, confirmationRequired, usageError } from "../errors.js";
export async function handleWebhookMaterialPackPreview(filePath: string) {
export async function handleWebhookMaterialPackPreview(
filePath: string,
filePolicy?: MaterialPackFilePolicyPatch
) {
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
const input = readMaterialPackFile(filePath);
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName), null, 2));
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName, filePolicy), null, 2));
}
export async function handleWebhookCommand(
@@ -28,6 +40,42 @@ export async function handleWebhookCommand(
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "ready" || action === "status") {
const filePath = maybeName ?? stringOption(args.options.file) ?? stringOption(args.options.input);
const result = await checkWebhookReadiness(client, corp, {
filePath,
webhook: stringOption(args.options.webhook) ?? stringOption(args.options.selector)
});
console.error(`[webhook-ready] 企业环境: ${result.corp.name} (${result.corp.id}) [${result.stateMode}]`);
if (result.corp.tenant?.name) {
console.error(`[webhook-ready] 租户信息: ${result.corp.tenant.name} (${result.corp.tenant.id})`);
}
console.error(`[webhook-ready] 凭证状态: ${result.authStatus === "ok" ? "OK" : `异常 (${result.authError})`}`);
console.error(`[webhook-ready] Webhook 通道: ${result.activeWebhooks.length} 个可用`);
for (const hook of result.activeWebhooks) {
const defLabel = hook.isDefault ? " [默认通道]" : "";
console.error(` - ${hook.name} (${hook.id}) mode=${hook.mode}${defLabel}`);
}
if (result.materialPack) {
console.error(
`[webhook-ready] 材料包预检: ${
result.materialPack.valid
? `通过 (${result.materialPack.documentCount} 单)`
: `失败 (${result.materialPack.errors?.join("; ")})`
}`
);
}
if (result.ready) {
console.error(`🟢 ${result.statusMessage}`);
console.error(`👉 Next action: ${result.nextAction}`);
} else {
console.error(`🔴 准备阶段未通过: ${result.statusMessage}`);
console.error(`👉 Next action: ${result.nextAction}`);
}
console.log(JSON.stringify(result, null, 2));
return;
}
if (action === "material-pack" || action === "material-pack-push") {
const operation = action === "material-pack-push" ? "push" : maybeName;
const filePath = action === "material-pack-push"
@@ -42,11 +90,27 @@ export async function handleWebhookCommand(
}
if (operation !== "push") throw new Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
if (!selector) throw new Error("Push requires --webhook <idOrName>");
const integration = findWebhookIntegration(await api.listWebhookIntegrations(client), selector);
const integrations = await api.listWebhookIntegrations(client, corp.seal.endpoints.approvalStylePreferences);
let integration: WebhookIntegration;
if (selector) {
integration = findWebhookIntegration(integrations, selector);
} else if (integrations.length === 1) {
integration = integrations[0]!;
console.error(`👉 自动锁定唯一可用 Webhook 通道: ${integration.name} (${integration.id})`);
} else if (integrations.length > 1) {
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
throw new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook <idOrName> 指定目标通道。`);
} else {
throw new CliError(
"当前租户未配置任何 Webhook 集成通道。",
1,
`seal-use webhook add --name <name> --result-url <url> --corp ${corp.id}`
);
}
const result = await pushMaterialPack(input.fileBuffer, input.fileName, {
webhookUrl: integration.incomingDocumentWebhook.url,
secret: integration.secret
secret: integration.secret,
materialPackFilePolicy: integration.materialPackFilePolicy
});
console.log(JSON.stringify(result, null, 2));
return;
@@ -92,6 +156,8 @@ export async function handleWebhookCommand(
throw new Error("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");
}
const autoApprovalRate = webhookRateOption(args.options);
const materialPackFilePolicy = materialPackFilePolicyOptions(args.options);
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
await runTool(
"seal_webhook_add",
client,
@@ -101,7 +167,9 @@ export async function handleWebhookCommand(
mode: parseWebhookMode(stringOption(args.options.mode)),
outgoingResultWebhook,
autoApprovalRate,
secret: stringOption(args.options.secret)
secret: stringOption(args.options.secret),
materialPackFilePolicy,
dryRun
},
outputOptions(args.options)
);
@@ -114,7 +182,7 @@ export async function handleWebhookCommand(
const secret = stringOption(args.options.secret);
const rotateSecret = booleanOption(args.options.rotateSecret) ?? booleanOption(args.options["rotate-secret"]);
if (secret !== undefined && rotateSecret) {
throw new Error("Use either --secret or --rotate-secret, not both");
throw usageError("Use either --secret or --rotate-secret, not both");
}
const name = stringOption(args.options.name);
const mode = parseWebhookMode(stringOption(args.options.mode));
@@ -124,15 +192,19 @@ export async function handleWebhookCommand(
stringOption(args.options.outgoingResultWebhook) ??
stringOption(args.options["outgoing-result-webhook"]);
const autoApprovalRate = webhookRateOption(args.options);
const materialPackFilePolicy = materialPackFilePolicyOptions(args.options);
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
if (
name === undefined &&
mode === undefined &&
outgoingResultWebhook === undefined &&
autoApprovalRate === undefined &&
secret === undefined &&
!rotateSecret
!rotateSecret &&
materialPackFilePolicy === undefined &&
!dryRun
) {
throw new Error("Webhook update requires at least one field option");
throw usageError("Webhook update requires at least one field option");
}
await runTool(
"seal_webhook_update",
@@ -145,7 +217,9 @@ export async function handleWebhookCommand(
outgoingResultWebhook,
autoApprovalRate,
secret,
rotateSecret
rotateSecret,
materialPackFilePolicy,
dryRun
},
outputOptions(args.options)
);
@@ -154,9 +228,13 @@ export async function handleWebhookCommand(
if (action === "delete") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
if (!selector) throw new Error("Usage: seal-use webhook delete <idOrName> --yes");
if (booleanOption(args.options.yes) !== true) {
throw new Error("Refusing to delete Webhook integration without --yes");
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
if (!selector) throw new Error("Usage: seal-use webhook delete <idOrName> [--yes|--dry-run]");
if (booleanOption(args.options.yes) !== true && !dryRun) {
throw confirmationRequired(
"Refusing to delete Webhook integration without --yes",
`seal-use webhook delete ${selector} --corp ${corp.id} --yes`
);
}
await runTool(
"seal_webhook_delete",
@@ -164,7 +242,8 @@ export async function handleWebhookCommand(
corp,
{
selector,
confirm: true
confirm: true,
dryRun
},
outputOptions(args.options)
);
+37
View File
@@ -0,0 +1,37 @@
import { describe, expect, test } from "bun:test";
import { CliError, classifyCliError, confirmationRequired, PayloadTooLargeError } from "./errors.js";
describe("CLI semantic errors", () => {
test("preserves explicit exit codes and next actions", () => {
const error = new CliError("missing sign key", 2, "seal-use deploy hosecloud get <sign-key>");
expect(classifyCliError(error)).toEqual({
exitCode: 2,
nextAction: "seal-use deploy hosecloud get <sign-key>"
});
});
test("classifies confirmation and output protection distinctly", () => {
expect(classifyCliError(confirmationRequired("Refusing to delete", "seal-use webhook delete <id> --yes"))).toMatchObject({
exitCode: 10,
nextAction: "seal-use webhook delete <id> --yes"
});
expect(classifyCliError(new PayloadTooLargeError("Output too large"))).toEqual({ exitCode: 12 });
});
test("classifies authentication failures from response status", () => {
expect(classifyCliError({ response: { status: 401 } })).toEqual({ exitCode: 11 });
expect(classifyCliError(new Error("bearer token expired"))).toEqual({ exitCode: 11 });
});
test("classifies unknown commands and subcommands across all domains as usage errors", () => {
expect(classifyCliError(new Error("Unknown command: not-a-command"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown contacts command: . Run 'seal-use help' for available commands."))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown data command: bad-subcommand"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown analytics command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown approval-runs command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown billing command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Unknown webhook command: invalid"))).toEqual({ exitCode: 2 });
expect(classifyCliError(new Error("Usage: seal-use contacts children <departmentId>"))).toEqual({ exitCode: 2 });
});
});
+58
View File
@@ -0,0 +1,58 @@
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
export class CliError extends Error {
readonly exitCode: CliExitCode;
readonly nextAction?: string;
constructor(message: string, exitCode: CliExitCode, nextAction?: string) {
super(message);
this.name = "CliError";
this.exitCode = exitCode;
this.nextAction = nextAction;
}
}
export class PayloadTooLargeError extends CliError {
constructor(message: string, nextAction?: string) {
super(message, 12, nextAction);
this.name = "PayloadTooLargeError";
}
}
export function usageError(message: string, nextAction?: string): CliError {
return new CliError(message, 2, nextAction);
}
export function confirmationRequired(message: string, nextAction: string): CliError {
return new CliError(message, 10, nextAction);
}
export function classifyCliError(error: unknown): {
exitCode: CliExitCode;
nextAction?: string;
} {
if (error instanceof CliError) {
return { exitCode: error.exitCode, nextAction: error.nextAction };
}
const value = error instanceof Error ? error.message : String(error);
const status = responseStatus(error);
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
return { exitCode: 11 };
}
if (/^(?:Usage:|Unknown (?:[a-z0-9_-]+ )?command|Invalid (?:number|boolean|command)|--json must|Missing required JSON field)/i.test(value)) {
return { exitCode: 2 };
}
if (/^Refusing to (?:clear|delete)|without --yes|without confirm=true/i.test(value)) {
return { exitCode: 10 };
}
return { exitCode: 1 };
}
function responseStatus(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const response = (error as { response?: unknown }).response;
if (!response || typeof response !== "object") return undefined;
const status = (response as { status?: unknown }).status;
return typeof status === "number" ? status : undefined;
}
+128
View File
@@ -0,0 +1,128 @@
import { describe, expect, test } from "bun:test";
import { extractHelpRequest, renderHelp } from "./help.js";
import { runCli } from "./runner.js";
describe("extractHelpRequest", () => {
test("detects global help from empty command or help option", () => {
expect(extractHelpRequest({ command: [], options: {} })).toEqual({ isHelp: true, target: [] });
expect(extractHelpRequest({ command: ["help"], options: {} })).toEqual({ isHelp: true, target: [] });
expect(extractHelpRequest({ command: [], options: { help: true } })).toEqual({ isHelp: true, target: [] });
expect(extractHelpRequest({ command: [], options: { h: true } })).toEqual({ isHelp: true, target: [] });
});
test("detects area help across various syntax styles", () => {
expect(extractHelpRequest({ command: ["corps"], options: { help: true } })).toEqual({
isHelp: true,
target: ["corps"]
});
expect(extractHelpRequest({ command: ["corps"], options: { h: true } })).toEqual({
isHelp: true,
target: ["corps"]
});
expect(extractHelpRequest({ command: ["corps", "help"], options: {} })).toEqual({
isHelp: true,
target: ["corps"]
});
expect(extractHelpRequest({ command: ["help", "corps"], options: {} })).toEqual({
isHelp: true,
target: ["corps"]
});
});
test("detects subcommand help across various syntax styles", () => {
expect(extractHelpRequest({ command: ["corps", "bind-test"], options: { help: true } })).toEqual({
isHelp: true,
target: ["corps", "bind-test"]
});
expect(extractHelpRequest({ command: ["corps", "bind-test"], options: { h: true } })).toEqual({
isHelp: true,
target: ["corps", "bind-test"]
});
expect(extractHelpRequest({ command: ["corps", "help", "bind-test"], options: {} })).toEqual({
isHelp: true,
target: ["corps", "bind-test"]
});
expect(extractHelpRequest({ command: ["help", "corps", "bind-test"], options: {} })).toEqual({
isHelp: true,
target: ["corps", "bind-test"]
});
});
test("returns isHelp: false for normal executions", () => {
expect(extractHelpRequest({ command: ["corps", "list"], options: {} })).toEqual({
isHelp: false,
target: []
});
expect(extractHelpRequest({ command: ["corps", "bind-test", "prod", "test"], options: { confirm: true } })).toEqual({
isHelp: false,
target: []
});
});
});
describe("renderHelp", () => {
test("renders global help when target is empty", () => {
const help = renderHelp([]);
expect(help).toContain("seal-use CLI");
expect(help).toContain("seal-use corps list");
expect(help).toContain("seal-use webhook add");
});
test("renders focused area help without polluting with other domains", () => {
const help = renderHelp(["corps"]);
expect(help).toContain("seal-use corps - Enterprise and tenant management");
expect(help).toContain("seal-use corps bind-test");
expect(help).toContain("seal-use corps sync-test");
expect(help).not.toContain("seal-use webhook");
expect(help).not.toContain("seal-use simulation");
expect(help).not.toContain("seal-use billing");
});
test("renders focused subcommand help with usage, options, and description", () => {
const help = renderHelp(["corps", "bind-test"]);
expect(help).toContain("seal-use corps bind-test");
expect(help).toContain("--confirm");
expect(help).toContain("--force");
expect(help).toContain("1-to-1 association");
expect(help).not.toContain("seal-use corps list");
expect(help).not.toContain("seal-use webhook");
});
test("throws usage error for unknown area or subcommand", () => {
expect(() => renderHelp(["nonexistent-domain"])).toThrow(/Unknown command/);
expect(() => renderHelp(["corps", "nonexistent-cmd"])).toThrow(/Unknown corps command/);
});
});
describe("CLI help execution via runCli", () => {
test("seal-use corps bind-test --help prints only bind-test help with exitCode 0", async () => {
const result = await runCli(["corps", "bind-test", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("seal-use corps bind-test");
expect(result.stdout).toContain("--confirm");
expect(result.stdout).toContain("--force");
expect(result.stdout).not.toContain("seal-use webhook");
expect(result.stdout).not.toContain("seal-use simulation");
expect(result.stdout).not.toContain("seal-use billing");
expect(result.stdout).not.toContain("seal-use preference");
});
test("seal-use corps --help prints only corps domain commands with exitCode 0", async () => {
const result = await runCli(["corps", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("seal-use corps - Enterprise and tenant management");
expect(result.stdout).toContain("seal-use corps list");
expect(result.stdout).toContain("seal-use corps bind-test");
expect(result.stdout).not.toContain("seal-use webhook");
expect(result.stdout).not.toContain("seal-use simulation");
});
test("seal-use corps unknown-cmd --help exits with code 2", async () => {
const result = await runCli(["corps", "unknown-cmd", "--help"]);
expect(result.exitCode).toBe(2);
expect(result.isError).toBe(true);
expect(result.stderr).toContain("Unknown corps command: unknown-cmd");
});
});
+1076
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -27,6 +27,9 @@ export function globalConfigSummary(config: GlobalConfig = loadGlobalConfig()) {
...(config.stateful && config.defaultCorpId
? { defaultCorpId: config.defaultCorpId }
: {}),
...(config.testEnterprisesDir
? { testEnterprisesDir: config.testEnterprisesDir }
: {}),
lint: config.lint,
configFile: resolveGlobalConfigFile()
};
+43 -5
View File
@@ -1,5 +1,7 @@
import type { WebhookMode } from "../domains/seal/types.js";
import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js";
import type { ParsedArgs } from "./types.js";
import { usageError } from "./errors.js";
export function parseArgs(argv: string[]): ParsedArgs {
const command: string[] = [];
@@ -12,8 +14,12 @@ export function parseArgs(argv: string[]): ParsedArgs {
if (arg === "--json") {
const raw = argv[index + 1];
if (!raw) throw new Error("--json requires a JSON object argument");
json = JSON.parse(raw);
if (!raw) throw usageError("--json requires a JSON object argument");
try {
json = JSON.parse(raw);
} catch (error) {
throw usageError(`Invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
}
index += 1;
continue;
}
@@ -46,7 +52,7 @@ export function parseArgs(argv: string[]): ParsedArgs {
export function jsonObject(value: unknown): Record<string, unknown> {
if (value === undefined) return {};
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error("--json must be an object");
throw usageError("--json must be an object");
}
return value as Record<string, unknown>;
}
@@ -58,7 +64,7 @@ export function stringOption(value: string | boolean | undefined): string | unde
export function numberOption(value: string | boolean | undefined): number | undefined {
if (typeof value !== "string") return undefined;
const number = Number(value);
if (!Number.isFinite(number)) throw new Error(`Invalid number: ${value}`);
if (!Number.isFinite(number)) throw usageError(`Invalid number: ${value}`);
return number;
}
@@ -73,7 +79,7 @@ export function booleanOption(value: string | boolean | undefined): boolean | un
if (typeof value === "boolean") return value;
if (value === "true") return true;
if (value === "false") return false;
throw new Error(`Invalid boolean: ${value}`);
throw usageError(`Invalid boolean: ${value}`);
}
export function requiredString(input: Record<string, unknown>, key: string): string {
@@ -201,3 +207,35 @@ export function webhookRateOption(options: Record<string, string | boolean>): nu
export function webhookShowSecretOption(options: Record<string, string | boolean>): boolean | undefined {
return booleanOption(options.showSecret) ?? booleanOption(options["show-secret"]);
}
export function materialPackFilePolicyOptions(
options: Record<string, string | boolean>
): MaterialPackFilePolicyPatch | undefined {
const clearMaxFileSize = booleanOption(
options.clearMaxFileSize ?? options["clear-max-file-size"]
) === true;
const minFileSizeBytes = numberOption(
options.minFileSizeBytes ?? options["min-file-size-bytes"] ?? options.minFileSize ?? options["min-file-size"]
);
const maxFileSizeBytes = numberOption(
options.maxFileSizeBytes ?? options["max-file-size-bytes"] ?? options.maxFileSize ?? options["max-file-size"]
);
const allowedExtensions = splitOption(
options.allowedExtensions ?? options["allowed-extensions"] ?? options.extensions
);
if (
minFileSizeBytes === undefined &&
maxFileSizeBytes === undefined &&
allowedExtensions === undefined &&
!clearMaxFileSize
) {
return undefined;
}
return {
minFileSizeBytes,
maxFileSizeBytes: clearMaxFileSize ? null : maxFileSizeBytes,
allowedExtensions
};
}
+13 -111
View File
@@ -1,11 +1,12 @@
import { writeFileSync } from "node:fs";
import { booleanOption, stringOption } from "./parser.js";
import { PayloadTooLargeError } from "./errors.js";
import type { OutputOptions } from "./types.js";
export const RULE_LIST_FULL_COUNT_LIMIT = 100;
export const RULE_LIST_FULL_BYTES_LIMIT = 120_000;
const RULE_LIST_FULL_COUNT_LIMIT = 100;
const RULE_LIST_FULL_BYTES_LIMIT = 120_000;
export const RULE_SUMMARY_FIELDS = ["id", "code", "status", "strictness", "scope", "createdAt", "updatedAt"];
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
export function formatConsoleOutput(values: unknown[]): string {
return values.map((value) => (typeof value === "string" ? value : String(value))).join(" ");
@@ -33,11 +34,11 @@ export function printJson(value: unknown, options: OutputOptions = {}) {
console.log(json.trimEnd());
}
export function protectLargeOutput(result: unknown, options: OutputOptions = {}) {
function protectLargeOutput(result: unknown, options: OutputOptions = {}) {
if (options.allowFull || options.outputFile) return;
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) {
throw new Error(
throw new PayloadTooLargeError(
`Output is large (${bodyBytes} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`
);
}
@@ -56,8 +57,9 @@ export function protectLargeRuleListOutput(result: unknown, allowFull: boolean)
const effectiveCount = count ?? rulesCount ?? 0;
if (effectiveCount > RULE_LIST_FULL_COUNT_LIMIT || bodyBytes > RULE_LIST_FULL_BYTES_LIMIT) {
throw new Error(
`Rule list is large (${effectiveCount} rules, ${bodyBytes} bytes). Use "seal-use rules list --summary" or "seal-use rules count"; pass --full only when you really need full descriptions.`
throw new PayloadTooLargeError(
`Rule list is large (${effectiveCount} rules, ${bodyBytes} bytes). Use "seal-use rules list --summary" or "seal-use rules count"; pass --full only when you really need full descriptions.`,
"seal-use rules list --summary"
);
}
}
@@ -69,109 +71,9 @@ export function outputOptions(options: Record<string, string | boolean>): Output
};
}
export function printHelp() {
console.log(`seal-use CLI
import { renderHelp } from "./help.js";
Usage:
seal-use version
seal-use mcp
seal-use mcp config
seal-use mcp-config
seal-use skill dump
seal-use skill install [--dir <path>|--local]
seal-use skill status
seal-use http [--port 8787] [--host 127.0.0.1]
seal-use serve [--port 8787]
seal-use openapi
seal-use probe [<corpId>]
seal-use config paths
seal-use config get
seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use update [--check] [--force] [--version <v>]
seal-use update check
seal-use update changelog [--limit <n>]
seal-use changelog [--limit <n>]
seal-use tools list
seal-use corps list [--corp <corpId>]
seal-use corps current [--corp <corpId>]
seal-use corps switch <corpId>
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]
seal-use auth diagnose [--corp <corpId>]
seal-use auth hose-link [--corp <corpId>] [--expire 7200]
seal-use delegation list [--corp <corpId>]
seal-use delegation create [--note <note>] [--from-link <url>] [--corp <corpId>]
seal-use delegation revoke <tokenId> [--corp <corpId>]
seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
seal-use users search <keyword> [--corp <corpId>]
seal-use users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]
seal-use users reset-password <userId> [--corp <corpId>]
seal-use users get <userId> [--corp <corpId>]
seal-use users delete <userId> [--corp <corpId>]
seal-use llm config [--corp <corpId>]
seal-use llm providers [--corp <corpId>]
seal-use permissions available [--corp <corpId>]
seal-use permissions configs [--corp <corpId>]
seal-use billing status [--corp <corpId>]
seal-use billing plans [--corp <corpId>]
seal-use billing features [--corp <corpId>]
seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]
seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]
seal-use webhook delete <idOrName> --yes [--corp <corpId>]
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--corp <corpId>]
seal-use webhook material-pack push <材料包.zip|信息表.xlsx> --webhook <idOrName> [--corp <corpId>]
seal-use deploy hosecloud requirements [--corp <corpId>]
seal-use deploy hosecloud list [--corp <corpId>]
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
seal-use deploy hosecloud status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]
seal-use deploy hosecloud sync <sign-key> [--corp <corpId>]
seal-use preference get [--corp <corpId>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--corp <corpId>]
seal-use preference thinking-depth policies list [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--corp <corpId>]
seal-use source config [--corp <corpId>]
seal-use tool <toolName> [--corp <corpId>] [--json '{"key":"value"}']
seal-use rules count [--corp <corpId>]
seal-use rules list [--summary] [--count] [--limit 20] [--offset 0] [--corp <corpId>]
seal-use rules clear [--corp <corpId>] [--dry-run|--yes]
seal-use rules versions [--corp <corpId>]
seal-use rules version <versionId|versionNumber|latest> [--corp <corpId>]
seal-use rules get --corp <corpId> --version <number|latest> --code '#0038'
seal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205
seal-use rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20] [--corp <corpId>]
seal-use context [--ruleVersion <versionId|versionNumber|latest>] [--documentLimit 50] [--corp <corpId>]
seal-use approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] [--corp <corpId>]
seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] [--corp <corpId>]
seal-use approval-runs count [--status APPROVED] [--corp <corpId>]
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]
seal-use approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]
seal-use approval-runs cited-rules <recordId> [--corp <corpId>]
seal-use approval-runs document-summary <recordId> [--corp <corpId>]
seal-use approval-runs attachments <recordId> [--summary] [--corp <corpId>]
seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] [--corp <corpId>]
seal-use approval-runs result <recordId> [--summary] [--corp <corpId>]
seal-use approval-runs url [--corp <corpId>]
seal-use approval-runs url <recordId> [--corp <corpId>]
seal-use approval-runs url --sourceDocumentSN B26022501 [--corp <corpId>]
seal-use approval-runs bridge [--sourceDocumentSN B26001887] [--corp <corpId>]
seal-use simulation batch-records <batchId> [--corp <corpId>]
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--corp <corpId>]
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" [--corp <corpId>]
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] [--corp <corpId>]
seal-use simulation clean <batchId> [--corp <corpId>]
seal-use simulation specifications [--integration <sign-key>] [--corp <corpId>]
seal-use simulation list [--limit 50] [--corp <corpId>]
seal-use simulation get <batchId> [--corp <corpId>]
seal-use simulation templates [--corp <corpId>]
seal-use simulation integrations [--corp <corpId>]
seal-use simulation package-upload <材料包.zip> [--corp <corpId>]
`);
export function printHelp(target: string[] = []) {
console.log(renderHelp(target));
}
+46 -1
View File
@@ -1,3 +1,6 @@
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, test } from "bun:test";
import { runCli } from "./runner.js";
@@ -17,7 +20,49 @@ describe("CLI runner", () => {
const result = await runCli(["not-a-command"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(1);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("Unknown command: not-a-command");
});
test("returns a semantic usage exit code for invalid JSON", async () => {
const result = await runCli(["version", "--json", "not-json"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("Invalid JSON:");
});
test("returns usage exit code 2 for unknown subcommands across standalone domains", async () => {
const result = await runCli(["skill", "not-a-subcommand"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("Unknown skill command: not-a-subcommand");
});
test("returns usage exit code 2 for unknown subcommands with an active enterprise", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "seal-use-runner-test-"));
const originalEnv = process.env.SEAL_USE_ENTERPRISES_DIR;
try {
process.env.SEAL_USE_ENTERPRISES_DIR = tempDir;
writeFileSync(
join(tempDir, "test.json"),
JSON.stringify({
id: "test",
name: "Test Corp",
source: { type: "seal", token: "dummy-token", sealUrl: "https://test.sealai.cc" },
seal: { url: "https://test.sealai.cc" }
})
);
const result = await runCli(["contacts", "not-a-subcommand", "--corp", "test"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("Unknown contacts command: not-a-subcommand");
} finally {
if (originalEnv === undefined) delete process.env.SEAL_USE_ENTERPRISES_DIR;
else process.env.SEAL_USE_ENTERPRISES_DIR = originalEnv;
rmSync(tempDir, { recursive: true, force: true });
}
});
});
+44 -12
View File
@@ -4,11 +4,14 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { createSealClient } from "../core/http/factory.js";
import type { CorpConfig } from "../core/config/types.js";
import { VERSION } from "../version.js";
import { VERSION, VERSION_INFO } from "../version.js";
import { handleApprovalRunsCommand } from "./commands/approval-runs.js";
import { handleAnalyticsCommand } from "./commands/analytics.js";
import { handleAuthCommand } from "./commands/auth.js";
import { handleBillingCommand } from "./commands/billing.js";
import { handleConfigCommand } from "./commands/config.js";
import { handleContactsCommand } from "./commands/contacts.js";
import { handleDataCommand } from "./commands/data.js";
import { handleContextCommand } from "./commands/context.js";
import { handleCorpsCommand } from "./commands/corps.js";
import { handleDelegationCommand, handleDelegationFromHoseLink } from "./commands/delegation.js";
@@ -30,8 +33,16 @@ import { handleToolsListCommand } from "./commands/tools.js";
import { handleUpdateCommand } from "./commands/update.js";
import { handleUsersCommand } from "./commands/users.js";
import { handleWebhookCommand, handleWebhookMaterialPackPreview } from "./commands/webhook.js";
import { classifyCliError } from "./errors.js";
import { selectCorp } from "./helpers.js";
import { booleanOption, numberOption, parseArgs, stringOption } from "./parser.js";
import {
booleanOption,
materialPackFilePolicyOptions,
numberOption,
parseArgs,
stringOption
} from "./parser.js";
import { extractHelpRequest } from "./help.js";
import {
formatConsoleOutput,
joinOutput,
@@ -56,6 +67,8 @@ const KNOWN_AREAS = new Set([
"auth",
"delegation",
"users",
"contacts",
"data",
"llm",
"permissions",
"billing",
@@ -64,6 +77,7 @@ const KNOWN_AREAS = new Set([
"context",
"rules",
"approval-runs",
"analytics",
"simulation",
"deploy",
"preference",
@@ -131,12 +145,17 @@ async function runCliOnce(argv: string[], options: CliRunOptions): Promise<CliRe
exitCode: 0
};
} catch (error) {
stderr.push(redactSensitiveText(error instanceof Error ? error.message : String(error)));
const message = redactSensitiveText(error instanceof Error ? error.message : String(error));
const classification = classifyCliError(error);
stderr.push(message);
if (classification.nextAction && !message.includes("Next action:")) {
stderr.push(`👉 Next action: ${classification.nextAction}`);
}
return {
stdout: joinOutput(stdout),
stderr: joinOutput(stderr),
isError: true,
exitCode: 1
exitCode: classification.exitCode
};
} finally {
console.log = originalLog;
@@ -155,26 +174,24 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
Boolean(args.options.v) ||
Boolean(args.options.V)
) {
printJson({
name: "seal-use",
version: VERSION
});
printJson(VERSION_INFO);
return;
}
if (!area || area === "help" || args.options.help) {
printHelp();
const helpRequest = extractHelpRequest(args);
if (helpRequest.isHelp) {
printHelp(helpRequest.target);
return;
}
if (!KNOWN_AREAS.has(area)) {
if (!area || !KNOWN_AREAS.has(area)) {
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
}
if (area === "webhook" && action === "material-pack" && maybeName === "preview") {
const filePath = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw new Error("Usage: seal-use webhook material-pack preview <材料包.zip>");
await handleWebhookMaterialPackPreview(filePath);
await handleWebhookMaterialPackPreview(filePath, materialPackFilePolicyOptions(args.options));
return;
}
@@ -308,6 +325,16 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "contacts") {
await handleContactsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "data") {
await handleDataCommand(action, client, corp, args);
return;
}
if (area === "llm") {
await handleLlmCommand(action, client, corp, args);
return;
@@ -343,6 +370,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "analytics") {
await handleAnalyticsCommand(action, client, corp, args);
return;
}
if (area === "simulation") {
await handleSimulationCommand(action, maybeName, client, corp, args);
return;
+2
View File
@@ -7,6 +7,7 @@ describe("getDirectSealSession", () => {
const corp: CorpConfig = {
id: "corp-direct-1",
name: "Direct Corp",
environment: "production",
seal: {
url: "https://seal.example.com",
tenantSlug: "direct-slug",
@@ -48,6 +49,7 @@ describe("getDirectSealSession", () => {
const corp: CorpConfig = {
id: "corp-native-1",
name: "Native Seal Corp",
environment: "production",
seal: {
url: "https://tenant.sealai.cc",
tenantSlug: "tenant-slug",
+3
View File
@@ -59,6 +59,7 @@ describe("hose auth helpers", () => {
const corpWithSealUrl: CorpConfig = {
id: "corp-1",
name: "Corp 1",
environment: "production",
seal: { url: "https://custom.sealai.cc", endpoints: { approvalStylePreferences: "" } },
source,
auth: { refreshTtl: 300 }
@@ -68,6 +69,7 @@ describe("hose auth helpers", () => {
const corpWithoutSealUrl: CorpConfig = {
id: "corp-1",
name: "Corp 1",
environment: "production",
seal: { endpoints: { approvalStylePreferences: "" } },
source,
auth: { refreshTtl: 300 }
@@ -91,6 +93,7 @@ describe("hose auth helpers", () => {
const corp: CorpConfig = {
id: "corp-cached",
name: "Corp Cached",
environment: "production",
seal: { endpoints: { approvalStylePreferences: "" } },
source: {
type: "hose",
-4
View File
@@ -39,10 +39,6 @@ export async function getSealSessionForCorp(corp: CorpConfig): Promise<SealSessi
return next;
}
export async function getSealToken(corp: CorpConfig): Promise<string> {
return (await getSealSessionForCorp(corp)).token;
}
export async function resolveSealEnterpriseConfig(
corp: CorpConfig
): Promise<SealEnterpriseConfig> {
+92 -11
View File
@@ -1,13 +1,16 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
findCorpConfigFile,
loadCorpConfigs,
loadGlobalConfig,
resolveEnterprisesDir,
resolveGlobalConfigFile,
saveGlobalConfig
saveGlobalConfig,
syncLegacyEnterprisesDir,
updateCorpConfig
} from "./loader.js";
const ORIGINAL_USE_ENV = process.env.SEAL_USE_ENTERPRISES_DIR;
@@ -84,21 +87,34 @@ describe("loadCorpConfigs", () => {
expect(loadCorpConfigs()).toEqual([]);
});
test("merges local and user enterprise directories with user configs taking precedence", () => {
test("does not load current directory enterprises by default, only reading user directory", () => {
const workspace = makeTempDir();
const workspaceEnterprises = join(workspace, "enterprises");
const userDir = makeTempDir();
mkdirSync(workspaceEnterprises, { recursive: true });
writeCorpConfig(join(workspaceEnterprises, "shared.json"), "shared", "Workspace");
writeCorpConfig(join(userDir, "shared.json"), "shared", "User");
writeCorpConfig(join(workspaceEnterprises, "cwd-only.json"), "cwd-only", "CWD Enterprise");
writeCorpConfig(join(userDir, "user-only.json"), "user-only", "User Only");
process.chdir(workspace);
process.env.SEAL_USE_USER_ENTERPRISES_DIR = userDir;
expect(loadCorpConfigs().map((corp) => [corp.id, corp.name])).toEqual([
["shared", "User"],
["user-only", "User Only"]
]);
// cwd enterprises/ should NOT be loaded by default
expect(loadCorpConfigs().map((corp) => corp.id)).toEqual(["user-only"]);
});
test("loads testEnterprisesDir from global config when specified", () => {
const testDir = makeTempDir();
const userDir = makeTempDir();
writeCorpConfig(join(testDir, "test-corp.json"), "test-corp", "Test Corp");
writeCorpConfig(join(userDir, "user-corp.json"), "user-corp", "User Corp");
const configFile = join(makeTempDir(), "config.json");
process.env.SEAL_USE_CONFIG_FILE = configFile;
process.env.SEAL_USE_USER_ENTERPRISES_DIR = userDir;
saveGlobalConfig({ testEnterprisesDir: testDir });
const corps = loadCorpConfigs();
expect(corps.map((corp) => corp.id).sort()).toEqual(["test-corp", "user-corp"].sort());
});
test("defaults global config to stateless", () => {
@@ -114,13 +130,14 @@ describe("loadCorpConfigs", () => {
});
});
test("saves and loads the global state mode", () => {
test("saves and loads the global state mode and testEnterprisesDir", () => {
const file = join(makeTempDir(), "nested", "config.json");
process.env.SEAL_USE_CONFIG_FILE = file;
expect(saveGlobalConfig({ stateful: true, defaultCorpId: "corp-a" })).toEqual({
expect(saveGlobalConfig({ stateful: true, defaultCorpId: "corp-a", testEnterprisesDir: "/tmp/test-corps" })).toEqual({
stateful: true,
defaultCorpId: "corp-a",
testEnterprisesDir: "/tmp/test-corps",
lint: {
enabled: false,
activeLinter: "builtin",
@@ -131,6 +148,7 @@ describe("loadCorpConfigs", () => {
expect(loadGlobalConfig()).toEqual({
stateful: true,
defaultCorpId: "corp-a",
testEnterprisesDir: "/tmp/test-corps",
lint: {
enabled: false,
activeLinter: "builtin",
@@ -138,6 +156,69 @@ describe("loadCorpConfigs", () => {
}
});
});
test("finds and updates an enterprise config file in-place", () => {
const dir = makeTempDir();
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
writeCorpConfig(join(dir, "alpha.json"), "alpha", "Alpha Corp");
expect(findCorpConfigFile("alpha")).toBe(join(dir, "alpha.json"));
expect(findCorpConfigFile("nonexistent")).toBeUndefined();
const updated = updateCorpConfig("alpha", {
environment: "production",
testCorpId: "alpha-test"
});
expect(updated.id).toBe("alpha");
expect(updated.environment).toBe("production");
expect(updated.testCorpId).toBe("alpha-test");
// Check on-disk persistence
const reloaded = loadCorpConfigs().find((c) => c.id === "alpha");
expect(reloaded?.testCorpId).toBe("alpha-test");
// Unsetting / clearing testCorpId
const cleared = updateCorpConfig("alpha", {
testCorpId: undefined
});
expect(cleared.testCorpId).toBeUndefined();
const reloadedAfterClear = loadCorpConfigs().find((c) => c.id === "alpha");
expect(reloadedAfterClear?.testCorpId).toBeUndefined();
});
});
describe("syncLegacyEnterprisesDir", () => {
test("migrates files from legacy to primary and deletes legacy when > 7 days old", () => {
const primary = makeTempDir();
const legacy = makeTempDir();
writeCorpConfig(join(legacy, "old-corp.json"), "old-corp", "Old Corp");
const tenDaysAgo = (Date.now() - 10 * 24 * 60 * 60 * 1000) / 1000;
utimesSync(join(legacy, "old-corp.json"), tenDaysAgo, tenDaysAgo);
utimesSync(legacy, tenDaysAgo, tenDaysAgo);
const result = syncLegacyEnterprisesDir(primary, legacy);
expect(result.copied).toEqual(["old-corp.json"]);
expect(result.deletedLegacyDir).toBe(true);
expect(existsSync(join(primary, "old-corp.json"))).toBe(true);
expect(existsSync(legacy)).toBe(false);
});
test("preserves legacy directory when modified within 7 days", () => {
const primary = makeTempDir();
const legacy = makeTempDir();
writeCorpConfig(join(legacy, "recent-corp.json"), "recent-corp", "Recent Corp");
const result = syncLegacyEnterprisesDir(primary, legacy);
expect(result.copied).toEqual(["recent-corp.json"]);
expect(result.deletedLegacyDir).toBe(false);
expect(existsSync(join(primary, "recent-corp.json"))).toBe(true);
expect(existsSync(legacy)).toBe(true);
});
});
function makeTempDir(): string {
+130 -17
View File
@@ -1,9 +1,8 @@
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigInput, GlobalConfigSchema } from "./types.js";
const ENTERPRISES_DIR = "enterprises";
const CONFIG_ENV = "SEAL_USE_ENTERPRISES_DIR";
const LEGACY_CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR";
const USER_DIR_ENV = "SEAL_USE_USER_ENTERPRISES_DIR";
@@ -13,11 +12,79 @@ const LEGACY_GLOBAL_CONFIG_ENV = "SEAL_HOME_CONFIG_FILE";
export const PRIMARY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "seal-use", "enterprises");
export const LEGACY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "seal-home", "enterprises");
export const USER_ENTERPRISES_DIR = PRIMARY_USER_ENTERPRISES_DIR;
const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "seal-use", "config.json");
const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "seal-home", "config.json");
export function syncLegacyEnterprisesDir(
primaryDir: string = PRIMARY_USER_ENTERPRISES_DIR,
legacyDir: string = LEGACY_USER_ENTERPRISES_DIR
): { copied: string[]; deletedLegacyDir: boolean } {
if (!existsSync(legacyDir)) {
return { copied: [], deletedLegacyDir: false };
}
mkdirSync(primaryDir, { recursive: true, mode: 0o700 });
const copied: string[] = [];
let legacyFiles: string[] = [];
try {
legacyFiles = readdirSync(legacyDir).filter((file) => file.endsWith(".json"));
} catch {
return { copied: [], deletedLegacyDir: false };
}
for (const file of legacyFiles) {
const legacyPath = join(legacyDir, file);
const primaryPath = join(primaryDir, file);
if (!existsSync(primaryPath)) {
copyFileSync(legacyPath, primaryPath);
copied.push(file);
} else {
const legacyMtime = statSync(legacyPath).mtimeMs;
const primaryMtime = statSync(primaryPath).mtimeMs;
if (legacyMtime > primaryMtime) {
copyFileSync(legacyPath, primaryPath);
copied.push(file);
}
}
}
const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000;
const now = Date.now();
let hasNewerFileInLegacy = false;
let hasRecentlyModifiedFile = false;
for (const file of readdirSync(legacyDir)) {
const legacyPath = join(legacyDir, file);
const primaryPath = join(primaryDir, file);
const stat = statSync(legacyPath);
if (now - stat.mtimeMs < SEVEN_DAYS_MS) {
hasRecentlyModifiedFile = true;
}
if (file.endsWith(".json") && existsSync(primaryPath)) {
if (stat.mtimeMs > statSync(primaryPath).mtimeMs) {
hasNewerFileInLegacy = true;
}
}
}
const dirStat = statSync(legacyDir);
const dirRecentlyModified = now - dirStat.mtimeMs < SEVEN_DAYS_MS;
let deletedLegacyDir = false;
if (!hasNewerFileInLegacy && !hasRecentlyModifiedFile && !dirRecentlyModified) {
rmSync(legacyDir, { recursive: true, force: true });
deletedLegacyDir = true;
}
return { copied, deletedLegacyDir };
}
export function loadCorpConfigs(): CorpConfig[] {
const dirs = resolveEnterprisesDirs();
const byId = new Map<string, CorpConfig>();
@@ -39,18 +106,31 @@ export function resolveEnterprisesDir(): string | undefined {
return resolveEnterprisesDirs()[0];
}
export function resolveEnterprisesDirs(): string[] {
function resolveEnterprisesDirs(): string[] {
const configured = (process.env[CONFIG_ENV] ?? process.env[LEGACY_CONFIG_ENV])?.trim();
if (configured) return existsSync(configured) ? [configured] : [];
const configuredUserDir = (process.env[USER_DIR_ENV] ?? process.env[LEGACY_USER_DIR_ENV])?.trim();
let userDirs: string[];
if (configuredUserDir) {
return [ENTERPRISES_DIR, configuredUserDir].filter((dir) => existsSync(dir));
userDirs = existsSync(configuredUserDir) ? [configuredUserDir] : [];
} else {
try {
syncLegacyEnterprisesDir();
} catch {}
userDirs = existsSync(PRIMARY_USER_ENTERPRISES_DIR)
? [PRIMARY_USER_ENTERPRISES_DIR]
: (existsSync(LEGACY_USER_ENTERPRISES_DIR) ? [LEGACY_USER_ENTERPRISES_DIR] : [PRIMARY_USER_ENTERPRISES_DIR]);
}
const dirs = [ENTERPRISES_DIR, PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
const globalConfig = loadGlobalConfig();
const testDir = globalConfig.testEnterprisesDir?.trim();
const candidates = testDir ? [testDir, ...userDirs] : userDirs;
const uniqueExisting: string[] = [];
for (const d of dirs) {
for (const d of candidates) {
if (existsSync(d) && !uniqueExisting.includes(d)) {
uniqueExisting.push(d);
}
@@ -58,27 +138,21 @@ export function resolveEnterprisesDirs(): string[] {
return uniqueExisting;
}
export function resolvePrimaryEnterprisesDir(): string | undefined {
const configured = (process.env[CONFIG_ENV] ?? process.env[LEGACY_CONFIG_ENV])?.trim();
if (configured) return existsSync(configured) ? configured : undefined;
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
if (existsSync(PRIMARY_USER_ENTERPRISES_DIR)) return PRIMARY_USER_ENTERPRISES_DIR;
if (existsSync(LEGACY_USER_ENTERPRISES_DIR)) return LEGACY_USER_ENTERPRISES_DIR;
return undefined;
}
export function resolveWritableEnterprisesDir(): string {
const configured = (process.env[CONFIG_ENV] ?? process.env[LEGACY_CONFIG_ENV])?.trim();
if (configured) return configured;
const configuredUserDir = (process.env[USER_DIR_ENV] ?? process.env[LEGACY_USER_DIR_ENV])?.trim();
if (configuredUserDir) return configuredUserDir;
const testDir = loadGlobalConfig().testEnterprisesDir?.trim();
if (testDir && existsSync(testDir)) return testDir;
return PRIMARY_USER_ENTERPRISES_DIR;
}
export function getEnterprisesDirCandidates(): string[] {
const testDir = loadGlobalConfig().testEnterprisesDir?.trim();
return [
`${CONFIG_ENV}=<path>`,
ENTERPRISES_DIR,
...(testDir ? [`testEnterprisesDir: ${testDir}`] : []),
PRIMARY_USER_ENTERPRISES_DIR,
LEGACY_USER_ENTERPRISES_DIR
];
@@ -109,3 +183,42 @@ export function saveGlobalConfig(config: GlobalConfigInput): GlobalConfig {
writeFileSync(file, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 });
return normalized;
}
export function findCorpConfigFile(corpId: string): string | undefined {
const dirs = resolveEnterprisesDirs();
for (const dir of dirs) {
if (!existsSync(dir)) continue;
for (const file of readdirSync(dir)
.filter((item) => item.endsWith(".json"))
.filter((item) => !item.startsWith("example."))) {
const fullPath = join(dir, file);
try {
const content = readFileSync(fullPath, "utf-8");
const parsed = JSON.parse(content);
if (parsed && typeof parsed === "object" && parsed.id === corpId) {
return fullPath;
}
} catch {
// ignore malformed files
}
}
}
return undefined;
}
export function updateCorpConfig(corpId: string, patch: Partial<CorpConfig>): CorpConfig {
const filePath = findCorpConfigFile(corpId);
if (!filePath) {
throw new Error(`Enterprise config not found: ${corpId}`);
}
const raw = JSON.parse(readFileSync(filePath, "utf-8"));
const merged = { ...raw, ...patch };
for (const key of Object.keys(patch) as Array<keyof CorpConfig>) {
if (patch[key] === undefined) {
delete merged[key];
}
}
const validated = CorpConfigSchema.parse(merged);
writeFileSync(filePath, `${JSON.stringify(validated, null, 2)}\n`, "utf-8");
return validated;
}
+1
View File
@@ -6,6 +6,7 @@ function corp(id: string, name = id): CorpConfig {
return {
id,
name,
environment: "production",
seal: {
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
+92 -1
View File
@@ -1,5 +1,10 @@
import { describe, expect, test } from "bun:test";
import { CorpConfigSchema, GlobalConfigSchema } from "./types.js";
import {
CorpConfigSchema,
GlobalConfigSchema,
SealCookieMapSchema,
SealHeaderMapSchema
} from "./types.js";
describe("CorpConfigSchema", () => {
test("accepts Hose key/password aliases", () => {
@@ -78,6 +83,92 @@ describe("CorpConfigSchema", () => {
expect(config.source.staffId).toBe("seal");
expect(config.source.tenantSlug).toBe("xiezihao");
});
test("leaves custom headers and cookies absent by default", () => {
const config = CorpConfigSchema.parse({
id: "direct",
name: "Direct",
source: {
type: "direct",
token: "seal-token",
sealUrl: "https://direct.sealai.cc"
}
});
expect(config.seal.headers).toBeUndefined();
expect(config.seal.cookies).toBeUndefined();
expect(config.environment).toBe("production");
expect(config.testCorpId).toBeUndefined();
expect(config.prodCorpId).toBeUndefined();
});
test("accepts environment, testCorpId, and prodCorpId", () => {
const prodConfig = CorpConfigSchema.parse({
id: "prod-corp",
name: "Prod Corp",
environment: "production",
testCorpId: "test-corp",
source: {
type: "direct",
token: "seal-token",
sealUrl: "https://direct.sealai.cc"
}
});
expect(prodConfig.environment).toBe("production");
expect(prodConfig.testCorpId).toBe("test-corp");
const testConfig = CorpConfigSchema.parse({
id: "test-corp",
name: "Test Corp",
environment: "test",
prodCorpId: "prod-corp",
source: {
type: "direct",
token: "seal-token",
sealUrl: "https://direct.sealai.cc"
}
});
expect(testConfig.environment).toBe("test");
expect(testConfig.prodCorpId).toBe("prod-corp");
});
test("accepts custom headers and cookies on the Seal endpoint", () => {
const config = CorpConfigSchema.parse({
id: "gated",
name: "Gated",
seal: {
url: "https://gated.sealai.cc",
headers: { "X-Tenant": "acme" },
cookies: { sdp_app_session_20142: "abc" }
},
source: {
type: "direct",
token: "seal-token",
sealUrl: "https://gated.sealai.cc"
}
});
expect(config.seal.headers).toEqual({ "X-Tenant": "acme" });
expect(config.seal.cookies).toEqual({ sdp_app_session_20142: "abc" });
});
});
describe("Seal custom header schemas", () => {
test("rejects an Authorization header supplied through config", () => {
expect(SealHeaderMapSchema.safeParse({ Authorization: "Bearer x" }).success).toBe(false);
expect(SealHeaderMapSchema.safeParse({ authorization: "Bearer x" }).success).toBe(false);
});
test("rejects malformed header and cookie names", () => {
expect(SealHeaderMapSchema.safeParse({ "bad name": "v" }).success).toBe(false);
expect(SealCookieMapSchema.safeParse({ "bad;name": "v" }).success).toBe(false);
});
test("rejects cookie values containing separators", () => {
expect(SealCookieMapSchema.safeParse({ name: "v;other=1" }).success).toBe(false);
expect(SealCookieMapSchema.safeParse({ name: "line\nbreak" }).success).toBe(false);
expect(SealCookieMapSchema.safeParse({ name: "ok-value" }).success).toBe(true);
});
});
describe("GlobalConfigSchema", () => {
+37 -1
View File
@@ -58,9 +58,38 @@ export const SealSourceSchema = z.discriminatedUnion("type", [
NativeSealSourceSchema
]);
// RFC 7230 token: shared by HTTP header names and cookie names.
const HTTP_TOKEN_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
export const SealHeaderMapSchema = z.record(
z.string().regex(HTTP_TOKEN_PATTERN, "Invalid HTTP header name"),
z.string()
).superRefine((headers, ctx) => {
for (const name of Object.keys(headers)) {
if (name.toLowerCase() === "authorization") {
ctx.addIssue({
code: "custom",
path: [name],
message: "seal.headers cannot set Authorization; the Seal session supplies the bearer token"
});
}
}
}).optional();
export const SealCookieMapSchema = z.record(
z.string().regex(HTTP_TOKEN_PATTERN, "Invalid cookie name"),
z.string().refine((value) => !/[\u0000-\u001f\u007f;]/.test(value), {
message: "Cookie value cannot contain control characters or semicolons"
})
).optional();
export const SealEndpointSchema = z.object({
url: z.string().url().optional(),
tenantSlug: z.string().optional(),
// Extra headers/cookies for Seal deployments reachable only through an
// upstream gateway that expects its own session cookie.
headers: SealHeaderMapSchema,
cookies: SealCookieMapSchema,
endpoints: z.object({
approvalStylePreferences: z.string().default("api/v1/agent/ai-approval/config")
}).default({
@@ -76,12 +105,17 @@ export const CorpAuthConfigSchema = z.object({
refreshTtl: z.number().int().positive().default(300)
}).default({ refreshTtl: 300 });
export const CorpEnvironmentSchema = z.enum(["production", "test"]).default("production");
export const CorpConfigSchema = z.object({
id: z.string(),
name: z.string(),
seal: SealEndpointSchema,
source: SealSourceSchema,
auth: CorpAuthConfigSchema
auth: CorpAuthConfigSchema,
environment: CorpEnvironmentSchema,
testCorpId: z.string().optional(),
prodCorpId: z.string().optional()
});
export const GlobalLintConfigSchema = z.object({
@@ -97,9 +131,11 @@ export const GlobalLintConfigSchema = z.object({
export const GlobalConfigSchema = z.object({
stateful: z.boolean().default(false),
defaultCorpId: z.string().min(1).optional(),
testEnterprisesDir: z.string().min(1).optional(),
lint: GlobalLintConfigSchema
});
export type CorpEnvironment = z.infer<typeof CorpEnvironmentSchema>;
export type HoseSealSource = z.infer<typeof HoseSealSourceSchema>;
export type DirectSealSource = z.infer<typeof DirectSealSourceSchema>;
export type NativeSealSource = z.infer<typeof NativeSealSourceSchema>;
+2 -2
View File
@@ -36,11 +36,11 @@ export function getDefaultGlobalSkillDir(): string {
return join(homedir(), ".agents", "skills", "seal-use");
}
export function getLegacyGlobalSkillDir(): string {
function getLegacyGlobalSkillDir(): string {
return join(homedir(), ".agents", "skills", "seal-home");
}
export function cleanLegacySkillDir(): boolean {
function cleanLegacySkillDir(): boolean {
const legacyDir = getLegacyGlobalSkillDir();
if (existsSync(legacyDir)) {
try {
+33
View File
@@ -0,0 +1,33 @@
import { afterEach, describe, expect, test } from "bun:test";
import { createSealClientForUrl } from "./factory.js";
const servers: Array<ReturnType<typeof Bun.serve>> = [];
afterEach(() => {
for (const server of servers.splice(0)) server.stop(true);
});
describe("Seal HTTP client errors", () => {
test("includes ky's parsed response body after the response stream is consumed", async () => {
const server = Bun.serve({
port: 0,
fetch: () => new Response(JSON.stringify({
error: {
code: "error:common:invalid-parameter",
message: "contentType 取值非法"
}
}), {
status: 400,
headers: { "content-type": "application/json" }
})
});
servers.push(server);
await expect(
createSealClientForUrl(`http://127.0.0.1:${server.port}`, "dummy-token").get("/")
).rejects.toThrow(
'Request failed with status code 400 Bad Request: GET http://127.0.0.1:' +
`${server.port}/: {"error":{"code":"error:common:invalid-parameter","message":"contentType 取值非法"}}`
);
});
});
+37 -25
View File
@@ -1,6 +1,33 @@
import ky, { HTTPError, KyInstance } from "ky";
import { CorpConfig } from "../config/types.js";
import { clearSealToken, getSealSessionForCorp } from "../auth/seal.js";
import { resolveSealCustomHeaders } from "./request-headers.js";
function formatErrorData(data: unknown): string {
if (data === undefined || data === null || data === "") return "";
if (typeof data === "string") return data;
try {
return JSON.stringify(data);
} catch {
return String(data);
}
}
function withResponseBody(error: unknown): Error {
if (!(error instanceof HTTPError)) return error as Error;
const body = formatErrorData(error.data);
if (body) error.message = `${error.message}: ${body}`;
return error;
}
function createBeforeErrorHook(corpId?: string) {
return async ({ error }: { error: unknown }) => {
if (corpId && error instanceof HTTPError && error.response.status === 401) {
clearSealToken(corpId);
}
return withResponseBody(error);
};
}
export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
const session = await getSealSessionForCorp(corp);
@@ -9,22 +36,11 @@ export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
prefix: session.enterprise.sealUrl,
timeout: 30000,
headers: {
...resolveSealCustomHeaders(corp.seal),
Authorization: `Bearer ${session.token}`
},
hooks: {
beforeError: [
async ({ error }) => {
if (error instanceof HTTPError && error.response.status === 401) {
clearSealToken(corp.id);
}
const body =
error instanceof HTTPError
? await error.response.text().catch(() => "")
: "";
error.message = `${error.message}${body ? `: ${body}` : ""}`;
return error;
}
]
beforeError: [createBeforeErrorHook(corp.id)]
}
});
}
@@ -32,27 +48,23 @@ export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
export async function createSealClientForToken(corp: CorpConfig, token: string): Promise<KyInstance> {
const session = await getSealSessionForCorp(corp);
return createSealClientForUrl(session.enterprise.sealUrl, token);
return createSealClientForUrl(session.enterprise.sealUrl, token, resolveSealCustomHeaders(corp.seal));
}
export function createSealClientForUrl(sealUrl: string, token: string): KyInstance {
export function createSealClientForUrl(
sealUrl: string,
token: string,
customHeaders: Record<string, string> = {}
): KyInstance {
return ky.create({
prefix: sealUrl.replace(/\/+$/, ""),
timeout: 30000,
headers: {
...customHeaders,
Authorization: `Bearer ${token}`
},
hooks: {
beforeError: [
async ({ error }) => {
const body =
error instanceof HTTPError
? await error.response.text().catch(() => "")
: "";
error.message = `${error.message}${body ? `: ${body}` : ""}`;
return error;
}
]
beforeError: [createBeforeErrorHook()]
}
});
}
+64
View File
@@ -0,0 +1,64 @@
import { describe, expect, test } from "bun:test";
import { createSealClientForUrl } from "./factory.js";
import { formatCookieHeader, resolveSealCustomHeaders } from "./request-headers.js";
describe("formatCookieHeader", () => {
test("returns undefined when there are no cookies", () => {
expect(formatCookieHeader(undefined)).toBeUndefined();
expect(formatCookieHeader({})).toBeUndefined();
});
test("joins cookies with a semicolon and a space", () => {
expect(formatCookieHeader({ a: "1", b: "2" })).toBe("a=1; b=2");
});
});
describe("resolveSealCustomHeaders", () => {
test("returns an empty map when no custom headers are configured", () => {
expect(resolveSealCustomHeaders(undefined)).toEqual({});
});
test("keeps configured headers and renders cookies", () => {
expect(resolveSealCustomHeaders({
headers: { "X-Tenant": "acme" },
cookies: { sdp_session: "token" }
})).toEqual({
"X-Tenant": "acme",
Cookie: "sdp_session=token"
});
});
test("lets configured cookies replace a raw Cookie header", () => {
expect(resolveSealCustomHeaders({
headers: { Cookie: "stale=1" },
cookies: { fresh: "2" }
})).toEqual({ Cookie: "fresh=2" });
});
});
describe("createSealClientForUrl", () => {
test("sends custom headers and keeps the session Authorization", async () => {
const originalFetch = globalThis.fetch;
let sent: Headers | undefined;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = input instanceof Request ? input : new Request(input, init);
sent = new Headers(request.headers);
return new Response(JSON.stringify({ data: {} }), {
headers: { "content-type": "application/json" }
});
}) as typeof fetch;
try {
const client = createSealClientForUrl("https://corp-a.sealai.cc", "session-token", {
Cookie: "sdp_session=token",
Authorization: "Bearer stale"
});
await client.get("api/v1/auth/me");
} finally {
globalThis.fetch = originalFetch;
}
expect(sent?.get("cookie")).toBe("sdp_session=token");
expect(sent?.get("authorization")).toBe("Bearer session-token");
});
});
+20
View File
@@ -0,0 +1,20 @@
import type { CorpConfig } from "../config/types.js";
// The subset of the Seal endpoint config that carries extra request headers.
export type SealCustomHeaderSource = Pick<CorpConfig["seal"], "headers" | "cookies">;
// Renders configured cookies into one Cookie header, joined with "; ".
export function formatCookieHeader(cookies: Record<string, string> | undefined): string | undefined {
const pairs = Object.entries(cookies ?? {}).map(([name, value]) => `${name}=${value}`);
return pairs.length ? pairs.join("; ") : undefined;
}
// Extra tenant headers from corp config. A rendered Cookie header replaces a
// same-named entry, while Authorization is always left to the caller so the
// session bearer token can never be silently replaced by config.
export function resolveSealCustomHeaders(seal: SealCustomHeaderSource | undefined): Record<string, string> {
const headers: Record<string, string> = { ...(seal?.headers ?? {}) };
const cookieHeader = formatCookieHeader(seal?.cookies);
if (cookieHeader) headers.Cookie = cookieHeader;
return headers;
}
+196 -1
View File
@@ -6,6 +6,18 @@ import {
filterWebhookIntegrations,
findWebhookIntegration,
listWebhookIntegrations,
previewAddWebhookIntegration,
previewDeleteWebhookIntegration,
previewUpdateWebhookIntegration,
getDepartment,
getContactsLastSyncTime,
getInsightStats,
listExpenses,
listInvoices,
listFeishuSimulationApprovalDefinitions,
listDepartmentChildren,
listDepartmentUsers,
listRootDepartments,
searchUsers,
updateWebhookIntegration
} from "./api.js";
@@ -35,6 +47,150 @@ describe("Seal contact API", () => {
expect(requestedParams).toEqual({ query: "欧阳楠楠" });
expect(result.users).toEqual([{ _id: "user-1", name: "欧阳楠楠", departmentIds: [], permissions: [] }]);
});
test("reads the department tree, department users, and last sync time", async () => {
const requestedUrls: string[] = [];
const client = {
get: (url: string) => {
requestedUrls.push(url);
const data = url.endsWith("last-sync-time")
? { lastSyncTime: "2026-06-23T08:14:40.000Z" }
: url.endsWith("/users")
? { items: [{ _id: "user-1", name: "测试用户" }] }
: url.endsWith("/children") || url.endsWith("root/children")
? { items: [{ _id: "department-2", name: "财务" }] }
: { _id: "department-1", name: "公司", parentId: null };
return { json: async () => ({ data }) };
}
} as unknown as KyInstance;
await expect(listRootDepartments(client)).resolves.toMatchObject({
items: [{ _id: "department-2", name: "财务" }]
});
await expect(getDepartment(client, "department-1")).resolves.toMatchObject({
_id: "department-1",
name: "公司"
});
await expect(listDepartmentChildren(client, "department-1")).resolves.toMatchObject({
items: [{ _id: "department-2" }]
});
await expect(listDepartmentUsers(client, "department-1")).resolves.toMatchObject({
items: [{ _id: "user-1", name: "测试用户" }]
});
await expect(getContactsLastSyncTime(client)).resolves.toEqual({
lastSyncTime: "2026-06-23T08:14:40.000Z"
});
expect(requestedUrls).toEqual([
"api/v1/contacts/departments/root/children",
"api/v1/contacts/departments/department-1",
"api/v1/contacts/departments/department-1/children",
"api/v1/contacts/departments/department-1/users",
"api/v1/contacts/last-sync-time"
]);
});
test("forwards the insight stats date range and limit", async () => {
let requestedUrl = "";
const client = {
get: (url: string, options?: { searchParams?: URLSearchParams }) => {
requestedUrl = `${url}?${options?.searchParams?.toString() ?? ""}`;
return {
json: async () => ({
data: { tagStats: [], totalRisks: 2, analyzedRisks: 1, pendingRisks: 1 }
})
};
}
} as unknown as KyInstance;
await expect(getInsightStats(client, {
startDate: "2026-09-01T00:00:00+08:00",
endDate: "2026-09-30T23:59:59+08:00",
limit: 10
})).resolves.toEqual({
tagStats: [],
totalRisks: 2,
analyzedRisks: 1,
pendingRisks: 1
});
expect(requestedUrl).toBe(
"api/v1/insight/stats?startDate=2026-09-01T00%3A00%3A00%2B08%3A00&endDate=2026-09-30T23%3A59%3A59%2B08%3A00&limit=10"
);
});
test("defaults insight stats to the current calendar month", async () => {
let requestedUrl = "";
const client = {
get: (url: string, options?: { searchParams?: URLSearchParams }) => {
requestedUrl = `${url}?${options?.searchParams?.toString() ?? ""}`;
return { json: async () => ({ data: {} }) };
}
} as unknown as KyInstance;
await getInsightStats(client);
const parsed = new URL(`https://seal.test/${requestedUrl}`);
const now = new Date();
expect(parsed.searchParams.get("startDate")).toBe(
new Date(now.getFullYear(), now.getMonth(), 1).toISOString()
);
expect(parsed.searchParams.get("endDate")).toBe(
new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999).toISOString()
);
});
test("uses the frontend filter parameter names for expenses and invoices", async () => {
const requestedUrls: string[] = [];
const client = {
get: (url: string, options?: { searchParams?: URLSearchParams }) => {
requestedUrls.push(`${url}?${options?.searchParams?.toString() ?? ""}`);
return {
json: async () => ({
data: url.includes("expenses")
? { expenses: [], total: 0 }
: { invoices: [], total: 0, feishuApprovalAppId: null }
})
};
}
} as unknown as KyInstance;
await expect(listExpenses(client, {
startDate: "1757520000000",
endDate: "1789142399999",
search: "zz-probe-no-match",
offset: 0,
limit: 50
})).resolves.toEqual({ expenses: [], total: 0 });
await expect(listInvoices(client, {
startDate: "2026-08-31T16:00:00.000Z",
endDate: "2026-09-30T15:59:59.999Z",
search: "zz-probe-no-match",
offset: 0,
limit: 50
})).resolves.toEqual({ invoices: [], total: 0, feishuApprovalAppId: null });
expect(requestedUrls).toEqual([
"api/v1/expenses/list?filter%5BstartDate%5D=1757520000000&filter%5BendDate%5D=1789142399999&filter%5Bsearch%5D=zz-probe-no-match&offset=0&limit=50",
"api/v1/invoice/list?filter%5BstartDate%5D=2026-08-31T16%3A00%3A00.000Z&filter%5BendDate%5D=2026-09-30T15%3A59%3A59.999Z&filter%5Bsearch%5D=zz-probe-no-match&offset=0&limit=50"
]);
});
test("lists Feishu simulation approval definitions", async () => {
let requestedUrl = "";
const client = {
get: (url: string) => {
requestedUrl = url;
return {
json: async () => ({ data: [{ code: "travel", name: "差旅报销" }] })
};
}
} as unknown as KyInstance;
await expect(listFeishuSimulationApprovalDefinitions(client)).resolves.toEqual([
{ code: "travel", name: "差旅报销" }
]);
expect(requestedUrl).toBe("api/v1/integrations/feishu/simulation/approval-definitions");
});
});
describe("Seal Webhook API", () => {
@@ -112,10 +268,20 @@ describe("Seal Webhook API", () => {
const updated = await updateWebhookIntegration(client, "integration-1", {
name: "Renamed webhook",
rotateSecret: true
rotateSecret: true,
materialPackFilePolicy: {
minFileSizeBytes: 1000,
maxFileSizeBytes: 2000,
allowedExtensions: ["PDF", "xlsx"]
}
});
expect(updated.name).toBe("Renamed webhook");
expect(updated.secret).not.toBe("webhook-secret");
expect(updated.materialPackFilePolicy).toEqual({
minFileSizeBytes: 1000,
maxFileSizeBytes: 2000,
allowedExtensions: [".pdf", ".xlsx"]
});
expect((posted?.integrations as Array<Record<string, unknown>>)[1]).toMatchObject({ type: "hosecloud" });
const found = findWebhookIntegration([updated], "Renamed webhook");
@@ -126,6 +292,35 @@ describe("Seal Webhook API", () => {
expect(deleted.id).toBe("integration-1");
expect((posted?.integrations as Array<Record<string, unknown>>)).toHaveLength(1);
});
test("previews Webhook mutations without sending a write request", async () => {
const writes: string[] = [];
const client = {
get: () => ({
json: async () => ({ data: webhookConfig() })
}),
post: (url: string) => {
writes.push(`post:${url}`);
throw new Error("preview must not write");
},
patch: (url: string) => {
writes.push(`patch:${url}`);
throw new Error("preview must not write");
}
} as unknown as KyInstance;
const added = await previewAddWebhookIntegration(client, "https://seal.test", {
name: "Preview webhook",
outgoingResultWebhook: "https://callback.test/preview"
});
const updated = await previewUpdateWebhookIntegration(client, "integration-1", { name: "Preview rename" });
const deleted = await previewDeleteWebhookIntegration(client, "integration-1");
expect(added.integration?.name).toBe("Preview webhook");
expect(updated.integration?.name).toBe("Preview rename");
expect(deleted.after.integrations).toHaveLength(1);
expect(writes).toEqual([]);
});
});
function webhookConfig() {
+265 -20
View File
@@ -1,6 +1,11 @@
import { randomBytes } from "node:crypto";
import ky, { HTTPError, KyInstance } from "ky";
import { z } from "zod";
import {
mergeMaterialPackFilePolicy,
normalizeMaterialPackFilePolicy,
type MaterialPackFilePolicyPatch
} from "./material-pack/policy.js";
import { CorpConfig } from "../../core/config/types.js";
import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
import {
@@ -36,6 +41,22 @@ import {
SealUserDetailSchema,
SealContactSearchResult,
SealContactSearchResultSchema,
SealDepartment,
SealDepartmentSchema,
SealDepartmentListData,
SealDepartmentListDataSchema,
SealDepartmentUsersData,
SealDepartmentUsersDataSchema,
SealContactsLastSyncTime,
SealContactsLastSyncTimeSchema,
InsightStats,
InsightStatsSchema,
ExpenseListData,
ExpenseListDataSchema,
InvoiceListData,
InvoiceListDataSchema,
SimulationApprovalDefinition,
SimulationApprovalDefinitionSchema,
LlmConfig,
LlmConfigSchema,
LlmProvider,
@@ -194,6 +215,7 @@ export async function createApprovalDocument(
content: string;
contentType?: string;
status?: string;
enabled?: boolean;
scenarios?: string[];
tags?: string[];
}
@@ -204,7 +226,8 @@ export async function createApprovalDocument(
...params,
contentType: params.contentType ?? "policy",
status: params.status ?? "published",
scenarios: params.scenarios ?? [],
enabled: params.enabled ?? true,
scenarios: params.scenarios && params.scenarios.length > 0 ? params.scenarios : ["audit"],
tags: params.tags ?? []
}
}),
@@ -238,6 +261,14 @@ export async function updateApprovalDocument(
);
}
export async function deleteApprovalDocument(
client: KyInstance,
documentId: string
): Promise<{ success: boolean; id: string }> {
await client.delete(`api/v1/knowledge/articles/${documentId}`);
return { success: true, id: documentId };
}
export async function getApprovalStylePreferences(
client: KyInstance,
endpoint = "api/v1/agent/ai-approval/config"
@@ -253,12 +284,16 @@ export async function updateApprovalStylePreferences(
params: Record<string, unknown>,
endpoint = "api/v1/agent/ai-approval/config"
): Promise<ApprovalStylePreferences> {
return unwrap(
await client.patch(endpoint, { json: params }),
ApprovalStylePreferencesSchema
);
await client.post(endpoint, { json: params });
return getApprovalStylePreferences(client, endpoint);
}
export type WebhookMutationPreview = {
before: ApprovalStylePreferences;
after: ApprovalStylePreferences;
integration?: WebhookIntegration;
};
export async function saveApprovalStylePreferences(
client: KyInstance,
params: Record<string, unknown>,
@@ -289,6 +324,7 @@ export async function addWebhookIntegration(
outgoingResultWebhook: string;
autoApprovalRate?: number;
secret?: string;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
},
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookIntegration> {
@@ -307,6 +343,29 @@ export async function addWebhookIntegration(
return integration;
}
export async function previewAddWebhookIntegration(
client: KyInstance,
baseUrl: string,
params: {
name: string;
mode?: WebhookMode;
outgoingResultWebhook: string;
autoApprovalRate?: number;
secret?: string;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
},
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookMutationPreview> {
const before = await getApprovalStylePreferences(client, endpoint);
const existing = parseWebhookIntegrations(before.integrations);
const integration = createWebhookIntegration(baseUrl, existing, params);
return {
before,
after: { ...before, integrations: [...before.integrations, integration] },
integration
};
}
export async function updateWebhookIntegration(
client: KyInstance,
selector: string,
@@ -317,26 +376,14 @@ export async function updateWebhookIntegration(
autoApprovalRate?: number;
secret?: string;
rotateSecret?: boolean;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
},
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookIntegration> {
const preferences = await getApprovalStylePreferences(client, endpoint);
const entries = getWebhookEntries(preferences.integrations);
const entry = findWebhookEntry(entries, selector);
const updated = WebhookIntegrationSchema.parse({
...entry.integration,
...(params.name === undefined ? {} : { name: requiredText(params.name, "name") }),
...(params.mode === undefined ? {} : { mode: params.mode }),
...(params.outgoingResultWebhook === undefined
? {}
: { outgoingResultWebhook: validUrl(params.outgoingResultWebhook, "outgoingResultWebhook") }),
...(params.autoApprovalRate === undefined
? {}
: { autoApprovalRate: validApprovalRate(params.autoApprovalRate) }),
...(params.rotateSecret || params.secret !== undefined
? { secret: params.rotateSecret ? generateWebhookSecret() : requiredText(params.secret ?? "", "secret") }
: {})
});
const updated = buildUpdatedWebhookIntegration(entry.integration, params);
const saved = await saveApprovalStylePreferences(client, {
...preferences,
@@ -352,6 +399,34 @@ export async function updateWebhookIntegration(
return updated;
}
export async function previewUpdateWebhookIntegration(
client: KyInstance,
selector: string,
params: {
name?: string;
mode?: WebhookMode;
outgoingResultWebhook?: string;
autoApprovalRate?: number;
secret?: string;
rotateSecret?: boolean;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
},
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookMutationPreview> {
const before = await getApprovalStylePreferences(client, endpoint);
const entries = getWebhookEntries(before.integrations);
const entry = findWebhookEntry(entries, selector);
const integration = buildUpdatedWebhookIntegration(entry.integration, params);
return {
before,
after: {
...before,
integrations: before.integrations.map((item, index) => index === entry.index ? integration : item)
},
integration
};
}
export async function deleteWebhookIntegration(
client: KyInstance,
selector: string,
@@ -372,6 +447,24 @@ export async function deleteWebhookIntegration(
return entry.integration;
}
export async function previewDeleteWebhookIntegration(
client: KyInstance,
selector: string,
endpoint = "api/v1/agent/ai-approval/config"
): Promise<WebhookMutationPreview> {
const before = await getApprovalStylePreferences(client, endpoint);
const entries = getWebhookEntries(before.integrations);
const entry = findWebhookEntry(entries, selector);
return {
before,
after: {
...before,
integrations: before.integrations.filter((_, index) => index !== entry.index)
},
integration: entry.integration
};
}
export function findWebhookIntegration(
integrations: WebhookIntegration[],
selector: string
@@ -445,6 +538,7 @@ function createWebhookIntegration(
outgoingResultWebhook: string;
autoApprovalRate?: number;
secret?: string;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
}
): WebhookIntegration {
const name = requiredText(params.name, "name");
@@ -470,7 +564,44 @@ function createWebhookIntegration(
url: `${root}/api/v1/integrations/webhook/${webhookId}/manual-result`
},
secret: params.secret ? requiredText(params.secret, "secret") : generateWebhookSecret(),
autoApprovalRate
autoApprovalRate,
materialPackFilePolicy: normalizeMaterialPackFilePolicy(params.materialPackFilePolicy)
});
}
function buildUpdatedWebhookIntegration(
integration: WebhookIntegration,
params: {
name?: string;
mode?: WebhookMode;
outgoingResultWebhook?: string;
autoApprovalRate?: number;
secret?: string;
rotateSecret?: boolean;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
}
): WebhookIntegration {
return WebhookIntegrationSchema.parse({
...integration,
...(params.name === undefined ? {} : { name: requiredText(params.name, "name") }),
...(params.mode === undefined ? {} : { mode: params.mode }),
...(params.outgoingResultWebhook === undefined
? {}
: { outgoingResultWebhook: validUrl(params.outgoingResultWebhook, "outgoingResultWebhook") }),
...(params.autoApprovalRate === undefined
? {}
: { autoApprovalRate: validApprovalRate(params.autoApprovalRate) }),
...(params.rotateSecret || params.secret !== undefined
? { secret: params.rotateSecret ? generateWebhookSecret() : requiredText(params.secret ?? "", "secret") }
: {}),
...(params.materialPackFilePolicy === undefined
? {}
: {
materialPackFilePolicy: mergeMaterialPackFilePolicy(
integration.materialPackFilePolicy,
params.materialPackFilePolicy
)
})
});
}
@@ -819,6 +950,120 @@ export async function searchUsers(
);
}
export async function listRootDepartments(client: KyInstance): Promise<SealDepartmentListData> {
return unwrap(
await client.get("api/v1/contacts/departments/root/children"),
SealDepartmentListDataSchema
);
}
export async function getDepartment(
client: KyInstance,
departmentId: string
): Promise<SealDepartment> {
return unwrap(
await client.get(`api/v1/contacts/departments/${encodeURIComponent(departmentId)}`),
SealDepartmentSchema
);
}
export async function listDepartmentChildren(
client: KyInstance,
departmentId: string
): Promise<SealDepartmentListData> {
return unwrap(
await client.get(`api/v1/contacts/departments/${encodeURIComponent(departmentId)}/children`),
SealDepartmentListDataSchema
);
}
export async function listDepartmentUsers(
client: KyInstance,
departmentId: string
): Promise<SealDepartmentUsersData> {
return unwrap(
await client.get(`api/v1/contacts/departments/${encodeURIComponent(departmentId)}/users`),
SealDepartmentUsersDataSchema
);
}
export async function getContactsLastSyncTime(client: KyInstance): Promise<SealContactsLastSyncTime> {
return unwrap(await client.get("api/v1/contacts/last-sync-time"), SealContactsLastSyncTimeSchema);
}
export async function getInsightStats(
client: KyInstance,
params: { startDate?: string; endDate?: string; limit?: number } = {}
): Promise<InsightStats> {
const defaultRange = currentMonthDateRange();
const searchParams = new URLSearchParams();
setOptional(searchParams, "startDate", params.startDate ?? defaultRange.startDate);
setOptional(searchParams, "endDate", params.endDate ?? defaultRange.endDate);
if (params.limit !== undefined) searchParams.set("limit", String(params.limit));
return unwrap(
await client.get("api/v1/insight/stats", { searchParams }),
InsightStatsSchema
);
}
function currentMonthDateRange(): { startDate: string; endDate: string } {
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth(), 1);
const end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
return {
startDate: start.toISOString(),
endDate: end.toISOString()
};
}
export type DataListParams = {
offset?: number;
limit?: number;
startDate?: string;
endDate?: string;
search?: string;
};
function dataListSearchParams(params: DataListParams): URLSearchParams {
const searchParams = new URLSearchParams();
setOptional(searchParams, "filter[startDate]", params.startDate);
setOptional(searchParams, "filter[endDate]", params.endDate);
setOptional(searchParams, "filter[search]", params.search);
searchParams.set("offset", String(params.offset ?? 0));
searchParams.set("limit", String(params.limit ?? 50));
return searchParams;
}
export async function listExpenses(
client: KyInstance,
params: DataListParams = {}
): Promise<ExpenseListData> {
return unwrap(
await client.get("api/v1/expenses/list", { searchParams: dataListSearchParams(params) }),
ExpenseListDataSchema
);
}
export async function listInvoices(
client: KyInstance,
params: DataListParams = {}
): Promise<InvoiceListData> {
return unwrap(
await client.get("api/v1/invoice/list", { searchParams: dataListSearchParams(params) }),
InvoiceListDataSchema
);
}
export async function listFeishuSimulationApprovalDefinitions(
client: KyInstance
): Promise<SimulationApprovalDefinition[]> {
return unwrap(
await client.get("api/v1/integrations/feishu/simulation/approval-definitions"),
z.array(SimulationApprovalDefinitionSchema)
);
}
export async function deleteLocalUser(
client: KyInstance,
userId: string
@@ -0,0 +1,192 @@
import { describe, expect, test } from "bun:test";
import { existsSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import ExcelJS from "exceljs";
import {
getRuleBriefTitle,
normalizeManualApprovalStatus,
normalizeTimestamp,
resolveOutputFilePath,
exportApprovalRunsToExcel
} from "./approval-runs-export.js";
import type { CorpConfig } from "../../core/config/types.js";
describe("approval-runs-export helpers", () => {
test("normalizeTimestamp converts YYYY-MM-DD to Beijing time epoch string", () => {
const start = normalizeTimestamp("2026-08-07", false);
expect(start).toBe(String(new Date("2026-08-07T00:00:00.000+08:00").getTime()));
const end = normalizeTimestamp("2026-08-07", true);
expect(end).toBe(String(new Date("2026-08-07T23:59:59.999+08:00").getTime()));
// 10-digit epoch
expect(normalizeTimestamp("1786032000")).toBe("1786032000000");
// 13-digit epoch
expect(normalizeTimestamp("1786032000123")).toBe("1786032000123");
// number
expect(normalizeTimestamp(1786032000000)).toBe("1786032000000");
// undefined/empty
expect(normalizeTimestamp(undefined)).toBeUndefined();
expect(normalizeTimestamp("")).toBeUndefined();
});
test("normalizeManualApprovalStatus maps human words to backend enum", () => {
expect(normalizeManualApprovalStatus("APPROVED")).toEqual(["APPROVED"]);
expect(normalizeManualApprovalStatus("已通过")).toEqual(["APPROVED"]);
expect(normalizeManualApprovalStatus("已支付/审批完成")).toEqual(["APPROVED"]);
expect(normalizeManualApprovalStatus("TERMINATED")).toEqual(["TERMINATED"]);
expect(normalizeManualApprovalStatus("被驳回")).toEqual(["TERMINATED"]);
expect(normalizeManualApprovalStatus("处理中")).toEqual(["PROCESSING"]);
expect(normalizeManualApprovalStatus("已撤回")).toEqual(["CANCELLED"]);
expect(normalizeManualApprovalStatus(["已通过", "被驳回"])).toEqual(["APPROVED", "TERMINATED"]);
expect(normalizeManualApprovalStatus(undefined)).toBeUndefined();
});
test("getRuleBriefTitle extracts clean concise summary", () => {
expect(getRuleBriefTitle("rule-0", "所有单据:报销公司不是浙江大黄蜂建筑机械设备有限公司时提示")).toBe(
"所有单据:报销公司不是浙江大黄蜂建筑机械设备"
);
expect(getRuleBriefTitle("rule-1", "### 发票合规校验\n第二行内容")).toBe("发票合规校验");
expect(getRuleBriefTitle("rule-2", undefined, "通用范围")).toBe("rule-2 (通用范围)");
});
test("resolveOutputFilePath supports custom path, downloads, and default exports dir", () => {
const custom = resolveOutputFilePath({
outputFile: "/tmp/custom-export.xlsx",
corpName: "TestCorp",
recordCount: 10
});
expect(custom).toBe("/tmp/custom-export.xlsx");
const dl = resolveOutputFilePath({
toDownloads: true,
corpName: "大黄蜂",
dateTag: "2026-08-07至今",
recordCount: 50
});
expect(dl).toContain("Downloads/大黄蜂_审核记录_2026-08-07至今_50条.xlsx");
});
});
describe("exportApprovalRunsToExcel integration", () => {
const testCorp: CorpConfig = {
id: "test-corp",
name: "测试企业",
environment: "production",
seal: {
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "direct",
token: "test-token",
sealUrl: "https://mock.sealai.cc",
expiresIn: 3600,
staffId: "direct"
},
auth: {
refreshTtl: 300
}
};
test("generates valid formatted excel workbook", async () => {
const mockClient = {
get: (url: string, opts?: any) => {
if (url.includes("api/v1/rules")) {
return {
json: async () => ({
rules: [
{ id: "r1", code: 0, description: "发票与收据真实性核验", scope: "全局", strictness: "SHOULD_FOLLOW" },
{ id: "r2", code: 1, description: "差旅标准不得超标", scope: "差旅", strictness: "MUST_FOLLOW" }
]
})
};
}
if (url.includes("api/v1/approvals")) {
return {
json: async () => ({
total: 2,
records: [
{
id: "run-1",
sourceDocumentSN: "B26001",
status: "completed",
taskMode: "assisted",
sourceSystem: "hosecloud",
document: {
fields: [{ label: "单据模板", value: "差旅报销单" }]
},
result: {
decision: "APPROVE",
rulesResult: [{ id: "rule-0", checkResult: "PASS" }]
},
manualApprovalRecord: {
status: { label: "已支付/审批完成", type: "APPROVED" }
},
createdAt: 1788760000000,
updatedAt: 1788760020000
},
{
id: "run-2",
sourceDocumentSN: "B26002",
status: "completed",
taskMode: "assisted",
sourceSystem: "hosecloud",
document: {
fields: [{ label: "单据模板", value: "差旅报销单" }]
},
result: {
decision: "REJECT",
rulesResult: [{ id: "rule-0", checkResult: "FAIL" }]
},
manualApprovalRecord: {
status: { label: "被驳回", type: "TERMINATED" },
rejectComment: "请上传正确的行程单凭据"
},
createdAt: 1788760000000,
updatedAt: 1788760030000
}
]
})
};
}
throw new Error(`Unexpected url: ${url}`);
}
} as any;
const tmpOut = join(tmpdir(), `test-export-${Date.now()}.xlsx`);
try {
const result = await exportApprovalRunsToExcel(mockClient, testCorp, {
outputFile: tmpOut,
limit: 10,
pageDelayMs: 0
});
expect(result.recordCount).toBe(2);
expect(result.ruleColumnCount).toBe(2);
expect(result.statusCounts["已支付/审批完成"]).toBe(1);
expect(result.statusCounts["被驳回"]).toBe(1);
expect(result.rejectReasonCount).toBe(1);
expect(existsSync(tmpOut)).toBe(true);
// Verify Excel contents with ExcelJS
const wb = new ExcelJS.Workbook();
await wb.xlsx.readFile(tmpOut);
const ws = wb.worksheets[0]!;
expect(ws.rowCount).toBe(3); // 1 header + 2 rows
expect(ws.getRow(1).getCell(1).value).toBe("单据编号");
expect(ws.getRow(2).getCell(1).value).toBe("B26001");
expect(ws.getRow(2).getCell(9).value).toBe("已支付/审批完成");
expect(ws.getRow(3).getCell(1).value).toBe("B26002");
expect(ws.getRow(3).getCell(9).value).toBe("被驳回");
expect(ws.getRow(3).getCell(10).value).toBe("请上传正确的行程单凭据");
} finally {
if (existsSync(tmpOut)) {
rmSync(tmpOut, { force: true });
}
}
});
});
+531
View File
@@ -0,0 +1,531 @@
import { existsSync, mkdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, resolve } from "node:path";
import ExcelJS from "exceljs";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import type { ApprovalRun, ApprovalRunListData } from "./types.js";
export interface ApprovalRunsExportOptions {
limit?: number;
startDate?: string | number;
endDate?: string | number;
status?: string;
manualApprovalStatus?: string | string[];
includeCompletedOnly?: boolean;
outputFile?: string;
toDownloads?: boolean;
pageSize?: number;
pageDelayMs?: number;
}
export interface ApprovalRunsExportResult {
filePath: string;
corpId: string;
corpName: string;
recordCount: number;
ruleColumnCount: number;
statusCounts: Record<string, number>;
rejectReasonCount: number;
fileSizeBytes: number;
exportedAt: string;
}
export function normalizeTimestamp(val?: string | number, endOfDay = false): string | undefined {
if (val === undefined || val === null || val === "") return undefined;
if (typeof val === "number") return String(val);
const str = String(val).trim();
if (!str) return undefined;
if (/^\d{10,13}$/.test(str)) {
return str.length === 10 ? `${str}000` : str;
}
if (/^\d{4}-\d{2}-\d{2}$/.test(str)) {
const timeSuffix = endOfDay ? "T23:59:59.999+08:00" : "T00:00:00.000+08:00";
const parsed = new Date(`${str}${timeSuffix}`).getTime();
if (!Number.isNaN(parsed)) return String(parsed);
}
const parsed = new Date(str).getTime();
if (!Number.isNaN(parsed)) return String(parsed);
return str;
}
export function normalizeManualApprovalStatus(status?: string | string[]): string[] | undefined {
if (!status) return undefined;
const rawList = Array.isArray(status) ? status : [status];
const list: string[] = [];
for (const s of rawList) {
const normalized = s.trim().toUpperCase();
if (["APPROVED", "已通过", "已完成", "已支付", "已支付/审批完成"].includes(normalized)) {
list.push("APPROVED");
} else if (["TERMINATED", "REJECTED", "REJECT", "驳回", "被驳回", "已驳回"].includes(normalized)) {
list.push("TERMINATED");
} else if (["PROCESSING", "审批中", "处理中"].includes(normalized)) {
list.push("PROCESSING");
} else if (["CANCELLED", "CANCELED", "已撤回", "已撤销"].includes(normalized)) {
list.push("CANCELLED");
} else if (normalized) {
list.push(normalized);
}
}
return list.length > 0 ? list : undefined;
}
export function getRuleBriefTitle(ruleId: string, desc?: string, scope?: string): string {
if (!desc) return scope ? `${ruleId} (${scope})` : ruleId;
const firstSentence = desc.split(/[。\n\r;;!!]/)[0]?.trim() || desc.trim();
const clean = firstSentence.replace(/[*#`_]/g, "").trim();
return clean.slice(0, 22);
}
export function resolveOutputFilePath(options: {
outputFile?: string;
toDownloads?: boolean;
corpName: string;
dateTag?: string;
recordCount: number;
}): string {
if (options.outputFile) {
const p = resolve(options.outputFile);
const dir = dirname(p);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
return p;
}
const safeCorpName = options.corpName.replace(/[/\\?%*:|"<>]/g, "_").trim() || "审批记录";
const dateTag = options.dateTag || new Date().toISOString().slice(0, 10);
const countTag = options.recordCount > 0 ? `${options.recordCount}条` : "空数据";
const fileName = `${safeCorpName}_审核记录_${dateTag}_${countTag}.xlsx`;
let targetDir: string;
if (options.toDownloads) {
targetDir = resolve(homedir(), "Downloads");
} else {
targetDir = resolve(process.cwd(), "exports");
}
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
return resolve(targetDir, fileName);
}
export async function exportApprovalRunsToExcel(
client: KyInstance,
corp: CorpConfig,
options: ApprovalRunsExportOptions = {}
): Promise<ApprovalRunsExportResult> {
const corpName = corp.name || corp.id;
const pageSize = options.pageSize ?? 100;
const pageDelayMs = options.pageDelayMs ?? 250;
const limit = options.limit ?? 100000;
const startDateTs = normalizeTimestamp(options.startDate, false);
const endDateTs = normalizeTimestamp(options.endDate, true);
const manualStatusFilter = normalizeManualApprovalStatus(options.manualApprovalStatus);
// 1. 动态加载企业规则集,生成列定义
console.error(`正在加载企业「${corpName}」审核规则集...`);
const ruleMap = new Map<string, { id: string; code: string; title: string; desc: string }>();
try {
const rulesData = await api.listApprovalRules(client);
rulesData.rules.forEach((r, idx) => {
const runtimeId = `rule-${r.code ?? idx}`;
const title = getRuleBriefTitle(runtimeId, r.description, r.scope);
ruleMap.set(runtimeId, {
id: runtimeId,
code: String(r.code ?? idx),
title: `[${runtimeId}] ${title}`,
desc: r.description
});
});
} catch (err: any) {
console.error(`⚠️ 加载规则字典失败: ${err.message},将仅导出基础信息列。`);
}
const sortedRuleKeys = Array.from(ruleMap.keys()).sort((a, b) => {
const numA = parseInt(a.replace(/\D/g, ""), 10) || 0;
const numB = parseInt(b.replace(/\D/g, ""), 10) || 0;
return numA - numB;
});
console.error(`已就绪 ${sortedRuleKeys.length} 个规则列。开始拉取单据...`);
// 2. 温和分页拉取单据记录
const fetchedRecords: ApprovalRun[] = [];
let offset = 0;
let totalAvailable = 0;
while (fetchedRecords.length < limit) {
let batch: ApprovalRunListData | undefined;
let retries = 3;
while (retries > 0) {
try {
batch = await api.listApprovalRuns(client, {
limit: pageSize,
offset,
startDate: startDateTs,
endDate: endDateTs,
status: options.status,
manualApprovalStatus: manualStatusFilter
});
break;
} catch (e: any) {
retries--;
console.error(`分页拉取失败 (offset=${offset}): ${e.message},剩余重试 ${retries} 次...`);
if (retries === 0) throw e;
await new Promise((r) => setTimeout(r, 1000));
}
}
if (!batch || !batch.records || batch.records.length === 0) break;
totalAvailable = batch.total ?? totalAvailable;
for (const r of batch.records) {
if (options.includeCompletedOnly && r.status !== "completed") {
continue;
}
// 如果是已完成单据但列表未附带规则结果,做安全补查
if (r.status === "completed" && (!r.result || !(r.result as any).rulesResult)) {
try {
const full = await api.getApprovalRun(client, r.id);
fetchedRecords.push(full);
} catch {
fetchedRecords.push(r);
}
} else {
fetchedRecords.push(r);
}
if (fetchedRecords.length >= limit) break;
}
offset += batch.records.length;
const currentProgress = totalAvailable > 0 ? ((offset / totalAvailable) * 100).toFixed(1) : "-";
if (offset % 500 === 0 || offset >= totalAvailable || fetchedRecords.length >= limit) {
console.error(
`[进度] 已读取单据: ${offset}/${totalAvailable} (${currentProgress}%),有效加入: ${fetchedRecords.length} 条`
);
}
if (batch.records.length < pageSize || offset >= totalAvailable) {
break;
}
if (pageDelayMs > 0) {
await new Promise((r) => setTimeout(r, pageDelayMs));
}
}
console.error(`成功拉取 ${fetchedRecords.length} 条单据数据,正在生成高保真 Excel...`);
// 3. 构建 Excel 工作簿
const workbook = new ExcelJS.Workbook();
workbook.creator = "Seal AI (seal-use)";
workbook.created = new Date();
const worksheet = workbook.addWorksheet("审核记录明细", {
views: [{ state: "frozen", ySplit: 1, xSplit: 2 }]
});
const baseColumns: Array<{ header: string; key: string; width: number }> = [
{ header: "单据编号", key: "sn", width: 16 },
{ header: "单据模板名称", key: "templateName", width: 26 },
{ header: "来源系统", key: "sourceSystem", width: 12 },
{ header: "任务模式", key: "taskMode", width: 12 },
{ header: "状态", key: "status", width: 12 },
{ header: "AI行为", key: "aiAction", width: 14 },
{ header: "AI决策", key: "aiDecision", width: 14 },
{ header: "思考深度", key: "thinkingDepth", width: 12 },
{ header: "人工审核", key: "manualStatus", width: 16 },
{ header: "人工驳回原因", key: "humanRejectReason", width: 36 },
{ header: "创建时间", key: "createdAt", width: 20 },
{ header: "任务耗时", key: "duration", width: 12 },
{ header: "关联规则数", key: "hitRuleCount", width: 12 },
{ header: "关联规则汇总", key: "hitRulesSummary", width: 30 },
{ header: "AI审核结论摘要", key: "aiSummary", width: 45 }
];
const ruleColumns = sortedRuleKeys.map((ruleKey) => {
const rInfo = ruleMap.get(ruleKey)!;
return {
header: rInfo.title,
key: `rule_${ruleKey}`,
width: 22
};
});
worksheet.columns = [...baseColumns, ...ruleColumns];
// 表头样式设置
const headerRow = worksheet.getRow(1);
headerRow.height = 32;
headerRow.eachCell((cell, colNumber) => {
const isBase = colNumber <= baseColumns.length;
cell.font = {
name: "Microsoft YaHei",
bold: true,
color: { argb: "FFFFFFFF" },
size: 11
};
cell.fill = {
type: "pattern",
pattern: "solid",
fgColor: { argb: isBase ? "FF1E3A8A" : "FF334155" }
};
cell.alignment = {
vertical: "middle",
horizontal: isBase && colNumber <= 2 ? "left" : "center",
wrapText: false
};
});
const statusCounts: Record<string, number> = {};
let rejectReasonCount = 0;
// 填充数据行
for (const record of fetchedRecords) {
const res = (record.result as any) || {};
const doc = (record.document as any) || {};
// 1. 提取单据模板名称
let templateName = "未知模板";
if (Array.isArray(doc.fields)) {
const tField = doc.fields.find(
(f: any) =>
f.label === "单据模板" ||
f.label === "流程名称" ||
f.key === "templateName" ||
f.key === "specificationId" ||
f.key === "formName"
);
if (tField?.value) templateName = String(tField.value);
}
if (templateName === "未知模板" && (doc.name || doc.title)) {
templateName = doc.name || doc.title;
}
// 2. 映射任务模式
let taskModeDesc = record.taskMode || "-";
if (taskModeDesc === "assisted") taskModeDesc = "辅助审核";
else if (taskModeDesc === "simulation") taskModeDesc = "测试任务";
else if (taskModeDesc === "automatic") taskModeDesc = "自动审批";
// 3. 映射状态
let statusDesc = record.status || "-";
if (statusDesc === "completed") statusDesc = "已完成";
else if (statusDesc === "processing") statusDesc = "处理中";
else if (statusDesc === "failed") statusDesc = "失败";
// 4. AI 决策与行为
const aiDecision = res.decision || (record as any).aiDecision || "-";
let aiDecisionDesc = aiDecision;
let aiAction = "-";
if (aiDecision === "APPROVE") {
aiDecisionDesc = "通过";
aiAction = "添加评论";
} else if (aiDecision === "REVIEW") {
aiDecisionDesc = "转交复核";
aiAction = "转交复核";
} else if (aiDecision === "REJECT") {
aiDecisionDesc = "驳回";
aiAction = "驳回";
}
// 5. 耗时计算
let durationStr = "-";
if (record.createdAt && record.updatedAt && record.status === "completed") {
const diffSec = Math.round((Number(record.updatedAt) - Number(record.createdAt)) / 1000);
if (diffSec >= 60) {
durationStr = `${Math.floor(diffSec / 60)}分${diffSec % 60}秒`;
} else if (diffSec > 0) {
durationStr = `${diffSec}秒`;
}
}
// 6. 人工审核状态与驳回原因
const mar = (record as any).manualApprovalRecord || {};
let manualStatus = "-";
if (mar.status?.label) {
manualStatus = String(mar.status.label);
} else if (mar.status?.type) {
const t = String(mar.status.type);
if (t === "APPROVED") manualStatus = "已通过";
else if (t === "TERMINATED") manualStatus = "被驳回";
else if (t === "PROCESSING") manualStatus = "处理中";
else if (t === "CANCELLED") manualStatus = "已撤回";
else manualStatus = t;
}
statusCounts[manualStatus] = (statusCounts[manualStatus] || 0) + 1;
const humanRejectReason = mar.rejectComment ? String(mar.rejectComment).trim() : "-";
if (humanRejectReason !== "-") {
rejectReasonCount++;
}
// 7. 解析规则核验结果
const ruleResultMap = new Map<string, string>();
const hitRuleIds: string[] = [];
if (Array.isArray(res.rulesResult)) {
for (const rr of res.rulesResult) {
if (rr.id) {
ruleResultMap.set(rr.id, rr.checkResult || "PASS");
hitRuleIds.push(rr.id);
}
}
}
if (Array.isArray(res.hitRules)) {
for (const hr of res.hitRules) {
if (hr.id && !ruleResultMap.has(hr.id)) {
ruleResultMap.set(hr.id, "TRIGGERED");
hitRuleIds.push(hr.id);
}
}
}
// 8. 创建时间
let createdAtStr = "-";
if (record.createdAt) {
const d = new Date(Number(record.createdAt));
createdAtStr = d.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai", hour12: false });
}
const rowData: Record<string, any> = {
sn: record.sourceDocumentSN || record.sourceDocumentId || "-",
templateName,
sourceSystem: record.sourceSystem || "合思",
taskMode: taskModeDesc,
status: statusDesc,
aiAction,
aiDecision: aiDecisionDesc,
thinkingDepth: "标准",
manualStatus,
humanRejectReason,
createdAt: createdAtStr,
duration: durationStr,
hitRuleCount: hitRuleIds.length,
hitRulesSummary: hitRuleIds.join(", ") || "-",
aiSummary: res.summary || "-"
};
for (const ruleKey of sortedRuleKeys) {
const checkResult = ruleResultMap.get(ruleKey);
if (checkResult) {
if (checkResult === "PASS") rowData[`rule_${ruleKey}`] = "关联 (通过)";
else if (checkResult === "FAIL") rowData[`rule_${ruleKey}`] = "关联 (不通过)";
else if (checkResult === "UNKNOWN") rowData[`rule_${ruleKey}`] = "关联 (待复核)";
else rowData[`rule_${ruleKey}`] = "已关联";
} else {
rowData[`rule_${ruleKey}`] = "未关联";
}
}
const addedRow = worksheet.addRow(rowData);
addedRow.height = 24;
addedRow.eachCell((cell, colNumber) => {
const val = String(cell.value || "");
cell.font = { name: "Microsoft YaHei", size: 10 };
cell.border = {
top: { style: "thin", color: { argb: "FFE2E8F0" } },
bottom: { style: "thin", color: { argb: "FFE2E8F0" } },
left: { style: "thin", color: { argb: "FFE2E8F0" } },
right: { style: "thin", color: { argb: "FFE2E8F0" } }
};
if (colNumber <= baseColumns.length) {
cell.alignment = {
vertical: "middle",
horizontal: [1, 2, 10, 14, 15].includes(colNumber) ? "left" : "center",
wrapText: [10, 14, 15].includes(colNumber)
};
// AI 决策颜色区分
if (colNumber === 7) {
if (val === "通过") cell.font = { color: { argb: "FF16A34A" }, bold: true };
else if (val === "转交复核") cell.font = { color: { argb: "FFD97706" }, bold: true };
else if (val === "驳回") cell.font = { color: { argb: "FFDC2626" }, bold: true };
}
// 人工审核高亮
if (colNumber === 9) {
if (val.includes("驳回")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FFDC2626" }, bold: true };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } };
} else if (val.includes("通过") || val.includes("支付") || val.includes("完成")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF16A34A" }, bold: true };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFDCFCE7" } };
} else if (val.includes("处理中") || val.includes("审批中")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF2563EB" } };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFEFF6FF" } };
}
}
// 人工驳回原因字体
if (colNumber === 10 && val !== "-") {
cell.font = { name: "Microsoft YaHei", size: 9, color: { argb: "FF991B1B" } };
}
} else {
cell.alignment = { vertical: "middle", horizontal: "center" };
if (val.includes("不通过")) {
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } };
cell.font = { color: { argb: "FF991B1B" }, bold: true };
} else if (val.includes("通过")) {
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFDCFCE7" } };
cell.font = { color: { argb: "FF166534" }, bold: true };
} else if (val.includes("待复核") || val.includes("已关联")) {
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEF3C7" } };
cell.font = { color: { argb: "FF92400E" } };
} else {
cell.font = { color: { argb: "FF94A3B8" } };
}
}
});
}
// 4. 保存文件落地
let dateTag: string | undefined;
if (options.startDate) {
const rawStart = String(options.startDate);
if (/^\d{4}-\d{2}-\d{2}/.test(rawStart)) {
dateTag = `${rawStart.slice(0, 10)}至今`;
} else if (/^\d+$/.test(rawStart)) {
const d = new Date(Number(rawStart));
dateTag = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, "0")}${String(d.getDate()).padStart(2, "0")}至今`;
}
}
const targetPath = resolveOutputFilePath({
outputFile: options.outputFile,
toDownloads: options.toDownloads,
corpName,
dateTag,
recordCount: fetchedRecords.length
});
await workbook.xlsx.writeFile(targetPath);
console.error(`Excel 文件已成功落地: ${targetPath}`);
const stat = statSync(targetPath);
return {
filePath: targetPath,
corpId: corp.id,
corpName,
recordCount: fetchedRecords.length,
ruleColumnCount: sortedRuleKeys.length,
statusCounts,
rejectReasonCount,
fileSizeBytes: stat.size,
exportedAt: new Date().toISOString()
};
}
+1 -1
View File
@@ -46,7 +46,7 @@ export function listAvailableLinters(): Array<{ name: string; type: "builtin" |
return list;
}
export function resolveLinterPath(nameOrPath: string): string | undefined {
function resolveLinterPath(nameOrPath: string): string | undefined {
if (!nameOrPath || nameOrPath === "builtin") {
return undefined;
}
+146 -43
View File
@@ -1,51 +1,154 @@
import { pinyin } from "pinyin-pro";
import type { MaterialAttachmentPlan, MaterialDocument, MaterialField } from "./types.js";
import type { ZipEntry } from "./validate.js";
import type { AttachmentGroup, MaterialAttachmentPlan, MaterialDocument, MaterialField } from "./types.js"
import { MaterialPackValidationError } from "./types.js"
import type { ZipEntry } from "./validate.js"
import type { Parsed } from "./parse.js"
function keyFromLabel(value: string): string {
const label = value.replace(/^\d+[\s.\-_—]*/, "").trim();
const parts = pinyin(label, { toneType: "none", type: "all", nonZh: "consecutive" })
.map((item: any) => item.pinyin ? item.pinyin : String(item.origin).toLowerCase().replace(/[^a-z0-9]+/g, ""))
.filter(Boolean);
return parts.join("") || "attachments";
// ─── Key deduplication (applied at call site in parse.ts; exported for tests) ─
export function deduplicateKeys(groups: AttachmentGroup[]): AttachmentGroup[] {
const seen = new Map<string, number>()
return groups.map((g) => {
const count = (seen.get(g.key) ?? 0) + 1
seen.set(g.key, count)
return count === 1 ? g : { ...g, key: `${g.key}-${count}` }
})
}
export function buildAttachmentPlans(entries: ZipEntry[], documents: Array<{ document: MaterialDocument; laborNames: string[] }>): MaterialAttachmentPlan[] {
return documents.map(({ document, laborNames }) => {
const plan: MaterialAttachmentPlan = { documentId: document.documentId, categoryFields: [], personAttachments: {} };
for (const entry of entries) {
if (entry.fileName === "信息表.xlsx") continue;
const segments = entry.fileName.split("/");
if (segments[0] !== document.documentId || segments.length < 2) continue;
const add = (list: Array<{ key: string; label: string; entries: any[] }>, label: string) => {
const clean = label.replace(/^\d+[\s.\-_—]*/, "");
const item = list.find((value) => value.label === clean) ?? { key: clean === "附件" ? "attachments" : keyFromLabel(clean), label: clean, entries: [] };
if (!list.includes(item)) list.push(item);
item.entries.push({ fileName: entry.fileName, path: entry.fileName, size: entry.uncompressedSize });
};
if (segments.length === 2) add(plan.categoryFields, "附件");
else if (laborNames.includes(segments[1]!)) {
const list = plan.personAttachments[segments[1]!] ?? (plan.personAttachments[segments[1]!] = []);
add(list, segments.length === 3 ? "附件" : segments[2]!);
} else add(plan.categoryFields, segments[1]!);
// ─── Build attachment plans with strict bidirectional validation ──────────────
export function buildAttachmentPlans(
entries: ZipEntry[],
parsed: Parsed[]
): MaterialAttachmentPlan[] {
const errors: string[] = []
// Map of path -> Array of declaration locations: { documentId, location }
const declaredPathLocations = new Map<string, Array<{ documentId: string; location: string }>>()
const plans: MaterialAttachmentPlan[] = parsed.map((item) => {
const { documentAttachments, expenseAttachments, personAttachments } = item
const docId = item.document.documentId
const recordPath = (path: string, location: string) => {
// 1. Check directory scope: path must start with docId/ or docId@.../
const rootDir = path.split("/")[0]!
const atIdx = rootDir.indexOf("@")
const dirDocId = atIdx >= 0 ? rootDir.slice(0, atIdx) : rootDir
if (dirDocId !== docId) {
errors.push(
`单据「${docId}」声明了跨单据或非本单据目录的附件路径: ${path}。附件必须位于该单据自己的根目录「${docId}/」或「${docId}@备注/」下。`
)
}
// 2. Track path location for uniqueness check
const existing = declaredPathLocations.get(path)
if (existing) {
existing.push({ documentId: docId, location })
} else {
declaredPathLocations.set(path, [{ documentId: docId, location }])
}
}
return plan;
});
}
export function injectAttachmentPlan(document: MaterialDocument, plan: MaterialAttachmentPlan, uploaded: Map<string, unknown[]>): MaterialDocument {
const clone = structuredClone(document);
const lookup = (path: string) => uploaded.get(path) ?? [];
for (const category of plan.categoryFields) {
const value = category.entries.flatMap((entry) => lookup(entry.path));
clone.fields.push({ key: category.key, label: category.label, type: "ATTACHMENT", value });
}
const list = clone.fields.find((item) => item.key === "daoshi_list" && item.type === "LIST");
if (list && Array.isArray(list.value)) {
for (const row of list.value as MaterialField[][]) {
const name = row.find((item) => item.key === "name")?.value;
for (const category of plan.personAttachments[String(name)] ?? []) row.push({ key: category.key, label: category.label, type: "ATTACHMENT", value: category.entries.flatMap((entry) => lookup(entry.path)) });
for (const g of documentAttachments) {
g.paths.forEach((p) => recordPath(p, `主表 [附件]${g.label}`))
}
for (const [rowIdxStr, groups] of Object.entries(expenseAttachments)) {
const rowNum = Number(rowIdxStr) + 1
for (const g of groups) {
g.paths.forEach((p) => recordPath(p, `费用明细行 ${rowNum} [附件]${g.label}`))
}
}
for (const [personName, groups] of Object.entries(personAttachments)) {
for (const g of groups) {
g.paths.forEach((p) => recordPath(p, `劳务人员「${personName}」[附件]${g.label}`))
}
}
return {
documentId: docId,
categoryFields: documentAttachments,
expenseAttachments,
personAttachments,
}
})
// Duplicate path check: the same path cannot be declared multiple times (even in same document)
for (const [path, locs] of declaredPathLocations.entries()) {
if (locs.length > 1) {
const locDescriptions = locs.map((l) => `单据「${l.documentId}」的 ${l.location}`).join("、")
errors.push(
`附件路径「${path}」被重复声明了 ${locs.length} 次(出现在 ${locDescriptions})。禁止复用同一路径,若需在不同单据或不同字段使用,请分别放置到独立的附件文件路径。`
)
}
}
return clone;
// xlsx-only mode: skip file-level checks against ZIP entries
if (!entries.length) {
if (errors.length) throw new MaterialPackValidationError(errors)
return plans
}
// Check 3: every declared path must exist as a ZIP entry
const zipFileSet = new Set(entries.map((e) => e.fileName))
for (const path of declaredPathLocations.keys()) {
if (!zipFileSet.has(path)) {
errors.push(`Excel 声明的附件路径在 ZIP 中不存在: ${path}`)
}
}
// Check 4: every ZIP file (non-信息表.xlsx) must be declared in exactly one [附件] column
for (const entry of entries) {
if (entry.fileName === "信息表.xlsx") continue
if (!declaredPathLocations.has(entry.fileName)) {
errors.push(`ZIP 中的文件未在 Excel 任何 [附件] 列中声明: ${entry.fileName}`)
}
}
if (errors.length) throw new MaterialPackValidationError(errors)
return plans
}
// ─── Inject attachment plan into document ─────────────────────────────────────
export function injectAttachmentPlan(
document: MaterialDocument,
plan: MaterialAttachmentPlan,
uploaded: Map<string, unknown[]>
): MaterialDocument {
const clone = structuredClone(document)
const lookup = (path: string) => {
if (uploaded.has(path)) return uploaded.get(path)!
// preview fallback: return a placeholder representing the file
return [{ path, fileName: path.split("/").pop() ?? path }]
}
// Root-level document fields
for (const group of plan.categoryFields) {
const value = group.paths.flatMap(lookup)
clone.fields.push({ key: group.key, label: group.label, type: "ATTACHMENT", value })
}
// daoshi_list (labor) rows
const laborList = clone.fields.find((f) => f.key === "daoshi_list" && f.type === "LIST")
if (laborList && Array.isArray(laborList.value)) {
for (const row of laborList.value as MaterialField[][]) {
const name = row.find((f) => f.key === "name")?.value
for (const group of plan.personAttachments[String(name)] ?? []) {
row.push({ key: group.key, label: group.label, type: "ATTACHMENT", value: group.paths.flatMap(lookup) })
}
}
}
// mingxi_list (expense) rows
const expenseList = clone.fields.find((f) => f.key === "mingxi_list" && f.type === "LIST")
if (expenseList && Array.isArray(expenseList.value)) {
for (let i = 0; i < expenseList.value.length; i++) {
const row = expenseList.value[i] as MaterialField[]
for (const group of plan.expenseAttachments[i] ?? []) {
row.push({ key: group.key, label: group.label, type: "ATTACHMENT", value: group.paths.flatMap(lookup) })
}
}
}
return clone
}
+2
View File
@@ -1,6 +1,8 @@
export * from "./types.js";
export * from "./policy.js";
export * from "./signature.js";
export * from "./validate.js";
export * from "./parse.js";
export * from "./attachments.js";
export * from "./service.js";
export * from "./ready.js";
@@ -1,29 +1,489 @@
import ExcelJS from "exceljs";
import { describe, expect, test } from "bun:test";
import { previewMaterialPack } from "./service.js";
import { signWebhookPayload } from "./signature.js";
import ExcelJS from "exceljs"
import { describe, expect, test } from "bun:test"
import { previewMaterialPack } from "./service.js"
import { signWebhookPayload } from "./signature.js"
import {
isAttachmentColumn,
attachmentLabel,
attachmentKey,
parsePaths,
collectRowAttachments,
} from "./parse.js"
import { buildAttachmentPlans } from "./attachments.js"
import { MaterialPackValidationError } from "./types.js"
// ─── Workbook fixtures ────────────────────────────────────────────────────────
async function workbookBuffer() {
const workbook = new ExcelJS.Workbook();
const main = workbook.addWorksheet("会议");
main.addRow(["会议编号", "会议名称", "总金额", "申请日期"]);
main.addRow(["DOC-001", "测试单据", 100, "2026-09-03 12:00:00"]);
const labor = workbook.addWorksheet("劳务明细");
labor.addRow(["会议编号", "姓名", "劳务费用"]);
labor.addRow(["DOC-001", "张三", 100]);
return Buffer.from(await workbook.xlsx.writeBuffer());
const workbook = new ExcelJS.Workbook()
const main = workbook.addWorksheet("会议")
main.addRow(["会议编号", "会议名称", "总金额", "申请日期", "[附件]合同协议", "[附件]支付凭证"])
main.addRow(["DOC-001", "测试单据", 100, "2026-09-03 12:00:00", "", ""])
const labor = workbook.addWorksheet("劳务明细")
labor.addRow(["会议编号", "姓名", "劳务费用", "[附件]身份证"])
labor.addRow(["DOC-001", "张三", 100, ""])
return Buffer.from(await workbook.xlsx.writeBuffer())
}
async function workbookWithAttachmentPaths() {
const workbook = new ExcelJS.Workbook()
const main = workbook.addWorksheet("会议")
main.addRow(["会议编号", "会议名称", "总金额", "申请日期", "[附件]合同协议", "[附件]支付凭证"])
main.addRow([
"DOC-001",
"测试单据",
100,
"2026-09-03 12:00:00",
"DOC-001/合同协议/采购合同.pdf",
"DOC-001/支付凭证/支付宝.pdf",
])
return Buffer.from(await workbook.xlsx.writeBuffer())
}
// ─── Unit tests: attachment column helpers ───────────────────────────────────
describe("attachment column helpers", () => {
test("isAttachmentColumn", () => {
expect(isAttachmentColumn("[附件]合同协议")).toBe(true)
expect(isAttachmentColumn("合同协议")).toBe(false)
expect(isAttachmentColumn("[附件]")).toBe(true)
})
test("attachmentLabel strips prefix", () => {
expect(attachmentLabel("[附件]合同协议")).toBe("合同协议")
expect(attachmentLabel("合同协议")).toBe("合同协议")
})
test("attachmentKey lowercases and replaces spaces", () => {
expect(attachmentKey("[附件]Contract Doc")).toBe("contract_doc")
expect(attachmentKey("[附件]合同协议")).toBe("合同协议")
})
test("parsePaths splits by newline, comma, semicolon", () => {
expect(parsePaths("a/b.pdf\nc/d.pdf")).toEqual(["a/b.pdf", "c/d.pdf"])
expect(parsePaths("a/b.pdf,c/d.pdf")).toEqual(["a/b.pdf", "c/d.pdf"])
expect(parsePaths("a/b.pdf;c/d.pdf")).toEqual(["a/b.pdf", "c/d.pdf"])
expect(parsePaths("a/b.pdf,c/d.pdf")).toEqual(["a/b.pdf", "c/d.pdf"])
expect(parsePaths(null)).toEqual([])
expect(parsePaths("")).toEqual([])
})
})
// ─── Unit tests: buildAttachmentPlans ───────────────────────────────────────
describe("buildAttachmentPlans", () => {
test("xlsx-only mode: no file checks performed", async () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
]
// No ZIP entries = xlsx-only mode, no validation
const plans = buildAttachmentPlans([], parsed)
expect(plans).toHaveLength(1)
expect(plans[0]?.categoryFields[0]?.paths).toEqual(["DOC-001/合同/a.pdf"])
})
test("throws when Excel declares path missing from ZIP", async () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001/合同/b.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
expect(() => buildAttachmentPlans(entries, parsed)).toThrow(MaterialPackValidationError)
try {
buildAttachmentPlans(entries, parsed)
} catch (e) {
const err = e as MaterialPackValidationError
expect(err.errors.some((m) => m.includes("DOC-001/合同/a.pdf") && m.includes("不存在"))).toBe(true)
expect(err.errors.some((m) => m.includes("DOC-001/合同/b.pdf") && m.includes("未在 Excel"))).toBe(true)
}
})
test("throws when ZIP file is not declared in any [附件] column", async () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001/合同/a.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001/合同/undeclared.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
expect(() => buildAttachmentPlans(entries, parsed)).toThrow(MaterialPackValidationError)
try {
buildAttachmentPlans(entries, parsed)
} catch (e) {
const err = e as MaterialPackValidationError
expect(err.errors.some((m) => m.includes("undeclared.pdf"))).toBe(true)
}
})
test("passes when all paths match bidirectionally", () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001/合同/a.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
const plans = buildAttachmentPlans(entries, parsed)
expect(plans[0]?.categoryFields[0]?.paths).toEqual(["DOC-001/合同/a.pdf"])
})
test("throws when document declares attachment outside its own directory", () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-002/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
{
document: { type: "document" as const, documentId: "DOC-002", documentSN: "DOC-002", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [],
expenseAttachments: {},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-002/合同/a.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
try {
buildAttachmentPlans(entries, parsed)
expect(true).toBe(false)
} catch (e) {
const err = e as MaterialPackValidationError
expect(err.errors.some((m) => m.includes("DOC-001") && m.includes("跨单据或非本单据目录"))).toBe(true)
}
})
test("throws when same path is declared multiple times within the same document", () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {
0: [{ key: "invoice", label: "发票", paths: ["DOC-001/合同/a.pdf"] }],
},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001/合同/a.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
try {
buildAttachmentPlans(entries, parsed)
expect(true).toBe(false)
} catch (e) {
const err = e as MaterialPackValidationError
expect(err.errors.some((m) => m.includes("重复声明") && m.includes("DOC-001/合同/a.pdf"))).toBe(true)
}
})
test("throws when same path is declared across different documents", () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
{
document: { type: "document" as const, documentId: "DOC-002", documentSN: "DOC-002", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001/合同/a.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
try {
buildAttachmentPlans(entries, parsed)
expect(true).toBe(false)
} catch (e) {
const err = e as MaterialPackValidationError
expect(err.errors.some((m) => m.includes("重复声明") && m.includes("DOC-001/合同/a.pdf"))).toBe(true)
}
})
test("accepts attachment paths in directory with @annotation", () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001@广州技术服务/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001@广州技术服务/合同/a.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
const plans = buildAttachmentPlans(entries, parsed)
expect(plans).toHaveLength(1)
expect(plans[0]?.categoryFields[0]?.paths).toEqual(["DOC-001@广州技术服务/合同/a.pdf"])
})
})
// ─── Integration tests: previewMaterialPack ──────────────────────────────────
describe("Webhook material pack", () => {
test("previews official workbook shape without network access", async () => {
const result = await previewMaterialPack(await workbookBuffer(), "材料包.xlsx");
expect(result.documents).toHaveLength(1);
expect(result.documents[0]).toMatchObject({ documentId: "DOC-001", documentSN: "DOC-001" });
expect(result.documents[0]?.fields).toContainEqual(expect.objectContaining({ key: "daoshi_list", type: "LIST" }));
});
const result = await previewMaterialPack(await workbookBuffer(), "材料包.xlsx")
expect(result.documents).toHaveLength(1)
expect(result.documents[0]).toMatchObject({ documentId: "DOC-001", documentSN: "DOC-001" })
expect(result.documents[0]?.fields).toContainEqual(expect.objectContaining({ key: "daoshi_list", type: "LIST" }))
})
test("parses [附件] columns from main sheet into categoryFields", async () => {
const result = await previewMaterialPack(await workbookWithAttachmentPaths(), "材料包.xlsx")
const plan = result.attachmentPlan[0]!
expect(plan.categoryFields).toHaveLength(2)
expect(plan.categoryFields[0]).toMatchObject({ label: "合同协议", paths: ["DOC-001/合同协议/采购合同.pdf"] })
expect(plan.categoryFields[1]).toMatchObject({ label: "支付凭证", paths: ["DOC-001/支付凭证/支付宝.pdf"] })
})
test("injects ATTACHMENT fields into document on preview", async () => {
const result = await previewMaterialPack(await workbookWithAttachmentPaths(), "材料包.xlsx")
const doc = result.documents[0]!
const contractField = doc.fields.find((f) => f.label === "合同协议")
expect(contractField).toBeDefined()
expect(contractField?.type).toBe("ATTACHMENT")
expect(Array.isArray(contractField?.value)).toBe(true)
})
test("uses the confirmed timestamp.nonce.payload HMAC contract", () => {
expect(signWebhookPayload(1700000000, "nonce", { webhookId: "wh-1", value: 1 }, "secret"))
.toBe("d65d858afb6adc33dc640ebc6b259861c2b73ef0e6f0995ff822b41465fbfdf1");
});
});
.toBe("d65d858afb6adc33dc640ebc6b259861c2b73ef0e6f0995ff822b41465fbfdf1")
})
test("checkWebhookReadiness locks single webhook as default", async () => {
const { checkWebhookReadiness } = await import("./ready.js")
const mockCorp: any = {
id: "test-corp",
name: "测试企业",
seal: { url: "https://test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
source: { type: "seal" }
}
const client: any = {
get: (url: string) => {
if (url.includes("auth/me")) return { json: async () => ({ data: { user: { id: "u-1", name: "管理员", tenantId: "t-1" }, tenant: { id: "t-1", name: "测试租户" } } }) }
if (url.includes("ai-approval/config")) return {
json: async () => ({
data: {
integrations: [{
type: "webhook",
id: "wh-only",
name: "唯一通道",
mode: "assisted",
incomingDocumentWebhook: { id: "in-1", url: "https://test.sealai.cc/webhook/wh-only/document" },
outgoingResultWebhook: "https://example.com/callback",
incomingManualResultWebhook: { id: "man-1", url: "https://test.sealai.cc/webhook/wh-only/manual" },
secret: "sec-1"
}]
}
})
}
throw new Error(url)
}
}
const res = await checkWebhookReadiness(client, mockCorp)
expect(res.ready).toBe(true)
expect(res.authStatus).toBe("ok")
expect(res.corp.name).toBe("测试企业")
expect(res.corp.tenant?.name).toBe("测试租户")
expect(res.activeWebhooks).toHaveLength(1)
expect(res.activeWebhooks[0]?.isDefault).toBe(true)
expect(res.defaultWebhook).toEqual({ id: "wh-only", name: "唯一通道", mode: "assisted" })
expect(res.nextAction).toContain("seal-use webhook material-pack push")
expect(res.statusMessage).toContain("已自动锁定唯一 Webhook 通道")
})
test("checkWebhookReadiness lists multiple webhooks without auto-locking", async () => {
const { checkWebhookReadiness } = await import("./ready.js")
const mockCorp: any = {
id: "test-corp",
name: "测试企业",
seal: { url: "https://test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
source: { type: "seal" }
}
const client: any = {
get: (url: string) => {
if (url.includes("auth/me")) return { json: async () => ({ data: { user: { id: "u-1", name: "管理员", tenantId: "t-1" }, tenant: { id: "t-1", name: "测试租户" } } }) }
if (url.includes("ai-approval/config")) return {
json: async () => ({
data: {
integrations: [
{
type: "webhook",
id: "wh-1",
name: "通道A",
mode: "assisted",
incomingDocumentWebhook: { id: "in-1", url: "https://test.sealai.cc/webhook/wh-1/document" },
outgoingResultWebhook: "https://example.com/callback-a",
incomingManualResultWebhook: { id: "man-1", url: "https://test.sealai.cc/webhook/wh-1/manual" },
secret: "sec-1"
},
{
type: "webhook",
id: "wh-2",
name: "通道B",
mode: "fully_automatic",
incomingDocumentWebhook: { id: "in-2", url: "https://test.sealai.cc/webhook/wh-2/document" },
outgoingResultWebhook: "https://example.com/callback-b",
incomingManualResultWebhook: { id: "man-2", url: "https://test.sealai.cc/webhook/wh-2/manual" },
secret: "sec-2"
}
]
}
})
}
throw new Error(url)
}
}
const res = await checkWebhookReadiness(client, mockCorp)
expect(res.ready).toBe(true)
expect(res.activeWebhooks).toHaveLength(2)
expect(res.defaultWebhook).toBeNull()
expect(res.activeWebhooks[0]?.isDefault).toBeUndefined()
expect(res.nextAction).toContain("--webhook <webhookIdOrName>")
expect(res.statusMessage).toContain("检测到 2 个 Webhook 通道")
})
test("checkWebhookReadiness flags not ready when no webhooks exist", async () => {
const { checkWebhookReadiness } = await import("./ready.js")
const mockCorp: any = {
id: "test-corp",
name: "测试企业",
seal: { url: "https://test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
source: { type: "seal" }
}
const client: any = {
get: (url: string) => {
if (url.includes("auth/me")) return { json: async () => ({ data: { user: { id: "u-1", name: "管理员", tenantId: "t-1" }, tenant: { id: "t-1", name: "测试租户" } } }) }
if (url.includes("ai-approval/config")) return { json: async () => ({ data: { integrations: [] } }) }
throw new Error(url)
}
}
const res = await checkWebhookReadiness(client, mockCorp)
expect(res.ready).toBe(false)
expect(res.activeWebhooks).toHaveLength(0)
expect(res.nextAction).toContain("seal-use webhook add")
})
test("checkWebhookReadiness flags not ready when auth fails", async () => {
const { checkWebhookReadiness } = await import("./ready.js")
const mockCorp: any = {
id: "test-corp",
name: "测试企业",
seal: { url: "https://test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
source: { type: "seal" }
}
const client: any = {
get: () => {
throw new Error("401 Unauthorized")
}
}
const res = await checkWebhookReadiness(client, mockCorp)
expect(res.ready).toBe(false)
expect(res.authStatus).toBe("error")
expect(res.nextAction).toContain("seal-use auth diagnose")
})
test("checkWebhookReadiness validates material pack file when provided", async () => {
const { checkWebhookReadiness } = await import("./ready.js")
const mockCorp: any = {
id: "test-corp",
name: "测试企业",
seal: { url: "https://test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
source: { type: "seal" }
}
const client: any = {
get: (url: string) => {
if (url.includes("auth/me")) return { json: async () => ({ data: { user: { id: "u-1", name: "管理员", tenantId: "t-1" }, tenant: { id: "t-1", name: "测试租户" } } }) }
if (url.includes("ai-approval/config")) return {
json: async () => ({
data: {
integrations: [{
type: "webhook",
id: "wh-1",
name: "通道A",
mode: "assisted",
incomingDocumentWebhook: { id: "in-1", url: "https://test.sealai.cc/webhook/wh-1/document" },
outgoingResultWebhook: "https://example.com/callback",
incomingManualResultWebhook: { id: "man-1", url: "https://test.sealai.cc/webhook/wh-1/manual" },
secret: "sec-1"
}]
}
})
}
throw new Error(url)
}
}
const notFoundRes = await checkWebhookReadiness(client, mockCorp, { filePath: "/tmp/non-existent-pack.zip" })
expect(notFoundRes.ready).toBe(false)
expect(notFoundRes.materialPack?.valid).toBe(false)
expect(notFoundRes.statusMessage).toContain("材料包预检失败")
const tmpFile = `/tmp/test-material-${Date.now()}.xlsx`
const { writeFileSync, unlinkSync } = await import("node:fs")
writeFileSync(tmpFile, await workbookBuffer())
try {
const validRes = await checkWebhookReadiness(client, mockCorp, { filePath: tmpFile })
expect(validRes.ready).toBe(true)
expect(validRes.materialPack?.valid).toBe(true)
expect(validRes.materialPack?.documentCount).toBe(1)
expect(validRes.nextAction).toContain(tmpFile)
} finally {
unlinkSync(tmpFile)
}
})
test("@ annotation in ZIP dir names is accepted by validateDocIdDirectories", async () => {
// This tests that DOC-001@重新提交v2 correctly matches documentId DOC-001
// We build a ZIP-like structure by constructing entries manually and checking service's prepare path
// Since we can't easily build a real ZIP without writing to disk, we test the logic via buildAttachmentPlans
// with the paths already having the @annotation stripped in service.ts
// Verify the path stripping logic: if a ZIP entry has root "DOC-001@v2", its documentId becomes "DOC-001"
const rootWithAnnotation = "DOC-001@重新提交v2"
const atIdx = rootWithAnnotation.indexOf("@")
const stripped = atIdx >= 0 ? rootWithAnnotation.slice(0, atIdx) : rootWithAnnotation
expect(stripped).toBe("DOC-001")
})
})
+158 -57
View File
@@ -1,44 +1,107 @@
import ExcelJS from "exceljs";
import { MaterialPackValidationError, type MaterialDocument, type MaterialField } from "./types.js";
import ExcelJS from "exceljs"
import { MaterialPackValidationError, type MaterialDocument, type MaterialField } from "./types.js"
type Parsed = { document: MaterialDocument; laborNames: string[] };
export type DeclaredAttachment = { key: string; label: string; paths: string[] }
export type Parsed = {
document: MaterialDocument;
laborNames: string[];
documentAttachments: DeclaredAttachment[];
expenseAttachments: Record<number, DeclaredAttachment[]>;
personAttachments: Record<string, DeclaredAttachment[]>;
}
// ─── Attachment column helpers ───────────────────────────────────────────────
export function isAttachmentColumn(label: string): boolean {
return label.startsWith("[附件]")
}
export function attachmentLabel(label: string): string {
return label.startsWith("[附件]") ? label.slice(4) : label
}
export function attachmentKey(label: string): string {
const stripped = attachmentLabel(label)
return stripped.toLowerCase().replace(/\s+/g, "_") || "attachment"
}
export function parsePaths(raw: unknown): string[] {
if (raw == null || raw === "") return []
return String(raw)
.split(/[\n,;,;]/)
.map((s) => s.trim())
.filter(Boolean)
}
export function collectRowAttachments(
row: ExcelJS.Row,
map: Map<string, number>
): DeclaredAttachment[] {
const groups: DeclaredAttachment[] = []
for (const [colLabel, colIdx] of map.entries()) {
if (!isAttachmentColumn(colLabel)) continue
const raw = row.getCell(colIdx).value
const paths = parsePaths(raw)
if (!paths.length) continue
groups.push({
key: attachmentKey(colLabel),
label: attachmentLabel(colLabel),
paths,
})
}
return groups
}
// ─── Key deduplication ───────────────────────────────────────────────────────
function deduplicateKeys(groups: DeclaredAttachment[]): DeclaredAttachment[] {
const seen = new Map<string, number>()
return groups.map((g) => {
const count = (seen.get(g.key) ?? 0) + 1
seen.set(g.key, count)
return count === 1 ? g : { ...g, key: `${g.key}-${count}` }
})
}
// ─── Field builders ──────────────────────────────────────────────────────────
function field(key: string, label: string, type: string, value: unknown): MaterialField {
return { key, label, type, value };
return { key, label, type, value }
}
function text(key: string, label: string, value: unknown) {
return field(key, label, "TEXT", value == null ? "" : String(value));
return field(key, label, "TEXT", value == null ? "" : String(value))
}
function amount(key: string, label: string, value: unknown) {
return field(key, label, "AMOUNT", typeof value === "number" ? { amount: value, currency: "CNY" } : null);
return field(key, label, "AMOUNT", typeof value === "number" ? { amount: value, currency: "CNY" } : null)
}
function dateValue(value: unknown): string | null {
if (value instanceof Date) return value.toISOString();
if (typeof value === "string" && value.trim()) return value.trim();
return null;
if (value instanceof Date) return value.toISOString()
if (typeof value === "string" && value.trim()) return value.trim()
return null
}
function startTimeValue(value: unknown): number | null {
if (value instanceof Date) return Math.floor(value.getTime() / 1000);
if (value instanceof Date) return Math.floor(value.getTime() / 1000)
if (typeof value === "string" && value.trim()) {
const timestamp = Date.parse(value.trim().replace(" ", "T"));
if (Number.isFinite(timestamp)) return Math.floor(timestamp / 1000);
const timestamp = Date.parse(value.trim().replace(" ", "T"))
if (Number.isFinite(timestamp)) return Math.floor(timestamp / 1000)
}
return null;
return null
}
function headerMap(sheet: ExcelJS.Worksheet): Map<string, number> {
const map = new Map<string, number>();
sheet.getRow(1).eachCell((cell, index) => map.set(String(cell.value ?? "").trim(), index));
return map;
const map = new Map<string, number>()
sheet.getRow(1).eachCell((cell, index) => map.set(String(cell.value ?? "").trim(), index))
return map
}
function cell(row: ExcelJS.Row, map: Map<string, number>, name: string): unknown {
const index = map.get(name);
return index ? row.getCell(index).value : undefined;
const index = map.get(name)
return index ? row.getCell(index).value : undefined
}
function buildMainFields(row: ExcelJS.Row, map: Map<string, number>): MaterialField[] {
@@ -47,53 +110,91 @@ function buildMainFields(row: ExcelJS.Row, map: Map<string, number>): MaterialFi
["总金额", "total_amount", "AMOUNT"], ["税前劳务总额", "pretax_labor_total", "AMOUNT"],
["报销事由", "reimbursement_reason", "TEXT"], ["po码", "po_code", "TEXT"], ["快递单号", "tracking_number", "TEXT"],
["申请日期", "application_date", "DATE"], ["更新日期", "updated_date", "DATE"]
];
]
return specs.flatMap(([label, key, type]) => {
const value = cell(row, map, label);
if (value == null || value === "") return [];
return [type === "TEXT" ? text(key, label, value) : type === "AMOUNT" ? amount(key, label, value) : field(key, label, type, dateValue(value))];
});
const value = cell(row, map, label)
if (value == null || value === "") return []
return [type === "TEXT" ? text(key, label, value) : type === "AMOUNT" ? amount(key, label, value) : field(key, label, type, dateValue(value))]
})
}
function buildDetailFields(row: ExcelJS.Row, map: Map<string, number>, specs: Array<[string, string, string]>): MaterialField[] {
return specs.flatMap(([label, key, type]) => {
const value = cell(row, map, label);
if (value == null || value === "") return [];
return [type === "TEXT" ? text(key, label, value) : type === "AMOUNT" ? amount(key, label, value) : field(key, label, type, dateValue(value))];
});
const value = cell(row, map, label)
if (value == null || value === "") return []
return [type === "TEXT" ? text(key, label, value) : type === "AMOUNT" ? amount(key, label, value) : field(key, label, type, dateValue(value))]
})
}
const laborSpecs: Array<[string, string, string]> = [["姓名", "name", "TEXT"], ["身份证号码", "id_number", "TEXT"], ["手机号", "phone", "TEXT"], ["劳务费用", "labor_fee", "AMOUNT"], ["税前费用", "pretax_fee", "AMOUNT"], ["开户行", "bank", "TEXT"], ["支行名称", "branch_name", "TEXT"], ["联行号", "bank_code", "TEXT"], ["银行卡号", "bank_card_number", "TEXT"]];
const expenseSpecs: Array<[string, string, string]> = [["报销金额", "reimbursement_amount", "AMOUNT"], ["费用类型", "expense_type", "TEXT"], ["发生时间", "occurrence_time", "DATE"], ["收款人", "payee", "TEXT"], ["开户行", "bank", "TEXT"], ["支行名称", "branch_name", "TEXT"], ["支行行号", "branch_code", "TEXT"], ["银行卡号", "bank_card_number", "TEXT"], ["费用说明", "expense_description", "TEXT"]];
const laborSpecs: Array<[string, string, string]> = [["姓名", "name", "TEXT"], ["身份证号码", "id_number", "TEXT"], ["手机号", "phone", "TEXT"], ["劳务费用", "labor_fee", "AMOUNT"], ["税前费用", "pretax_fee", "AMOUNT"], ["开户行", "bank", "TEXT"], ["支行名称", "branch_name", "TEXT"], ["联行号", "bank_code", "TEXT"], ["银行卡号", "bank_card_number", "TEXT"]]
const expenseSpecs: Array<[string, string, string]> = [["报销金额", "reimbursement_amount", "AMOUNT"], ["费用类型", "expense_type", "TEXT"], ["发生时间", "occurrence_time", "DATE"], ["收款人", "payee", "TEXT"], ["开户行", "bank", "TEXT"], ["支行名称", "branch_name", "TEXT"], ["支行行号", "branch_code", "TEXT"], ["银行卡号", "bank_card_number", "TEXT"], ["费用说明", "expense_description", "TEXT"]]
// ─── Main parser ─────────────────────────────────────────────────────────────
export async function parseMaterialWorkbook(buffer: Uint8Array): Promise<Parsed[]> {
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.load(Buffer.from(buffer) as any);
if (!workbook.worksheets.length) throw new MaterialPackValidationError(["信息表没有任何 Sheet"]);
const sheets = workbook.worksheets;
const mainSheet = sheets[0]!;
const maps = sheets.map(headerMap);
const mainMap = maps[0]!;
const idColumn = mainMap.get("会议编号") ?? 1;
const mainRows = (mainSheet.getRows(2, mainSheet.rowCount) ?? []).filter((row) => row.getCell(idColumn).value != null && row.getCell(idColumn).value !== "");
const ids = new Set<string>();
const workbook = new ExcelJS.Workbook()
await workbook.xlsx.load(Buffer.from(buffer) as any)
if (!workbook.worksheets.length) throw new MaterialPackValidationError(["信息表没有任何 Sheet"])
const sheets = workbook.worksheets
const mainSheet = sheets[0]!
const mainMap = headerMap(mainSheet)
const idColumn = mainMap.get("会议编号") ?? 1
const mainRows = (mainSheet.getRows(2, mainSheet.rowCount) ?? []).filter(
(row) => row.getCell(idColumn).value != null && row.getCell(idColumn).value !== ""
)
const ids = new Set<string>()
const laborSheet = sheets.find((sheet, index) => index > 0 && headerMap(sheet).has("姓名"))
const expenseSheet = sheets.find((sheet, index) => index > 0 && headerMap(sheet).has("报销金额"))
const laborMap = laborSheet ? headerMap(laborSheet) : undefined
const expenseMap = expenseSheet ? headerMap(expenseSheet) : undefined
const parsed: Parsed[] = mainRows.map((row) => {
const id = String(row.getCell(idColumn).value).trim();
if (!id) throw new MaterialPackValidationError(["主表会议编号不能为空"]);
if (ids.has(id)) throw new MaterialPackValidationError([`主表会议编号重复: ${id}`]);
ids.add(id);
const apply = cell(row, mainMap, "申请日期");
const laborSheet = sheets.find((sheet, index) => index > 0 && headerMap(sheet).has("姓名"));
const expenseSheet = sheets.find((sheet, index) => index > 0 && headerMap(sheet).has("报销金额"));
const laborMap = laborSheet ? headerMap(laborSheet) : undefined;
const expenseMap = expenseSheet ? headerMap(expenseSheet) : undefined;
const laborRows = (laborSheet?.getRows(2, laborSheet.rowCount) ?? []).filter((r) => String(cell(r, laborMap!, "会议编号") ?? "").trim() === id);
const expenseRows = (expenseSheet?.getRows(2, expenseSheet.rowCount) ?? []).filter((r) => String(cell(r, expenseMap!, "会议编号") ?? "").trim() === id);
const laborNames = laborRows.map((r) => String(cell(r, headerMap(laborSheet!), "姓名") ?? "").trim()).filter(Boolean);
const fields = buildMainFields(row, mainMap);
if (laborRows.length) fields.push({ key: "daoshi_list", label: "导师列表", type: "LIST", value: laborRows.map((r) => buildDetailFields(r, laborMap!, laborSpecs)) });
if (expenseRows.length) fields.push({ key: "mingxi_list", label: "明细列表", type: "LIST", value: expenseRows.map((r) => buildDetailFields(r, expenseMap!, expenseSpecs)) });
return { laborNames, document: { type: "document", documentId: id, documentSN: id, startTime: startTimeValue(apply), fields } };
});
return parsed;
const id = String(row.getCell(idColumn).value).trim()
if (!id) throw new MaterialPackValidationError(["主表会议编号不能为空"])
if (ids.has(id)) throw new MaterialPackValidationError([`主表会议编号重复: ${id}`])
ids.add(id)
const apply = cell(row, mainMap, "申请日期")
const laborRows = (laborSheet?.getRows(2, laborSheet.rowCount) ?? []).filter(
(r) => String(cell(r, laborMap!, "会议编号") ?? "").trim() === id
)
const expenseRows = (expenseSheet?.getRows(2, expenseSheet.rowCount) ?? []).filter(
(r) => String(cell(r, expenseMap!, "会议编号") ?? "").trim() === id
)
const laborNames = laborRows
.map((r) => String(cell(r, laborMap!, "姓名") ?? "").trim())
.filter(Boolean)
// Collect attachment declarations from main sheet row
const documentAttachments = deduplicateKeys(collectRowAttachments(row, mainMap))
// Collect expense attachment declarations per row index
const expenseAttachments: Record<number, DeclaredAttachment[]> = {}
expenseRows.forEach((r, rowIdx) => {
const groups = deduplicateKeys(collectRowAttachments(r, expenseMap!))
if (groups.length) expenseAttachments[rowIdx] = groups
})
// Collect person attachment declarations per person name
const personAttachments: Record<string, DeclaredAttachment[]> = {}
laborRows.forEach((r) => {
const name = String(cell(r, laborMap!, "姓名") ?? "").trim()
if (!name) return
const groups = deduplicateKeys(collectRowAttachments(r, laborMap!))
if (groups.length) personAttachments[name] = groups
})
const fields = buildMainFields(row, mainMap)
if (laborRows.length) fields.push({ key: "daoshi_list", label: "导师列表", type: "LIST", value: laborRows.map((r) => buildDetailFields(r, laborMap!, laborSpecs)) })
if (expenseRows.length) fields.push({ key: "mingxi_list", label: "明细列表", type: "LIST", value: expenseRows.map((r) => buildDetailFields(r, expenseMap!, expenseSpecs)) })
return {
laborNames,
documentAttachments,
expenseAttachments,
personAttachments,
document: { type: "document", documentId: id, documentSN: id, startTime: startTimeValue(apply), fields },
}
})
return parsed
}
+83
View File
@@ -0,0 +1,83 @@
import { z } from "zod"
export const DEFAULT_MATERIAL_PACK_ALLOWED_EXTENSIONS = [
".pdf",
".xls",
".xlsx",
".csv",
".doc",
".docx",
".ppt",
".pptx",
".txt",
".rtf",
".odt",
".ods",
".odp",
".jpg",
".jpeg",
".png",
".gif",
".bmp",
".webp",
".heic",
".eml",
".msg"
] as const
export const DEFAULT_MATERIAL_PACK_FILE_POLICY = {
minFileSizeBytes: 500,
allowedExtensions: [...DEFAULT_MATERIAL_PACK_ALLOWED_EXTENSIONS]
}
const fileExtensionSchema = z.string().trim().min(1).transform((value) => {
const normalized = value.toLowerCase()
return normalized.startsWith(".") ? normalized : `.${normalized}`
}).refine((value) => /^\.[a-z0-9][a-z0-9+_-]*$/.test(value), {
message: "文件后缀必须是简单扩展名,例如 .pdf 或 xlsx"
})
export const MaterialPackFilePolicySchema = z.object({
minFileSizeBytes: z.number().int().min(0).default(DEFAULT_MATERIAL_PACK_FILE_POLICY.minFileSizeBytes),
maxFileSizeBytes: z.number().int().positive().nullable().optional(),
allowedExtensions: z.array(fileExtensionSchema).min(1).default([...DEFAULT_MATERIAL_PACK_ALLOWED_EXTENSIONS])
.transform((extensions) => [...new Set(extensions)])
}).superRefine((policy, ctx) => {
if (
policy.maxFileSizeBytes !== undefined &&
policy.maxFileSizeBytes !== null &&
policy.maxFileSizeBytes < policy.minFileSizeBytes
) {
ctx.addIssue({
code: "custom",
path: ["maxFileSizeBytes"],
message: "最大文件大小不能小于最小文件大小"
})
}
})
export const MaterialPackFilePolicyPatchSchema = z.object({
minFileSizeBytes: z.number().int().min(0).optional(),
maxFileSizeBytes: z.number().int().positive().nullable().optional(),
allowedExtensions: z.array(fileExtensionSchema).min(1)
.transform((extensions) => [...new Set(extensions)])
}).optional()
export type MaterialPackFilePolicy = z.infer<typeof MaterialPackFilePolicySchema>
export type MaterialPackFilePolicyPatch = Partial<MaterialPackFilePolicy>
export function normalizeMaterialPackFilePolicy(
policy: MaterialPackFilePolicyPatch | undefined = undefined
): MaterialPackFilePolicy {
return MaterialPackFilePolicySchema.parse(policy ?? {})
}
export function mergeMaterialPackFilePolicy(
current: MaterialPackFilePolicy | undefined,
patch: MaterialPackFilePolicyPatch
): MaterialPackFilePolicy {
return normalizeMaterialPackFilePolicy({
...normalizeMaterialPackFilePolicy(current),
...patch
})
}
+156
View File
@@ -0,0 +1,156 @@
import type { KyInstance } from "ky";
import { existsSync } from "node:fs";
import type { CorpConfig } from "../../../core/config/types.js";
import { loadGlobalConfig } from "../../../core/config/loader.js";
import * as api from "../api.js";
import type { WebhookIntegration } from "../types.js";
import { previewMaterialPack, readMaterialPackFile } from "./service.js";
import type { WebhookReadyResult } from "./types.js";
export async function checkWebhookReadiness(
client: KyInstance,
corp: CorpConfig,
options: { filePath?: string; webhook?: string } = {}
): Promise<WebhookReadyResult> {
const globalConfig = loadGlobalConfig();
const stateMode = globalConfig.stateful ? "stateful" : "stateless";
let authStatus: "ok" | "error" = "ok";
let authError: string | undefined;
let tenantInfo: WebhookReadyResult["corp"]["tenant"];
let userInfo: WebhookReadyResult["corp"]["user"];
try {
const me = await api.getMe(client);
userInfo = {
id: me.user.id,
name: me.user.name,
isAdmin: me.user.isAdmin
};
tenantInfo = {
id: me.tenant.id,
name: me.tenant.name,
tenantSlug: me.tenant.tenantSlug,
corporationName: me.tenant.hoseCorpConfig?.corporationName
};
} catch (err) {
authStatus = "error";
authError = err instanceof Error ? err.message : String(err);
}
let rawWebhooks: WebhookIntegration[] = [];
if (authStatus === "ok") {
try {
rawWebhooks = await api.listWebhookIntegrations(
client,
corp.seal.endpoints.approvalStylePreferences
);
} catch (err) {
authStatus = "error";
authError = `读取 Webhook 配置失败: ${err instanceof Error ? err.message : String(err)}`;
}
}
const isSingle = rawWebhooks.length === 1;
const activeWebhooks = rawWebhooks.map((w) => ({
id: w.id,
name: w.name,
mode: w.mode,
incomingDocumentWebhookUrl: w.incomingDocumentWebhook.url,
outgoingResultWebhookUrl: w.outgoingResultWebhook,
autoApprovalRate: w.autoApprovalRate,
...(isSingle ? { isDefault: true } : {})
}));
const defaultWebhook = isSingle
? { id: rawWebhooks[0]!.id, name: rawWebhooks[0]!.name, mode: rawWebhooks[0]!.mode }
: null;
const materialPackWebhook = options.webhook
? api.findWebhookIntegration(rawWebhooks, options.webhook)
: isSingle
? rawWebhooks[0]
: undefined;
let materialPack: WebhookReadyResult["materialPack"];
if (options.filePath) {
if (!existsSync(options.filePath)) {
materialPack = {
valid: false,
filePath: options.filePath,
fileName: options.filePath.split(/[\\/]/).pop() ?? options.filePath,
documentCount: 0,
errors: [`文件不存在: ${options.filePath}`]
};
} else {
try {
const input = readMaterialPackFile(options.filePath);
const preview = await previewMaterialPack(
input.fileBuffer,
input.fileName,
materialPackWebhook?.materialPackFilePolicy
);
materialPack = {
valid: true,
filePath: options.filePath,
fileName: input.fileName,
documentCount: preview.documents.length,
warnings: preview.warnings
};
} catch (err) {
materialPack = {
valid: false,
filePath: options.filePath,
fileName: options.filePath.split(/[\\/]/).pop() ?? options.filePath,
documentCount: 0,
errors: [err instanceof Error ? err.message : String(err)]
};
}
}
}
const materialPackOk = materialPack ? materialPack.valid : true;
const ready = authStatus === "ok" && activeWebhooks.length > 0 && materialPackOk;
const corpFlag = stateMode === "stateful" ? "" : ` --corp ${corp.id}`;
let nextAction = "";
let statusMessage = "";
if (authStatus !== "ok") {
statusMessage = `凭证鉴权异常: ${authError}`;
nextAction = `seal-use auth diagnose${corpFlag}`;
} else if (activeWebhooks.length === 0) {
statusMessage = "当前企业尚未配置任何 Webhook 集成通道";
nextAction = `seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${corpFlag}`;
} else if (materialPack && !materialPack.valid) {
statusMessage = `材料包预检失败: ${materialPack.errors?.join("; ")}`;
nextAction = `seal-use webhook material-pack preview ${materialPack.filePath}${corpFlag}`;
} else {
statusMessage = isSingle
? "所有通道正常,已自动锁定唯一 Webhook 通道,等待载入"
: `所有通道正常,检测到 ${activeWebhooks.length} 个 Webhook 通道,等待载入`;
const targetFile = materialPack?.filePath ?? "<材料包.zip>";
const webhookOption = isSingle ? "" : ` --webhook ${defaultWebhook ? defaultWebhook.id : "<webhookIdOrName>"}`;
nextAction = `seal-use webhook material-pack push ${targetFile}${webhookOption}${corpFlag}`;
}
return {
ready,
corp: {
id: corp.id,
name: corp.name,
sourceType: corp.source.type,
tenant: tenantInfo,
user: userInfo
},
stateMode,
authStatus,
authError,
activeWebhooks,
defaultWebhook,
materialPack,
statusMessage,
nextAction
};
}
+138 -51
View File
@@ -1,71 +1,158 @@
import { readFileSync } from "node:fs";
import { webhookHeaders } from "./signature.js";
import { buildAttachmentPlans, injectAttachmentPlan } from "./attachments.js";
import { parseMaterialWorkbook } from "./parse.js";
import { extractZipEntry, readZipEntries, validatePackEntries, type ZipEntry } from "./validate.js";
import type { MaterialPackPreview, MaterialPackPushResult } from "./types.js";
import { readFileSync } from "node:fs"
import { webhookHeaders } from "./signature.js"
import { buildAttachmentPlans, injectAttachmentPlan } from "./attachments.js"
import { parseMaterialWorkbook } from "./parse.js"
import { extractZipEntry, readZipEntries, validatePackEntries, type ZipEntry } from "./validate.js"
import { MaterialPackValidationError, type MaterialPackPreview, type MaterialPackPushResult } from "./types.js"
import type { MaterialPackFilePolicyPatch } from "./policy.js"
function webhookInfo(url: string): { baseUrl: string; webhookId: string } {
const parsed = new URL(url);
const match = parsed.pathname.match(/\/webhook\/([^/]+)/);
if (!match) throw new Error("Webhook URL 必须包含 /webhook/{webhookId}/document");
return { baseUrl: `${parsed.protocol}//${parsed.host}`, webhookId: match[1]! };
const parsed = new URL(url)
const match = parsed.pathname.match(/\/webhook\/([^/]+)/)
if (!match) throw new Error("Webhook URL 必须包含 /webhook/{webhookId}/document")
return { baseUrl: `${parsed.protocol}//${parsed.host}`, webhookId: match[1]! }
}
function isZip(buffer: Uint8Array, fileName: string): boolean {
return fileName.toLowerCase().endsWith(".zip") || (buffer[0] === 0x50 && buffer[1] === 0x4b && !fileName.toLowerCase().endsWith(".xlsx"));
return fileName.toLowerCase().endsWith(".zip") || (buffer[0] === 0x50 && buffer[1] === 0x4b && !fileName.toLowerCase().endsWith(".xlsx"))
}
async function prepare(fileBuffer: Uint8Array, fileName: string) {
let entries: ZipEntry[] = [];
let workbook = fileBuffer;
if (isZip(fileBuffer, fileName)) {
entries = await readZipEntries(fileBuffer);
validatePackEntries(entries);
const info = entries.find((entry) => entry.fileName === "信息表.xlsx");
if (!info) throw new Error("ZIP 根目录缺少信息表.xlsx");
workbook = await extractZipEntry(fileBuffer, info);
function validateDocIdDirectories(entries: ZipEntry[], documentIds: string[]): void {
if (!entries.length) return // xlsx-only mode, skip
// Extract documentId from dir name: strip @annotation suffix
const zipDocIds = new Set(
entries
.map((e) => {
const root = e.fileName.split("/")[0]!
const atIdx = root.indexOf("@")
return atIdx >= 0 ? root.slice(0, atIdx) : root
})
.filter((r) => r !== "信息表.xlsx")
)
const errors: string[] = []
// Every documentId must have a matching root directory (possibly with @annotation)
for (const id of documentIds) {
if (!zipDocIds.has(id)) {
errors.push(
`Excel 会议编号「${id}」在 ZIP 中找不到对应的根目录「${id}/」或「${id}@.../」。`
)
}
}
const parsed = await parseMaterialWorkbook(workbook);
const plans = buildAttachmentPlans(entries, parsed);
const documents = parsed.map((item) => item.document);
return { entries, parsed, plans, documents, fileBuffer };
// Every root directory must correspond to a known documentId
const docIdSet = new Set(documentIds)
for (const zipDocId of zipDocIds) {
if (!docIdSet.has(zipDocId)) {
errors.push(
`ZIP 根目录对应的编号「${zipDocId}」在信息表中找不到对应的会议编号。`
)
}
}
if (errors.length) throw new MaterialPackValidationError(errors)
}
export async function previewMaterialPack(fileBuffer: Uint8Array, fileName: string): Promise<MaterialPackPreview> {
const prepared = await prepare(fileBuffer, fileName);
return { warnings: [], documents: prepared.documents, attachmentPlan: prepared.plans };
async function prepare(
fileBuffer: Uint8Array,
fileName: string,
filePolicy?: MaterialPackFilePolicyPatch
) {
let entries: ZipEntry[] = []
let workbook = fileBuffer
if (isZip(fileBuffer, fileName)) {
entries = await readZipEntries(fileBuffer)
validatePackEntries(entries, filePolicy)
const info = entries.find((entry) => entry.fileName === "信息表.xlsx")
if (!info) throw new Error("ZIP 根目录缺少信息表.xlsx")
workbook = await extractZipEntry(fileBuffer, info)
}
const parsed = await parseMaterialWorkbook(workbook)
// Validate: ZIP root dir names must correspond to documentIds (supports @annotation suffix)
validateDocIdDirectories(entries, parsed.map((p) => p.document.documentId))
const plans = buildAttachmentPlans(entries, parsed)
const documents = parsed.map((item) => item.document)
return { entries, parsed, plans, documents, fileBuffer }
}
export async function pushMaterialPack(fileBuffer: Uint8Array, fileName: string, config: { webhookUrl: string; secret: string }): Promise<MaterialPackPushResult> {
const prepared = await prepare(fileBuffer, fileName);
const { baseUrl, webhookId } = webhookInfo(config.webhookUrl);
const results: MaterialPackPushResult["results"] = [];
export async function previewMaterialPack(
fileBuffer: Uint8Array,
fileName: string,
filePolicy?: MaterialPackFilePolicyPatch
): Promise<MaterialPackPreview> {
const prepared = await prepare(fileBuffer, fileName, filePolicy)
const documents = prepared.parsed.map((item, index) =>
injectAttachmentPlan(item.document, prepared.plans[index]!, new Map())
)
return { warnings: [], documents, attachmentPlan: prepared.plans }
}
export async function pushMaterialPack(
fileBuffer: Uint8Array,
fileName: string,
config: {
webhookUrl: string;
secret: string;
docIdSuffix?: string;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
}
): Promise<MaterialPackPushResult> {
const prepared = await prepare(fileBuffer, fileName, config.materialPackFilePolicy)
const { baseUrl, webhookId } = webhookInfo(config.webhookUrl)
const results: MaterialPackPushResult["results"] = []
for (let index = 0; index < prepared.parsed.length; index += 1) {
const item = prepared.parsed[index]!;
const plan = prepared.plans[index]!;
const uploaded = new Map<string, unknown[]>();
for (const category of [...plan.categoryFields, ...Object.values(plan.personAttachments).flat()]) {
for (const entry of category.entries) {
const zipEntry = prepared.entries.find((candidate) => candidate.fileName === entry.path);
if (!zipEntry) continue;
const body = new FormData();
const attachment = await extractZipEntry(prepared.fileBuffer, zipEntry);
body.append("files", new File([new Uint8Array(attachment)], entry.fileName));
const response = await fetch(`${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/attachments`, { method: "POST", headers: webhookHeaders({}, config.secret), body });
if (!response.ok) throw new Error(`附件上传失败 ${response.status}: ${await response.text()}`);
const json = await response.json() as { data?: unknown; attachments?: Array<{ data: unknown }> };
uploaded.set(entry.path, json.attachments?.map((value) => value.data) ?? (json.data === undefined ? [] : [json.data]));
const item = prepared.parsed[index]!
const plan = prepared.plans[index]!
const uploaded = new Map<string, unknown[]>()
// Collect all groups from all attachment levels
const allGroups = [
...plan.categoryFields,
...Object.values(plan.personAttachments).flat(),
...Object.values(plan.expenseAttachments).flat(),
]
for (const group of allGroups) {
for (const path of group.paths) {
if (uploaded.has(path)) continue // already uploaded this path
const zipEntry = prepared.entries.find((e) => e.fileName === path)
if (!zipEntry) continue
process.stderr.write(`⬆ 上传附件: ${path}\n`)
const body = new FormData()
const attachment = await extractZipEntry(prepared.fileBuffer, zipEntry)
const baseName = path.split("/").pop() ?? path
body.append("files", new File([new Uint8Array(attachment)], baseName))
const response = await fetch(
`${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/attachments`,
{ method: "POST", headers: webhookHeaders({}, config.secret), body }
)
if (!response.ok) throw new Error(`附件上传失败 ${response.status}: ${await response.text()}`)
const json = await response.json() as { data?: unknown; attachments?: Array<{ data: unknown }> }
uploaded.set(path, json.attachments?.map((v) => v.data) ?? (json.data === undefined ? [] : [json.data]))
process.stderr.write(`✓ 附件上传成功: ${path}\n`)
}
}
const document = injectAttachmentPlan(item.document, plan, uploaded);
const response = await fetch(`${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/document`, { method: "POST", headers: { "Content-Type": "application/json", ...webhookHeaders({ webhookId, ...document }, config.secret) }, body: JSON.stringify(document) });
if (!response.ok) throw new Error(`Webhook 单据推送失败 ${response.status}: ${await response.text()}`);
results.push({ documentId: document.documentId, document, pushResult: await response.json() });
process.stderr.write(`📤 推送单据: ${item.document.documentId}\n`)
const document = injectAttachmentPlan(item.document, plan, uploaded)
const response = await fetch(
`${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/document`,
{
method: "POST",
headers: { "Content-Type": "application/json", ...webhookHeaders({ webhookId, ...document }, config.secret) },
body: JSON.stringify(document),
}
)
if (!response.ok) throw new Error(`Webhook 单据推送失败 ${response.status}: ${await response.text()}`)
results.push({ documentId: document.documentId, document, pushResult: await response.json() })
process.stderr.write(`✓ 单据推送成功: ${document.documentId}\n`)
}
return { warnings: [], results };
return { warnings: [], results }
}
export function readMaterialPackFile(filePath: string): { fileBuffer: Buffer; fileName: string } {
return { fileBuffer: readFileSync(filePath), fileName: filePath.split(/[\\/]/).pop() ?? "material-pack.zip" };
return { fileBuffer: readFileSync(filePath), fileName: filePath.split(/[\\\/]/).pop() ?? "material-pack.zip" }
}
+56 -8
View File
@@ -13,16 +13,17 @@ export type MaterialDocument = {
fields: MaterialField[];
};
export type MaterialAttachmentEntry = {
fileName: string;
size: number;
path: string;
export type AttachmentGroup = {
key: string; // derived from label: attachmentKey(label)
label: string; // [附件] prefix stripped
paths: string[]; // full ZIP-relative paths
};
export type MaterialAttachmentPlan = {
documentId: string;
categoryFields: Array<{ key: string; label: string; entries: MaterialAttachmentEntry[] }>;
personAttachments: Record<string, Array<{ key: string; label: string; entries: MaterialAttachmentEntry[] }>>;
categoryFields: AttachmentGroup[]; // root document level
personAttachments: Record<string, AttachmentGroup[]>; // daoshi_list, keyed by person name
expenseAttachments: Record<number, AttachmentGroup[]>; // mingxi_list, keyed by row index
};
export type MaterialPackPreview = {
@@ -38,7 +39,54 @@ export type MaterialPackPushResult = {
export class MaterialPackValidationError extends Error {
constructor(public readonly errors: string[], public readonly warnings: string[] = []) {
super(`材料包校验失败:${errors.length} 个错误`);
this.name = "MaterialPackValidationError";
super([`材料包校验失败:${errors.length} 个错误`, ...errors.map((error) => `- ${error}`)].join("\n"))
this.name = "MaterialPackValidationError"
}
}
export type WebhookReadyResult = {
ready: boolean;
corp: {
id: string;
name: string;
sourceType: string;
tenant?: {
id: string;
name: string;
tenantSlug?: string;
corporationName?: string;
};
user?: {
id: string;
name: string;
isAdmin?: boolean;
};
};
stateMode: "stateful" | "stateless";
authStatus: "ok" | "error";
authError?: string;
activeWebhooks: Array<{
id: string;
name: string;
mode: string;
incomingDocumentWebhookUrl: string;
outgoingResultWebhookUrl: string;
autoApprovalRate?: number;
isDefault?: boolean;
}>;
defaultWebhook: {
id: string;
name: string;
mode: string;
} | null;
materialPack?: {
valid: boolean;
filePath: string;
fileName: string;
documentCount: number;
errors?: string[];
warnings?: string[];
};
statusMessage: string;
nextAction: string;
};
@@ -0,0 +1,46 @@
import { describe, expect, test } from "bun:test"
import { validatePackEntries, type ZipEntry } from "./validate.js"
function entries(attachment: Partial<ZipEntry> = {}): ZipEntry[] {
return [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{
fileName: "DOC-001/合同/合同.pdf",
uncompressedSize: 500,
compressedSize: 400,
raw: {},
...attachment
}
]
}
describe("material pack attachment file policy", () => {
test("accepts the default 500-byte minimum and common PDF extension", () => {
expect(() => validatePackEntries(entries())).not.toThrow()
})
test("rejects attachments smaller than the configured minimum", () => {
expect(() => validatePackEntries(entries({ uncompressedSize: 499 }))).toThrow(
"附件文件过小"
)
})
test("rejects attachments larger than the configured maximum", () => {
expect(() => validatePackEntries(entries({ uncompressedSize: 1001 }), {
maxFileSizeBytes: 1000
})).toThrow("附件文件过大")
})
test("rejects extensions outside the configured whitelist", () => {
expect(() => validatePackEntries(entries({ fileName: "DOC-001/合同/合同.exe" }), {
allowedExtensions: [".pdf"]
})).toThrow("附件后缀不在白名单中")
})
test("rejects an invalid size range before any upload can start", () => {
expect(() => validatePackEntries(entries(), {
minFileSizeBytes: 1000,
maxFileSizeBytes: 999
})).toThrow("最大文件大小不能小于最小文件大小")
})
})
+51 -10
View File
@@ -1,6 +1,11 @@
import yauzl from "yauzl";
import iconv from "iconv-lite";
import { MaterialPackValidationError } from "./types.js";
import {
normalizeMaterialPackFilePolicy,
type MaterialPackFilePolicy,
type MaterialPackFilePolicyPatch
} from "./policy.js";
export const MATERIAL_PACK_LIMITS = { maxEntries: 1000, maxTotalSize: 500 * 1024 * 1024, maxCompressionRatio: 150 };
@@ -8,7 +13,7 @@ export type ZipEntry = { fileName: string; uncompressedSize: number; compressedS
export async function readZipEntries(buffer: Uint8Array): Promise<ZipEntry[]> {
return new Promise((resolve, reject) => {
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true }, (openError: Error | null, zipFile: any) => {
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true, decodeStrings: false }, (openError: Error | null, zipFile: any) => {
if (openError || !zipFile) return reject(openError ?? new Error("无法打开 ZIP"));
const entries: ZipEntry[] = [];
zipFile.readEntry();
@@ -26,29 +31,32 @@ export async function readZipEntries(buffer: Uint8Array): Promise<ZipEntry[]> {
}
function decodeZipEntryName(entry: any): string {
if (entry.fileNameUTF8 || (entry.generalPurposeBitFlag & 0x800)) return entry.fileNameUTF8 ?? entry.fileName;
const raw = Buffer.from(String(entry.fileName), "binary");
const raw: Buffer = Buffer.isBuffer(entry.fileName)
? entry.fileName
: Buffer.from(String(entry.fileName), "binary");
const utf8 = raw.toString("utf8");
if (utf8.includes("\uFFFD") || /[\u0080-\u00FF]/.test(utf8)) {
const gbk = iconv.decode(raw, "gbk");
if (!gbk.includes("\uFFFD")) return gbk;
}
if (!utf8.includes("\uFFFD")) return utf8;
const gbk = iconv.decode(raw, "gbk");
if (!gbk.includes("\uFFFD")) return gbk;
return utf8;
}
export function isJunk(name: string): boolean {
function isJunk(name: string): boolean {
const base = name.split("/").pop() ?? "";
return name.split("/").includes("__MACOSX") || base === ".DS_Store" || base.startsWith("._") || base.startsWith(".~") || base.startsWith("~$");
}
export function validatePackEntries(entries: ZipEntry[]): void {
export function validatePackEntries(entries: ZipEntry[], policy?: MaterialPackFilePolicyPatch): void {
const errors: string[] = [];
const filePolicy = normalizeMaterialPackFilePolicy(policy);
if (entries.length > MATERIAL_PACK_LIMITS.maxEntries) errors.push(`文件数超过 ${MATERIAL_PACK_LIMITS.maxEntries}`);
const total = entries.reduce((sum, entry) => sum + entry.uncompressedSize, 0);
if (total > MATERIAL_PACK_LIMITS.maxTotalSize) errors.push("解压后总大小超过 500MB");
for (const entry of entries) {
if (entry.fileName.startsWith("/") || entry.fileName.split("/").includes("..")) errors.push(`存在不安全路径: ${entry.fileName}`);
if (entry.compressedSize > 0 && entry.uncompressedSize / entry.compressedSize > MATERIAL_PACK_LIMITS.maxCompressionRatio) errors.push(`压缩比超过 150: ${entry.fileName}`);
if (entry.fileName === "信息表.xlsx") continue;
validateAttachmentFile(entry, filePolicy, errors);
}
const info = entries.find((entry) => entry.fileName === "信息表.xlsx");
if (!info) errors.push("ZIP 根目录缺少精确名为「信息表.xlsx」的文件");
@@ -56,9 +64,42 @@ export function validatePackEntries(entries: ZipEntry[]): void {
if (errors.length) throw new MaterialPackValidationError(errors);
}
function validateAttachmentFile(
entry: ZipEntry,
policy: MaterialPackFilePolicy,
errors: string[]
): void {
const extension = getFileExtension(entry.fileName);
if (!extension || !policy.allowedExtensions.includes(extension)) {
errors.push(
`附件后缀不在白名单中: ${entry.fileName}(允许: ${policy.allowedExtensions.join(", ")})`
);
}
if (entry.uncompressedSize < policy.minFileSizeBytes) {
errors.push(
`附件文件过小: ${entry.fileName}(${entry.uncompressedSize} B,小于最小值 ${policy.minFileSizeBytes} B)`
);
}
if (
policy.maxFileSizeBytes !== undefined &&
policy.maxFileSizeBytes !== null &&
entry.uncompressedSize > policy.maxFileSizeBytes
) {
errors.push(
`附件文件过大: ${entry.fileName}(${entry.uncompressedSize} B,大于最大值 ${policy.maxFileSizeBytes} B)`
);
}
}
function getFileExtension(fileName: string): string {
const baseName = fileName.split("/").pop() ?? fileName;
const dotIndex = baseName.lastIndexOf(".");
return dotIndex > 0 ? baseName.slice(dotIndex).toLowerCase() : "";
}
export function extractZipEntry(buffer: Uint8Array, target: ZipEntry): Promise<Buffer> {
return new Promise((resolve, reject) => {
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true }, (openError: Error | null, zipFile: any) => {
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true, decodeStrings: false }, (openError: Error | null, zipFile: any) => {
if (openError || !zipFile) return reject(openError ?? new Error("无法打开 ZIP"));
zipFile.readEntry();
zipFile.on("entry", (entry: any) => {
+186
View File
@@ -0,0 +1,186 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { existsSync, mkdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
computeNextSyncIteration,
filterRuleMapping,
formatSyncVersionName,
getMappingsDir,
loadRuleMappingSnapshot,
RuleMappingSnapshot,
saveRuleMappingSnapshot
} from "./rule-mapping.js";
describe("rule-mapping", () => {
let testDir: string;
const originalEnv = process.env.SEAL_USE_MAPPINGS_DIR;
beforeEach(() => {
testDir = join(tmpdir(), `seal-mappings-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
mkdirSync(testDir, { recursive: true });
process.env.SEAL_USE_MAPPINGS_DIR = testDir;
});
afterEach(() => {
if (originalEnv) {
process.env.SEAL_USE_MAPPINGS_DIR = originalEnv;
} else {
delete process.env.SEAL_USE_MAPPINGS_DIR;
}
if (existsSync(testDir)) {
rmSync(testDir, { recursive: true, force: true });
}
});
test("getMappingsDir respects custom environment variable", () => {
expect(getMappingsDir()).toBe(testDir);
});
test("saveRuleMappingSnapshot and loadRuleMappingSnapshot round-trip", () => {
const snapshot: RuleMappingSnapshot = {
syncedAt: new Date().toISOString(),
source: {
id: "prod-1",
name: "Acme Corp",
latestPublishedVersionNumber: 22,
latestPublishedVersionName: "Version 22"
},
target: {
id: "test-1",
name: "Acme Test",
publishedVersionNumber: 7,
publishedVersionName: "Sync from Acme Corp [Prod v22 · #1]",
rulesCount: 2
},
versionMapping: {
sourceProdVersionNumber: 22,
sourceProdVersionName: "Version 22",
targetTestVersionNumber: 7,
targetTestVersionName: "Sync from Acme Corp [Prod v22 · #1]"
},
ruleMapping: [
{
index: 1,
sourceRuleId: "src-rule-1",
sourceRuleCode: 10,
targetRuleId: "tgt-rule-1",
targetRuleCode: "rule-1",
description: "No alcohol above 50%",
scope: "all",
strictness: "MUST_FOLLOW"
},
{
index: 2,
sourceRuleId: "src-rule-2",
sourceRuleCode: 11,
targetRuleId: "tgt-rule-2",
targetRuleCode: "rule-2",
description: "Private car mileage limit",
scope: "travel",
strictness: "MUST_FOLLOW"
}
]
};
const savedFile = saveRuleMappingSnapshot(snapshot);
expect(existsSync(savedFile)).toBe(true);
const loadedByVersion = loadRuleMappingSnapshot("test-1", 7);
expect(loadedByVersion).not.toBeNull();
expect(loadedByVersion?.target.publishedVersionNumber).toBe(7);
expect(loadedByVersion?.ruleMapping.length).toBe(2);
expect(loadedByVersion?.ruleMapping[0]!.sourceRuleCode).toBe(10);
expect(loadedByVersion?.ruleMapping[0]!.targetRuleCode).toBe("rule-1");
const loadedByVString = loadRuleMappingSnapshot("test-1", "v7");
expect(loadedByVString?.target.publishedVersionNumber).toBe(7);
const loadedLatest = loadRuleMappingSnapshot("test-1", "latest");
expect(loadedLatest?.target.publishedVersionNumber).toBe(7);
const missing = loadRuleMappingSnapshot("test-1", 999);
expect(missing).toBeNull();
});
test("filterRuleMapping filters by target code, source code, and IDs", () => {
const items = [
{
index: 1,
sourceRuleId: "src-uuid-1",
sourceRuleCode: 14,
targetRuleId: "tgt-uuid-1",
targetRuleCode: "rule-14",
description: "Rule 14 desc",
scope: "scope 1",
strictness: "MUST_FOLLOW"
},
{
index: 2,
sourceRuleId: "src-uuid-2",
sourceRuleCode: 15,
targetRuleId: "tgt-uuid-2",
targetRuleCode: "rule-15",
description: "Rule 15 desc",
scope: "scope 2",
strictness: "SUGGESTION"
}
];
expect(filterRuleMapping(items)).toHaveLength(2);
expect(filterRuleMapping(items, "rule-14")).toHaveLength(1);
expect(filterRuleMapping(items, "rule-14")[0]!.sourceRuleCode).toBe(14);
expect(filterRuleMapping(items, "14")).toHaveLength(1);
expect(filterRuleMapping(items, "#14")).toHaveLength(1);
expect(filterRuleMapping(items, "#rule-15")).toHaveLength(1);
expect(filterRuleMapping(items, "src-uuid-2")).toHaveLength(1);
expect(filterRuleMapping(items, "non-existent")).toHaveLength(0);
});
test("computeNextSyncIteration calculates iteration sequence accurately", () => {
// 1. Initial sync when test enterprise has no history
expect(computeNextSyncIteration("Acme Corp", 22, [])).toBe(1);
// 2. Legacy un-numbered sync exists
expect(
computeNextSyncIteration("Acme Corp", 22, [
{ versionName: "Sync from Acme Corp (2026-09-11)" }
])
).toBe(2);
// 3. Structured iterations exist for same prodVersion (including with target test version)
expect(
computeNextSyncIteration("Acme Corp", 22, [
{ versionName: "Sync from Acme Corp [Prod v22 · #1 -> Test v1]" },
{ versionName: "Sync from Acme Corp [Prod v22 · #2 -> Test v2]" }
])
).toBe(3);
// 4. Production version bumped to 23 -> resets to 1
expect(
computeNextSyncIteration("Acme Corp", 23, [
{ versionName: "Sync from Acme Corp [Prod v22 · #1 -> Test v1]" },
{ versionName: "Sync from Acme Corp [Prod v22 · #2 -> Test v2]" }
])
).toBe(1);
// 5. Production has no published version (draft only)
expect(
computeNextSyncIteration("Acme Corp", undefined, [
{ versionName: "Sync from Acme Corp [Prod draft · #1 -> Test v1]" }
])
).toBe(2);
});
test("formatSyncVersionName formats cleanly with test version mapping", () => {
expect(formatSyncVersionName("Acme Corp", 22, 1, 3)).toBe(
"Sync from Acme Corp [Prod v22 · #1 -> Test v3]"
);
expect(formatSyncVersionName("Acme Corp", 22, 1)).toBe(
"Sync from Acme Corp [Prod v22 · #1]"
);
expect(formatSyncVersionName("Acme Corp", undefined, 1, 5)).toBe(
"Sync from Acme Corp [Prod draft · #1 -> Test v5]"
);
});
});
+154
View File
@@ -0,0 +1,154 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
export interface RuleMappingItem {
index: number;
sourceRuleId: string;
sourceRuleCode: string | number;
targetRuleId: string;
targetRuleCode: string | number;
description: string;
scope: string;
strictness: string;
}
export interface RuleMappingSnapshot {
syncedAt: string;
source: {
id: string;
name: string;
latestPublishedVersionNumber?: number | null;
latestPublishedVersionName?: string | null;
};
target: {
id: string;
name: string;
publishedVersionNumber: number;
publishedVersionName?: string | null;
rulesCount: number;
};
versionMapping: {
sourceProdVersionNumber: number | null;
sourceProdVersionName: string | null;
targetTestVersionNumber: number;
targetTestVersionName: string | null;
};
ruleMapping: RuleMappingItem[];
}
export function getMappingsDir(): string {
const custom = process.env.SEAL_USE_MAPPINGS_DIR?.trim();
if (custom) return custom;
return join(homedir(), ".config", "seal-use", "mappings");
}
export function saveRuleMappingSnapshot(snapshot: RuleMappingSnapshot): string {
const dir = getMappingsDir();
mkdirSync(dir, { recursive: true, mode: 0o700 });
const versionFile = join(dir, `${snapshot.target.id}-v${snapshot.target.publishedVersionNumber}.json`);
const latestFile = join(dir, `${snapshot.target.id}-latest.json`);
const content = JSON.stringify(snapshot, null, 2);
writeFileSync(versionFile, content, { encoding: "utf-8", mode: 0o600 });
writeFileSync(latestFile, content, { encoding: "utf-8", mode: 0o600 });
return versionFile;
}
export function loadRuleMappingSnapshot(
targetCorpId: string,
versionSelector?: string | number
): RuleMappingSnapshot | null {
const dir = getMappingsDir();
let filename: string;
if (!versionSelector || versionSelector === "latest") {
filename = `${targetCorpId}-latest.json`;
} else {
const vStr = String(versionSelector).replace(/^v/i, "");
filename = `${targetCorpId}-v${vStr}.json`;
}
const filePath = join(dir, filename);
if (!existsSync(filePath)) {
return null;
}
try {
const raw = readFileSync(filePath, "utf-8");
return JSON.parse(raw) as RuleMappingSnapshot;
} catch {
return null;
}
}
export function filterRuleMapping(
mapping: RuleMappingItem[],
codeOrId?: string
): RuleMappingItem[] {
if (!codeOrId) return mapping;
const target = codeOrId.trim().toLowerCase();
return mapping.filter((item) => {
return (
String(item.sourceRuleCode).toLowerCase() === target ||
String(item.targetRuleCode).toLowerCase() === target ||
item.sourceRuleId.toLowerCase() === target ||
item.targetRuleId.toLowerCase() === target ||
`#${item.sourceRuleCode}`.toLowerCase() === target ||
`#${item.targetRuleCode}`.toLowerCase() === target
);
});
}
export function computeNextSyncIteration(
prodCorpName: string,
prodVersionNumber: number | undefined,
testVersions: Array<{ versionName?: string | null }>
): number {
let maxIteration = 0;
const prefixRegex = prodVersionNumber !== undefined
? new RegExp(`\\[Prod v${prodVersionNumber}\\s*·\\s*#(\\d+)(?:[^\\]]*)\\]`)
: /\[Prod draft\s*·\s*#(\d+)(?:[^\]]*)\]/;
for (const tv of testVersions) {
if (!tv.versionName) continue;
const match = tv.versionName.match(prefixRegex);
if (match && match[1]) {
const num = parseInt(match[1], 10);
if (!isNaN(num) && num > maxIteration) {
maxIteration = num;
}
}
}
if (maxIteration > 0) {
return maxIteration + 1;
}
// If no structured tag exists at all, check legacy un-numbered sync versions
const anyStructuredTag = testVersions.some(
(tv) => tv.versionName && /\[Prod v\d+/.test(tv.versionName)
);
if (!anyStructuredTag) {
const legacySyncCount = testVersions.filter(
(tv) => tv.versionName && tv.versionName.includes(`Sync from ${prodCorpName}`)
).length;
if (legacySyncCount > 0) {
return legacySyncCount + 1;
}
}
return 1;
}
export function formatSyncVersionName(
prodCorpName: string,
prodVersionNumber: number | undefined,
iteration: number,
targetTestVersionNumber?: number
): string {
const prodLabel = prodVersionNumber !== undefined ? `Prod v${prodVersionNumber}` : "Prod draft";
const testLabel = targetTestVersionNumber !== undefined ? ` -> Test v${targetTestVersionNumber}` : "";
return `Sync from ${prodCorpName} [${prodLabel} · #${iteration}${testLabel}]`;
}
+1
View File
@@ -76,6 +76,7 @@ function fakeCorp(): CorpConfig {
return {
id: "corp-search-test",
name: "Search Test Corp",
environment: "production",
seal: {
url: "https://seal.test",
endpoints: {
+33 -2
View File
@@ -501,7 +501,12 @@ describe("simulation tool handlers", () => {
sourceSystem: "hosecloud"
});
expect(postedBody).not.toHaveProperty("limit");
expect(result).toMatchObject({ batchId: "batch-1", created: true });
expect(result).toMatchObject({
batchId: "batch-1",
created: true,
noWait: true,
asyncTicket: "batch-1"
});
});
test("create tool surface exposes mode, flowIds, and rawParams", () => {
@@ -509,18 +514,44 @@ describe("simulation tool handlers", () => {
const { z } = require("zod") as typeof import("zod");
const schema = z.toJSONSchema(tool!.parameters) as { properties?: Record<string, unknown> };
expect(Object.keys(schema.properties ?? {})).toEqual(
expect.arrayContaining(["mode", "flowIds", "rawParams", "schemaConfig", "packageIds"])
expect.arrayContaining(["mode", "flowIds", "rawParams", "schemaConfig", "packageIds", "noWait"])
);
});
test("includes the simulation management tool set", () => {
expect(sealTools.find((item) => item.name === "seal_simulation_batches_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_batch_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_batch_status")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_templates_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_integrations_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_batch_records_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_material_package_upload")).toBeDefined();
});
test("status tool performs one non-blocking check and exposes the next action", async () => {
const tool = sealTools.find((item) => item.name === "seal_simulation_batch_status");
expect(tool).toBeDefined();
const client = {
get: (url: string) => {
expect(url).toBe("api/v1/simulation/batch/batch-1");
return { json: async () => ({ data: { ...hosecloudBatchFixture, id: "batch-1" } }) };
}
} as unknown as KyInstance;
const handler = tool!.handler as ToolHandler;
const result = await handler(client, { batchId: "batch-1" }, fakeContext()) as Record<string, unknown>;
expect(result).toMatchObject({
batchId: "batch-1",
status: "SYNCING",
terminal: false,
next: {
status: "seal-use simulation status batch-1",
wait: "seal-use simulation wait batch-1"
}
});
});
});
describe("simulation response schemas", () => {
+144 -45
View File
@@ -5,7 +5,7 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { CorpConfig } from "../../core/config/types.js";
import { findSealMcpTool, findSealTool, sealMcpTools, sealTools } from "./tools.js";
import { buildRulePushPlan, findSealTool, sealTools } from "./tools.js";
type ToolHandler = (
client: KyInstance,
@@ -84,6 +84,27 @@ describe("sealTools", () => {
expect(userDelegationTool).toBeDefined();
});
test("includes read-only contacts directory tools", () => {
expect(sealTools.find((item) => item.name === "seal_contacts_departments_root_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_contacts_department_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_contacts_department_children_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_contacts_department_users_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_contacts_last_sync_time_get")).toBeDefined();
});
test("includes the read-only insight stats tool", () => {
expect(sealTools.find((item) => item.name === "seal_insight_stats_get")).toBeDefined();
});
test("includes read-only financial data tools", () => {
expect(sealTools.find((item) => item.name === "seal_expenses_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_invoices_list")).toBeDefined();
});
test("includes the Feishu simulation approval definition tool", () => {
expect(sealTools.find((item) => item.name === "seal_simulation_feishu_approval_definitions_list")).toBeDefined();
});
test("includes system configuration tools", () => {
expect(sealTools.find((item) => item.name === "seal_llm_config_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_llm_providers_list")).toBeDefined();
@@ -223,6 +244,124 @@ describe("sealTools", () => {
expect(await countFakeRules(client)).toBe(0);
});
test("preference dry run reads config without patching it", async () => {
const tool = sealTools.find((item) => item.name === "seal_preference_decision_update");
expect(tool).toBeDefined();
let patched = false;
const client = {
get: () => ({
json: async () => ({
data: {
decisionPreferences: {
explicitApprove: "old",
explicitReject: "reject",
exemptApprove: "exempt",
review: "review"
},
integrations: []
}
})
}),
patch: () => {
patched = true;
throw new Error("preview must not patch");
}
} as unknown as KyInstance;
const handler = tool!.handler as ToolHandler;
const result = await handler(client, { explicitApprove: "new", dryRun: true }, fakeContext()) as {
preview: boolean;
targetUrl: string;
changesDiff: { after: { decisionPreferences: { explicitApprove: string } } };
};
expect(result.preview).toBe(true);
expect(result.targetUrl).toBe("https://seal.test/api/v1/agent/ai-approval/config");
expect(result.changesDiff.after.decisionPreferences.explicitApprove).toBe("new");
expect(patched).toBe(false);
});
test("plans incremental rule updates without rebuilding matched rules", () => {
const plan = buildRulePushPlan(
[
{
id: "rule-1",
code: 1,
description: "Keep receipts",
scope: "travel",
strictness: "MUST_FOLLOW"
},
{
id: "rule-2",
code: 2,
description: "Keep attendee names",
scope: "meal",
strictness: "SHOULD_FOLLOW"
}
],
[
{
id: "rule-1",
description: "Keep complete receipts",
scope: "travel",
strictness: "MUST_FOLLOW"
},
{
description: "Require cost center",
scope: "all",
strictness: "SUGGESTION"
}
]
);
expect(plan.updated).toMatchObject([
{ id: "rule-1", changedFields: ["description"] }
]);
expect(plan.created).toMatchObject([
{ description: "Require cost center" }
]);
expect(plan.deleted).toMatchObject([{ id: "rule-2", code: 2 }]);
expect(plan.unchanged).toEqual([]);
});
test("matches legacy local rules by unique content when no id is present", () => {
const plan = buildRulePushPlan(
[{
id: "rule-1",
description: "Keep receipts",
scope: "travel",
strictness: "MUST_FOLLOW"
}],
[{
description: "Keep receipts",
scope: "travel",
strictness: "MUST_FOLLOW"
}]
);
expect(plan.created).toEqual([]);
expect(plan.updated).toEqual([]);
expect(plan.deleted).toEqual([]);
expect(plan.unchanged).toEqual([{ id: "rule-1" }]);
});
test("rejects local rule ids that are absent from the current draft", () => {
expect(() => buildRulePushPlan(
[{
id: "rule-1",
description: "Keep receipts",
scope: "travel",
strictness: "MUST_FOLLOW"
}],
[{
id: "stale-rule",
description: "Keep receipts",
scope: "travel",
strictness: "MUST_FOLLOW"
}]
)).toThrow("stale-rule");
});
test("includes approval run Langfuse bridge tools", () => {
expect(sealTools.find((item) => item.name === "seal_approval_runs_search")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_approval_runs_summary")).toBeDefined();
@@ -230,51 +369,9 @@ describe("sealTools", () => {
expect(sealTools.find((item) => item.name === "seal_approval_run_langfuse_bridge_get")).toBeDefined();
});
test("keeps the MCP exposed tool surface narrow", () => {
expect(sealMcpTools.map((tool) => tool.name)).toEqual([
"seal_whoami",
"seal_approval_search",
"seal_approval_context_get",
"seal_webhook_material_pack",
"seal_runs_search",
"seal_action"
]);
});
test("routes low-frequency management tools through seal_action", async () => {
const tool = sealMcpTools.find((item) => item.name === "seal_action");
expect(tool).toBeDefined();
const handler = tool!.handler as ToolHandler;
const result = await handler(
fakeApprovalRunsClient(),
{ action: "runs.summary", payload: { date: "2026-06-08", timezone: "Asia/Shanghai" } },
fakeContext()
) as { matched: number };
expect(result.matched).toBe(2);
});
test("routes lightweight approval run actions through seal_action", async () => {
const tool = sealMcpTools.find((item) => item.name === "seal_action");
expect(tool).toBeDefined();
const handler = tool!.handler as ToolHandler;
const result = await handler(
fakeApprovalRunsClient(),
{ action: "runs.citedRules", payload: { recordId: "run-1" } },
fakeContext()
) as { count: number };
expect(result.count).toBe(1);
});
test("keeps old fine-grained tools available to compatibility callers but hidden from MCP list", () => {
expect(sealMcpTools.find((item) => item.name === "seal_approval_rule_create")).toBeUndefined();
expect(findSealMcpTool("seal_approval_rule_create")).toBeUndefined();
test("can find tools by name in sealTools", () => {
expect(findSealTool("seal_approval_rule_create")).toBeDefined();
expect(findSealMcpTool("seal_action")).toBeDefined();
expect(findSealMcpTool("seal_runs_search")?.name).toBe("seal_runs_search");
expect(findSealTool("non_existent_tool")).toBeUndefined();
});
test("approval run search omits bridge unless requested", async () => {
@@ -934,6 +1031,7 @@ function fakeContext(): { corp: CorpConfig } {
corp: {
id: "corp-a",
name: "Corp A",
environment: "production",
seal: {
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
@@ -958,6 +1056,7 @@ function fakeHoseContext(): { corp: CorpConfig } {
corp: {
id: "corp-a",
name: "Corp A",
environment: "production",
seal: {
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
+464 -307
View File
File diff suppressed because it is too large. Load diff
+62 -1
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { DEFAULT_MATERIAL_PACK_FILE_POLICY, MaterialPackFilePolicySchema } from "./material-pack/policy.js";
export const HosecloudStaffSchema = z.object({
staffId: z.string(),
@@ -181,7 +182,8 @@ export const WebhookIntegrationSchema = z.object({
outgoingResultWebhook: z.string().url(),
incomingManualResultWebhook: WebhookEndpointSchema,
secret: z.string().min(1),
autoApprovalRate: z.number().int().min(0).max(100).optional()
autoApprovalRate: z.number().int().min(0).max(100).optional(),
materialPackFilePolicy: MaterialPackFilePolicySchema.default(DEFAULT_MATERIAL_PACK_FILE_POLICY)
}).passthrough();
export const ApprovalStylePreferencesSchema = z.object({
@@ -286,6 +288,56 @@ export const SealContactSearchResultSchema = z.object({
users: z.array(SealUserDetailSchema).default([])
}).passthrough();
export const SealDepartmentSchema = z.object({
_id: z.string(),
tenantId: z.string().optional(),
name: z.string().optional(),
parentId: z.string().nullable().optional(),
ancestors: z.array(z.string()).default([]),
provider: z.string().optional(),
permissions: z.array(z.string()).default([]),
isDeleted: z.boolean().optional(),
syncedAt: z.string().optional(),
createdAt: z.string().optional(),
updatedAt: z.string().optional()
}).passthrough();
export const SealDepartmentListDataSchema = z.object({
items: z.array(SealDepartmentSchema).default([])
}).passthrough();
export const SealDepartmentUsersDataSchema = z.object({
items: z.array(SealUserDetailSchema).default([])
}).passthrough();
export const SealContactsLastSyncTimeSchema = z.object({
lastSyncTime: z.union([z.string(), z.number(), z.null()])
}).passthrough();
export const InsightTagStatsSchema = z.record(z.string(), z.unknown());
export const InsightStatsSchema = z.object({
tagStats: z.array(InsightTagStatsSchema).default([]),
totalRisks: z.number().default(0),
analyzedRisks: z.number().default(0),
pendingRisks: z.number().default(0)
}).passthrough();
const DataRecordSchema = z.record(z.string(), z.unknown());
export const ExpenseListDataSchema = z.object({
expenses: z.array(DataRecordSchema).default([]),
total: z.number().optional()
}).passthrough();
export const InvoiceListDataSchema = z.object({
invoices: z.array(DataRecordSchema).default([]),
total: z.number().optional(),
feishuApprovalAppId: z.string().nullable().optional()
}).passthrough();
export const SimulationApprovalDefinitionSchema = z.record(z.string(), z.unknown());
export const LlmConfigSchema = z.object({
provider: z.string(),
config: z.record(z.string(), z.unknown()).default({})
@@ -486,6 +538,7 @@ export const ThinkingDepthPreferenceSchema = z.object({
}).passthrough();
export const HosecloudConfigInputSchema = z.object({
dryRun: z.boolean().optional(),
signKey: z.string().min(1).optional(),
outboundName: z.string().optional(),
specificationId: z.string().optional(),
@@ -536,6 +589,14 @@ export type SealUserCreateResult = z.infer<typeof SealUserCreateResultSchema>;
export type SealUserResetPasswordResult = z.infer<typeof SealUserResetPasswordResultSchema>;
export type SealUserDetail = z.infer<typeof SealUserDetailSchema>;
export type SealContactSearchResult = z.infer<typeof SealContactSearchResultSchema>;
export type SealDepartment = z.infer<typeof SealDepartmentSchema>;
export type SealDepartmentListData = z.infer<typeof SealDepartmentListDataSchema>;
export type SealDepartmentUsersData = z.infer<typeof SealDepartmentUsersDataSchema>;
export type SealContactsLastSyncTime = z.infer<typeof SealContactsLastSyncTimeSchema>;
export type InsightStats = z.infer<typeof InsightStatsSchema>;
export type ExpenseListData = z.infer<typeof ExpenseListDataSchema>;
export type InvoiceListData = z.infer<typeof InvoiceListDataSchema>;
export type SimulationApprovalDefinition = z.infer<typeof SimulationApprovalDefinitionSchema>;
export type LlmConfig = z.infer<typeof LlmConfigSchema>;
export type LlmProvider = z.infer<typeof LlmProviderSchema>;
export type AvailablePermissionsData = z.infer<typeof AvailablePermissionsDataSchema>;
+1 -1
View File
@@ -124,7 +124,7 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
// 5. Generic Tool Invocation endpoint (POST /api/tool/:name)
if (method === "POST" && pathname.startsWith("/api/tool/")) {
const toolName = pathname.slice("/api/tool/".length).trim();
const tool = findSealTool(toolName, { includeMcpAliases: true });
const tool = findSealTool(toolName);
if (!tool) {
sendError(res, 404, `Tool not found: '${toolName}'`);
return;
+4 -2
View File
@@ -7,6 +7,7 @@ import {
ListToolsRequestSchema
} from "@modelcontextprotocol/sdk/types.js";
import { runCli } from "./cli/runner.js";
import { classifyCliError } from "./cli/errors.js";
import { VERSION } from "./version.js";
const serverEntryFile = fileURLToPath(import.meta.url);
@@ -69,7 +70,7 @@ export function createServer(options: { enableCli?: boolean } = {}) {
stdout: "",
stderr: "seal_cli requires a non-empty command string",
isError: true,
exitCode: 1
exitCode: 2
});
}
@@ -89,11 +90,12 @@ export function createServer(options: { enableCli?: boolean } = {}) {
}
}));
} catch (error) {
const classification = classifyCliError(error);
return cliResult({
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
isError: true,
exitCode: 1
exitCode: classification.exitCode
});
}
});
+124
View File
@@ -0,0 +1,124 @@
import { describe, expect, test } from "bun:test";
import { formatDevVersion, parseGitDescribe, resolveVersionInfo } from "./version.js";
import { compareSemVer, isNewerVersion } from "./cli/commands/update.js";
describe("Git version parsing and formatting", () => {
test("parses full git describe string with commits ahead and dirty state", () => {
const parsed = parseGitDescribe("v0.10.15-2-ga521a24-dirty");
expect(parsed).toEqual({
baseVersion: "0.10.15",
commitsAhead: 2,
commit: "a521a24",
dirty: true,
describe: "v0.10.15-2-ga521a24-dirty"
});
});
test("parses clean git describe string without dirty suffix", () => {
const parsed = parseGitDescribe("v0.10.15-0-g83ade4d");
expect(parsed).toEqual({
baseVersion: "0.10.15",
commitsAhead: 0,
commit: "83ade4d",
dirty: false,
describe: "v0.10.15-0-g83ade4d"
});
});
test("parses tag-only git describe with dirty status", () => {
const parsed = parseGitDescribe("v0.10.15-dirty");
expect(parsed).toEqual({
baseVersion: "0.10.15",
commitsAhead: 0,
commit: "",
dirty: true,
describe: "v0.10.15-dirty"
});
});
test("parses raw commit hash fallback", () => {
const parsed = parseGitDescribe("83ade4d-dirty", "0.10.15");
expect(parsed).toEqual({
baseVersion: "0.10.15",
commitsAhead: 0,
commit: "83ade4d",
dirty: true,
describe: "83ade4d-dirty"
});
});
test("returns null for empty or invalid describe strings", () => {
expect(parseGitDescribe("")).toBeNull();
expect(parseGitDescribe(" ")).toBeNull();
expect(parseGitDescribe("invalid/string/without/semver")).toBeNull();
});
test("formats dev version according to standard SemVer 2.0 rules", () => {
expect(formatDevVersion("0.10.15", 2, "a521a24", false)).toBe("0.10.15-dev.2+ga521a24");
expect(formatDevVersion("0.10.15", 2, "a521a24", true)).toBe("0.10.15-dev.2+ga521a24.dirty");
expect(formatDevVersion("0.10.15", 0, "83ade4d", false)).toBe("0.10.15-dev.0+g83ade4d");
expect(formatDevVersion("0.10.15", 0, "83ade4d", true)).toBe("0.10.15-dev.0+g83ade4d.dirty");
});
});
describe("resolveVersionInfo configuration modes", () => {
test("resolves inlined environment variables when preset", () => {
const info = resolveVersionInfo({
env: {
SEAL_BUILD_VERSION: "0.10.15-dev.3+g9a7be16",
SEAL_BUILD_CHANNEL: "dev",
SEAL_BUILD_IS_RELEASE: "false",
SEAL_BUILD_GIT_BASE: "0.10.15",
SEAL_BUILD_GIT_COMMITS_AHEAD: "3",
SEAL_BUILD_GIT_COMMIT: "9a7be16",
SEAL_BUILD_GIT_DIRTY: "false",
SEAL_BUILD_GIT_DESCRIBE: "v0.10.15-3-g9a7be16"
}
});
expect(info.name).toBe("seal-use");
expect(info.version).toBe("0.10.15-dev.3+g9a7be16");
expect(info.channel).toBe("dev");
expect(info.isRelease).toBe(false);
expect(info.git).toBeDefined();
expect(info.git?.baseVersion).toBe("0.10.15");
expect(info.git?.commitsAhead).toBe(3);
expect(info.git?.commit).toBe("9a7be16");
expect(info.git?.dirty).toBe(false);
});
test("resolves release mode when SEAL_FORCE_RELEASE is set", () => {
const info = resolveVersionInfo({
env: {
SEAL_FORCE_RELEASE: "1"
}
});
expect(info.name).toBe("seal-use");
expect(info.channel).toBe("release");
expect(info.isRelease).toBe(true);
expect(info.git).toBeUndefined();
});
});
describe("compareSemVer dev version handling", () => {
test("recognizes future release as newer than dev build", () => {
expect(isNewerVersion("0.10.16", "0.10.15-dev.2+ga521a24")).toBe(true);
expect(isNewerVersion("0.11.0", "0.10.15-dev.2+ga521a24")).toBe(true);
expect(isNewerVersion("1.0.0", "0.10.15-dev.2+ga521a24")).toBe(true);
});
test("recognizes base release as older than ahead dev build", () => {
expect(compareSemVer("0.10.15", "0.10.15-dev.2+ga521a24")).toBe(-1);
expect(isNewerVersion("0.10.15", "0.10.15-dev.2+ga521a24")).toBe(false);
});
test("correctly compares dev builds by commits ahead", () => {
expect(compareSemVer("0.10.15-dev.3", "0.10.15-dev.2")).toBe(1);
expect(compareSemVer("0.10.15-dev.1", "0.10.15-dev.2")).toBe(-1);
});
test("identifies older legacy release as downgrade", () => {
expect(compareSemVer("0.3.3", "0.10.15-dev.2+ga521a24")).toBe(-1);
});
});
+173 -1
View File
@@ -1,3 +1,175 @@
import { spawnSync } from "node:child_process";
import packageJson from "../package.json" with { type: "json" };
export const VERSION = packageJson.version;
export interface GitBuildInfo {
baseVersion: string;
commitsAhead: number;
commit: string;
dirty: boolean;
describe: string;
}
export interface VersionInfo {
name: "seal-use";
version: string;
channel: "release" | "dev";
isRelease: boolean;
git?: GitBuildInfo;
}
export function parseGitDescribe(output: string, fallbackVersion = packageJson.version): GitBuildInfo | null {
const trimmed = output.trim();
if (!trimmed) return null;
const dirty = trimmed.endsWith("-dirty");
const clean = dirty ? trimmed.slice(0, -6) : trimmed;
// Format 1: v0.10.15-2-ga521a24
const longMatch = clean.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/);
if (longMatch && longMatch[1] && longMatch[2] && longMatch[3]) {
return {
baseVersion: longMatch[1],
commitsAhead: Number.parseInt(longMatch[2], 10),
commit: longMatch[3],
dirty,
describe: trimmed
};
}
// Format 2: v0.10.15
const tagMatch = clean.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)$/);
if (tagMatch && tagMatch[1]) {
return {
baseVersion: tagMatch[1],
commitsAhead: 0,
commit: "",
dirty,
describe: trimmed
};
}
// Format 3: 83ade4d
const commitMatch = clean.match(/^([0-9a-f]{7,40})$/);
if (commitMatch && commitMatch[1]) {
return {
baseVersion: fallbackVersion,
commitsAhead: 0,
commit: commitMatch[1],
dirty,
describe: trimmed
};
}
return null;
}
export function formatDevVersion(baseVersion: string, commitsAhead: number, commit: string, dirty: boolean): string {
const dirtySuffix = dirty ? ".dirty" : "";
const commitSuffix = commit ? `+g${commit}${dirtySuffix}` : dirty ? "+dirty" : "";
return `${baseVersion}-dev.${commitsAhead}${commitSuffix}`;
}
export function resolveVersionInfo(options?: {
env?: Record<string, string | undefined>;
cwd?: string;
}): VersionInfo {
const customEnv = options?.env;
const buildVersion = customEnv?.SEAL_BUILD_VERSION ?? process.env.SEAL_BUILD_VERSION;
const buildIsRelease = customEnv?.SEAL_BUILD_IS_RELEASE ?? process.env.SEAL_BUILD_IS_RELEASE;
const buildChannel = customEnv?.SEAL_BUILD_CHANNEL ?? process.env.SEAL_BUILD_CHANNEL;
const buildGitBase = customEnv?.SEAL_BUILD_GIT_BASE ?? process.env.SEAL_BUILD_GIT_BASE;
const buildGitCommitsAhead = customEnv?.SEAL_BUILD_GIT_COMMITS_AHEAD ?? process.env.SEAL_BUILD_GIT_COMMITS_AHEAD;
const buildGitCommit = customEnv?.SEAL_BUILD_GIT_COMMIT ?? process.env.SEAL_BUILD_GIT_COMMIT;
const buildGitDirty = customEnv?.SEAL_BUILD_GIT_DIRTY ?? process.env.SEAL_BUILD_GIT_DIRTY;
const buildGitDescribe = customEnv?.SEAL_BUILD_GIT_DESCRIBE ?? process.env.SEAL_BUILD_GIT_DESCRIBE;
const forceRelease = customEnv?.SEAL_FORCE_RELEASE ?? process.env.SEAL_FORCE_RELEASE;
const cwd = options?.cwd;
// 1. Check compile-time inlined environment variables
if (buildVersion) {
const isRelease = buildIsRelease === "true";
const channel = (buildChannel as "release" | "dev") || (isRelease ? "release" : "dev");
const result: VersionInfo = {
name: "seal-use",
version: buildVersion,
channel,
isRelease
};
if (buildGitBase) {
result.git = {
baseVersion: buildGitBase,
commitsAhead: Number.parseInt(buildGitCommitsAhead || "0", 10),
commit: buildGitCommit || "",
dirty: buildGitDirty === "true",
describe: buildGitDescribe || buildVersion
};
}
return result;
}
// 2. Explicit force release via environment
if (buildIsRelease === "true" || forceRelease === "1") {
return {
name: "seal-use",
version: packageJson.version,
channel: "release",
isRelease: true
};
}
// 3. Dynamic resolution from git repository in dev mode
try {
const res = spawnSync("git", ["describe", "--tags", "--long", "--dirty", "--always"], {
cwd,
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"]
});
if (res.status === 0 && res.stdout) {
const gitInfo = parseGitDescribe(res.stdout.trim(), packageJson.version);
if (gitInfo) {
if (!gitInfo.commit) {
const revRes = spawnSync("git", ["rev-parse", "--short", "HEAD"], {
cwd,
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"]
});
if (revRes.status === 0 && revRes.stdout) {
gitInfo.commit = revRes.stdout.trim();
}
}
const devVersion = formatDevVersion(
gitInfo.baseVersion,
gitInfo.commitsAhead,
gitInfo.commit,
gitInfo.dirty
);
return {
name: "seal-use",
version: devVersion,
channel: "dev",
isRelease: false,
git: gitInfo
};
}
}
} catch {
// Fall back below if git is not installed or error occurs
}
// 4. Default fallback when git is not available
return {
name: "seal-use",
version: `${packageJson.version}-dev.0+local`,
channel: "dev",
isRelease: false
};
}
export const VERSION_INFO = resolveVersionInfo();
export const VERSION = VERSION_INFO.version;
export const IS_RELEASE = VERSION_INFO.isRelease;
export const CHANNEL = VERSION_INFO.channel;