Compare commits

...
62 Commits
Author SHA1 Message Date
yunyingk 92967a8653 Merge pull request #131 from yunyingk/codex/release-v0.10.26
🧪 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.26: updater installs the skill from the new binary, archive-first downloads
2026-09-15 23:44:51 +08:00
gitea 6b4f0f26e6 Release v0.10.26: updater installs the skill from the new binary, archive-first downloads 2026-09-15 23:43:14 +08:00
yunyingk 719c7ffe06 Merge pull request #130 from yunyingk/codex/fix-update-skill-and-asset-priority
Fix the stale Agent Skill in self-update, and prefer the release archive
2026-09-15 23:41:59 +08:00
gitea 5b05c2695a Fix stale skill install and prefer the release archive 2026-09-15 23:39:06 +08:00
yunyingk bb3929bfc8 Merge pull request #129 from yunyingk/codex/release-v0.10.25
🧪 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.25: MCP boot fix, read-only/write tool split, contract and release gates
2026-09-15 23:09:00 +08:00
gitea a707eff850 Release v0.10.25: MCP boot fix, read-only/write tool split, contract and release gates 2026-09-15 23:07:13 +08:00
yunyingk d460fa4b7b Merge pull request #122 from yunyingk/codex/production-hygiene
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Gate the OpenAPI contract, guard releases, tighten credentials
2026-09-15 17:44:13 +08:00
gitea c3ec09d0a0 Tighten credential modes, pid identity and repo hygiene 2026-09-15 17:40:52 +08:00
gitea 6b2e0f7463 Guard releases on the tag being merged to main 2026-09-15 17:40:46 +08:00
gitea ce7eb7895c Mark package.json private and pin the Bun toolchain 2026-09-15 17:40:46 +08:00
gitea 58885f1949 Add implementation status to every OpenAPI operation 2026-09-15 17:40:40 +08:00
yunyingk 290d73c38f Merge pull request #121 from yunyingk/codex/drop-stale-master-trigger
Drop the master branch trigger now that the branch is gone
2026-09-15 16:47:43 +08:00
gitea 6509a1c535 Drop the master branch trigger now that the branch is gone
ci.yml triggered on push/pull_request for both main and master. master does
not exist on the remote (GitHub's default is main, and the stale remote branch
was deleted), so that filter could never match.

Left alone deliberately: AGENTS.md and bump-version.ts referring to
codex/release-vX.Y.Z, which describe the naming pattern for future release
branches rather than a specific existing one.
2026-09-15 16:45:57 +08:00
yunyingk c74e00eb1c Merge pull request #120 from yunyingk/codex/docs-drop-skill-symlink-refs
Drop stale references to the removed skill symlink
2026-09-15 16:40:08 +08:00
gitea 98b397888a Drop stale references to the removed skill symlink
`872b617` removed the in-repo `.agents/skills/seal-use` symlink, but two docs
still described it as present, so the repository's own instructions
contradicted the tree:

- AGENTS.md claimed the symlink exists "so workspace and Codex skill loading
  keep working". It is gone; loading now uses the global
  ~/.agents/skills/seal-use copy installed by `seal-use skill install`.
- README.md told readers the symlink mirrors `skills/seal-use`, and pointed
  them at a path that no longer resolves.

No code or test depended on the removed path — verified by grepping src/ and
scripts/, which only ever reference the global `~/.agents/skills/seal-use`.
plugin-migration-plan.md also mentions the symlink, but it is a historical
record of that migration and is left as-is.
2026-09-15 16:38:57 +08:00
gitea 872b617891 chore: drop project-level seal-use skill symlink (global copy retained) 2026-09-15 16:37:05 +08:00
yunyingk 27e7fab297 Merge pull request #119 from yunyingk/codex/read-only-consistency
Fix refusals of read-only approval-runs verbs and keep the two classifications in sync
2026-09-15 16:28:42 +08:00
gitea 1a80a0fb4c Fix refusals of read-only approval-runs verbs and keep the lists in sync
The read-only MCP tool refused three verbs that only query:
approval-runs search, pick and bridge. #117's changelog claimed pick had
'moved into read-only', which was true of the tool registry but not of the CLI
allow-list — the two are hand-maintained in different files and had drifted.

Adds the missing entries, and a test that derives the pairing mechanically:
every 'action === "x"' in src/cli/commands/* that dispatches to a
runTool("seal_...") must be read-only when the tool it reaches is read-only.
It asserts a minimum number of pairs so a change in dispatch shape cannot make
it silently vacuous, and names its exceptions explicitly — the deploy
<action> short forms (rejected at runtime, so unreachable) and
approval-runs search (an accepted alias of list with no registry row).

Half of these were found by that check rather than by reading the code.
2026-09-15 16:26:17 +08:00
yunyingk 76eb4575f8 Merge pull request #118 from yunyingk/codex/pin-bun-version
Pin bun-version and gate dist/mcp/server.js freshness
2026-09-15 16:23:04 +08:00
gitea d0acb02e4b Pin bun-version and gate dist/mcp/server.js freshness
The committed MCP bundle is the only thing that ships, but nothing checked
that it matched src/. The gate could not be added while CI ran
'bun-version: latest': that resolved to 1.4.2, and the minifier allocates
identifiers differently across Bun releases, so the runner rebuilt the
macOS/1.3.14-built bundle into different bytes — identical code, renamed
variables (N/S, A/I, q/p). Measured on #116.

Pin bun-version to 1.3.14 in both workflows, matching the local toolchain and
the @types/bun/bun-types already declared in package.json, then add the diff
gate alongside the existing boot check.

The boot check stays: a bundle that cannot start is invisible to a byte diff
when it is in sync with its broken source, which is exactly how #114 shipped.
2026-09-15 16:21:01 +08:00
yunyingk 2f0b4525a1 Merge pull request #117 from yunyingk/codex/tool-registry-classification
Classify the tool registry so read-only MCP can reach read-only tools
2026-09-15 16:20:16 +08:00
gitea 11b8cfce39 Classify the tool registry so read-only MCP can reach read-only tools
The read-only MCP tool refused the whole `seal-use tool <name>` area, because
the 98-entry internal tool registry had no read/write classification. Now it
does: SEAL_READ_ONLY_TOOLS (66) and SEAL_MUTATING_TOOLS (32), exported from
src/domains/seal/tools.ts, with the policy delegating `tool` to them.

The two sets are exhaustive by construction — a test asserts they partition
sealTools exactly — so a newly added tool fails the suite until it is
classified, rather than silently defaulting into one bucket.

Classifying by inspection was not enough. Cross-checking mechanically (every
exported function in src/domains/seal that performs a mutating HTTP call,
mapped to the tools that invoke it) caught a real mistake shipped in #115:
`analytics analyze` was allow-listed as read-only, but it calls
seal_insight_record_analyze, which issues a POST and starts an analysis
server-side. Removed from the CLI allow-list; a comment records why it is
absent, since the name reads like a query.

`approval-runs pick` went the other way into read-only: it dispatches to
seal_approval_run_pick, which is a query over approval runs rather than a
local-state mutation.

Read-only means: reads tenant state, or writes only a local file. Anything
that creates, updates, deletes, publishes, pushes, replays, uploads, activates
or mints a credential counts as mutating. `seal_webhook_material_pack` is
mutating because push mode sends the pack even though preview mode does not;
`seal_approval_runs_export` and `seal_insight_export` are read-only because
they only write a local workbook.
2026-09-15 16:18:44 +08:00
yunyingk 81504df98d Merge pull request #116 from yunyingk/codex/ci-dist-freshness
Boot the freshly built MCP bundle in CI (byte-diff freshness gate rejected by measurement)
2026-09-15 16:08:53 +08:00
gitea 8a032f02d1 Drop the byte-diff gate; keep booting the freshly built bundle
CI disproved the freshness gate on the first run: an ubuntu rebuild of the
macOS-built committed dist/mcp/server.js differs, and the diff is entirely
minified identifier renaming (N->S, A->I, q->p) with identical code. The
minifier does not allocate names reproducibly across platforms and Bun
versions, so a byte-for-byte gate cannot work here without pinning the
toolchain and matching runners.

Keep the check that does hold: boot the freshly built bundle and complete an
MCP handshake. Booting is what #114 actually needed — the byte diff would not
have caught that bug either, since the broken bundle was in sync with its
broken source.
2026-09-15 16:07:41 +08:00
gitea b0bad7e33d Add CI gate for dist/mcp/server.js freshness
The committed bundle is the only thing that ships, but CI only checked that
it compiled — never that it matched src/, and never that it could start.

- Fail when a fresh build differs from the committed dist/mcp/server.js,
  mirroring the existing dist/openapi.json gate, with the same actionable
  error. This is viable now: the bundle is byte-reproducible with the current
  toolchain (a rebuild of the committed file is byte-identical). Before the
  #114 rebuild it was not, which is why this was previously left out.
- Keep booting the freshly built bundle through a handshake, since a bundle
  that cannot start is invisible to source-level tests.
2026-09-15 16:04:56 +08:00
yunyingk 5e4c5bb727 Merge pull request #115 from yunyingk/codex/mcp-read-write-tools
Split the MCP passthrough into read-only and write tools
2026-09-15 16:03:24 +08:00
gitea 758c26354a Split the MCP passthrough into read-only and write tools
seal_cli could reach every CLI command, so its tool annotations had to be
all-or-nothing: destructiveHint true on a tool that mostly reads, which meant
clients could not auto-approve anything, and there was no way to gate the
mutating minority. Split it in two:

- seal_cli      read-only, readOnlyHint true / destructiveHint false.
- seal_cli_write mutations, publishing, credential minting, self-update and
                server commands; destructiveHint true.

The boundary is enforced rather than advertised. seal_cli runs only commands
on an explicit allow-list (84 entries, src/cli/read-only.ts) and fails closed
on anything unclassified, including commands added to the CLI later. Matching
reuses the CLI's own parseArgs and compares whole tokens, so a read prefix
cannot smuggle a mutation (corps listing is refused) and a bare allow-listed
command does not cover its subcommands. Refusals name seal_cli_write.

Deliberately excluded from the read-only set even though they look harmless:
anything writing local config (corps switch, config test-dir), minting or
printing credentials (auth keys, corps extract-keys), self-updating (update),
or standing up a long-running server (http, mcp, service run). seal-use
tool <name> is excluded too, since the 98-entry internal tool registry is not
itself classified.

A test asserts every allow-listed command still exists in the help registry,
so the list cannot silently rot.

Also, per the note that MCP is an optional, default-off path, the skill now
says so explicitly: the CLI is primary, a missing seal_cli* tool is the normal
default rather than a fault, and enabling it is the user's choice in the plugin
settings. Corrected skill docs that presented internal tool-registry names
(seal_webhook_get, seal_webhook_update, ...) as if they were MCP tools; the MCP
server exposes only the two seal_cli* tools.

CI: the MCP build step now boots the freshly built bundle and completes a
handshake, instead of only checking that it compiles. A bundle that cannot
start is invisible to source-level tests, which is how the previous unbootable
entry point shipped. No byte-for-byte dist diff gate here: the committed
bundle is not byte-reproducible with the current toolchain (~186 lines of drift
rebuilding the unmodified release commit), and such a gate would not have
caught that bug anyway, since the broken bundle was in sync with its source.
2026-09-15 16:02:03 +08:00
yunyingk 3fcfe3011a Merge pull request #114 from yunyingk/codex/mcp-sdk-v2
Migrate MCP server to SDK v2 and fix the bundle that never booted
2026-09-15 15:34:40 +08:00
gitea 524259c67c Migrate MCP server to SDK v2 and fix the bundle that never booted
The plugin ships dist/mcp/server.js as its MCP entry point, and that bundle
could not start at all: it threw "TypeError: ... is not a constructor" while
loading and never answered a request. MCP defaults to off, so enabling it
produced no seal_cli tool and no visible error.

Root cause: src/server.ts is circularly entangled with the CLI command graph
(server -> cli/runner -> cli/commands/mcp -> server, and
server -> cli/runner -> cli/commands/http -> http/routes -> server). When
bun build --target=node flattened that cycle together with zod's own
core <-> classic cycle, zod's class initialisers landed after the top-level
z.lazy() call the SDK makes at import time, leaving ZodLazy undefined.

Not fixable by changing targets: --target=bun, --compile, and dropping
--minify all fail the same way. Only removing the cycles fixes it.

- Moved tokenizeCommand / normalizeCliArgs to a leaf module (src/cli/tokenize.ts)
  and made the mcp command import the server lazily, removing both cycles.
- Added a test that boots the packaged bundle over stdio and completes a
  handshake; the existing tests exercise source, not the shipped artifact,
  which is why this went unnoticed. Verified it fails on the old bundle.
- Committed the rebuilt dist/mcp/server.js, since the previously committed
  artifact is the broken one.

Also migrated the monolithic @modelcontextprotocol/sdk v1 to the v2 split
packages (@modelcontextprotocol/server for the server,
@modelcontextprotocol/client for tests):

- Low-level Server + setRequestHandler -> high-level McpServer + registerTool;
  hand-written JSON Schema -> z.strictObject (still emits
  additionalProperties: false).
- Added the title and annotations clients could not previously see:
  readOnlyHint false, destructiveHint true, idempotentHint false,
  openWorldHint true. seal_cli is a passthrough that can reach mutating verbs,
  so it must not be advertised as safe to auto-run or safe to retry; the
  description now names the command families needing user confirmation.
- startServer uses serveStdio, which owns protocol-era negotiation
  (2025-era clients keep working) and teardown.
- .mcp.json uses the ZCode-native ${ZCODE_PLUGIN_ROOT}; verified in ZCode's
  resolver that CLAUDE_PLUGIN_ROOT and ZCODE_PLUGIN_ROOT are the same alias.

Dropping the v1 SDK removes express, hono, cors and ajv from the dependency
graph (bun.lock -149 lines).
2026-09-15 15:32:39 +08:00
yunyingk ac779cad88 Merge pull request #113 from yunyingk/codex/fix-112-remove-driftcount
Remove untraceable driftCount from approval-runs export (#112)
2026-09-15 15:01:18 +08:00
gitea 82d0d97efb Remove untraceable driftCount from approval-runs export (#112)
`approval-runs export` returned a bare audit-drift counter with no way to
trace it back to a document: no sourceDocumentSN, no recordId, no reason.
Interpreting it required a separate per-document `approval-runs flow`
query, and the word "drift" alone suggested the tool or the approval flow
was broken rather than a snapshot/lifecycle difference.

The drift itself is already visible in the workbook row: AI 决策「通过」
next to 人工审核「已取消」 and E人工行为「已撤回」, with the retraction
recorded in the standard formatted E人工意见 column. The aggregate carried
no information those columns do not.

`seal_approval_runs_export` never enabled flow alignment, so for MCP
consumers the field was a constant 0.

Rather than enriching the field, remove it. Per-run auditDrift and
auditDriftReason in `approval-runs flow` are unchanged.
2026-09-15 15:00:00 +08:00
yunyingk a8a30f6065 Merge pull request #111 from yunyingk/codex/release-v0.10.24
🧪 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.24: Hose assist link OpenAPI key extraction and privilege elevation
2026-09-15 11:24:48 +08:00
gitea d83f3f74e5 Add equal credential scope principle for Hose admin cURL privilege elevation 2026-09-15 11:23:27 +08:00
gitea c50ea3edad Release v0.10.24: Hose assist link OpenAPI key extraction and privilege elevation 2026-09-15 11:17:03 +08:00
yunyingk 4ba3dabc79 Merge pull request #110 from yunyingk/codex/extract-hose-keys-from-link
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add Hose OpenAPI key extraction from assist links
2026-09-15 11:15:24 +08:00
gitea fcbc87e997 Add Hose OpenAPI key extraction from assist links 2026-09-15 11:14:16 +08:00
yunyingk e30bca6e11 Merge pull request #109 from yunyingk/codex/adjust-gitea-sync-timeout
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Increase Gitea release mirror timeout to 60 minutes
2026-09-15 11:12:10 +08:00
gitea f5772c6053 Increase Gitea sync timeout to 60 minutes for high payload uploads 2026-09-15 11:10:58 +08:00
yunyingk 36d7d42e89 Merge pull request #108 from yunyingk/codex/fix-release-workflow-and-bump-guardrails
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Fix release workflow quota resilience and add bump-version workspace guardrails
2026-09-15 11:09:05 +08:00
gitea f027d65856 Fix release workflow quota resilience and add bump-version workspace guardrails 2026-09-15 11:07:56 +08:00
yunyingk a03731671e Merge pull request #107 from yunyingk/codex/release-v0.10.23
🧪 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.23: Hose flow alignment, targeted SN export, and minute timestamp suffix
2026-09-15 10:42:11 +08:00
gitea 564566032d Release v0.10.23: Hose flow alignment, targeted SN export, and minute timestamp suffix 2026-09-15 10:40:55 +08:00
yunyingk 5a95fa2bd5 Merge pull request #106 from yunyingk/codex/hose-flow-alignment
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add Hose flow alignment, targeted SN export, and minute timestamp suffix
2026-09-15 10:40:01 +08:00
gitea 9e85305098 Update CLI help, skill documentation, and next-step stderr guidance 2026-09-15 10:38:54 +08:00
gitea a7c7ecb0c7 Add target SN export filter and minute timestamp suffix 2026-09-15 10:36:31 +08:00
gitea 643676afd9 Add distinctive emojis for special actions in Hose human opinions 2026-09-15 10:28:24 +08:00
gitea e3c7f93dd9 Preserve strict flow sequence numbers when hoisting mid-flow modifications 2026-09-15 10:22:13 +08:00
gitea a91f4b5f25 Refine Hose flow alignment for rejection targets and mid-flow modifications 2026-09-15 10:19:20 +08:00
gitea f493d5911b Refine subsequent human event filtering to use effectiveRunTime 2026-09-15 09:50:41 +08:00
gitea cfc6ff3b88 Anchor AI runs to Hose flow via exact nodeId with 60s queue delay fallback 2026-09-15 09:48:26 +08:00
gitea 8264865aec Fix isLatestRun cross-period blindspot: detect subsequent ebot/AI runs in Hose history 2026-09-15 09:37:51 +08:00
gitea 577ad0415c Fix time-windowed rejection scoping, revert synthetic mapping on system fields, and make E columns strictly opt-in via --with-flow 2026-09-15 09:23:06 +08:00
gitea de79e9735b Make --with-flow opt-in: E人工行为/E人工意见 columns require explicit --with-flow flag 2026-09-14 18:28:38 +08:00
gitea 870975b5f7 Use 提交人(xxx): 单据撤回 prefix for retract events (no Hose nodeName) 2026-09-14 18:18:25 +08:00
gitea 047c877c1f Fix retracted run status and eliminate synthetic node leakage 2026-09-14 18:11:21 +08:00
gitea 86ac075c48 Refine flow alignment with native Hose states, numbering, and prefix 2026-09-14 17:55:52 +08:00
gitea 2d4b0b1d36 Translate freeflow.back and refine payment and CC actions 2026-09-14 17:42:09 +08:00
gitea 6c351b34df Prioritize reject event and Seal rejection over post-AI mutation 2026-09-14 17:39:06 +08:00
gitea 6c6b3034a0 Support paid flow states, freeflow pay actions, and clean pending nodes 2026-09-14 17:34:35 +08:00
gitea d5f68ea2f3 Map EXEMPT_APPROVE to 备注通过 and ERROR to 错误 in AI decision column 2026-09-14 17:27:05 +08:00
gitea 1a2c41c70c Fix flow alignment for retracted runs and add cancel cell styling 2026-09-14 17:24:27 +08:00
gitea b9ea04adc6 Add Hose approval flow alignment for approval runs export
- Add Hose flow domain with OpenAPI & CloseAPI timeline and staff opinion parsing
- Add E人工行为 and E人工意见 columns in approval runs Excel export
- Add pre-flight scale/duration warning and smooth concurrency throttling (default concurrency 3, batch delay 150ms)
- Add seal-use approval-runs flow diagnostic CLI command and tool
- Support --to-downloads and --flow-concurrency CLI flags
2026-09-14 17:20:19 +08:00
72 changed files with 8125 additions and 800 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
../../skills/seal-use
+3
View File
@@ -0,0 +1,3 @@
# Reviewers for this repository. Enforce through branch protection ("Require review from Code
# Owners") on main, so the release-critical paths below cannot be changed unreviewed.
* @yunyingk
+18
View File
@@ -0,0 +1,18 @@
version: 2
updates:
# Both workflows pin actions to commit SHAs, so nothing updates them implicitly — this is what
# keeps the pins from silently rotting, and it is the only reviewer-visible record of an action
# bump.
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
groups:
github-actions:
patterns: ["*"]
- package-ecosystem: bun
directory: /
schedule:
interval: weekly
open-pull-requests-limit: 5
+15 -5
View File
@@ -4,11 +4,9 @@ on:
push:
branches:
- main
- master
pull_request:
branches:
- main
- master
workflow_dispatch:
concurrency:
@@ -24,12 +22,12 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: latest
bun-version: 1.3.14
- name: Install dependencies
run: bun install --frozen-lockfile
@@ -48,6 +46,18 @@ jobs:
- name: Build MCP Plugin & Verify
run: |
bun run build:plugin
git diff --exit-code dist/mcp/server.js || (echo "::error::dist/mcp/server.js is out of sync with src/. Run 'bun run build:plugin' and commit changes." && exit 1)
# Boot the freshly built bundle and complete an MCP handshake. A bundle that cannot start
# is invisible to source-level tests — this has regressed before, when circular imports
# scrambled zod's initialisation order and shipped an entry point that never answered.
# Re-running the server tests here points them at the artifact just built, not the
# committed one.
#
# The diff gate above depends on bun-version being pinned: the minifier allocates
# identifiers differently across Bun releases, so an unpinned runner rebuilds to
# different bytes (measured: a bun 1.4.2 rebuild of a 1.3.14-built bundle differed only
# by renamed minified variables). Keep the pin in step with the committed bundle.
bun test src/server.test.ts
- name: Verify Binary Compilation
run: |
+39 -6
View File
@@ -22,16 +22,45 @@ jobs:
build-and-publish-github:
name: 🚀 Build & Publish GitHub Release
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
fetch-depth: 0
# The tag is the publish trigger, but on its own it says nothing about review: `contents:
# write` plus any pushed tag would ship binaries built from an unreviewed commit, and the
# manual dispatch input can name a tag that was never merged. Require the tagged commit to
# be an ancestor of origin/main, i.e. to have gone through the protected branch.
- name: Verify the release tag is on main
env:
TAG_NAME: ${{ github.event.inputs.tag || github.ref_name }}
run: |
if [ -z "${TAG_NAME}" ]; then
echo "::error::Could not resolve a release tag from this event."
exit 1
fi
git fetch --no-tags origin main
if ! git rev-parse --verify --quiet "refs/tags/${TAG_NAME}" >/dev/null; then
if ! git fetch --no-tags origin "refs/tags/${TAG_NAME}:refs/tags/${TAG_NAME}"; then
echo "::error::'${TAG_NAME}' is not a tag in this repository. Pass the release tag as the workflow input."
exit 1
fi
fi
TAG_COMMIT=$(git rev-list -n 1 "refs/tags/${TAG_NAME}")
if ! git merge-base --is-ancestor "${TAG_COMMIT}" origin/main; then
echo "::error::Tag ${TAG_NAME} (${TAG_COMMIT}) is not an ancestor of origin/main. Merge it through a PR first, then re-tag."
exit 1
fi
echo "✓ ${TAG_NAME} -> ${TAG_COMMIT} is on main"
- name: Setup Bun
uses: oven-sh/setup-bun@v2
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: latest
bun-version: 1.3.14
- name: Install dependencies
run: bun install --frozen-lockfile
@@ -74,7 +103,8 @@ jobs:
gh release upload "${TAG_NAME}" dist/bin/seal-use-* dist/bin/checksums.txt --repo "${GITHUB_REPOSITORY}" --clobber
- name: Upload binaries artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
continue-on-error: true
with:
name: release-binaries
path: dist/bin/
@@ -83,12 +113,15 @@ jobs:
publish-gitea:
name: 📦 Sync Gitea Mirror
needs: build-and-publish-github
if: ${{ always() }}
# Mirror only a release that was actually published. `always()` also ran this after the
# tag-on-main guard refused to publish, so the mirror chased assets that were never built.
if: ${{ !cancelled() && needs.build-and-publish-github.result == 'success' }}
runs-on: ubuntu-latest
timeout-minutes: 60
continue-on-error: true
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
fetch-depth: 0
+4 -2
View File
@@ -17,5 +17,7 @@ enterprises/*.json
exports/
scripts/export-*.ts
# Local custom linters
linters/
# Local custom linters. Loaded and executed from <cwd>/linters at runtime, so a fresh
# clone has none — README.md is tracked to explain the convention, the linters stay private.
linters/*
!linters/README.md
+1 -1
View File
@@ -4,7 +4,7 @@
"type": "stdio",
"command": "node",
"args": [
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
"${ZCODE_PLUGIN_ROOT}/dist/mcp/server.js"
],
"env": {
"SEAL_USE_MCP_ENABLED": "${user_config.enable_mcp}"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.22",
"version": "0.10.26",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+15 -3
View File
@@ -4,7 +4,7 @@
This is a Bun + TypeScript toolkit for the `seal-use` CLI and optional MCP server. Entry points are `src/cli.ts`, `src/server.ts`, and `src/probe.ts`. Shared config, auth, token, and HTTP code is under `src/core/`. Seal-specific API and tool logic is under `src/domains/seal/`.
The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares the plugin manifest, `.mcp.json` declares the optional MCP server (disabled by default), and the agent skill lives under `skills/seal-use/`. `.agents/skills/seal-use` is a symlink to `skills/seal-use` so workspace and Codex skill loading keep working.
The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares the plugin manifest, `.mcp.json` declares the optional MCP server (disabled by default), and the agent skill lives under `skills/seal-use/`. The in-repo `.agents/skills/seal-use` symlink has been dropped; workspace and Codex skill loading use the global `~/.agents/skills/seal-use` copy installed by `seal-use skill install`.
Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in `openapi/`; bundled output is `dist/openapi.json`. Example enterprise configs are in `enterprises/example.*.json`; real configs must stay untracked.
@@ -31,7 +31,8 @@ Prefer small domain functions over broad utility modules.
## CLI & Agent Harness Protocol Guidelines
- **Machine Channel (`stdout`)**: CLI commands MUST output clean, parseable JSON on `stdout`. Never dump human prose, raw logs, or progress banners into `stdout`. The Agent Harness parses `stdout` directly into typed payloads.
- **Machine Channel (`stdout`)**: Data commands MUST output clean, parseable JSON on `stdout`. Never dump human prose, raw logs, or progress banners into `stdout`. The Agent Harness parses `stdout` directly into typed payloads.
- **Documented exception — document-output commands**: `seal-use --help` / `seal-use help <area>` (`src/cli/printer.ts`) and `seal-use doctor guide` (`src/cli/commands/doctor.ts`) intentionally write Markdown to `stdout`, because their output *is* the payload the caller redirects or reads (e.g. `seal-use doctor guide > guide.md`). Never add a new prose-on-stdout command outside this list: return structured JSON and put the readable rendering on `stderr` instead. `src/probe.ts` is a local developer probe script rather than a `bin` entry point, so its `[probe] …` lines are outside this contract.
- **Guidance & Diagnostic Channel (`stderr`)**: Use `stderr` for runtime logs, network probing status, self-healing notifications, and explicit **Next-Step Command Suggestions** (e.g. `👉 Next action: seal-use deploy hosecloud sync <signKey>`).
- **Exit Code Contract**:
- Successful executions MUST terminate with exit code `0`.
@@ -52,7 +53,15 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
- Run `bun run bump <new-version | patch | minor>` (automatically updates `package.json`, `.zcode-plugin/plugin.json`, `skills/seal-use/SKILL.md`, `openapi/openapi.yaml`, and bundles `dist/`).
- Update `CHANGELOG.md` with new features and fixes.
- Run `bun test && bun run check`.
2. **Protected-Branch Release**:
2. **Protected-Branch Release & Workspace Isolation**:
- **Isolation Rule**: If the main working directory contains uncommitted changes or another branch is actively being edited, NEVER switch branches or stash in the shared repository. Instead, use an isolated worktree for release operations:
```bash
git worktree add -b codex/release-vX.Y.Z /tmp/seal-use-release main
cd /tmp/seal-use-release
# Execute bump, commit, push, PR, merge, tag here
# When finished, remove the worktree:
git worktree remove /tmp/seal-use-release
```
- Do not tag or push `main` directly. Create a release branch, commit the version bump, push it, open a PR to `main`, wait for the required CI check, and merge the PR first.
- After the PR is merged, fast-forward the local `main`, then synchronize `home/main` before creating the tag:
```bash
@@ -74,11 +83,14 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
git push origin refs/tags/vX.Y.Z
```
- GitHub Actions will automatically extract the tag message, append commit notes via `--generate-notes`, cross-compile all 5 target binaries, and publish GitHub and Gitea releases. Wait for the workflow, then verify that both releases point to the intended tag commit and contain every expected asset exactly once.
- The workflow enforces the merge-before-tag rule rather than trusting the operator: `release.yml` refuses to publish unless the tagged commit is an ancestor of `origin/main`, and the Gitea mirror job runs only after a successful publish. Actions in both workflows are pinned to commit SHAs, so an action bump arrives as a Dependabot PR (`.github/dependabot.yml`) rather than silently.
## Security & Configuration Tips
Never commit real enterprise credentials, Seal tokens, service logs, or local generated state. Use `enterprises/example.hose.json` or `enterprises/example.direct.json` as templates, then place real configs in `enterprises/local.json` or `~/.config/seal-use/enterprises` (with legacy fallback to `~/.config/seal-home/enterprises`). For auth or tenant changes, verify with `bun run probe` or `seal-use auth diagnose`.
Credential files are written `0600`; a config placed by hand keeps the `0o644` default, so run `seal-use doctor` and act on its `credential_permissions` check before sharing a machine or a backup. See `SECURITY.md` for the trust model (local HTTP adapter, self-update, custom linters).
## Agent-Specific Instructions
Do not create `.codex/skills`; Codex is compatible with `.agents/skills`, and this project treats `.agents/` as authoritative. At project scope, prefer `AGENT.md` instructions when present.
+95
View File
@@ -7,6 +7,101 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.10.26] - 2026-09-15
### Fixed
- **`seal-use update` Installed the Previous Release's Agent Skill**: `update` replaced the binary and then called the in-process skill sync, which writes the `EMBEDDED_SKILL_FILES` compiled into the *running* image — and after `renameSync` the running image is still the release being replaced. Every self-update therefore installed the binary it had just downloaded together with the skill of the version it was leaving. Measured on a real update: binary v0.10.25, `~/.agents/skills/seal-use/SKILL.md` rewritten in the same minute, still reading `version: 0.10.24` and 25 lines behind. The stale copy is not cosmetic — the 0.10.24 skill told agents to use `seal_cli` as the primary MCP path and knew nothing about the `seal_cli` / `seal_cli_write` split, so write commands were refused with no follow-up tool named. Nothing healed it: the only automatic sync is gated on the long-removed `seal-home` legacy directory. `update` now installs the skill by running the **newly installed binary** as one synchronous child process (nothing is left running), then reads `SKILL.md` back and fails loudly when the version is not the version it just installed — the binary stays updated, and the error names `seal-use skill install`. The old failure mode was invisible because "the file was written" was the only thing ever checked.
- **`install.sh` Verified the Wrong Line of `checksums.txt`**: `grep "${asset}" | head -n1` is a regex match, and `seal-use-darwin-arm64` also matches the `seal-use-darwin-arm64.tar.gz` line, which `sha256sum seal-use-*` emits first — so verifying an archive compared it against the raw binary's hash. Now an exact `awk '$2 == name'` match against the asset that was actually downloaded.
### Changed
- **The Compressed Archive Is Now the Preferred Download**: `seal-use update` and `scripts/install.sh` both fetched the raw executable (67–102 MB) even though a `.tar.gz` (25–39 MB) ships beside it — and the Gitea mirror publishes the darwin-arm64 archive first precisely because it is small, so the raw-binary preference was also the slowest path through the mirror. `matchAssetForPlatform` now prefers the archive on darwin and linux; Windows still prefers the raw `.exe`, because extracting the `.zip` there would rely on an `unzip` binary that stock Windows does not ship. `install.sh` tries the archive across every mirror and falls back to the raw binary when a release or mirror only carries that.
- **`install.sh` Accepts `SEAL_USE_INSTALL_DIR`, and Extraction No Longer Needs `find`**: the target directory used to be whichever writable global bin the script found first, which made the installer impossible to exercise without touching a real global bin; it now takes an explicit directory (which is how this change was tested end-to-end against a scratch directory, including the archive-404 fallback). Archive extraction also stopped shelling out to `find`, which Windows does not ship — the archive path could not have worked there even after a successful download.
## [0.10.25] - 2026-09-15
### Added
- **`x-implementation-status` on Every OpenAPI Operation, Gated by a Test**: the published contract and the adapter had drifted in **both** directions, and the CI sync gate only compared `openapi/openapi.yaml` against `dist/openapi.json`, so neither direction was visible. It advertised `/v1/approval/rules/{ruleId}` PATCH/DELETE, `/v1/approval/documents*`, `/v1/corps/current/switch` and `/v1/material-packages/upload` — none of which `src/http/routes.ts` routes, so a caller following the contract got 404 — while omitting `/v1/approval-runs/stats`, `/v1/preferences` and `/v1/preferences/decision`, which it does serve. All 46 operations now carry `implemented` (19) or `planned` (27); the three missing implemented endpoints are documented; and `src/http/openapi-implementation.test.ts` fails when an `implemented` operation has no matching route, when an exact `/v1` route is undocumented, or when either status goes unused.
- **Release Guard: the Tag Must Be on `main`**: `release.yml` published on any pushed `v*` tag with `contents: write`, so a tag on an unreviewed branch shipped binaries, and the `workflow_dispatch` tag input could name a tag that was never merged. A guard step now requires the tagged commit to be an ancestor of `origin/main` and fails loudly otherwise (verified against a real release tag, a nonexistent tag, and a branch name). The Gitea mirror job changed from `always()` to "the publish job succeeded", so it no longer chases assets after a refused publish.
- **`SECURITY.md`, `CODEOWNERS` and Dependabot**: the trust model was implicit in the code. `SECURITY.md` records how to report privately, which files hold credentials and their modes, and the three documented limitations (the local HTTP adapter does not authenticate; `update`/`install.sh` do not verify signatures; `linters/` is executed code). `.github/dependabot.yml` keeps dependencies and the newly SHA-pinned actions fresh, and `CODEOWNERS` gives branch protection something to require.
- **`dist/mcp/server.js` Freshness Gate, Enabled by Pinning Bun**: CI now fails when the committed MCP bundle does not match a fresh build from `src/`, mirroring the `dist/openapi.json` gate. This needed `bun-version` pinned to `1.3.14` in both workflows first — previously `latest`, which resolved to 1.4.2 on the runner, and the minifier allocates identifiers differently across Bun releases, so an unpinned rebuild never matched the committed bytes (measured: identical code, only renamed minified variables). The pin also makes release binaries reproducible and matches the `@types/bun`/`bun-types` already declared in `package.json`.
- **CI Boots the Packaged MCP Bundle**: the MCP build step now starts the freshly built `dist/mcp/server.js` and completes a handshake, instead of only checking that it compiles. The artifact is the only thing that ships, so an unbootable bundle is now caught in CI rather than at runtime. This runs *in addition to* the byte-for-byte freshness diff above, which is what the `bun-version` pin exists to keep meaningful; the handshake covers the failure the diff cannot see (a bundle that rebuilds identically but cannot start).
### Fixed
- **Credential Files Could Be Group/World-Readable**: the tool writes credentials `0600` (`core/config/loader.ts`, `cli/commands/corps.ts`, `core/auth/token-store.ts`), but `usage.json` used the `0o644` default and hand-placed enterprise configs kept it too — `enterprises/local.json` holds a plaintext Hose app key and password. `usage.json` is now written `0600`, and `seal-use doctor` gained a `credential_permissions` check that lists any credential file wider than `0600` (skipping the `example.*.json` templates) instead of leaving the mode to be discovered by hand.
- **`isSealHomeProcess` Matched Substrings Instead of the Daemon**: the pid file proves only that *some* process holds that pid, yet `service stop` accepted any command line containing `seal-use`, `service` and `run` as substrings anywhere — so a stale pid could look like our daemon and get signalled. Identity is now matched as argv tokens: an exact adjacent `service run` pair plus a path to this app root or a `seal-use`/`seal-home` launcher.
- **OpenAPI Described the Adapter as Unimplemented, and an Unauthenticated Header as "Optional"**: `info.description` said the contract applied "once the HTTP adapter is implemented" and `servers[0]` called itself "reserved for a future local HTTP adapter; the current service uses MCP stdio" — both false, since `seal-use http` and the `service start` daemon serve it. The `localSession` scheme was documented as an "optional" header that no code reads. The description now states what is served, and the scheme states plainly that requests are not authenticated and the port must stay on loopback.
- **Read-Only MCP Refused Three Read-Only `approval-runs` Verbs**: `approval-runs search`, `approval-runs pick` and `approval-runs bridge` were refused by the read-only tool even though each only queries. The #117 note that `pick` had "moved into read-only" was true of the tool registry but not of the CLI allow-list, which is exactly the kind of split-brain the next entry prevents.
- **Consistency Test Between the CLI Allow-List and the Tool Registry**: the two read/write classifications are maintained by hand in different files, and they had already disagreed twice (`analytics analyze` allow-listed while its tool POSTs; the three verbs above missing). A test now derives the pairing mechanically — every `action === "x"` in `src/cli/commands/*` that dispatches to a `runTool("seal_…")` — and fails when a CLI verb that reaches a read-only tool is itself refused. It asserts a minimum number of pairs so a change in dispatch shape cannot make it silently vacuous, and names its two exceptions explicitly: the `deploy <action>` short forms, which `deploy` rejects at runtime, and `approval-runs search`, an accepted alias of `list` with no help-registry row.
- **MCP Server Bundle Could Not Start At All**: the plugin shipped `dist/mcp/server.js` as its MCP entry point, but that bundle threw `TypeError: ... is not a constructor` while loading and never answered a single request. Because MCP defaults to off, it failed silently — enabling it produced no `seal_cli` tool and no visible error.
- Root cause: the MCP entry (`src/server.ts`) was circularly entangled with the CLI command graph (`server → cli/runner → cli/commands/mcp → server`, and `server → cli/runner → cli/commands/http → http/routes → server`). When `bun build --target=node` flattened that cycle together with zod's own `core ↔ classic` cycle, zod's class initialisers ended up ordered after the top-level `z.lazy()` call the SDK makes at import time, leaving `ZodLazy` undefined at call time.
- Fix: moved `tokenizeCommand` / `normalizeCliArgs` into a leaf module (`src/cli/tokenize.ts`) and made the `mcp` command import the server lazily, removing both cycles. The stock build command now emits a working bundle.
- Added a regression test that boots the packaged `dist/mcp/server.js` over stdio and completes a handshake. The existing tests exercise source rather than the shipped artifact, which is why this went unnoticed.
### Changed
- **`package.json` Can No Longer Be Published by Accident**: it had no `private` flag, no `files` list and none of `description`/`license`/`author`/`repository`, so an `npm publish` would have shipped 212 files including `.github/workflows`, `openapi/`, `docs/proposals`, `src/**/*.test.ts` and `dist/raw-seal-openapi.json` — and the `bin` entries point at `src/cli.ts`, which npm cannot execute, so the published package would have been broken on arrival. `private: true` makes the Release binaries the only distribution channel (the `bin` field stays for `npm link`, which the README recommends for development). Added the missing metadata.
- **`packageManager` and `engines` Now Match the Pinned CI Toolchain**: both workflows pin `bun-version: 1.3.14` because the MCP bundle's byte-for-byte freshness gate depends on it, but the repository declared nothing — so a contributor on a different Bun got a bundle that failed the gate for reasons unrelated to their change. `packageManager: "bun@1.3.14"` and `engines.bun` record the same pin, alongside the build instructions.
- **Documented Exception for Prose on `stdout`**: `AGENTS.md` required clean JSON on `stdout` without exception, yet `seal-use --help` and `seal-use doctor guide` deliberately write Markdown there — their output *is* the payload callers redirect (`seal-use doctor guide > guide.md`). Rather than break that, the contract now names the allowed document-output commands, keeps `src/probe.ts` out of scope as a developer script, and forbids adding new prose-on-stdout commands.
- **Actions Pinned to Commit SHAs**: `actions/checkout`, `oven-sh/setup-bun` and `actions/upload-artifact` were referenced by moving tags (`@v4`, `@v2`) in a workflow that cross-compiles the binaries users install. Both workflows now pin the commit each tag resolved to, with the version in a trailing comment for Dependabot to update.
- **`plugin-migration-plan.md` Archived to `docs/proposals/`**: a completed migration plan (status: code and release finished 2026-08-12) was sitting at the repository root next to `README.md` and `AGENTS.md`.
- **`linters/` Explains Itself**: the directory is gitignored in full and loaded at runtime from `<cwd>/linters`, so a fresh clone silently had no custom linters and no way to learn the convention. `linters/README.md` is now tracked (the only tracked file there) and records the resolution order, the module shape, and the trust boundary — these files are imported and executed in the CLI process.
- **Read-Only Coverage for `seal-use tool <name>`, and a Misclassification Fixed**: the 98-entry internal tool registry now carries an exhaustive read/write classification (`SEAL_READ_ONLY_TOOLS` / `SEAL_MUTATING_TOOLS` in `src/domains/seal/tools.ts`), so the read-only MCP tool reaches read-only registry tools (66 of them) instead of refusing the whole `tool` area. A test asserts the two sets partition the registry exactly, so a newly added tool fails the suite until it is classified rather than silently defaulting.
- This caught a mistake shipped in #115: `analytics analyze` was allow-listed as read-only, but it calls `seal_insight_record_analyze`, which issues a **POST** and starts an analysis server-side. Removed. The classification was cross-checked mechanically — every exported function in `src/domains/seal` that performs a mutating HTTP call was mapped to the tools invoking it — rather than by trusting tool names.
- `approval-runs pick` moved the other way, into read-only: it is a query, not a local-state mutation.
- **MCP TypeScript SDK v1 to v2**: the monolithic `@modelcontextprotocol/sdk` package has been split into scoped packages. Migrated the server to `@modelcontextprotocol/server` and the tests to `@modelcontextprotocol/client`, both at v2.
- Replaced the low-level `Server` + `setRequestHandler` usage with the high-level `McpServer` + `registerTool`, and the hand-written JSON Schema literal with a Zod `z.strictObject` schema (which still emits `additionalProperties: false`).
- Added tool metadata clients could not previously see: a `title` and `annotations` (`readOnlyHint: false`, `destructiveHint: true`, `idempotentHint: false`, `openWorldHint: true`). `seal_cli` is a passthrough that can reach mutating verbs, so it must not be advertised as safe to auto-run or safe to retry; the description now names the command families that need user confirmation.
- `startServer` uses the v2 `serveStdio` entry point, which owns protocol-era negotiation (2025-era clients keep working) and connection teardown.
- `.mcp.json` uses the ZCode-native `${ZCODE_PLUGIN_ROOT}` instead of the Claude-ecosystem alias (verified equivalent in ZCode's resolver).
- **Approval Runs Export No Longer Emits `driftCount`** (#112): `approval-runs export` returned a bare audit-drift counter with no way to trace it back to a document — no SN, no `recordId`, no reason — so interpreting it required a separate per-document `approval-runs flow` query. The drift itself is already visible in the workbook's `E人工行为` / `E人工意见` columns (e.g. AI 决策「通过」with E人工行为「已撤回」and a formatted retraction opinion), and `seal_approval_runs_export` never enabled the flow alignment, so the field was a constant `0` there. Removed `driftCount` from the export result rather than enriching it; per-run `auditDrift` / `auditDriftReason` in `approval-runs flow` are unchanged.
- **MCP Exposes a Read-Only Tool and a Write Tool Instead of One Passthrough**: `seal_cli` could reach every command, so its annotations had to be all-or-nothing (`destructiveHint: true` on a tool that mostly reads, meaning clients could not auto-approve anything, or nothing could be gated — no middle ground). Split into:
- `seal_cli` — read-only, annotated `readOnlyHint: true` / `destructiveHint: false`, so clients may auto-approve it.
- `seal_cli_write` — mutations, publishing, credential minting, self-update and server commands, annotated `destructiveHint: true`.
- The boundary is **enforced, not just annotated**: `seal_cli` executes only commands on an explicit allow-list (84 read-only entries in `src/cli/read-only.ts`) and fails closed on anything unclassified — including commands added to the CLI later. Matching reuses the CLI's own `parseArgs` and matches whole tokens, so a read prefix cannot smuggle a mutation (`corps listing` is refused) and read prefixes cannot cover subcommands (a bare `doctor` does not cover `doctor <anything>`). Refusals name `seal_cli_write` as the follow-up.
- Deliberately excluded from the read-only set even though they look harmless: anything writing local config (`corps switch`, `config test-dir`), minting or printing credentials (`auth keys`, `corps extract-keys`), self-updating (`update`), or standing up a long-running server (`http`, `mcp`, `service run`). `seal-use tool <name>` is also excluded, since the 98-entry internal tool registry is not itself classified.
- A test asserts every allow-listed command still exists in the help registry, so the list cannot silently rot.
- **MCP Is an Optional Path, Off by Default**: made explicit in the skill. The CLI is the primary channel; a missing `seal_cli*` tool is the normal default rather than a fault, and enabling it is the user's choice in the plugin settings. Also corrected skill docs that presented internal tool-registry names (`seal_webhook_get`, `seal_webhook_update`, …) as if they were MCP tools — the MCP server exposes only the two `seal_cli*` tools, and those registry entries are reached through them.
## [0.10.24] - 2026-09-15
### Added & Enhanced
- **Hose Subdomain Privilege Elevation & Assist Link Key Extraction (`extract-keys` / `add-link --as-hose`)**:
- Implemented extracting permanent OpenAPI developer credentials (`appKey` and `appSecurity`) from incoming Hose/Ekuaibao assistance links (`thirdparty.html`) via internal session key interfaces (`GET /api/innerapi/v1/key`).
- Added `seal-use corps extract-keys <url>` (alias: `seal-use auth extract-keys`) with `--reveal` (`-r`) for explicit unmasking and `--save` to upgrade short-lived session links into durable standard Hose enterprise configurations.
- Added `--as-hose` option to `seal-use corps add-link` to automatically elevate privileges to standard Hose configuration upon link import.
- **Strict Subdomain Hierarchy & Core Domain Boundaries**:
- Explicitly defined the Hose capability boundary: `seal-use` is the primary smart approval platform; Hose is an upstream integrated ecosystem.
- Calling key extraction or `keys` on native Seal enterprises (`corp.source.type !== "hose"`) is strictly rejected with exit code 2 and explicit subdomain boundary explanations.
- **Multi-Key Disambiguation Guardrails**:
- Enforced interactive disambiguation when an enterprise has multiple OpenAPI keys configured instead of guessing or silently picking the first key.
- Emits candidate key lists with application names, appKeys, keyIds, and active status to `stderr`, requiring explicit selection via `--app-key <key>` or `--key-id <id>`. Single-key enterprises are safely auto-selected.
- **Key Inspection Commands (`corps keys` / `auth keys`)**:
- Added `seal-use corps keys [<url> | <corpId>]` and `seal-use auth keys [--corp <corpId>]` to safely inspect configured developer credentials with automatic middle-segment masking (`sec_1234...5678`) and optional `--reveal` display.
- **同等凭据原则(Equal Credential Scope Principle)— Skill & Documentation**:
- Fully documented that a Hose assistance link and a browser cURL from an authenticated Hose admin session are both Hose web frontend sessions with identical privilege scope — the structural difference is delivery format only.
- Updated `SKILL.md` First Rules and `enterprise-onboarding.md` Route 3 with explicit guidance: when a Hose administrator provides a browser cURL, attempt privilege elevation first (extract `accesstoken`+`corpid`+`baseUrl` → call `/api/innerapi/v1/key`), not a downgraded short-term session import.
- Added Route 3a/3b/3c classification in `enterprise-onboarding.md` and a privilege comparison table (F12 session vs. elevated OpenAPI credentials).
## [0.10.23] - 2026-09-15
### Added & Enhanced
- **Hose Native Approval Flow Alignment (`--with-flow`)**:
- Added opt-in `--with-flow` flag to `seal-use approval-runs export` to enrich reports with **E人工行为** and **E人工意见** columns from native Hose/Ekuaibao approval timelines.
- **Rejection Formatting (样式 2-B 三行展开式)**: Cleanly structures rejections with explicit reject target nodes, staff names with roles, and resubmission routing (`↳ 驳回至: ...` / `↳ 重新提交后由...继续审批`).
- **Mid-Flow Modification Detection**: Identifies mid-flow edits (`已支付 (中途修改)` / `审批通过 (中途修改)`), hoists modification events to top (`✏️: 修改了单据`) for instant fact visibility while strictly preserving genuine approval-flow chronological sequence numbers.
- **Action Emojis**: Visual distinction across approval actions (`✏️` 修改、`🤖` 自动同意、`❌` 驳回、`💰` 支付、`💬` 附言、`↩️` 撤回、`🔀` 转审),while normal approvals maintain a clean text format (`: 同意`).
- **Targeted Document SN Export Filter (`--sn` / `--sns`)**:
- Supported `--sn <SN1,SN2>` or `--sns` option for `seal-use approval-runs export` to filter specific documents by single or comma-separated document SNs.
- Direct indexed lookup via Seal backend `search: sn`, bypassing full pagination scans and reducing export runtimes from 30+ seconds to ~1.5 seconds.
- Smart time windowing: searches across full history without artificial 1-day truncation when start/end dates are omitted, and dynamically computes filename date interval from retrieved records.
- **Strict Clean Export Filenames with Forced Minute Timestamp**:
- Enforced a standard format `${safeCorpName}_审核记录_${dateTag}_${countTag}_${YYYYMMDD_HHmm}.xlsx`.
- Filename timestamp suffix accurate to the minute prevents accidental overwrites and ambiguity.
- Eradicated document SN numbers from the output filename to maintain a concise, standard pattern regardless of export batch size.
- **CLI Help, Guidance & Diagnostics Channel**:
- Enhanced `seal-use approval-runs export --help` with complete option table.
- Added next-step command suggestions (`👉 查看导出文件: open "..."`) and flow enrichment hints to `stderr`.
- Synchronized `skills/seal-use/SKILL.md` and CLI documentation references.
## [0.10.22] - 2026-09-14
### Added & Enhanced
+1 -1
View File
@@ -130,7 +130,7 @@ enterprises/*.json
!enterprises/example.*.json
```
The canonical plugin skill lives at `skills/seal-use`; `.agents/skills/seal-use` is a workspace symlink to the same files. Install or copy that folder into a Codex skills directory when you want Codex to invoke the workflow as `$seal-use`.
The canonical plugin skill lives at `skills/seal-use`. There is no in-repo `.agents/skills/seal-use` symlink; run `seal-use skill install` (or copy that folder yourself) to place it in a Codex skills directory such as `~/.agents/skills/seal-use` when you want Codex to invoke the workflow as `$seal-use`.
## ZCode Plugin
+53
View File
@@ -0,0 +1,53 @@
# Security Policy
## Reporting a vulnerability
Please report suspected vulnerabilities privately — do not open a public issue.
- Preferred: GitHub private vulnerability reporting, via the **Security** tab of
<https://github.com/yunyingk/seal-use>.
- The maintainer listed in `package.json` is the fallback contact.
Include the version (`seal-use version`), the platform, and a minimal reproduction. Expect an
initial response within a few business days — this is a small project, not a staffed security team.
## What this tool holds
`seal-use` keeps tenant credentials on the machine that runs it:
| Path | Contents | Mode |
| --- | --- | --- |
| `~/.config/seal-use/seal_tokens.json` | Session tokens and derived keys | `0600` |
| `~/.config/seal-use/enterprises/*.json` | Per-enterprise Hose app key/password or Seal bearer token | `0600` |
| `enterprises/*.json` (working tree) | Same, for enterprises added from a checkout | `0600` |
| `~/.config/seal-use/usage.json` | Per-enterprise command counts | `0600` |
The tool writes these `0600`; a config placed by hand can keep the `0o644` default, so
`seal-use doctor` reports any credential file whose mode is wider than `0600`. Real enterprise
configs are gitignored — never commit them.
## Trust model and documented limitations
These are deliberate trade-offs, not unknown bugs. Report them anyway if you can make one worse
than described here.
- **The local HTTP adapter does not authenticate requests.** `seal-use http` and
`seal-use service start` serve `/api/cli`, `/v1/*` and `/shutdown` on `127.0.0.1:8787` with no
token check and `Access-Control-Allow-Origin: *`; the adapter acts with the credentials already
stored on the machine. It is a local automation surface. Keep it bound to loopback, and do not
run it on a shared or multi-user host. See the `securitySchemes.localSession` note in
`openapi/openapi.yaml`.
- **Self-update and the install script do not verify signatures.** `seal-use update` downloads a
release binary and replaces the running executable; `scripts/install.sh` compares
`checksums.txt` but only warns on a mismatch. Prefer the direct GitHub source
(`SEAL_USE_MIRROR=github`, which skips the third-party mirrors) and pass an explicit
`SEAL_USE_VERSION` when installing.
- **Custom rule linters are code that gets executed.** Files under `<cwd>/linters/` and
`~/.config/seal-use/linters/` are imported into the CLI process by `seal-use rules lint`, with
that process's filesystem access and enterprise credentials. Treat those directories as trusted
code and do not run the CLI from an untrusted checkout. See `linters/README.md`.
## Supported versions
Fixes land on `main` and ship in the next tagged release; only the latest release is supported.
Release binaries are published to GitHub Releases and mirrored to Gitea.
+8 -157
View File
@@ -4,7 +4,7 @@
"workspaces": {
"": {
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"@modelcontextprotocol/server": "^2.0.0",
"archiver": "^8.0.0",
"exceljs": "^4.4.0",
"iconv-lite": "^0.7.3",
@@ -14,6 +14,7 @@
"zod": "^4.4.3",
},
"devDependencies": {
"@modelcontextprotocol/client": "^2.0.0",
"@types/archiver": "^8.0.0",
"@types/bun": "^1.3.14",
"@types/yauzl": "^3.4.0",
@@ -28,9 +29,11 @@
"@fast-csv/parse": ["@fast-csv/parse@4.3.6", "", { "dependencies": { "@types/node": "^14.0.1", "lodash.escaperegexp": "^4.1.2", "lodash.groupby": "^4.6.0", "lodash.isfunction": "^3.0.9", "lodash.isnil": "^4.0.0", "lodash.isundefined": "^3.0.1", "lodash.uniq": "^4.5.0" } }, "sha512-uRsLYksqpbDmWaSmzvJcuApSEe38+6NQZBUsuAyMZKqHxH0g1wcJgsKUvN3WC8tewaqFjBMMGrkHmC+T7k8LvA=="],
"@hono/node-server": ["@hono/node-server@1.19.14", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="],
"@modelcontextprotocol/client": ["@modelcontextprotocol/client@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw=="],
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.29.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
"@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.0.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA=="],
"@modelcontextprotocol/server": ["@modelcontextprotocol/server@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "zod": "^4.2.0" } }, "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw=="],
"@types/archiver": ["@types/archiver@8.0.0", "", { "dependencies": { "@types/node": "*", "@types/readdir-glob": "*" } }, "sha512-YpXPbEuv9+eUIPPQWUPahj3cvs9isWRuF+J4z+KbdYVDO3rWorWQFxUVHnwPu2AgKwvgpki5F2VMX0Xx+mX45A=="],
@@ -44,12 +47,6 @@
"abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="],
"accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
"ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
"ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
"archiver": ["archiver@8.0.0", "", { "dependencies": { "async": "^3.2.4", "buffer-crc32": "^1.0.0", "is-stream": "^4.0.0", "lazystream": "^1.0.0", "normalize-path": "^3.0.0", "readable-stream": "^4.0.0", "readdir-glob": "^3.0.0", "tar-stream": "^3.0.0", "zip-stream": "^7.0.2" } }, "sha512-fV1orZfsnPn9BaSByR/qE67rJCLJEy2Ox5bq7nJh+jquWaNh6Sfec75kJ2T6PtdGUbPQlrVoSVCEOa5SdiTQ1g=="],
"archiver-utils": ["archiver-utils@2.1.0", "", { "dependencies": { "glob": "^7.1.4", "graceful-fs": "^4.2.0", "lazystream": "^1.0.0", "lodash.defaults": "^4.2.0", "lodash.difference": "^4.5.0", "lodash.flatten": "^4.4.0", "lodash.isplainobject": "^4.0.6", "lodash.union": "^4.6.0", "normalize-path": "^3.0.0", "readable-stream": "^2.0.0" } }, "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw=="],
@@ -80,8 +77,6 @@
"bluebird": ["bluebird@3.4.7", "", {}, "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA=="],
"body-parser": ["body-parser@2.2.2", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.3", "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" } }, "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA=="],
"brace-expansion": ["brace-expansion@5.0.9", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg=="],
"buffer": ["buffer@6.0.3", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA=="],
@@ -94,30 +89,14 @@
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
"bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
"call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
"call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
"chainsaw": ["chainsaw@0.1.0", "", { "dependencies": { "traverse": ">=0.3.0 <0.4" } }, "sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ=="],
"compress-commons": ["compress-commons@7.0.1", "", { "dependencies": { "crc-32": "^1.2.0", "crc32-stream": "^7.0.1", "is-stream": "^4.0.0", "normalize-path": "^3.0.0", "readable-stream": "^4.0.0" } }, "sha512-g0S8KAD8qf4+V//pr3BfB1aBnARLXNz2Gx+jmHU0LEriUuoQUOPOulVquHKTJ8+EAIIO7fhseNDr9wK5Q9FKBQ=="],
"concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],
"content-disposition": ["content-disposition@1.1.0", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="],
"content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
"cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="],
"cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="],
"core-util-is": ["core-util-is@1.0.3", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="],
"cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
"crc-32": ["crc-32@1.2.2", "", { "bin": { "crc32": "bin/crc32.njs" } }, "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ=="],
"crc32-stream": ["crc32-stream@7.0.1", "", { "dependencies": { "crc-32": "^1.2.0", "readable-stream": "^4.0.0" } }, "sha512-IBWsY8xznyQrcHn8h4bC8/4ErNke5elzgG8GcqF4RFPw6aHkWWRc7Tgw6upjaTX/CT/yQgqYENkxYsTYN+hW2g=="],
@@ -126,30 +105,10 @@
"dayjs": ["dayjs@1.11.23", "", {}, "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ=="],
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
"dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"duplexer2": ["duplexer2@0.1.4", "", { "dependencies": { "readable-stream": "^2.0.2" } }, "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA=="],
"ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
"encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
"end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
"es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
"es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
"es-object-atoms": ["es-object-atoms@1.1.2", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw=="],
"escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],
"etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
"event-target-shim": ["event-target-shim@5.0.1", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="],
"events": ["events@3.3.0", "", {}, "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q=="],
@@ -158,54 +117,24 @@
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
"eventsource-parser": ["eventsource-parser@3.1.0", "", {}, "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg=="],
"eventsource-parser": ["eventsource-parser@3.1.1", "", {}, "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ=="],
"exceljs": ["exceljs@4.4.0", "", { "dependencies": { "archiver": "^5.0.0", "dayjs": "^1.8.34", "fast-csv": "^4.3.1", "jszip": "^3.10.1", "readable-stream": "^3.6.0", "saxes": "^5.0.1", "tmp": "^0.2.0", "unzipper": "^0.10.11", "uuid": "^8.3.0" } }, "sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg=="],
"express": ["express@5.2.1", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],
"express-rate-limit": ["express-rate-limit@8.5.2", "", { "dependencies": { "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A=="],
"fast-csv": ["fast-csv@4.3.6", "", { "dependencies": { "@fast-csv/format": "4.3.5", "@fast-csv/parse": "4.3.6" } }, "sha512-2RNSpuwwsJGP0frGsOmTb9oUF+VkFSM4SyLTDgwf2ciHWTarN0lQTC+F2f/t5J9QjW+c65VFIAAu85GsvMIusw=="],
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-fifo": ["fast-fifo@1.3.2", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="],
"fast-uri": ["fast-uri@3.1.2", "", {}, "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ=="],
"finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="],
"forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="],
"fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="],
"fs-constants": ["fs-constants@1.0.0", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
"fs.realpath": ["fs.realpath@1.0.0", "", {}, "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw=="],
"fstream": ["fstream@1.0.12", "", { "dependencies": { "graceful-fs": "^4.1.2", "inherits": "~2.0.0", "mkdirp": ">=0.5 0", "rimraf": "2" } }, "sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg=="],
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
"get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
"get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
"glob": ["glob@7.2.3", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="],
"gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],
"graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
"has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
"hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],
"hono": ["hono@4.12.23", "", {}, "sha512-eIaZ9qDgu7XV0pxOCrg7/WhnQ6Ivm22UcxhXx/A3dcbqbbYgBEkc6e/J/s7j2tS96zoB0S9VBdLwQNCWwUo4LA=="],
"http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
"iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="],
"ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
@@ -216,23 +145,13 @@
"inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
"ip-address": ["ip-address@10.2.0", "", {}, "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA=="],
"ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
"is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
"is-stream": ["is-stream@4.0.1", "", {}, "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A=="],
"isarray": ["isarray@1.0.0", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="],
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
"jose": ["jose@6.2.3", "", {}, "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw=="],
"json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
"jose": ["jose@6.2.12", "", {}, "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw=="],
"jszip": ["jszip@3.10.1", "", { "dependencies": { "lie": "~3.3.0", "pako": "~1.0.2", "readable-stream": "~2.3.6", "setimmediate": "^1.0.5" } }, "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g=="],
@@ -270,44 +189,20 @@
"lodash.uniq": ["lodash.uniq@4.5.0", "", {}, "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ=="],
"math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
"media-typer": ["media-typer@1.1.0", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="],
"merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],
"mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
"mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
"minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
"mkdirp": ["mkdirp@3.0.1", "", { "bin": { "mkdirp": "dist/cjs/src/bin.js" } }, "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],
"normalize-path": ["normalize-path@3.0.0", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="],
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
"object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
"on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
"once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
"pako": ["pako@1.0.11", "", {}, "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="],
"parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],
"path-is-absolute": ["path-is-absolute@1.0.1", "", {}, "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg=="],
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="],
"pend": ["pend@1.2.0", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="],
"pinyin-pro": ["pinyin-pro@3.29.3", "", {}, "sha512-+UU9bx6vfDw8amOJGHm0TE0rdQl8VPylsDWviQ5OOQ3e+on1xRP4OqDbiDuMT5OISgvfl/Y6ez1BBRaIP80GLQ=="],
@@ -318,52 +213,24 @@
"process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],
"proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
"qs": ["qs@6.15.2", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw=="],
"range-parser": ["range-parser@1.2.1", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="],
"raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],
"readable-stream": ["readable-stream@4.7.0", "", { "dependencies": { "abort-controller": "^3.0.0", "buffer": "^6.0.3", "events": "^3.3.0", "process": "^0.11.10", "string_decoder": "^1.3.0" } }, "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg=="],
"readdir-glob": ["readdir-glob@3.0.0", "", { "dependencies": { "minimatch": "^10.2.2" } }, "sha512-AhNB2KgKeVJr16nK9LLZbJNWnYoT23ZrumNKFDebHBdkC8KHSqWo871JAUhoWC/RtjEVdqNMFpM6qrwRbaUqpw=="],
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
"rimraf": ["rimraf@2.7.1", "", { "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "./bin.js" } }, "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w=="],
"router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
"safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
"saxes": ["saxes@5.0.1", "", { "dependencies": { "xmlchars": "^2.2.0" } }, "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw=="],
"send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],
"serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],
"setimmediate": ["setimmediate@1.0.5", "", {}, "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA=="],
"setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
"side-channel": ["side-channel@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", "side-channel-list": "^1.0.0", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw=="],
"side-channel-list": ["side-channel-list@1.0.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="],
"side-channel-map": ["side-channel-map@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="],
"side-channel-weakmap": ["side-channel-weakmap@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"streamx": ["streamx@2.28.1", "", { "dependencies": { "events-universal": "^1.0.0", "fast-fifo": "^1.3.2", "text-decoder": "^1.1.0" } }, "sha512-zEzXb0s5Cds7tqMH6rhZ05lcJydCWiQPEwiNngVqzsxCc962vLY4Uw+mW7od8kDH258k2Uz/JrOkdIAAhSh9VA=="],
"string_decoder": ["string_decoder@1.3.0", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
@@ -376,26 +243,18 @@
"tmp": ["tmp@0.2.7", "", {}, "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw=="],
"toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
"traverse": ["traverse@0.3.9", "", {}, "sha512-iawgk0hLP3SxGKDfnDJf8wTz4p2qImnyihM5Hh/sGvQ3K37dPi/w8sRhdNIxYA1TwFwc5mDhIJq+O0RsvXBKdQ=="],
"type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],
"unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
"unzipper": ["unzipper@0.10.14", "", { "dependencies": { "big-integer": "^1.6.17", "binary": "~0.3.0", "bluebird": "~3.4.1", "buffer-indexof-polyfill": "~1.0.0", "duplexer2": "~0.1.4", "fstream": "^1.0.12", "graceful-fs": "^4.2.2", "listenercount": "~1.0.1", "readable-stream": "~2.3.6", "setimmediate": "~1.0.4" } }, "sha512-ti4wZj+0bQTiX2KmKWuwj7lhV+2n//uXEotUmGuQqrbVZSEGFMbI68+c6JCQ8aAmUWYvtHEz2A8K6wXvueR/6g=="],
"util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
"uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="],
"vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
@@ -410,8 +269,6 @@
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
"@fast-csv/format/@types/node": ["@types/node@14.18.63", "", {}, "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ=="],
"@fast-csv/parse/@types/node": ["@types/node@14.18.63", "", {}, "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ=="],
@@ -422,8 +279,6 @@
"bl/readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"body-parser/iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"duplexer2/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"exceljs/archiver": ["archiver@5.3.2", "", { "dependencies": { "archiver-utils": "^2.1.0", "async": "^3.2.4", "buffer-crc32": "^0.2.1", "readable-stream": "^3.6.0", "readdir-glob": "^1.1.2", "tar-stream": "^2.2.0", "zip-stream": "^4.1.0" } }, "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw=="],
@@ -436,12 +291,8 @@
"lazystream/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"raw-body/iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"string_decoder/safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"type-is/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],
"unzipper/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"archiver-utils/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
+322 -240
View File
@@ -1,33 +1,33 @@
import{createRequire as HS0}from"node:module";var $S0=Object.create;var{getPrototypeOf:IS0,defineProperty:QP,getOwnPropertyNames:zS0}=Object;var qS0=Object.prototype.hasOwnProperty;function US0($){return this[$]}var YS0,JS0,j4=($,I,z)=>{var q=$!=null&&typeof $==="object";if(q){var U=I?YS0??=new WeakMap:JS0??=new WeakMap,Y=U.get($);if(Y)return Y}z=$!=null?$S0(IS0($)):{};let J=I||!$||!$.__esModule?QP(z,"default",{value:$,enumerable:!0}):z;for(let Q of zS0($))if(!qS0.call(J,Q))QP(J,Q,{get:US0.bind($,Q),enumerable:!0});if(q)U.set($,J);return J};var M=($,I)=>()=>(I||$((I={exports:{}}).exports,I),I.exports);var QS0=($)=>$;function KS0($,I){this[$]=QS0.bind(null,I)}var o8=($,I)=>{for(var z in I)QP($,z,{get:I[z],enumerable:!0,configurable:!0,set:KS0.bind(I,z)})};var e=($,I)=>()=>($&&(I=$($=0)),I);var d=HS0(import.meta.url);function t($,I,z){function q(Q,K){if(!Q._zod)Object.defineProperty(Q,"_zod",{value:{def:K,constr:J,traits:new Set},enumerable:!1});if(Q._zod.traits.has($))return;Q._zod.traits.add($),I(Q,K);let H=J.prototype,G=Object.keys(H);for(let Z=0;Z<G.length;Z++){let W=G[Z];if(!(W in Q))Q[W]=H[W].bind(Q)}}let U=z?.Parent??Object;class Y extends U{}Object.defineProperty(Y,"name",{value:$});function J(Q){var K;let H=z?.Parent?new Y:this;q(H,Q),(K=H._zod).deferred??(K.deferred=[]);for(let G of H._zod.deferred)G();return H}return Object.defineProperty(J,"init",{value:q}),Object.defineProperty(J,Symbol.hasInstance,{value:(Q)=>{if(z?.Parent&&Q instanceof z.Parent)return!0;return Q?._zod?.traits?.has($)}}),Object.defineProperty(J,"name",{value:$}),J}function f4($){if($)Object.assign(H2,$);return H2}var qm,KP,HP,O5,G2,H2;var Z2=e(()=>{KP=Object.freeze({status:"aborted"});HP=Symbol("zod_brand");O5=class O5 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};G2=class G2 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(qm=globalThis).__zod_globalConfig??(qm.__zod_globalConfig={});H2=globalThis.__zod_globalConfig});var M0={};o8(M0,{unwrapMessage:()=>EJ,uint8ArrayToHex:()=>SS0,uint8ArrayToBase64url:()=>hS0,uint8ArrayToBase64:()=>Jm,stringifyPrimitive:()=>w0,slugify:()=>WP,shallowClone:()=>VP,safeExtend:()=>ES0,required:()=>_S0,randomString:()=>MS0,propertyKeyTypes:()=>_J,promiseAllObject:()=>FS0,primitiveTypes:()=>wP,prefixIssues:()=>E8,pick:()=>PS0,partial:()=>CS0,parsedType:()=>O0,optionalKeys:()=>LP,omit:()=>BS0,objectClone:()=>wS0,numKeys:()=>NS0,nullish:()=>L3,normalizeParams:()=>A0,mergeDefs:()=>H9,merge:()=>jS0,jsonStringifyReplacer:()=>Bz,joinValues:()=>Y0,issue:()=>Ez,isPlainObject:()=>F3,isObject:()=>W2,hexToUint8Array:()=>gS0,getSizableOrigin:()=>RJ,getParsedType:()=>DS0,getLengthableOrigin:()=>vJ,getEnumValues:()=>jJ,getElementAtPath:()=>OS0,floatSafeRemainder:()=>ZP,finalizeIssue:()=>K8,extend:()=>TS0,explicitlyAborted:()=>MP,escapeRegex:()=>w$,esc:()=>TW,defineLazy:()=>J1,createTransparentProxy:()=>AS0,cloneDef:()=>LS0,clone:()=>Q8,cleanRegex:()=>CJ,cleanEnum:()=>RS0,captureStackTrace:()=>EW,cached:()=>Tz,base64urlToUint8Array:()=>vS0,base64ToUint8Array:()=>Ym,assignProp:()=>O3,assertNotEqual:()=>ZS0,assertNever:()=>XS0,assertIs:()=>WS0,assertEqual:()=>GS0,assert:()=>VS0,allowsEval:()=>XP,aborted:()=>M3,NUMBER_FORMAT_RANGES:()=>OP,Class:()=>Qm,BIGINT_FORMAT_RANGES:()=>FP});function GS0($){return $}function ZS0($){return $}function WS0($){}function XS0($){throw Error("Unexpected value in exhaustive check")}function VS0($){}function jJ($){let I=Object.values($).filter((q)=>typeof q==="number");return Object.entries($).filter(([q,U])=>I.indexOf(+q)===-1).map(([q,U])=>U)}function Y0($,I="|"){return $.map((z)=>w0(z)).join(I)}function Bz($,I){if(typeof I==="bigint")return I.toString();return I}function Tz($){return{get value(){{let z=$();return Object.defineProperty(this,"value",{value:z}),z}throw Error("cached value already set")}}}function L3($){return $===null||$===void 0}function CJ($){let I=$.startsWith("^")?1:0,z=$.endsWith("$")?$.length-1:$.length;return $.slice(I,z)}function ZP($,I){let z=$/I,q=Math.round(z),U=Number.EPSILON*Math.max(Math.abs(z),1);if(Math.abs(z-q)<U)return 0;return z-q}function J1($,I,z){let q=void 0;Object.defineProperty($,I,{get(){if(q===Um)return;if(q===void 0)q=Um,q=z();return q},set(U){Object.defineProperty($,I,{value:U})},configurable:!0})}function wS0($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function O3($,I,z){Object.defineProperty($,I,{value:z,writable:!0,enumerable:!0,configurable:!0})}function H9(...$){let I={};for(let z of $){let q=Object.getOwnPropertyDescriptors(z);Object.assign(I,q)}return Object.defineProperties({},I)}function LS0($){return H9($._zod.def)}function OS0($,I){if(!I)return $;return I.reduce((z,q)=>z?.[q],$)}function FS0($){let I=Object.keys($),z=I.map((q)=>$[q]);return Promise.all(z).then((q)=>{let U={};for(let Y=0;Y<I.length;Y++)U[I[Y]]=q[Y];return U})}function MS0($=10){let z=""Line truncated
`)}var Km=($,I)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:I,enumerable:!1}),$.message=JSON.stringify(I,Bz,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},hJ,j8;var AP=e(()=>{Z2();h0();hJ=t("$ZodError",Km),j8=t("$ZodError",Km,{Parent:Error})});var jz=($)=>(I,z,q,U)=>{let Y=q?{...q,async:!1}:{async:!1},J=I._zod.run({value:z,issues:[]},Y);if(J instanceof Promise)throw new O5;if(J.issues.length){let Q=new(U?.Err??$)(J.issues.map((K)=>K8(K,Y,f4())));throw EW(Q,U?.callee),Q}return J.value},yJ,Cz=($)=>async(I,z,q,U)=>{let Y=q?{...q,async:!0}:{async:!0},J=I._zod.run({value:z,issues:[]},Y);if(J instanceof Promise)J=await J;if(J.issues.length){let Q=new(U?.Err??$)(J.issues.map((K)=>K8(K,Y,f4())));throw EW(Q,U?.callee),Q}return J.value},xJ,_z=($)=>(I,z,q)=>{let U=q?{...q,async:!1}:{async:!1},Y=I._zod.run({value:z,issues:[]},U);if(Y instanceof Promise)throw new O5;return Y.issues.length?{success:!1,error:new($??hJ)(Y.issues.map((J)=>K8(J,U,f4())))}:{success:!0,data:Y.value}},Rz,vz=($)=>async(I,z,q)=>{let U=q?{...q,async:!0}:{async:!0},Y=I._zod.run({value:z,issues:[]},U);if(Y instanceof Promise)Y=await Y;return Y.issues.length?{success:!1,error:new $(Y.issues.map((J)=>K8(J,U,f4())))}:{success:!0,data:Y.value}},uJ,jW=($)=>(I,z,q)=>{let U=q?{...q,direction:"backward"}:{direction:"backward"};return jz($)(I,z,U)},Gm,CW=($)=>(I,z,q)=>{return jz($)(I,z,q)},Zm,_W=($)=>async(I,z,q)=>{let U=q?{...q,direction:"backward"}:{direction:"backward"};return Cz($)(I,z,U)},Wm,RW=($)=>async(I,z,q)=>{return Cz($)(I,z,q)},Xm,vW=($)=>(I,z,q)=>{let U=q?{...q,direction:"backward"}:{direction:"backward"};return _z($)(I,z,U)},Vm,hW=($)=>(I,z,q)=>{return _z($)(I,z,q)},wm,gW=($)=>async(I,z,q)=>{let U=q?{...q,direction:"backward"}:{direction:"backward"};return vz($)(I,z,U)},Lm,SW=($)=>async(I,z,q)=>{return vz($)(I,z,q)},Om;var PP=e(()=>{Z2();AP();h0();yJ=jz(j8),xJ=Cz(j8),Rz=_z(j8),uJ=vz(j8),Gm=jW(j8),Zm=CW(j8),Wm=_W(j8),Xm=RW(j8),Vm=vW(j8),wm=hW(j8),Lm=gW(j8),Om=SW(j8)});var r8={};o8(r8,{xid:()=>jP,uuid7:()=>fS0,uuid6:()=>kS0,uuid4:()=>uS0,uuid:()=>X2,uppercase:()=>aP,unicodeEmail:()=>Fm,undefined:()=>sP,ulid:()=>EP,time:()=>cP,string:()=>dP,sha512_hex:()=>Jy0,sha512_base64url:()=>Ky0,sha512_base64:()=>Qy0,sha384_hex:()=>qy0,sha384_base64url:()=>Yy0,sha384_base64:()=>Uy0,sha256_hex:()=>$y0,sha256_base64url:()=>zy0,sha256_base64:()=>Iy0,sha1_hex:()=>tS0,sha1_base64url:()=>eS0,sha1_base64:()=>aS0,rfc5322Email:()=>iS0,number:()=>kJ,null:()=>rP,nanoid:()=>_P,md5_hex:()=>oS0,md5_base64url:()=>sS0,md5_base64:()=>rS0,mac:()=>xP,lowercase:()=>tP,ksuid:()=>CP,ipv6:()=>yP,ipv4:()=>SP,integer:()=>lP,idnEmail:()=>nS0,httpProtocol:()=>bP,html5Email:()=>bS0,hostname:()=>dS0,hex:()=>lS0,guid:()=>vP,extendedDuration:()=>xS0,emoji:()=>gP,email:()=>hP,e164:()=>iP,duration:()=>RP,domain:()=>mS0,datetime:()=>pP,date:()=>nP,cuid2:()=>TP,cuid:()=>BP,cidrv6:()=>kP,cidrv4:()=>uP,browserEmail:()=>cS0,boolean:()=>oP,bigint:()=>mP,base64url:()=>yW,base64:()=>fP});function gP(){return new RegExp(pS0,"u")}function Nm($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function cP($){return new RegExp(`^${Nm($)}$`)}function pP($){let I=Nm({precision:$.precision}),z=["Z"];if($.local)z.push("");if($.offset)z.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let q=`${I}(?:${z.join("|")})`;return new RegExp(`^${Mm}T(?:${q})$`)}function fJ($,I){return new RegExp(`^[A-Za-z0-9+/]{${$}}${I}$`)}function bJ($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var BP,TP,EP,jP,CP,_P,RP,xS0,vP,X2=($)=>{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})$`)},uS0,kS0,fS0,hP,bS0,iS0,Fm,nS0,cS0,pS0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",SP,yP,xP=($)=>{let I=w$($??":");return new RegExp(`^(?:[0-9A-F]{2}${I}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${I}){5}[0-9a-f]{2}$`)},uP,kP,fP,yW,dS0,mS0,bP,iP,Mm="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",nP,dP=($)=>{let I=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${I}$`)},mP,lP,kJ,oP,rP,sP,tP,aP,lS0,oS0,rS0,sS0,tS0,aS0,eS0,$y0,Iy0,zy0,qy0,Uy0,Yy0,Jy0,Qy0,Ky0;var xW=e(()=>{h0();BP=/^[cC][0-9a-z]{6,}$/,TP=/^[0-9a-z]+$/,EP=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,jP=/^[0-9a-vA-V]{20}$/,CP=/^[A-Za-z0-9]{27}$/,_P=/^[a-zA-Z0-9_-]{21}$/,RP=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?Line truncated
`).filter((Y)=>Y),q=Math.min(...z.map((Y)=>Y.length-Y.trimStart().length)),U=z.map((Y)=>Y.slice(q)).map((Y)=>" ".repeat(this.indent*2)+Y);for(let Y of U)this.content.push(Y)}compile(){let $=Function,I=this?.args,q=[...(this?.content??[""]).map((U)=>` ${U}`)];return new $(...I,q.join(`
`))}}var OB;var FB=e(()=>{OB={major:4,minor:4,patch:3}});function bB($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function km($){if(!yW.test($))return!1;let I=$.replace(/[-_]/g,(q)=>q==="-"?"+":"/"),z=I.padEnd(Math.ceil(I.length/4)*4,"=");return bB(z)}function fm($,I=null){try{let z=$.split(".");if(z.length!==3)return!1;let[q]=z;if(!q)return!1;let U=JSON.parse(atob(q));if("typ"in U&&U?.typ!=="JWT")return!1;if(!U.alg)return!1;if(I&&(!("alg"in U)||U.alg!==I))return!1;return!0}catch{return!1}}function Bm($,I,z){if($.issues.length)I.issues.push(...E8(z,$.issues));I.value[z]=$.value}function pW($,I,z,q,U,Y){let J=z in q;if($.issues.length){if(U&&Y&&!J)return;I.issues.push(...E8(z,$.issues))}if(!J&&!U){if(!$.issues.length)I.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[z]});return}if($.value===void 0){if(J)I.value[z]=void 0}else I.value[z]=$.value}function bm($){let I=Object.keys($.shape);for(let q of I)if(!$.shape?.[q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${q}": expected a Zod schema`);let z=LP($.shape);return{...$,keys:I,keySet:new Set(I),numKeys:I.length,optionalKeys:new Set(z)}}function im($,I,z,q,U,Y){let J=[],Q=U.keySet,K=U.catchall._zod,H=K.def.type,G=K.optin==="optional",Z=K.optout==="optional";for(let W in I){if(W==="__proto__")continue;if(Q.has(W))continue;if(H==="never"){J.push(W);continue}let X=K.run({value:I[W],issues:[]},q);if(X instanceof Promise)$.push(X.then((w)=>pW(w,z,W,I,G,Z)));else pW(X,z,W,I,G,Z)}if(J.length)z.issues.push({code:"unrecognized_keys",keys:J,input:I,inst:Y});if(!$.length)return z;return Promise.all($).then(()=>{return z})}function Tm($,I,z,q){for(let Y of $)if(Y.issues.length===0)return I.value=Y.value,I;let U=$.filter((Y)=>!M3(Y));if(U.length===1)return I.value=U[0].value,U[0];return I.issues.push({code:"invalid_union",input:I.value,inst:z,errors:$.map((Y)=>Y.issues.map((J)=>K8(J,q,f4())))}),I}function Em($,I,z,q){let U=$.filter((Y)=>Y.issues.length===0);if(U.length===1)return I.value=U[0].value,I;if(U.length===0)I.issues.push({code:"invalid_union",input:I.value,inst:z,errors:$.map((Y)=>Y.issues.map((J)=>K8(J,q,f4())))});else I.issues.push({code:"invalid_union",input:I.value,inst:z,errors:[],inclusive:!1});return I}function MB($,I){if($===I)return{valid:!0,data:$};if($ instanceof Date&&I instanceof Date&&+$===+I)return{valid:!0,data:$};if(F3($)&&F3(I)){let z=Object.keys(I),q=Object.keys($).filter((Y)=>z.indexOf(Y)!==-1),U={...$,...I};for(let Y of q){let J=MB($[Y],I[Y]);if(!J.valid)return{valid:!1,mergeErrorPath:[Y,...J.mergeErrorPath]};U[Y]=J.data}return{valid:!0,data:U}}if(Array.isArray($)&&Array.isArray(I)){if($.length!==I.length)return{valid:!1,mergeErrorPath:[]};let z=[];for(let q=0;q<$.length;q++){let U=$[q],Y=I[q],J=MB(U,Y);if(!J.valid)return{valid:!1,mergeErrorPath:[q,...J.mergeErrorPath]};z.push(J.data)}return{valid:!0,data:z}}return{valid:!1,mergeErrorPath:[]}}function jm($,I,z){let q=new Map,U;for(let Q of I.issues)if(Q.code==="unrecognized_keys"){U??(U=Q);for(let K of Q.keys){if(!q.has(K))q.set(K,{});q.get(K).l=!0}}else $.issues.push(Q);for(let Q of z.issues)if(Q.code==="unrecognized_keys")for(let K of Q.keys){if(!q.has(K))q.set(K,{});q.get(K).r=!0}else $.issues.push(Q);let Y=[...q].filter(([,Q])=>Q.l&&Q.r).map(([Q])=>Q);if(Y.length&&U)$.issues.push({...U,keys:Y});if(M3($))return $;let J=MB(I.value,z.value);if(!J.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(J.mergeErrorPath)}`);return $.value=J.data,$}function Cm($,I){for(let z=$.length-1;z>=0;z--)if($[z]._zod[I]!=="optional")return z+1;return 0}function _m($,I,z){if($.issues.length)I.issues.push(...E8(z,$.issues));I.value[z]=$.value}function Rm($,I,z,q,U){for(let Y=0;Y<z.length;Y++){let J=$[Y],Q=Y<q.length;if(J.issues.length){if(!Q&&Y>=U){I.value.length=Y;break}I.issues.push(...E8(Y,J.issues))}I.value[Y]=J.value}for(let Y=I.value.length-1;Y>=q.length;Y--)if(z[Y]._zod.optout==="optional"&&I.value[Y]===void 0)I.value.length=Y;else break;return I}function vm($,I,z,q,U,Y,J){if($.issues.length)if(_J.has(typeof q))z.issues.push(...E8(q,$.issues));else z.issues.push({code:"invalid_key",origin:"map",input:U,inst:Y,issues:$.issues.map((Q)=>K8(Q,J,f4()))});if(I.issues.length)if(_J.has(typeof q))z.issues.push(...E8(q,I.issues));else z.issues.push({origin:"map",code:"invalid_element",input:U,inst:Y,key:q,issues:I.issues.map((Q)=>K8(Q,J,f4()))});z.value.set($.value,I.value)}function hm($,I){if($.issues.length)I.issues.push(...$.issues);I.value.add($.value)}function gm($,I){if(I===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function Sm($,I){if($.value===void 0)$.value=I.defaultValue;return $}function ym($,I){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:I});return $}function iW($,I,z){if($.issues.length)return $.aborted=!0,$;return I._zod.run({value:$.value,issues:$.issues,fa Line truncated
if (${A}.issues.length) {
import{createRequire as Cg0}from"node:module";var Og0=Object.create;var{getPrototypeOf:Ng0,defineProperty:iT,getOwnPropertyNames:Dg0}=Object;var Bg0=Object.prototype.hasOwnProperty;function Pg0($){return this[$]}var Ag0,Tg0,J6=($,Y,z)=>{var U=$!=null&&typeof $==="object";if(U){var Q=Y?Ag0??=new WeakMap:Tg0??=new WeakMap,J=Q.get($);if(J)return J}z=$!=null?Og0(Ng0($)):{};let I=Y||!$||!$.__esModule?iT(z,"default",{value:$,enumerable:!0}):z;for(let K of Dg0($))if(!Bg0.call(I,K))iT(I,K,{get:Pg0.bind($,K),enumerable:!0});if(U)Q.set($,I);return I};var E=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);var jg0=($)=>$;function Eg0($,Y){this[$]=jg0.bind(null,Y)}var x8=($,Y)=>{for(var z in Y)iT($,z,{get:Y[z],enumerable:!0,configurable:!0,set:Eg0.bind(Y,z)})};var o=($,Y)=>()=>($&&(Y=$($=0)),Y);var I0=Cg0(import.meta.url);var Rg0,yq,_g0,vg0,hg0,Sg0,R0=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports),Po=($,Y)=>{let z={};for(var U in $)yq(z,U,{get:$[U],enumerable:!0});if(Y)yq(z,Symbol.toStringTag,{value:"Module"});return z},gg0=($,Y,z,U)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(var Q=vg0(Y),J=0,I=Q.length,K;J<I;J++)if(K=Q[J],!Sg0.call($,K)&&K!==z)yq($,K,{get:((G)=>Y[G]).bind(null,K),enumerable:!(U=_g0(Y,K))||U.enumerable})}return $},kq=($,Y,z)=>(z=$!=null?Rg0(hg0($)):{},gg0(Y||!$||!$.__esModule?yq(z,"default",{value:$,enumerable:!0}):z,$));var cT=o(()=>{Rg0=Object.create,yq=Object.defineProperty,_g0=Object.getOwnPropertyDescriptor,vg0=Object.getOwnPropertyNames,hg0=Object.getPrototypeOf,Sg0=Object.prototype.hasOwnProperty});function To($){return typeof $==="string"&&Ao.has($.replace(/#$/,""))}function jo($,Y){if(!("$schema"in $)||typeof $.$schema!=="string")return"2020-12";let z=$.$schema.replace(/#$/,"");if(yg0.has(z))return"2020-12";if(Ao.has(z))return"2019-09";if(kg0.has(z)||xg0.has(z))return"draft-7";throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${$.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${Y}`)}var yg0,Ao,kg0,xg0;var nT=o(()=>{yg0=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),Ao=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),kg0=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),xg0=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])});function W0($,Y,z){function U(K,G){if(!K._zod)Object.defineProperty(K,"_zod",{value:{def:G,constr:I,traits:new Set},enumerable:!1});if(K._zod.traits.has($))return;K._zod.traits.add($),Y(K,G);let W=I.prototype,H=Object.keys(W);for(let X=0;X<H.length;X++){let Z=H[X];if(!(Z in K))K[Z]=W[Z].bind(K)}}let Q=z?.Parent??Object;class J extends Q{}Object.defineProperty(J,"name",{value:$});function I(K){var G;let W=z?.Parent?new J:this;U(W,K),(G=W._zod).deferred??(G.deferred=[]);for(let H of W._zod.deferred)H();return W}return Object.defineProperty(I,"init",{value:U}),Object.defineProperty(I,Symbol.hasInstance,{value:(K)=>{if(z?.Parent&&K instanceof z.Parent)return!0;return K?._zod?.traits?.has($)}}),Object.defineProperty(I,"name",{value:$}),I}function a4($){if($)Object.assign(NY,$);return NY}var Eo,pK,pT,f5,DY,NY;var BY=o(()=>{pK=Object.freeze({status:"aborted"});pT=Symbol("zod_brand");f5=class f5 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};DY=class DY extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(Eo=globalThis).__zod_globalConfig??(Eo.__zod_globalConfig={});NY=globalThis.__zod_globalConfig});var y0={};x8(y0,{unwrapMessage:()=>dK,uint8ArrayToHex:()=>Gy0,uint8ArrayToBase64url:()=>Iy0,uint8ArrayToBase64:()=>_o,stringifyPrimitive:()=>v0,slugify:()=>lT,shallowClone:()=>rT,safeExtend:()=>$y0,required:()=>Uy0,randomString:()=>lg0,propertyKeyTypes:()=>oK,promiseAllObject:()=>mg0,primitiveTypes:()=>sT,prefixIssues:()=>f8,pick:()=>ag0,partial:()=>zy0,parsedType:()=>S0,optionalKeys:()=>aT,omit:()=>tg0,objectClone:()=>ng0,numKeys:()=>og0,nullish:()=>Q3,normalizeParams:()=>x0,mergeDefs:()=>i9,merge:()=>Yy0,jsonStringifyReplacer:()=>xU,joinValues:()=>N0,issue:()=>uU,isPlainObject:()=>I3,isObject:()=>PY,hexToUint8Array:()=>Ky0,getSizableOrigin:()=>rK,getParsedType:()=>rg0,getLengthableOrigin:()=>sK,getEnumValues:()=>mK,getElementAtPath:()=>dg0,floatSafeRemainder:()=>mT,finalizeIssue:()=>B8,extend:()=>eg0,explicitlyAborted:()=>$j,escapeRegex:()=>N$,esc:()=>xq,defineLazy:()=>T1,createTransparentProxy:()=>sg0,cloneDef:()=>pg0,clone:()=>D8,cleanRegex:()=>lK,cleanEnum:()=>Qy0,captureStackTrace:()=>fq,cached:()=>fU,base64urlToUint8Array:()=>Jy0,base64ToUint8Array:()=>Ro,assignProp:()=>J3,assertNotEqual:()=>ug0,assertNever:()=>ig0,assertIs:()=>bg0,assertEqual:()=>fg0,assert:()=>cg0,allowsEval:()=>oT,aborted:()=>K3,NUMBER_FORMAT_RANGES:()=>tT,Class:()=>voLine truncated
`)}var ho=($,Y)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:Y,enumerable:!1}),$.message=JSON.stringify(Y,xU,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},aK,u8;var Uj=o(()=>{BY();$1();aK=W0("$ZodError",ho),u8=W0("$ZodError",ho,{Parent:Error})});var bU=($)=>(Y,z,U,Q)=>{let J=U?{...U,async:!1}:{async:!1},I=Y._zod.run({value:z,issues:[]},J);if(I instanceof Promise)throw new f5;if(I.issues.length){let K=new(Q?.Err??$)(I.issues.map((G)=>B8(G,J,a4())));throw fq(K,Q?.callee),K}return I.value},uq,iU=($)=>async(Y,z,U,Q)=>{let J=U?{...U,async:!0}:{async:!0},I=Y._zod.run({value:z,issues:[]},J);if(I instanceof Promise)I=await I;if(I.issues.length){let K=new(Q?.Err??$)(I.issues.map((G)=>B8(G,J,a4())));throw fq(K,Q?.callee),K}return I.value},bq,cU=($)=>(Y,z,U)=>{let Q=U?{...U,async:!1}:{async:!1},J=Y._zod.run({value:z,issues:[]},Q);if(J instanceof Promise)throw new f5;return J.issues.length?{success:!1,error:new($??aK)(J.issues.map((I)=>B8(I,Q,a4())))}:{success:!0,data:J.value}},Qj,nU=($)=>async(Y,z,U)=>{let Q=U?{...U,async:!0}:{async:!0},J=Y._zod.run({value:z,issues:[]},Q);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((I)=>B8(I,Q,a4())))}:{success:!0,data:J.value}},Jj,iq=($)=>(Y,z,U)=>{let Q=U?{...U,direction:"backward"}:{direction:"backward"};return bU($)(Y,z,Q)},Hy0,cq=($)=>(Y,z,U)=>{return bU($)(Y,z,U)},Xy0,nq=($)=>async(Y,z,U)=>{let Q=U?{...U,direction:"backward"}:{direction:"backward"};return iU($)(Y,z,Q)},Zy0,pq=($)=>async(Y,z,U)=>{return iU($)(Y,z,U)},qy0,dq=($)=>(Y,z,U)=>{let Q=U?{...U,direction:"backward"}:{direction:"backward"};return cU($)(Y,z,Q)},Vy0,mq=($)=>(Y,z,U)=>{return cU($)(Y,z,U)},Ly0,lq=($)=>async(Y,z,U)=>{let Q=U?{...U,direction:"backward"}:{direction:"backward"};return nU($)(Y,z,Q)},Fy0,oq=($)=>async(Y,z,U)=>{return nU($)(Y,z,U)},wy0;var Ij=o(()=>{BY();Uj();$1();uq=bU(u8),bq=iU(u8),Qj=cU(u8),Jj=nU(u8),Hy0=iq(u8),Xy0=cq(u8),Zy0=nq(u8),qy0=pq(u8),Vy0=dq(u8),Ly0=mq(u8),Fy0=lq(u8),wy0=oq(u8)});var Y$={};x8(Y$,{xid:()=>Hj,uuid7:()=>Dy0,uuid6:()=>Ny0,uuid4:()=>Oy0,uuid:()=>AY,uppercase:()=>yj,unicodeEmail:()=>go,undefined:()=>Sj,ulid:()=>Wj,time:()=>jj,string:()=>Cj,sha512_hex:()=>cy0,sha512_base64url:()=>py0,sha512_base64:()=>ny0,sha384_hex:()=>uy0,sha384_base64url:()=>iy0,sha384_base64:()=>by0,sha256_hex:()=>ky0,sha256_base64url:()=>fy0,sha256_base64:()=>xy0,sha1_hex:()=>Sy0,sha1_base64url:()=>yy0,sha1_base64:()=>gy0,rfc5322Email:()=>Py0,number:()=>$G,null:()=>hj,nanoid:()=>Zj,md5_hex:()=>_y0,md5_base64url:()=>hy0,md5_base64:()=>vy0,mac:()=>Oj,lowercase:()=>gj,ksuid:()=>Xj,ipv6:()=>Mj,ipv4:()=>wj,integer:()=>_j,idnEmail:()=>Ay0,httpProtocol:()=>Pj,html5Email:()=>By0,hostname:()=>Ey0,hex:()=>Ry0,guid:()=>Vj,extendedDuration:()=>My0,emoji:()=>Fj,email:()=>Lj,e164:()=>Aj,duration:()=>qj,domain:()=>Cy0,datetime:()=>Ej,date:()=>Tj,cuid2:()=>Gj,cuid:()=>Kj,cidrv6:()=>Dj,cidrv4:()=>Nj,browserEmail:()=>Ty0,boolean:()=>vj,bigint:()=>Rj,base64url:()=>rq,base64:()=>Bj});function Fj(){return new RegExp(jy0,"u")}function ko($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function jj($){return new RegExp(`^${ko($)}$`)}function Ej($){let Y=ko({precision:$.precision}),z=["Z"];if($.local)z.push("");if($.offset)z.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let U=`${Y}(?:${z.join("|")})`;return new RegExp(`^${yo}T(?:${U})$`)}function YG($,Y){return new RegExp(`^[A-Za-z0-9+/]{${$}}${Y}$`)}function zG($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var Kj,Gj,Wj,Hj,Xj,Zj,qj,My0,Vj,AY=($)=>{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})$`)},Oy0,Ny0,Dy0,Lj,By0,Py0,go,Ay0,Ty0,jy0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",wj,Mj,Oj=($)=>{let Y=N$($??":");return new RegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},Nj,Dj,Bj,rq,Ey0,Cy0,Pj,Aj,yo="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Tj,Cj=($)=>{let Y=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${Y}$`)},Rj,_j,$G,vj,hj,Sj,gj,yj,Ry0,_y0,vy0,hy0,Sy0,gy0,yy0,ky0,xy0,fy0,uy0,by0,iy0,cy0,ny0,py0;var sq=o(()=>{$1();Kj=/^[cC][0-9a-z]{6,}$/,Gj=/^[0-9a-z]+$/,Wj=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Hj=/^[0-9a-vA-V]{20}$/,Xj=/^[A-Za-z0-9]{27}$/,Zj=/^[a-zA-Z0-9_-]{21}$/,qj=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\dLine truncated
`).filter((J)=>J),U=Math.min(...z.map((J)=>J.length-J.trimStart().length)),Q=z.map((J)=>J.slice(U)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of Q)this.content.push(J)}compile(){let $=Function,Y=this?.args,U=[...(this?.content??[""]).map((Q)=>` ${Q}`)];return new $(...Y,U.join(`
`))}}var $E;var YE=o(()=>{$E={major:4,minor:4,patch:3}});function PE($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function Yr($){if(!rq.test($))return!1;let Y=$.replace(/[-_]/g,(U)=>U==="-"?"+":"/"),z=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return PE(z)}function zr($,Y=null){try{let z=$.split(".");if(z.length!==3)return!1;let[U]=z;if(!U)return!1;let Q=JSON.parse(atob(U));if("typ"in Q&&Q?.typ!=="JWT")return!1;if(!Q.alg)return!1;if(Y&&(!("alg"in Q)||Q.alg!==Y))return!1;return!0}catch{return!1}}function bo($,Y,z){if($.issues.length)Y.issues.push(...f8(z,$.issues));Y.value[z]=$.value}function QV($,Y,z,U,Q,J){let I=z in U;if($.issues.length){if(Q&&J&&!I)return;Y.issues.push(...f8(z,$.issues))}if(!I&&!Q){if(!$.issues.length)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[z]});return}if($.value===void 0){if(I)Y.value[z]=void 0}else Y.value[z]=$.value}function Ur($){let Y=Object.keys($.shape);for(let U of Y)if(!$.shape?.[U]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${U}": expected a Zod schema`);let z=aT($.shape);return{...$,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(z)}}function Qr($,Y,z,U,Q,J){let I=[],K=Q.keySet,G=Q.catchall._zod,W=G.def.type,H=G.optin==="optional",X=G.optout==="optional";for(let Z in Y){if(Z==="__proto__")continue;if(K.has(Z))continue;if(W==="never"){I.push(Z);continue}let q=G.run({value:Y[Z],issues:[]},U);if(q instanceof Promise)$.push(q.then((V)=>QV(V,z,Z,Y,H,X)));else QV(q,z,Z,Y,H,X)}if(I.length)z.issues.push({code:"unrecognized_keys",keys:I,input:Y,inst:J});if(!$.length)return z;return Promise.all($).then(()=>{return z})}function io($,Y,z,U){for(let J of $)if(J.issues.length===0)return Y.value=J.value,Y;let Q=$.filter((J)=>!K3(J));if(Q.length===1)return Y.value=Q[0].value,Q[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:z,errors:$.map((J)=>J.issues.map((I)=>B8(I,U,a4())))}),Y}function co($,Y,z,U){let Q=$.filter((J)=>J.issues.length===0);if(Q.length===1)return Y.value=Q[0].value,Y;if(Q.length===0)Y.issues.push({code:"invalid_union",input:Y.value,inst:z,errors:$.map((J)=>J.issues.map((I)=>B8(I,U,a4())))});else Y.issues.push({code:"invalid_union",input:Y.value,inst:z,errors:[],inclusive:!1});return Y}function zE($,Y){if($===Y)return{valid:!0,data:$};if($ instanceof Date&&Y instanceof Date&&+$===+Y)return{valid:!0,data:$};if(I3($)&&I3(Y)){let z=Object.keys(Y),U=Object.keys($).filter((J)=>z.indexOf(J)!==-1),Q={...$,...Y};for(let J of U){let I=zE($[J],Y[J]);if(!I.valid)return{valid:!1,mergeErrorPath:[J,...I.mergeErrorPath]};Q[J]=I.data}return{valid:!0,data:Q}}if(Array.isArray($)&&Array.isArray(Y)){if($.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let z=[];for(let U=0;U<$.length;U++){let Q=$[U],J=Y[U],I=zE(Q,J);if(!I.valid)return{valid:!1,mergeErrorPath:[U,...I.mergeErrorPath]};z.push(I.data)}return{valid:!0,data:z}}return{valid:!1,mergeErrorPath:[]}}function no($,Y,z){let U=new Map,Q;for(let K of Y.issues)if(K.code==="unrecognized_keys"){Q??(Q=K);for(let G of K.keys){if(!U.has(G))U.set(G,{});U.get(G).l=!0}}else $.issues.push(K);for(let K of z.issues)if(K.code==="unrecognized_keys")for(let G of K.keys){if(!U.has(G))U.set(G,{});U.get(G).r=!0}else $.issues.push(K);let J=[...U].filter(([,K])=>K.l&&K.r).map(([K])=>K);if(J.length&&Q)$.issues.push({...Q,keys:J});if(K3($))return $;let I=zE(Y.value,z.value);if(!I.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(I.mergeErrorPath)}`);return $.value=I.data,$}function po($,Y){for(let z=$.length-1;z>=0;z--)if($[z]._zod[Y]!=="optional")return z+1;return 0}function mo($,Y,z){if($.issues.length)Y.issues.push(...f8(z,$.issues));Y.value[z]=$.value}function lo($,Y,z,U,Q){for(let J=0;J<z.length;J++){let I=$[J],K=J<U.length;if(I.issues.length){if(!K&&J>=Q){Y.value.length=J;break}Y.issues.push(...f8(J,I.issues))}Y.value[J]=I.value}for(let J=Y.value.length-1;J>=U.length;J--)if(z[J]._zod.optout==="optional"&&Y.value[J]===void 0)Y.value.length=J;else break;return Y}function oo($,Y,z,U,Q,J,I){if($.issues.length)if(oK.has(typeof U))z.issues.push(...f8(U,$.issues));else z.issues.push({code:"invalid_key",origin:"map",input:Q,inst:J,issues:$.issues.map((K)=>B8(K,I,a4()))});if(Y.issues.length)if(oK.has(typeof U))z.issues.push(...f8(U,Y.issues));else z.issues.push({origin:"map",code:"invalid_element",input:Q,inst:J,key:U,issues:Y.issues.map((K)=>B8(K,I,a4()))});z.value.set($.value,Y.value)}function ro($,Y){if($.issues.length)Y.issues.push(...$.issues);Y.value.add($.value)}function so($,Y){if(Y===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function ao($,Y){if($.value===void 0)$.value=Y.defaultValue;return $}function to($,Y){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:Y});return $}function YV($,Y,z){if($.issues.length)return $.aborted=!0,$;return Y._zod.run({value:$.value,issues:$.issues,fa Line truncated
if (${D}.issues.length) {
if (${T} in input) {
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
payload.issues = payload.issues.concat(${D}.issues.map(iss => ({
...iss,
path: iss.path ? [${T}, ...iss.path] : [${T}]
})));
}
}
if (${A}.value === undefined) {
if (${D}.value === undefined) {
if (${T} in input) {
newResult[${T}] = undefined;
}
} else {
newResult[${T}] = ${A}.value;
newResult[${T}] = ${D}.value;
}
`);else if(!h)X.write(`
const ${A}_present = ${T} in input;
if (${A}.issues.length) {
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
`);else if(!B)q.write(`
const ${D}_present = ${T} in input;
if (${D}.issues.length) {
payload.issues = payload.issues.concat(${D}.issues.map(iss => ({
...iss,
path: iss.path ? [${T}, ...iss.path] : [${T}]
})));
}
if (!${A}_present && !${A}.issues.length) {
if (!${D}_present && !${D}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
@@ -36,126 +36,132 @@ import{createRequire as HS0}from"node:module";var $S0=Object.create;var{getProto
});
}
if (${A}_present) {
if (${A}.value === undefined) {
if (${D}_present) {
if (${D}.value === undefined) {
newResult[${T}] = undefined;
} else {
newResult[${T}] = ${A}.value;
newResult[${T}] = ${D}.value;
}
}
`);else X.write(`
if (${A}.issues.length) {
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
`);else q.write(`
if (${D}.issues.length) {
payload.issues = payload.issues.concat(${D}.issues.map(iss => ({
...iss,
path: iss.path ? [${T}, ...iss.path] : [${T}]
})));
}
if (${A}.value === undefined) {
if (${D}.value === undefined) {
if (${T} in input) {
newResult[${T}] = undefined;
}
} else {
newResult[${T}] = ${A}.value;
newResult[${T}] = ${D}.value;
}
`)}X.write("payload.value = newResult;"),X.write("return payload;");let D=X.compile();return(P,A)=>D(W,P,A)},Y,J=W2,Q=!H2.jitless,H=Q&&XP.value,G=I.catchall,Z;$._zod.parse=(W,X)=>{Z??(Z=q.value);let w=W.value;if(!J(w))return W.issues.push({expected:"object",code:"invalid_type",input:w,inst:$}),W;if(Q&&H&&X?.async===!1&&X.jitless!==!0){if(!Y)Y=U(I.shape);if(W=Y(W,X),!G)return W;return im([],w,W,X,Z,$)}return z(W,X)}});nJ=t("$ZodUnion",($,I)=>{m0.init($,I),J1($._zod,"optin",()=>I.options.some((q)=>q._zod.optin==="optional")?"optional":void 0),J1($._zod,"optout",()=>I.options.some((q)=>q._zod.optout==="optional")?"optional":void 0),J1($._zod,"values",()=>{if(I.options.every((q)=>q._zod.values))return new Set(I.options.flatMap((q)=>Array.from(q._zod.values)));return}),J1($._zod,"pattern",()=>{if(I.options.every((q)=>q._zod.pattern)){let q=I.options.map((U)=>U._zod.pattern);return new RegExp(`^(${q.map((U)=>CJ(U.source)).join("|")})$`)}return});let z=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(q,U)=>{if(z)return z(q,U);let Y=!1,J=[];for(let Q of I.options){let K=Q._zod.run({value:q.value,issues:[]},U);if(K instanceof Promise)J.push(K),Y=!0;else{if(K.issues.length===0)return K;J.push(K)}}if(!Y)return Tm(J,q,$,U);return Promise.all(J).then((Q)=>{return Tm(Q,q,$,U)})}});UT=t("$ZodXor",($,I)=>{nJ.init($,I),I.inclusive=!1;let z=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(q,U)=>{if(z)return z(q,U);let Y=!1,J=[];for(let Q of I.options){let K=Q._zod.run({value:q.value,issues:[]},U);if(K instanceof Promise)J.push(K),Y=!0;else J.push(K)}if(!Y)return Em(J,q,$,U);return Promise.all(J).then((Q)=>{return Em(Q,q,$,U)})}}),YT=t("$ZodDiscriminatedUnion",($,I)=>{I.inclusive=!1,nJ.init($,I);let z=$._zod.parse;J1($._zod,"propValues",()=>{let U={};for(let Y of I.options){let J=Y._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${I.options.indexOf(Y)}"`);for(let[Q,K]of Object.entries(J)){if(!U[Q])U[Q]=new Set;for(let H of K)U[Q].add(H)}}return U});let q=Tz(()=>{let U=I.options,Y=new Map;for(let J of U){let Q=J._zod.propValues?.[I.discriminator];if(!Q||Q.size===0)throw Error(`Invalid discriminated union option at index "${I.options.indexOf(J)}"`);for(let K of Q){if(Y.has(K))throw Error(`Duplicate discriminator value "${String(K)}"`);Y.set(K,J)}}return Y});$._zod.parse=(U,Y)=>{let J=U.value;if(!W2(J))return U.issues.push({code:"invalid_type",expected:"object",input:J,inst:$}),U;let Q=q.value.get(J?.[I.discriminator]);if(Q)return Q._zod.run(U,Y);if(I.unionFallback||Y.direction==="backward")return z(U,Y);return U.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:I.discriminator,options:Array.from(q.value.keys()),input:J,path:[I.discriminator],inst:$}),U}}),JT=t("$ZodIntersection",($,I)=>{m0.init($,I),$._zod.parse=(z,q)=>{let U=z.value,Y=I.left._zod.run({value:U,issues:[]},q),J=I.right._zod.run({value:U,issues:[]},q);if(Y instanceof Promise||J instanceof Promise)return Promise.all([Y,J]).then(([K,H])=>{return jm(z,K,H)});return jm(z,Y,J)}});lW=t("$ZodTuple",($,I)=>{m0.init($,I);let z=I.items;$._zod.parse=(q,U)=>{let Y=q.value;if(!Array.isArray(Y))return q.issues.push({input:Y,inst:$,expected:"tuple",code:"invalid_type"}),q;q.value=[];let J=[],Q=Cm(z,"optin"),K=Cm(z,"optout");if(!I.rest){if(Y.length<Q)return q.issues.push({code:"too_small",minimum:Q,inclusive:!0,input:Y,inst:$,origin:"array"}),q;if(Y.length>z.length)q.issues.push({code:"too_big",maximum:z.length,inclusive:!0,input:Y,inst:$,origin:"array"})}let H=Array(z.length);for(let G=0;G<z.length;G++){let Z=z[G]._zod.run({value:Y[G],issues:[]},U);if(Z instanceof Promise)J.push(Z.then((W)=>{H[G]=W}));else H[G]=Z}if(I.rest){let G=z.length-1,Z=Y.slice(z.length);for(let W of Z){G++;let X=I.rest._zod.run({value:W,issues:[]},U);if(X instanceof Promise)J.push(X.then((w)=>_m(w,q,G)));else _m(X,q,G)}}if(J.length)return Promise.all(J).then(()=>Rm(H,q,z,Y,K));return Rm(H,q,z,Y,K)}});QT=t("$ZodRecord",($,I)=>{m0.init($,I),$._zod.parse=(z,q)=>{let U=z.value;if(!F3(U))return z.issues.push({expected:"record",code:"invalid_type",input:U,inst:$}),z;let Y=[],J=I.keyType._zod.values;if(J){z.value={};let Q=new Set;for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){Q.add(typeof H==="number"?H.toString():H);let G=I.keyType._zod.run({value:H,issues:[]},q);if(G instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(G.issues.length){z.issues.push({code:"invalid_key",origin:"record",issues:G.issues.map((X)=>K8(X,q,f4())),input:H,path:[H],inst:$});continue}let Z=G.value,W=I.valueType._zod.run({value:U[H],issues:[]},q);if(W instanceof Promise)Y.push(W.then((X)=>{if(X.issues.length)z.issues.push(...E8(H,X.issues));z.value[Z]=X.value}));else{if(W.issues.length)z.issues.push(...E8(H,W.issues));z.value[Z]=W.value}}let K;for(let H in U)if(!Q.has(H))K=K??[],K.push(H);if(K&&K.length>0)z.issues.push({code:"unrecognize Line truncated
`)}q.write("payload.value = newResult;"),q.write("return payload;");let O=q.compile();return(N,D)=>O(Z,N,D)},J,I=PY,K=!NY.jitless,W=K&&oT.value,H=Y.catchall,X;$._zod.parse=(Z,q)=>{X??(X=U.value);let V=Z.value;if(!I(V))return Z.issues.push({expected:"object",code:"invalid_type",input:V,inst:$}),Z;if(K&&W&&q?.async===!1&&q.jitless!==!0){if(!J)J=Q(Y.shape);if(Z=J(Z,q),!H)return Z;return Qr([],V,Z,q,X,$)}return z(Z,q)}});QG=W0("$ZodUnion",($,Y)=>{q1.init($,Y),T1($._zod,"optin",()=>Y.options.some((U)=>U._zod.optin==="optional")?"optional":void 0),T1($._zod,"optout",()=>Y.options.some((U)=>U._zod.optout==="optional")?"optional":void 0),T1($._zod,"values",()=>{if(Y.options.every((U)=>U._zod.values))return new Set(Y.options.flatMap((U)=>Array.from(U._zod.values)));return}),T1($._zod,"pattern",()=>{if(Y.options.every((U)=>U._zod.pattern)){let U=Y.options.map((Q)=>Q._zod.pattern);return new RegExp(`^(${U.map((Q)=>lK(Q.source)).join("|")})$`)}return});let z=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(U,Q)=>{if(z)return z(U,Q);let J=!1,I=[];for(let K of Y.options){let G=K._zod.run({value:U.value,issues:[]},Q);if(G instanceof Promise)I.push(G),J=!0;else{if(G.issues.length===0)return G;I.push(G)}}if(!J)return io(I,U,$,Q);return Promise.all(I).then((K)=>{return io(K,U,$,Q)})}});iE=W0("$ZodXor",($,Y)=>{QG.init($,Y),Y.inclusive=!1;let z=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(U,Q)=>{if(z)return z(U,Q);let J=!1,I=[];for(let K of Y.options){let G=K._zod.run({value:U.value,issues:[]},Q);if(G instanceof Promise)I.push(G),J=!0;else I.push(G)}if(!J)return co(I,U,$,Q);return Promise.all(I).then((K)=>{return co(K,U,$,Q)})}}),cE=W0("$ZodDiscriminatedUnion",($,Y)=>{Y.inclusive=!1,QG.init($,Y);let z=$._zod.parse;T1($._zod,"propValues",()=>{let Q={};for(let J of Y.options){let I=J._zod.propValues;if(!I||Object.keys(I).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(J)}"`);for(let[K,G]of Object.entries(I)){if(!Q[K])Q[K]=new Set;for(let W of G)Q[K].add(W)}}return Q});let U=fU(()=>{let Q=Y.options,J=new Map;for(let I of Q){let K=I._zod.propValues?.[Y.discriminator];if(!K||K.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(I)}"`);for(let G of K){if(J.has(G))throw Error(`Duplicate discriminator value "${String(G)}"`);J.set(G,I)}}return J});$._zod.parse=(Q,J)=>{let I=Q.value;if(!PY(I))return Q.issues.push({code:"invalid_type",expected:"object",input:I,inst:$}),Q;let K=U.value.get(I?.[Y.discriminator]);if(K)return K._zod.run(Q,J);if(Y.unionFallback||J.direction==="backward")return z(Q,J);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,options:Array.from(U.value.keys()),input:I,path:[Y.discriminator],inst:$}),Q}}),nE=W0("$ZodIntersection",($,Y)=>{q1.init($,Y),$._zod.parse=(z,U)=>{let Q=z.value,J=Y.left._zod.run({value:Q,issues:[]},U),I=Y.right._zod.run({value:Q,issues:[]},U);if(J instanceof Promise||I instanceof Promise)return Promise.all([J,I]).then(([G,W])=>{return no(z,G,W)});return no(z,J,I)}});KV=W0("$ZodTuple",($,Y)=>{q1.init($,Y);let z=Y.items;$._zod.parse=(U,Q)=>{let J=U.value;if(!Array.isArray(J))return U.issues.push({input:J,inst:$,expected:"tuple",code:"invalid_type"}),U;U.value=[];let I=[],K=po(z,"optin"),G=po(z,"optout");if(!Y.rest){if(J.length<K)return U.issues.push({code:"too_small",minimum:K,inclusive:!0,input:J,inst:$,origin:"array"}),U;if(J.length>z.length)U.issues.push({code:"too_big",maximum:z.length,inclusive:!0,input:J,inst:$,origin:"array"})}let W=Array(z.length);for(let H=0;H<z.length;H++){let X=z[H]._zod.run({value:J[H],issues:[]},Q);if(X instanceof Promise)I.push(X.then((Z)=>{W[H]=Z}));else W[H]=X}if(Y.rest){let H=z.length-1,X=J.slice(z.length);for(let Z of X){H++;let q=Y.rest._zod.run({value:Z,issues:[]},Q);if(q instanceof Promise)I.push(q.then((V)=>mo(V,U,H)));else mo(q,U,H)}}if(I.length)return Promise.all(I).then(()=>lo(W,U,z,J,G));return lo(W,U,z,J,G)}});pE=W0("$ZodRecord",($,Y)=>{q1.init($,Y),$._zod.parse=(z,U)=>{let Q=z.value;if(!I3(Q))return z.issues.push({expected:"record",code:"invalid_type",input:Q,inst:$}),z;let J=[],I=Y.keyType._zod.values;if(I){z.value={};let K=new Set;for(let W of I)if(typeof W==="string"||typeof W==="number"||typeof W==="symbol"){K.add(typeof W==="number"?W.toString():W);let H=Y.keyType._zod.run({value:W,issues:[]},U);if(H instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(H.issues.length){z.issues.push({code:"invalid_key",origin:"record",issues:H.issues.map((q)=>B8(q,U,a4())),input:W,path:[W],inst:$});continue}let X=H.value,Z=Y.valueType._zod.run({value:Q[W],issues:[]},U);if(Z instanceof Promise)J.push(Z.then((q)=>{if(q.issues.length)z.issues.push(...f8(W,q.issues));z.value[X]=q.value}));else{if(Z.issues.length)z.issues.push(...f8(W,Z.issues));z.value[X]=Z.value}}let G;for(let W in Q)if(!K.has(W))G=G??[],G.push(W);if(G&&G.length>0)z.issues.push({code:"unrec Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let J of $.seen.entries()){let Q=J[1];if(I===J[0]){Y(J);continue}if($.external){let H=$.external.registry.get(J[0])?.id;if(I!==J[0]&&H){Y(J);continue}}if($.metadataRegistry.get(J[0])?.id){Y(J);continue}if(Q.cycle){Y(J);continue}if(Q.count>1){if($.reused==="ref"){Y(J);continue}}}}function B3($,I){let z=$.seen.get(I);if(!z)throw Error("Unprocessed schema. This is a bug in Zod.");let q=(Q)=>{let K=$.seen.get(Q);if(K.ref===null)return;let H=K.def??K.schema,G={...H},Z=K.ref;if(K.ref=null,Z){q(Z);let X=$.seen.get(Z),w=X.schema;if(w.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(w);else Object.assign(H,w);if(Object.assign(H,G),Q._zod.parent===Z)for(let O in H){if(O==="$ref"||O==="allOf")continue;if(!(O in G))delete H[O]}if(w.$ref&&X.def)for(let O in H){if(O==="$ref"||O==="allOf")continue;if(O in X.def&&JSON.stringify(H[O])===JSON.stringify(X.def[O]))delete H[O]}}let W=Q._zod.parent;if(W&&W!==Z){q(W);let X=$.seen.get(W);if(X?.schema.$ref){if(H.$ref=X.schema.$ref,X.def)for(let w in H){if(w==="$ref"||w==="allOf")continue;if(w in X.def&&JSON.stringify(H[w])===JSON.stringify(X.def[w]))delete H[w]}}}$.override({zodSchema:Q,jsonSchema:H,path:K.path??[]})};for(let Q of[...$.seen.entries()].reverse())q(Q[0]);let U={};if($.target==="draft-2020-12")U.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")U.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")U.$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");U.$id=$.external.uri(Q)}Object.assign(U,z.def??z.schema);let Y=$.metadataRegistry.get(I)?.id;if(Y!==void 0&&U.id===Y)delete U.id;let J=$.external?.defs??{};for(let Q of $.seen.entries()){let K=Q[1];if(K.def&&K.defId){if(K.def.id===K.defId)delete K.def.id;J[K.defId]=K.def}}if($.external);else if(Object.keys(J).length>0)if($.target==="draft-2020-12")U.$defs=J;else U.definitions=J;try{let Q=JSON.parse(JSON.stringify(U));return Object.defineProperty(Q,"~standard",{value:{...I["~standard"],jsonSchema:{input:lz(I,"input",$.processors),output:lz(I,"output",$.processors)}},enumerable:!1,writable:!1}),Q}catch(Q){throw Error("Error converting schema to JSON.")}}function G8($,I){let z=I??{seen:new Set};if(z.seen.has($))return!1;z.seen.add($);let q=$._zod.def;if(q.type==="transform")return!0;if(q.type==="array")return G8(q.element,z);if(q.type==="set")return G8(q.valueType,z);if(q.type==="lazy")return G8(q.getter(),z);if(q.type==="promise"||q.type==="optional"||q.type==="nonoptional"||q.type==="nullable"||q.type==="readonly"||q.type==="default"||q.type==="prefault")return G8(q.innerType,z);if(q.type==="intersection")return G8(q.left,z)||G8(q.right,z);if(q.type==="record"||q.type==="map")return G8(q.keyType,z)||G8(q.valueType,z);if(q.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return G8(q.in,z)||G8(q.out,z)}if(q.type==="object"){for(let U in q.shape)if(G8(q.shape[U],z))return!0;return!1}if(q.type==="union"){for(let U of q.options)if(G8(U,z))return!0;return!1}if(q.type==="tuple"){for(let U of q.items)if(G8(U,z))return!0;if(q.rest&&G8(q.rest,z))return!0;return!1}return!1}var Oj=($,I={})=>(z)=>{let q=A3({...z,processors:I});return c1($,q),P3(q,$),B3(q,$)},lz=($,I,z={})=>(q)=>{let{libraryOptions:U,target:Y}=q??{},J=A3({...U??{},target:Y,io:I,processors:z});return c1($,J),P3(J,$),B3(J,$)};var aJ=e(()=>{rJ()});function TX($,I){if("_idmap"in $){let q=$,U=A3({...I,processors:AX}),Y={};for(let K of q._idmap.entries()){let[H,G]=K;c1(G,U)}let J={},Q={registry:q,uri:I?.uri,defs:Y};U.external=Q;for(let K of q._idmap.entries()){let[H,G]=K;P3(U,G),J[H]=B3(U,G)}if(Object.keys(Y).length>0){let K=U.target==="draft-2020-12"?"$defs":"definitions";J.__shared={[K]:Y}}return{schemas:J}}let z=A3({...I,processors:AX});return c1($,z),P3(z,$),B3(z,$)}var Rx0,Fj=($,I,z,q)=>{let U=z;U.type="string";let{minimum:Y,maximum:J,format:Q,patterns:K,contentEncoding:H}=$._zod.bag;if(typeof Y==="number")U.minLength=Y;if(typeof J==="number")U.maxLength=J;if(Q){if(U.format=Rx0[Q]??Q,U.format==="")delete U.format;if(Q==="time")delete U.format}if(H)U.contentEncoding=H;if(K&&K.size>0){let G=[...K];if(G.length===1)U.pattern=G[0].source;else if(G.length>1)U.allOf=[...G.map((Z)=>({...I.target==="draft-07"||I.target==="draft-04"||I.target==="openapi-3.0"?{type:"string"}:{},pattern:Z.source}))]}},Mj=($,I,z,q)=>{let U=z,{minimum:Y,maximum:J,format:Q,multipleOf:K,exclusiveMaximum:H,exclusiveMinimum:G}=$._zod.bag;if(typeof Q==="string"&&Q.includes("int"))U.type="integer";else U.type="number";let Z=typeof G==="number"&&G>=(Y??Number.NEGATIVE_INFINITY),W=typeof H==="number"&&H<=(J??Number.POSITIVE_INFINITY),X=I.target==="draft-04"||I.target==="openapi-3.0";if(Z)if(X)U.minimum=G,U.exclusiveMinimum=!0;else U.exclusiveMinimuLine truncated
`:""},this._extScope=$,this._scope=new o$.Scope({parent:$}),this._nodes=[new dr]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,I){let z=this._extScope.value($,I);return(this._values[z.prefix]||(this._values[z.prefix]=new Set)).add(z),z}getScopeValue($,I){return this._extScope.getValue($,I)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,I,z,q){let U=this._scope.toName(I);if(z!==void 0&&q)this._constants[U.str]=z;return this._leafNode(new fr($,U,z)),U}const($,I,z){return this._def(o$.varKinds.const,$,I,z)}let($,I,z){return this._def(o$.varKinds.let,$,I,z)}var($,I,z){return this._def(o$.varKinds.var,$,I,z)}assign($,I,z){return this._leafNode(new k_($,I,z))}add($,I){return this._leafNode(new br($,v8.operators.ADD,I))}code($){if(typeof $=="function")$();else if($!==M1.nil)this._leafNode(new pr($));return this}object(...$){let I=["{"];for(let[z,q]of $){if(I.length>1)I.push(",");if(I.push(z),z!==q||this.opts.es5)I.push(":"),(0,M1.addCodeArg)(I,q)}return I.push("}"),new M1._Code(I)}if($,I,z){if(this._blockNode(new X9($)),I&&z)this.code(I).else().code(z).endIf();else if(I)this.code(I).endIf();else if(z)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new X9($))}else(){return this._elseNode(new RQ)}endIf(){return this._endBlockNode(X9,RQ)}_for($,I){if(this._blockNode($),I)this.code(I).endFor();return this}for($,I){return this._for(new mr($),I)}forRange($,I,z,q,U=this.opts.es5?o$.varKinds.var:o$.varKinds.let){let Y=this._scope.toName($);return this._for(new lr(U,Y,I,z),()=>q(Y))}forOf($,I,z,q=o$.varKinds.const){let U=this._scope.toName($);if(this.opts.es5){let Y=I instanceof M1.Name?I:this.var("_arr",I);return this.forRange("_i",0,M1._`${Y}.length`,(J)=>{this.var(U,M1._`${Y}[${J}]`),z(U)})}return this._for(new x_("of",q,U,I),()=>z(U))}forIn($,I,z,q=this.opts.es5?o$.varKinds.var:o$.varKinds.const){if(this.opts.ownProperties)return this.forOf($,M1._`Object.keys(${I})`,z);let U=this._scope.toName($);return this._for(new x_("in",q,U,I),()=>z(U))}endFor(){return this._endBlockNode(Kq)}label($){return this._leafNode(new ir($))}break($){return this._leafNode(new nr($))}return($){let I=new AV;if(this._blockNode(I),this.code($),I.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(AV)}try($,I,z){if(!I&&!z)throw Error('CodeGen: "try" without "catch" and "finally"');let q=new or;if(this._blockNode(q),this.code($),I){let U=this.name("e");this._currNode=q.catch=new PV(U),I(U)}if(z)this._currNode=q.finally=new BV,this.code(z);return this._endBlockNode(PV,BV)}throw($){return this._leafNode(new cr($))}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 z=this._nodes.length-I;if(z<0||$!==void 0&&z!==$)throw Error(`CodeGen: wrong number of nodes: ${z} vs ${$} expected`);return this._nodes.length=I,this}func($,I=M1.nil,z,q){if(this._blockNode(new DV($,I,z)),q)this.code(q).endFunc();return this}endFunc(){return this._endBlockNode(DV)}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 z=this._currNode;if(z instanceof $||I&&z 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 X9))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]=$}}v8.CodeGen=rr;function M2($,I){for(let z in I)$[z]=($[z]||0)+(I[z]||0);return $}function TV($,I){return I instanceof M1._CodeOrName?M2($,I.names):$}function Hq($,I,z){if($ instanceof M1.Name)return q($);if(!U($))return $;return new M1._Code($._items.reduce((Y,J)=>{if(J instanceof M1.Name)J=q(J);if(J instanceof M1._Code)Y.push(...J._items);else Y.push(J);return Y},[]));function q(Y){let J=z[Y.str];if(J===void 0||I[Y.str]!==1)return Y;return delete I[Y.str],J}function U(Y){return Y instanceof M1._Code&&Y._items.some((J)=>J instanceof M1.Name&&I[J.str]===1&&z[J.str]!==void 0)}}function $f0($,I){for(let z in I)$[z]=($[z]||0)-(I[z]||0)}function sr($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:M1._`!${u_($)}`}v8.not=sr;var If0=tr(v8.operators.AND);function zf0(...$){return $.reduce(If0)}v8.and=zf0;var qf0=tr(v8.operators.OR);function Uf0(...$){return $.reduce(qf0)}v8.or=Uf0;function tr($){return(I,z)=>I===M1.nil?z:z===M1.nil?I:M1._`${u_(I)} ${$} ${u_(z)}`}function u_($){return $ instanceof M1.Name?$:M1._`(${Line truncated
|| (${J} == "string" && ${U} && ${U} == +${U})`).assign(Q,$1._`+${U}`);return;case"integer":q.elseIf($1._`${J} === "boolean" || ${U} === null
|| (${J} === "string" && ${U} && ${U} == +${U} && !(${U} % 1))`).assign(Q,$1._`+${U}`);return;case"boolean":q.elseIf($1._`${U} === "false" || ${U} === 0 || ${U} === null`).assign(Q,!1).elseIf($1._`${U} === "true" || ${U} === 1`).assign(Q,!0);return;case"null":q.elseIf($1._`${U} === "" || ${U} === 0 || ${U} === false`),q.assign(Q,null);return;case"array":q.elseIf($1._`${J} === "string" || ${J} === "number"
|| ${J} === "boolean" || ${U} === null`).assign(Q,$1._`[${U}]`)}}}function Ob0({gen:$,parentData:I,parentDataProperty:z},q){$.if($1._`${I} !== undefined`,()=>$.assign($1._`${I}[${z}]`,q))}function d_($,I,z,q=Gq.Correct){let U=q===Gq.Correct?$1.operators.EQ:$1.operators.NEQ,Y;switch($){case"null":return $1._`${I} ${U} null`;case"array":Y=$1._`Array.isArray(${I})`;break;case"object":Y=$1._`${I} && typeof ${I} == "object" && !Array.isArray(${I})`;break;case"integer":Y=J($1._`!(${I} % 1) && !isNaN(${I})`);break;case"number":Y=J();break;default:return $1._`typeof ${I} ${U} ${$}`}return q===Gq.Correct?Y:(0,$1.not)(Y);function J(Q=$1.nil){return(0,$1.and)($1._`typeof ${I} == "number"`,Q,z?$1._`isFinite(${I})`:$1.nil)}}js.checkDataType=d_;function m_($,I,z,q){if($.length===1)return d_($[0],I,z,q);let U,Y=(0,Bs.toHash)($);if(Y.array&&Y.object){let J=$1._`typeof ${I} != "object"`;U=Y.null?J:$1._`!${I} || ${J}`,delete Y.null,delete Y.array,delete Y.object}else U=$1.nil;if(Y.number)delete Y.integer;for(let J in Y)U=(0,$1.and)(U,d_(J,I,z,q));return U}js.checkDataTypes=m_;var Fb0={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:I})=>typeof $=="string"?$1._`{type: ${$}}`:$1._`{type: ${I}}`};function l_($){let I=Mb0($);(0,Wb0.reportError)(I,Fb0)}js.reportTypeError=l_;function Mb0($){let{gen:I,data:z,schema:q}=$,U=(0,Bs.schemaRefOrVal)($,q,"type");return{gen:I,keyword:"type",data:z,schema:q.type,schemaCode:U,schemaValue:U,parentSchema:q,params:{},it:$}}});var hs=M((Rs)=>{Object.defineProperty(Rs,"__esModule",{value:!0});Rs.assignDefaults=void 0;var Zq=z1(),Eb0=P1();function jb0($,I){let{properties:z,items:q}=$.schema;if(I==="object"&&z)for(let U in z)_s($,U,z[U].default);else if(I==="array"&&Array.isArray(q))q.forEach((U,Y)=>_s($,Y,U.default))}Rs.assignDefaults=jb0;function _s($,I,z){let{gen:q,compositeRule:U,data:Y,opts:J}=$;if(z===void 0)return;let Q=Zq._`${Y}${(0,Zq.getProperty)(I)}`;if(U){(0,Eb0.checkStrictMode)($,`default is ignored for: ${Q}`);return}let K=Zq._`${Q} === undefined`;if(J.useDefaults==="empty")K=Zq._`${K} || ${Q} === null || ${Q} === ""`;q.if(K,Zq._`${Q} = ${(0,Zq.stringify)(z)}`)}});var F$=M((ys)=>{Object.defineProperty(ys,"__esModule",{value:!0});ys.validateUnion=ys.validateArray=ys.usePattern=ys.callValidateCode=ys.schemaProperties=ys.allSchemaProperties=ys.noPropertyInData=ys.propertyInData=ys.isOwnProperty=ys.hasPropFunc=ys.reportMissingProp=ys.checkMissingProp=ys.checkReportMissingProp=void 0;var H4=z1(),o_=P1(),h3=V9(),Cb0=P1();function _b0($,I){let{gen:z,data:q,it:U}=$;z.if(s_(z,q,I,U.opts.ownProperties),()=>{$.setParams({missingProperty:H4._`${I}`},!0),$.error()})}ys.checkReportMissingProp=_b0;function Rb0({gen:$,data:I,it:{opts:z}},q,U){return(0,H4.or)(...q.map((Y)=>(0,H4.and)(s_($,I,Y,z.ownProperties),H4._`${U} = ${Y}`)))}ys.checkMissingProp=Rb0;function vb0($,I){$.setParams({missingProperty:I},!0),$.error()}ys.reportMissingProp=vb0;function gs($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:H4._`Object.prototype.hasOwnProperty`})}ys.hasPropFunc=gs;function r_($,I,z){return H4._`${gs($)}.call(${I}, ${z})`}ys.isOwnProperty=r_;function hb0($,I,z,q){let U=H4._`${I}${(0,H4.getProperty)(z)} !== undefined`;return q?H4._`${U} && ${r_($,I,z)}`:U}ys.propertyInData=hb0;function s_($,I,z,q){let U=H4._`${I}${(0,H4.getProperty)(z)} === undefined`;return q?(0,H4.or)(U,(0,H4.not)(r_($,I,z))):U}ys.noPropertyInData=s_;function Ss($){return $?Object.keys($).filter((I)=>I!=="__proto__"):[]}ys.allSchemaProperties=Ss;function gb0($,I){return Ss(I).filter((z)=>!(0,o_.alwaysValidSchema)($,I[z]))}ys.schemaProperties=gb0;function Sb0({schemaCode:$,data:I,it:{gen:z,topSchemaRef:q,schemaPath:U,errorPath:Y},it:J},Q,K,H){let G=H?H4._`${$}, ${I}, ${q}${U}`:I,Z=[[h3.default.instancePath,(0,H4.strConcat)(h3.default.instancePath,Y)],[h3.default.parentData,J.parentData],[h3.default.parentDataProperty,J.parentDataProperty],[h3.default.rootData,h3.default.rootData]];if(J.opts.dynamicRef)Z.push([h3.default.dynamicAnchors,h3.default.dynamicAnchors]);let W=H4._`${G}, ${z.object(...Z)}`;return K!==H4.nil?H4._`${Q}.call(${K}, ${W})`:H4._`${Q}(${W})`}ys.callValidateCode=Sb0;var yb0=H4._`new RegExp`;function xb0({gen:$,it:{opts:I}},z){let q=I.unicodeRegExp?"u":"",{regExp:U}=I.code,Y=U(z,q);return $.scopeValue("pattern",{key:Y.toString(),ref:Y,code:H4._`${U.code==="new RegExp"?yb0:(0,Cb0.useFunc)($,U)}(${z}, ${q})`})}ys.usePattern=xb0;function ub0($){let{gen:I,data:z,keyword:q,it:U}=$,Y=I.name("valid");if(U.allErrors){let Q=I.let("valid",!0);return J(()=>I.assign(Q,!1)),Q}return I.var(Y,!0),J(()=>I.break()),Y;function J(Q){let K=I.const("len",H4._`${z}.length`);I.forRange("i",0,K,(H)=>{$.subschema({keyword:q,dataProp:H,dataPropType:o_.Type.Num},Y),I.if((0,H4.not)(Y),Q)})}}ys.validateArray=ub0;function kb0($){let{gen:I,schema:z,keyword:q,it:U}=$;if(!Array.isArray(z))throw Error("ajv implementation error");if(z.some((K)=>(0,o_.alwaysValidSchema)(U,K))&&!U.opts.unevaluated)return;le Line truncated
missingProperty: ${q},
depsCount: ${I},
deps: ${z}}`};var qd0={keyword:"dependencies",type:"object",schemaType:"object",error:aa.error,code($){let[I,z]=Ud0($);sa($,I),ta($,z)}};function Ud0({schema:$}){let I={},z={};for(let q in $){if(q==="__proto__")continue;let U=Array.isArray($[q])?I:z;U[q]=$[q]}return[I,z]}function sa($,I=$.schema){let{gen:z,data:q,it:U}=$;if(Object.keys(I).length===0)return;let Y=z.let("missing");for(let J in I){let Q=I[J];if(Q.length===0)continue;let K=(0,oQ.propertyInData)(z,q,J,U.opts.ownProperties);if($.setParams({property:J,depsCount:Q.length,deps:Q.join(", ")}),U.allErrors)z.if(K,()=>{for(let H of Q)(0,oQ.checkReportMissingProp)($,H)});else z.if(MR._`${K} && (${(0,oQ.checkMissingProp)($,Q,Y)})`),(0,oQ.reportMissingProp)($,Y),z.else()}}aa.validatePropertyDeps=sa;function ta($,I=$.schema){let{gen:z,data:q,keyword:U,it:Y}=$,J=z.name("valid");for(let Q in I){if((0,zd0.alwaysValidSchema)(Y,I[Q]))continue;z.if((0,oQ.propertyInData)(z,q,Q,Y.opts.ownProperties),()=>{let K=$.subschema({keyword:U,schemaProp:Q},J);$.mergeValidEvaluated(K,J)},()=>z.var(J,!0)),$.ok(J)}}aa.validateSchemaDeps=ta;aa.default=qd0});var Ue=M((qe)=>{Object.defineProperty(qe,"__esModule",{value:!0});var ze=z1(),Qd0=P1(),Kd0={message:"property name must be valid",params:({params:$})=>ze._`{propertyName: ${$.propertyName}}`},Hd0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Kd0,code($){let{gen:I,schema:z,data:q,it:U}=$;if((0,Qd0.alwaysValidSchema)(U,z))return;let Y=I.name("valid");I.forIn("key",q,(J)=>{$.setParams({propertyName:J}),$.subschema({keyword:"propertyNames",data:J,dataTypes:["string"],propertyName:J,compositeRule:!0},Y),I.if((0,ze.not)(Y),()=>{if($.error(!0),!U.allErrors)I.break()})}),$.ok(Y)}};qe.default=Hd0});var NR=M((Ye)=>{Object.defineProperty(Ye,"__esModule",{value:!0});var lV=F$(),t$=z1(),Zd0=V9(),oV=P1(),Wd0={message:"must NOT have additional properties",params:({params:$})=>t$._`{additionalProperty: ${$.additionalProperty}}`},Xd0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Wd0,code($){let{gen:I,schema:z,parentSchema:q,data:U,errsCount:Y,it:J}=$;if(!Y)throw Error("ajv implementation error");let{allErrors:Q,opts:K}=J;if(J.props=!0,K.removeAdditional!=="all"&&(0,oV.alwaysValidSchema)(J,z))return;let H=(0,lV.allSchemaProperties)(q.properties),G=(0,lV.allSchemaProperties)(q.patternProperties);Z(),$.ok(t$._`${Y} === ${Zd0.default.errors}`);function Z(){I.forIn("key",U,(O)=>{if(!H.length&&!G.length)w(O);else I.if(W(O),()=>w(O))})}function W(O){let F;if(H.length>8){let D=(0,oV.schemaRefOrVal)(J,q.properties,"properties");F=(0,lV.isOwnProperty)(I,D,O)}else if(H.length)F=(0,t$.or)(...H.map((D)=>t$._`${O} === ${D}`));else F=t$.nil;if(G.length)F=(0,t$.or)(F,...G.map((D)=>t$._`${(0,lV.usePattern)($,D)}.test(${O})`));return(0,t$.not)(F)}function X(O){I.code(t$._`delete ${U}[${O}]`)}function w(O){if(K.removeAdditional==="all"||K.removeAdditional&&z===!1){X(O);return}if(z===!1){if($.setParams({additionalProperty:O}),$.error(),!Q)I.break();return}if(typeof z=="object"&&!(0,oV.alwaysValidSchema)(J,z)){let F=I.name("valid");if(K.removeAdditional==="failing")L(O,F,!1),I.if((0,t$.not)(F),()=>{$.reset(),X(O)});else if(L(O,F),!Q)I.if((0,t$.not)(F),()=>I.break())}}function L(O,F,D){let P={keyword:"additionalProperties",dataProp:O,dataPropType:oV.Type.Str};if(D===!1)Object.assign(P,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(P,F)}}};Ye.default=Xd0});var He=M((Ke)=>{Object.defineProperty(Ke,"__esModule",{value:!0});var wd0=xQ(),Je=F$(),DR=P1(),Qe=NR(),Ld0={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:I,schema:z,parentSchema:q,data:U,it:Y}=$;if(Y.opts.removeAdditional==="all"&&q.additionalProperties===void 0)Qe.default.code(new wd0.KeywordCxt(Y,Qe.default,"additionalProperties"));let J=(0,Je.allSchemaProperties)(z);for(let Z of J)Y.definedProperties.add(Z);if(Y.opts.unevaluated&&J.length&&Y.props!==!0)Y.props=DR.mergeEvaluated.props(I,(0,DR.toHash)(J),Y.props);let Q=J.filter((Z)=>!(0,DR.alwaysValidSchema)(Y,z[Z]));if(Q.length===0)return;let K=I.name("valid");for(let Z of Q){if(H(Z))G(Z);else{if(I.if((0,Je.propertyInData)(I,U,Z,Y.opts.ownProperties)),G(Z),!Y.allErrors)I.else().var(K,!0);I.endIf()}$.it.definedProperties.add(Z),$.ok(K)}function H(Z){return Y.opts.useDefaults&&!Y.compositeRule&&z[Z].default!==void 0}function G(Z){$.subschema({keyword:"properties",schemaProp:Z,dataProp:Z},K)}}};Ke.default=Ld0});var Ve=M((Xe)=>{Object.defineProperty(Xe,"__esModule",{value:!0});var Ge=F$(),rV=z1(),Ze=P1(),We=P1(),Fd0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:I,schema:z,data:q,parentSchema:U,it:Y}=$,{opts:J}=Y,Q=(0,Ge.allSchemaProperties)(z),K=Q.filter((L)=>(0,Ze.alwaysValidSchema)(Y,z[L]));if(Q.length===0||K.length===Q.length&&(!Y.opts.unevaluated||Y.props===!0))return;let H=J.strictSchema&&!J.allowMatchingProperties&&U.properties,G=I.name("valid");if(Y.props!==!0&&!(Y.props instanceo Line truncated
\x00`,i+=Y4(f,2),i+=Q.magic,i+=Y4(O,2),i+=Y4(F,2),i+=Y4(h.crc32,4),i+=Y4(h.compressedSize,4),i+=Y4(h.uncompressedSize,4),i+=Y4(H.length,2),i+=Y4(D.length,2);var v=xL.LOCAL_FILE_HEADER+i+H+D,y=xL.CENTRAL_FILE_HEADER+Y4(b,2)+i+Y4(W.length,2)+"\x00\x00\x00\x00"+Y4(C,4)+Y4(q,4)+H+D+W;return{fileRecord:v,dirRecord:y}},o01=function($,I,z,q,U){var Y="",J=aq.transformTo("string",U(q));return Y=xL.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+Y4($,2)+Y4($,2)+Y4(I,4)+Y4(z,4)+Y4(J.length,2)+J,Y},r01=function($){var I="";return I=xL.DATA_DESCRIPTOR+Y4($.crc32,4)+Y4($.compressedSize,4)+Y4($.uncompressedSize,4),I};function q5($,I,z,q){eq.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=I,this.zipPlatform=z,this.encodeFileName=q,this.streamFiles=$,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}aq.inherits(q5,eq);q5.prototype.push=function($){var I=$.meta.percent||0,z=this.entriesCount,q=this._sources.length;if(this.accumulate)this.contentBuffer.push($);else this.bytesWritten+=$.data.length,eq.prototype.push.call(this,{data:$.data,meta:{currentFile:this.currentFile,percent:z?(I+100*(z-q-1))/z:100}})};q5.prototype.openedSource=function($){this.currentSourceOffset=this.bytesWritten,this.currentFile=$.file.name;var I=this.streamFiles&&!$.file.dir;if(I){var z=L90($,I,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:z.fileRecord,meta:{percent:0}})}else this.accumulate=!0};q5.prototype.closedSource=function($){this.accumulate=!1;var I=this.streamFiles&&!$.file.dir,z=L90($,I,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(z.dirRecord),I)this.push({data:r01($),meta:{percent:100}});else{this.push({data:z.fileRecord,meta:{percent:0}});while(this.contentBuffer.length)this.push(this.contentBuffer.shift())}this.currentFile=null};q5.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 z=this.bytesWritten-$,q=o01(this.dirRecords.length,z,$,this.zipComment,this.encodeFileName);this.push({data:q,meta:{percent:100}})};q5.prototype.prepareNextSource=function(){if(this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused)this.previous.pause();else this.previous.resume()};q5.prototype.registerPrevious=function($){this._sources.push($);var I=this;return $.on("data",function(z){I.processChunk(z)}),$.on("end",function(){if(I.closedSource(I.previous.streamInfo),I._sources.length)I.prepareNextSource();else I.end()}),$.on("error",function(z){I.error(z)}),this};q5.prototype.resume=function(){if(!eq.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};q5.prototype.error=function($){var I=this._sources;if(!eq.prototype.error.call(this,$))return!1;for(var z=0;z<I.length;z++)try{I[z].error($)}catch(q){}return!0};q5.prototype.lock=function(){eq.prototype.lock.call(this);var $=this._sources;for(var I=0;I<$.length;I++)$[I].lock()};O90.exports=q5});var M90=M((e01)=>{var s01=Qg(),t01=F90(),a01=function($,I){var z=$||I,q=s01[z];if(!q)throw Error(z+" is not a valid compression method !");return q};e01.generateWorker=function($,I,z){var q=new t01(I.streamFiles,z,I.platform,I.encodeFileName),U=0;try{$.forEach(function(Y,J){U++;var Q=a01(J.options.compression,I.compression),K=J.options.compressionOptions||I.compressionOptions||{},H=J.dir,G=J.date;J._compressWorker(Q,K).withStreamInfo("file",{name:Y,dir:H,date:G,comment:J.comment||"",unixPermissions:J.unixPermissions,dosPermissions:J.dosPermissions}).pipe(q)}),q.entriesCount=U}catch(Y){q.error(Y)}return q}});var D90=M((He1,N90)=>{var I11=_4(),uL=$$();function tK($,I){uL.call(this,"Nodejs stream input adapter for "+$),this._upstreamEnded=!1,this._bindStream(I)}I11.inherits(tK,uL);tK.prototype._bindStream=function($){var I=this;this._stream=$,$.pause(),$.on("data",function(z){I.push({data:z,meta:{percent:0}})}).on("error",function(z){if(I.isPaused)this.generatedError=z;else I.error(z)}).on("end",function(){if(I.isPaused)I._upstreamEnded=!0;else I.end()})};tK.prototype.pause=function(){if(!uL.prototype.pause.call(this))return!1;return this._stream.pause(),!0};tK.prototype.resume=function(){if(!uL.prototype.resume.call(this))return!1;if(this._upstreamEnded)this.end();else this._stream.resume();return!0};N90.exports=tK});var v90=M((Ge1,R90)=>{var z11=nq(),aK=_4(),T90=$$(),q11=Xh(),E90=Vh(),A90=FL(),U11=P$0(),Y11=M90(),P90=RK(),J11=D90(),j90=function($,I,z){var q=aK.getTypeOf(I),U,Y=aK.extend(z||{},E90);if(Y.date=Y.date||new Date,Y.compression!==null)Y.compression=Y.compression.toUpperCase();if(typeof Y.unixPermissions==="string")Y.unixPermissions=parseInt(Y.unixPermissions,8);if(Y.unixPermissions&&Y.unixPermissions&16384)Y.dir=!0;if(Y.dosPermissions&&Y.dosPermission Line truncated
`)}openNode($,I){let z=this.tos,q=this._xml;if(z&&this.open)q.push(">");this._stack.push($),q.push("<"),q.push($),pg(q,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)D70(this._xml,$,I)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");pg(this._xml,$)}writeText($){let I=this._xml;if(this.open)I.push(">"),this.open=!1;this.leaf=!1,I.push(N70.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,z){if(this.openNode($,I),z!==void 0)this.writeText(z);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("")}}dg.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};A70.exports=dg});var mg=M((t61)=>{var P70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function s61($){if(typeof $==="string")return $;if(P70)return P70.decode($);return $.toString()}t61.bufferToString=s61});var C70=M((T70)=>{Object.defineProperty(T70,"__esModule",{value:!0});T70.CHAR=`
\r -퟿-�\uD800\uDC00-\uDBFF\uDFFF`;T70.S=` \r
`;T70.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";T70.NAME_CHAR="-"+T70.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";T70.CHAR_RE=new RegExp("^["+T70.CHAR+"]$","u");T70.S_RE=new RegExp("^["+T70.S+"]+$","u");T70.NAME_START_CHAR_RE=new RegExp("^["+T70.NAME_START_CHAR+"]$","u");T70.NAME_CHAR_RE=new RegExp("^["+T70.NAME_CHAR+"]$","u");T70.NAME_RE=new RegExp("^["+T70.NAME_START_CHAR+"]["+T70.NAME_CHAR+"]*$","u");T70.NMTOKEN_RE=new RegExp("^["+T70.NAME_CHAR+"]+$","u");var lg=9,og=10,rg=13,sg=32;T70.S_LIST=[sg,og,rg,lg];function e61($){return $>=sg&&$<=55295||$===og||$===rg||$===lg||$>=57344&&$<=65533||$>=65536&&$<=1114111}T70.isChar=e61;function $81($){return $===sg||$===og||$===rg||$===lg}T70.isS=$81;function B70($){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}T70.isNameStartChar=B70;function I81($){return B70($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}T70.isNameChar=I81});var k70=M((S70)=>{Object.defineProperty(S70,"__esModule",{value:!0});S70.CHAR="\x01-퟿-�\uD800\uDC00-\uDBFF\uDFFF";S70.RESTRICTED_CHAR="\x01-\b\v\f\x0E-\x1F-„†-Ÿ";S70.S=` \r
`;S70.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";S70.NAME_CHAR="-"+S70.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";S70.CHAR_RE=new RegExp("^["+S70.CHAR+"]$","u");S70.RESTRICTED_CHAR_RE=new RegExp("^["+S70.RESTRICTED_CHAR+"]$","u");S70.S_RE=new RegExp("^["+S70.S+"]+$","u");S70.NAME_START_CHAR_RE=new RegExp("^["+S70.NAME_START_CHAR+"]$","u");S70.NAME_CHAR_RE=new RegExp("^["+S70.NAME_CHAR+"]$","u");S70.NAME_RE=new RegExp("^["+S70.NAME_START_CHAR+"]["+S70.NAME_CHAR+"]*$","u");S70.NMTOKEN_RE=new RegExp("^["+S70.NAME_CHAR+"]+$","u");var _70=9,R70=10,v70=13,h70=32;S70.S_LIST=[h70,R70,v70,_70];function X81($){return $>=1&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}S70.isChar=X81;function V81($){return $>=1&&$<=8||$===11||$===12||$>=14&&$<=31||$>=127&&$<=132||$>=134&&$<=159}S70.isRestrictedChar=V81;function w81($){return $===9||$===10||$===13||$>31&&$<127||$===133||$>159&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}S70.isCharAndNotRestricted=w81;function L81($){return $===h70||$===R70||$===v70||$===_70}S70.isS=L81;function g70($){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}S70.isNameStartChar=g70;function O81($){return g70($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}S70.isNameChar=O81});var i70=M((b70)=>{Object.defineProperty(b70,"__esModule",{value:!0});b70.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";b70.NC_NAME_CHAR="-"+b70.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";b70.NC_NAME_START_CHAR_RE=new RegExp("^["+b70.NC_NAME_START_CHAR+"]$","u");b70.NC_NAME_CHAR_RE=new RegExp("^["+b70.NC_NAME_CHAR+"]$","u");b70.NC_NAME_RE=new RegExp("^["+b70.NC_NAME_START_CHAR+"]["+b70.NC_NAME_CHAR+"]*$","u");function f70($){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}b70.isNCNameStartChar=f70;function h81($){return f70($)||($===45||$===46||$>=48&&$<=57||$===183||$>=768&&$<=879||$>=8255&&$<=8256)}b70.isNCNameChar=h81});var H20=M((K20)=>{Object.defineProperty(K20,"__esModule",{value:!0});var ZU=C70(),k81=k70(),GS=i70(),u8=ZU.isS,f81=ZU.isChar,ZH=ZU.isNameStartChar,n70=ZU.isNameChar,z20=ZU.S_LIST,b81=ZU.NAME_RE,i81=k81.isChar,n81=GS.isNCNameStartChar,c81=GS.isNCNameChar,p81=GS.NC_NAME_RE,WO="http://www.w3.org/XML/1998/namespace",GU="http://www.w3.org/2000/xmlns/",d81={__proto__:null,xml:WO,xmlns:GU},m81={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},B4=-1,k5=-2,c70=0,l81=1,ag=2,o81=3,QU=4,r81=5,s81=6,t81=7,eg=8,a81=9,e81=10,$$1=11,I$1=12,L8=13,QO=14,$S=15,z$1=16,IS=17,q$1=18,U$1=19,zS=20,Y$1=21,J$1=22,Q$1=23,p70=24,qS=25,KO=26,d70=27,K$1=28,H$1=29,m70=30,G$1=31,Z$1=32,o2=33,W$1=34,US=35,WH=36,YS=37,X$1=38,l70=39,o70=40,V$1=41,r70=42,w$1=43,L$1=44,JS=9,Y5=10,QS=13,s70=32,t70=33,q20=34,XH=38,U20=39,HO=45,GO=47,O$1=59,U7=60,KU=61,G6=62,x6=63,Y20=91,HU=93,a70=133,e70=8232,ZO=($)=>$===q20||$===U20,J20=[q20,U20],F$1=[...J20,Y20,G6],M$1=[...J20,U7,HU],N$1=[KU,x6,...z20],D$1=[...z20,G6,XH,U7];function HS($,I,z){switch(I){case"xml":if(z!==WO)$.fail(`xml prefix must be bound to ${WO}.`);break;case"xmlns":if(z!==GU)$.fail(`xmlns prefix must be bound to ${GU}.`);break;default:}switch(z){case GU:$.fail(I===""?`the default namespace may not be set to ${z}.`:`may not assign a prefix (even "xmlns") to the URI ${GU}.`);break;case WO:switch(I){case"xml":break;case"":$.fail(`the default namespace may not be set to ${z}.`);break;default:$.fail("may not assign the xml namespace to another prefix.")}break;default:}}function A$1($,I){for(let z of Object.keys(I))HS($,z,I[z])}var P$1=($)=>p81.test($),B$1=($)=>b81.test($),r2=0,$20=1,KS=2;K20.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var I20={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 Q20{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=n81,this.nameCheck=c81,this.isName=P$1,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},d81);let z=this.opt.additionalNamesp Line truncated
`,I=this.i}}captureToChar($){let{i:I}=this,{chunk:z}=this;while(!0){let q=this.getCode();switch(q){case k5:this.text+=`${z.slice(I,this.prevI)}
`,I=this.i,q=Y5;break;case B4:return this.text+=z.slice(I),!1;default:}if(q===$)return this.text+=z.slice(I,this.prevI),!0}}captureNameChars(){let{chunk:$,i:I}=this;while(!0){let z=this.getCode();if(z===B4)return this.name+=$.slice(I),B4;if(!n70(z))return this.name+=$.slice(I,this.prevI),z===k5?Y5:z}}skipSpaces(){while(!0){let $=this.getCodeNorm();if($===B4||!u8($))return $}}setXMLVersion($){if(this.currentXMLVersion=$,$==="1.0")this.isChar=f81,this.getCode=this.getCode10;else this.isChar=i81,this.getCode=this.getCode11}sBegin(){if(this.chunk.charCodeAt(0)===65279)this.i++,this.column++;this.state=l81}sBeginWhitespace(){let $=this.i,I=this.skipSpaces();if(this.prevI!==$)this.xmlDeclPossible=!1;switch(I){case U7:if(this.state=$S,this.text.length!==0)throw Error("no-empty text at start");break;case B4:break;default:this.unget(),this.state=L8,this.xmlDeclPossible=!1}}sDoctype(){var $;let I=this.captureTo(F$1);switch(I){case G6:{($=this.doctypeHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=L8,this.doctype=!0;break}case B4:break;default:if(this.text+=String.fromCodePoint(I),I===Y20)this.state=QU;else if(ZO(I))this.state=o81,this.q=I}}sDoctypeQuote(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.q=null,this.state=ag}sDTD(){let $=this.captureTo(M$1);if($===B4)return;if(this.text+=String.fromCodePoint($),$===HU)this.state=ag;else if($===U7)this.state=s81;else if(ZO($))this.state=r81,this.q=$}sDTDQuoted(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.state=QU,this.q=null}sDTDOpenWaka(){let $=this.getCodeNorm();switch(this.text+=String.fromCodePoint($),$){case t70:this.state=t81,this.openWakaBang="";break;case x6:this.state=$$1;break;default:this.state=QU}}sDTDOpenWakaBang(){let $=String.fromCodePoint(this.getCodeNorm()),I=this.openWakaBang+=$;if(this.text+=$,I!=="-")this.state=I==="--"?eg:QU,this.openWakaBang=""}sDTDComment(){if(this.captureToChar(HO))this.text+="-",this.state=a81}sDTDCommentEnding(){let $=this.getCodeNorm();this.text+=String.fromCodePoint($),this.state=$===HO?e81:eg}sDTDCommentEnded(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===G6)this.state=QU;else this.fail("malformed comment."),this.state=eg}sDTDPI(){if(this.captureToChar(x6))this.text+="?",this.state=I$1}sDTDPIEnding(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===G6)this.state=QU}sText(){if(this.tags.length!==0)this.handleTextInRoot();else this.handleTextOutsideRoot()}sEntity(){let{i:$}=this,{chunk:I}=this;$:while(!0)switch(this.getCode()){case k5:this.entity+=`${I.slice($,this.prevI)}
`,$=this.i;break;case O$1:{let{entityReturnState:z}=this,q=this.entity+I.slice($,this.prevI);this.state=z;let U;if(q==="")this.fail("empty entity name."),U="&;";else U=this.parseEntity(q),this.entity="";if(z!==L8||this.textHandler!==void 0)this.text+=U;break $}case B4:this.entity+=I.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(ZH($))this.state=W$1,this.unget(),this.xmlDeclPossible=!1;else switch($){case GO:this.state=w$1,this.xmlDeclPossible=!1;break;case t70:this.state=z$1,this.openWakaBang="",this.xmlDeclPossible=!1;break;case x6:this.state=Q$1;break;default:this.fail("disallowed character in tag name"),this.state=L8,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=zS,this.openWakaBang="";break;case"--":this.state=IS,this.openWakaBang="";break;case"DOCTYPE":if(this.state=ag,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(HO))this.state=q$1}sCommentEnding(){var $;let I=this.getCodeNorm();if(I===HO)this.state=U$1,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(I)}`,this.state=IS}sCommentEnded(){let $=this.getCodeNorm();if($!==G6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=IS;else this.state=L8}sCData(){if(this.captureToChar(HU))this.state=Y$1}sCDataEnding(){let $=this.getCodeNorm();if($===HU)this.state=J$1;else this.text+=`]${String.fromCodePoint($)}`,this.state=zS}sCDataEnding2(){var $;let I=this.getCodeNorm();switch(I){case G6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=L8;break}case HU:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(I)}`,this.state=zS}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=p70;else if($===x6||u8($))this.fail("processing instruction without a target."),this.state=$===x6?KO:qS;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=p70}sPIRest(){let{chunk:$,i:I}=this;while(!0){let z=this.getCodeNorm();if(z===B4){this.piTarget+=$.slice(I);return}if(!this.nameCheck(z)){this.piTarget+=$.slice(I,this.prevI);let q=z===x6;if(q||u8(z))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=q?o2:d70}else this.state=q?KO:qS;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(z);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===x6)this.state=KO;else if(!u8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(x6))this.state=KO}sPIEnding(){var $;let I=this.getCodeNorm();if(I===G6){let{piTarget:z}=this;if(z.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:z,body:this.text}),this.piTarget=this.text="",this.state=L8}else if(I===x6)this.text+="?";else this.text+=`?${String.fromCodePoint(I)}`,this.state=qS;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===x6){this.state=o2;return}if($!==B4)this.state=K$1,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(N$1);if($===x6){this.state=o2,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(u8($)||$===KU))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=$===KU?m70:H$1}sXMLDeclEq(){let $=this.getCodeNorm();if($===x6){this.state=o2,this.fail("XML declaration is incomplete.");return}if(u8($))return;if($!==KU)this.fail("value required.");this.state=m70}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===x6){this.state=o2,this.fail("XML declaration is incomplete.");return}if(u8($))return;if(!ZO($))this.fail("value must be quoted."),this.q=s70;else this.q=$;this.state=G$1}sXMLDeclValue(){let $=this.captureTo([this.q,x6]);if($===x6){this.state=o2,this.text="",this.fail("XML declaration is incomplete.");return}if($===B4)return;let I=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let z=I;if(this.xmlDecl.version=z,!/^1\.[0-9]+$/.test(z))this.fail("ver Line truncated
`;$=this.i,I=r2;break;case B4:if(q!==void 0)this.text+=z.slice($);break $;default:I=r2}this.forbiddenState=I}handleTextOutsideRoot(){let{i:$}=this,{chunk:I,textHandler:z}=this,q=!1;$:while(!0){let U=this.getCode();switch(U){case U7:{if(this.state=$S,z!==void 0){let{text:Y}=this,J=I.slice($,this.prevI);if(Y.length!==0)z(Y+J),this.text="";else if(J.length!==0)z(J)}break $}case XH:if(this.state=QO,this.entityReturnState=L8,z!==void 0)this.text+=I.slice($,this.prevI);q=!0;break $;case k5:if(z!==void 0)this.text+=`${I.slice($,this.prevI)}
`;$=this.i;break;case B4:if(z!==void 0)this.text+=I.slice($);break $;default:if(!u8(U))q=!0}}if(!q)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 z;let{prefix:q,local:U}=this.qname($),Y={name:$,prefix:q,local:U,value:I};if(this.attribList.push(Y),(z=this.attributeHandler)===null||z===void 0||z.call(this,Y),q==="xmlns"){let J=I.trim();if(this.currentXMLVersion==="1.0"&&J==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[U]=J,HS(this,U,J)}else if($==="xmlns"){let J=I.trim();this.topNS[""]=J,HS(this,"",J)}}pushAttribPlain($,I){var z;let q={name:$,value:I};this.attribList.push(q),(z=this.attributeHandler)===null||z===void 0||z.call(this,q)}end(){var $,I;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:z}=this;while(z.length>0){let U=z.pop();this.fail(`unclosed tag: ${U.name}`)}if(this.state!==c70&&this.state!==L8)this.fail("unexpected end.");let{text:q}=this;if(q.length!==0)($=this.textHandler)===null||$===void 0||$.call(this,q),this.text="";return this._closed=!0,(I=this.endHandler)===null||I===void 0||I.call(this),this._init(),this}resolve($){var I,z;let q=this.topNS[$];if(q!==void 0)return q;let{tags:U}=this;for(let Y=U.length-1;Y>=0;Y--)if(q=U[Y].ns[$],q!==void 0)return q;if(q=this.ns[$],q!==void 0)return q;return(z=(I=this.opt).resolvePrefix)===null||z===void 0?void 0:z.call(I,$)}qname($){let I=$.indexOf(":");if(I===-1)return{prefix:"",local:$};let z=$.slice(I+1),q=$.slice(0,I);if(q===""||z===""||z.includes(":"))this.fail(`malformed name: ${$}.`);return{prefix:q,local:z}}processAttribsNS(){var $;let{attribList:I}=this,z=this.tag;{let{prefix:Y,local:J}=this.qname(z.name);z.prefix=Y,z.local=J;let Q=z.uri=($=this.resolve(Y))!==null&&$!==void 0?$:"";if(Y!==""){if(Y==="xmlns")this.fail('tags may not have "xmlns" as prefix.');if(Q==="")this.fail(`unbound namespace prefix: ${JSON.stringify(Y)}.`),z.uri=Y}}if(I.length===0)return;let{attributes:q}=z,U=new Set;for(let Y of I){let{name:J,prefix:Q,local:K}=Y,H,G;if(Q==="")H=J==="xmlns"?GU:"",G=J;else{if(H=this.resolve(Q),H===void 0)this.fail(`unbound namespace prefix: ${JSON.stringify(Q)}.`),H=Q;G=`{${H}}${K}`}if(U.has(G))this.fail(`duplicate attribute: ${G}.`);U.add(G),Y.uri=H,q[J]=Y}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,I=this.tag.attributes;for(let{name:z,value:q}of $){if(I[z]!==void 0)this.fail(`duplicate attribute: ${z}.`);I[z]=q}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:I}=this,z=this.tag;z.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,z),I.push(z),this.state=L8,this.name=""}openSelfClosingTag(){var $,I,z;this.processAttribs();let{tags:q}=this,U=this.tag;if(U.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,U),(I=this.closeTagHandler)===null||I===void 0||I.call(this,U),(this.tag=(z=q[q.length-1])!==null&&z!==void 0?z:null)===null)this.closedRoot=!0;this.state=L8,this.name=""}closeTag(){let{tags:$,name:I}=this;if(this.state=L8,this.name="",I===""){this.fail("weird empty close tag."),this.text+="</>";return}let z=this.closeTagHandler,q=$.length;while(q-- >0){let U=this.tag=$.pop();if(this.topNS=U.ns,z===null||z===void 0||z(U),U.name===I)break;this.fail("unexpected close tag.")}if(q===0)this.closedRoot=!0;else if(q<0)this.fail(`unmatched closing tag: ${I}.`),this.text+=`</${I}>`}parseEntity($){if($[0]!=="#"){let z=this.ENTITIES[$];if(z!==void 0)return z;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)}}K20.SaxesParser=Q20});var VH=M((le1,G20)=>{var{SaxesParser:j$1}=H20(),{PassThrough:C$1}=w8(),{bufferToString:_$1}=mg();G20.exports=async function*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(new C$1);let I=new j$1,z;I.on("error",(U)=>{z=U});let q=[];I.on("opentag",(U)=>q.push({eventType:"opentag",value:U})),I.on("text",(U)=>q.push({eventType:"text",value:U})),I.on("closetag",(U)=>q.push({eventType:"closetag",value:U}));for await(let U of $){if(I.write(_$1(U)),z)throw z;yield q,q=[]}}});var F0=M((oe1,Z20)=>{var R$1=VH(),v$1=y6();class WU{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,I){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($ instanceof WU)$.reset();else if($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}async parse($){for await(let I of $)for(let{eventType:z,value:q}of I)if(z==="opentag")this.parseOpen(q);else if(z==="text")this.parseText(q);else if(z==="closetag"){if(!this.parseClose(q.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}`}}iJ0.FormatterOptions=bJ0});var dO=M((M44,mJ0)=>{var iI1="[object AsyncFunction]",nI1="[object Function]",cI1="[object GeneratorFunction]",pI1="[object Null]",dI1="[object Proxy]",mI1="[object Undefined]",lI1=typeof global=="object"&&global&&global.Object===Object&&global,oI1=typeof self=="object"&&self&&self.Object===Object&&self,rI1=lI1||oI1||Function("return this")(),pJ0=Object.prototype,sI1=pJ0.hasOwnProperty,dJ0=pJ0.toString,cJ0=rI1.Symbol,zI=cJ0?cJ0.toStringTag:void 0;function tI1($){if($==null)return $===void 0?mI1:pI1;return zI&&zI in Object($)?aI1($):eI1($)}function aI1($){var I=sI1.call($,zI),z=$[zI];try{$[zI]=void 0;var q=!0}catch(Y){}var U=dJ0.call($);if(q)if(I)$[zI]=z;else delete $[zI];return U}function eI1($){return dJ0.call($)}function $z1($){if(!Iz1($))return!1;var I=tI1($);return I==nI1||I==cI1||I==iI1||I==dI1}function Iz1($){var I=typeof $;return $!=null&&(I=="object"||I=="function")}mJ0.exports=$z1});var jQ0=M((mO,AU)=>{var zz1=200,gy="__lodash_hash_undefined__",$F=1,UQ0=2,YQ0=9007199254740991,lO="[object Arguments]",Ey="[object Array]",qz1="[object AsyncFunction]",JQ0="[object Boolean]",QQ0="[object Date]",KQ0="[object Error]",HQ0="[object Function]",Uz1="[object GeneratorFunction]",oO="[object Map]",GQ0="[object Number]",Yz1="[object Null]",DU="[object Object]",lJ0="[object Promise]",Jz1="[object Proxy]",ZQ0="[object RegExp]",rO="[object Set]",WQ0="[object String]",Qz1="[object Symbol]",Kz1="[object Undefined]",jy="[object WeakMap]",XQ0="[object ArrayBuffer]",sO="[object DataView]",Hz1="[object Float32Array]",Gz1="[object Float64Array]",Zz1="[object Int8Array]",Wz1="[object Int16Array]",Xz1="[object Int32Array]",Vz1="[object Uint8Array]",wz1="[object Uint8ClampedArray]",Lz1="[object Uint16Array]",Oz1="[object Uint32Array]",Fz1=/[\\^$.*+?()[\]{}|]/g,Mz1=/^\[object .+?Constructor\]$/,Nz1=/^(?:0|[1-9]\d*)$/,Z4={};Z4[Hz1]=Z4[Gz1]=Z4[Zz1]=Z4[Wz1]=Z4[Xz1]=Z4[Vz1]=Z4[wz1]=Z4[Lz1]=Z4[Oz1]=!0;Z4[lO]=Z4[Ey]=Z4[XQ0]=Z4[JQ0]=Z4[sO]=Z4[QQ0]=Z4[KQ0]=Z4[HQ0]=Z4[oO]=Z4[GQ0]=Z4[DU]=Z4[ZQ0]=Z4[rO]=Z4[WQ0]=Z4[jy]=!1;var VQ0=typeof global=="object"&&global&&global.Object===Object&&global,Dz1=typeof self=="object"&&self&&self.Object===Object&&self,h9=VQ0||Dz1||Function("return this")(),wQ0=typeof mO=="object"&&mO&&!mO.nodeType&&mO,oJ0=wQ0&&typeof AU=="object"&&AU&&!AU.nodeType&&AU,LQ0=oJ0&&oJ0.exports===wQ0,Py=LQ0&&VQ0.process,rJ0=function(){try{return Py&&Py.binding&&Py.binding("util")}catch($){}}(),sJ0=rJ0&&rJ0.isTypedArray;function Az1($,I){var z=-1,q=$==null?0:$.length,U=0,Y=[];while(++z<q){var J=$[z];if(I(J,z,$))Y[U++]=J}return Y}function Pz1($,I){var z=-1,q=I.length,U=$.length;while(++z<q)$[U+z]=I[z];return $}function Bz1($,I){var z=-1,q=$==null?0:$.length;while(++z<q)if(I($[z],z,$))return!0;return!1}function Tz1($,I){var z=-1,q=Array($);while(++z<$)q[z]=I(z);return q}function Ez1($){return function(I){return $(I)}}function jz1($,I){return $.has(I)}function Cz1($,I){return $==null?void 0:$[I]}function _z1($){var I=-1,z=Array($.size);return $.forEach(function(q,U){z[++I]=[U,q]}),z}function Rz1($,I){return function(z){return $(I(z))}}function vz1($){var I=-1,z=Array($.size);return $.forEach(function(q){z[++I]=q}),z}var hz1=Array.prototype,gz1=Function.prototype,IF=Object.prototype,By=h9["__core-js_shared__"],OQ0=gz1.toString,b5=IF.hasOwnProperty,tJ0=function(){var $=/[^.]+$/.exec(By&&By.keys&&By.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),FQ0=IF.toString,Sz1=RegExp("^"+OQ0.call(b5).replace(Fz1,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),aJ0=LQ0?h9.Buffer:void 0,tO=h9.Symbol,eJ0=h9.Uint8Array,MQ0=IF.propertyIsEnumerable,yz1=hz1.splice,qI=tO?tO.toStringTag:void 0,$Q0=Object.getOwnPropertySymbols,xz1=aJ0?aJ0.isBuffer:void 0,uz1=Rz1(Object.keys,Object),Cy=PU(h9,"DataView"),DH=PU(h9,"Map"),_y=PU(h9,"Promise"),Ry=PU(h9,"Set"),vy=PU(h9,"WeakMap"),AH=PU(Object,"create"),kz1=JI(Cy),fz1=JI(DH),bz1=JI(_y),iz1=JI(Ry),nz1=JI(vy),IQ0=tO?tO.prototype:void 0,Ty=IQ0?IQ0.valueOf:void 0;function UI($){var I=-1,z=$==null?0:$.length;this.clear();while(++I<z){var q=$[I];this.set(q[0],q[1])}}function cz1(){this.__data__=AH?AH(null):{},this.size=0}function pz1($){var I=this.has($)&&delete this.__data__[$];return this.size-=I?1:0,I}function dz1($){var I=this.__data Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(I)}set headers($){this._headers=$}shouldQuote($,I){let z=I?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(tq1.default(z))return z;if(Array.isArray(z))return z[$];if(this._headers!==null)return z[this._headers[$]];return!1}format($,I,z){let q=`${aq1.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:U}=this;if(U.quote!==""){if(q.indexOf(U.quote)!==-1)return this.quoteField(q.replace(this.REPLACE_REGEXP,U.escapedQuote))}if(q.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(I,z))return this.quoteField(q);return q}quoteField($){let{quote:I}=this.formatterOptions;return`${I}${$}${I}`}}BU.FieldFormatter=xQ0});var ky=M((uQ0)=>{Object.defineProperty(uQ0,"__esModule",{value:!0});uQ0.isSyncTransform=void 0;uQ0.isSyncTransform=($)=>$.length===1});var bQ0=M((TU)=>{var fQ0=TU&&TU.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(TU,"__esModule",{value:!0});TU.RowFormatter=void 0;var $U1=fQ0(dO()),IU1=fQ0(jQ0()),zU1=uy(),qU1=ky();class QI{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new zU1.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(QI.isRowHashArray($))return $.map((I)=>I[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(qU1.isSyncTransform($))return(I,z)=>{let q=null;try{q=$(I)}catch(U){return z(U)}return z(null,q)};return(I,z)=>{$(I,z)}}set rowTransform($){if(!$U1.default($))throw TypeError("The transform should be a function");this._rowTransform=QI.createTransform($)}format($,I){this.callTransformer($,(z,q)=>{if(z)return I(z);if(!$)return I(null);let U=[];if(q){let{shouldFormatColumns:Y,headers:J}=this.checkHeaders(q);if(this.shouldWriteHeaders&&J&&!this.hasWrittenHeaders)U.push(this.formatColumns(J,!0)),this.hasWrittenHeaders=!0;if(Y){let Q=this.gatherColumns(q);U.push(this.formatColumns(Q,!1))}}return I(null,U)})}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=QI.gatherHeaders($);if(this.headers=I,this.fieldFormatter.headers=I,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!IU1.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(QI.isRowHashArray($))return this.headers.map((I,z)=>{let q=$[z];if(q)return q[1];return""});if(QI.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((I,z)=>$[z])}callTransformer($,I){if(!this._rowTransform)return I(null,$);return this._rowTransform($,I)}formatColumns($,I){let z=$.map((U,Y)=>this.fieldFormatter.format(U,Y,I)).join(this.formatterOptions.delimiter),{rowCount:q}=this;if(this.rowCount+=1,q)return[this.formatterOptions.rowDelimiter,z].join("");return z}}TU.RowFormatter=QI});var iQ0=M((UF)=>{Object.defineProperty(UF,"__esModule",{value:!0});UF.FieldFormatter=UF.RowFormatter=void 0;var UU1=bQ0();Object.defineProperty(UF,"RowFormatter",{enumerable:!0,get:function(){return UU1.RowFormatter}});var YU1=uy();Object.defineProperty(UF,"FieldFormatter",{enumerable:!0,get:function(){return YU1.FieldFormatter}})});var fy=M((cQ0)=>{Object.defineProperty(cQ0,"__esModule",{value:!0});cQ0.CsvFormatterStream=void 0;var QU1=d("stream"),KU1=iQ0();class nQ0 extends QU1.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new KU1.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,I,z){let q=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(U,Y)=>{if(U)return q=!0,z(U);if(Y)Y.forEach((J)=>{this.push(Buffer.from(J,"utf8"))});return q=!0,z()})}catch(U){if(q)throw U;z(U)}}_flush($){this.rowFormatter.finish((I,z)=>{if(I)return $(I);if(z)z.forEach((q)=>{this.push(Buffer.from(q,"utf8"))});return $()})}}cQ0.CsvFormatterStream=nQ0});var mQ0=M((g1)=>{var dQ0=g1&&g1.__createBinding||(Object.create?function($,I,z,q){if(q===void 0)q=z;Object.defineProperty($,q,{enumerable:!0,get:function(){return I[z]}})}:function($,I,z,q){if(q===void 0)q=z;$[q]=I[z]}),HU1=g1&&g1.__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}}lK0.Token=mK0});var Hx=M((tK0)=>{Object.defineProperty(tK0,"__esModule",{value:!0});tK0.Scanner=void 0;var rK0=w7(),OQ1=/((?:\r\n)|\n|\r)/;class sK0{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 z=I.exec($);if(z==null)return null;let q=z[1],U=this.cursor+(z.index||0);return new rK0.Token({token:q,startCursor:U,endCursor:U+q.length-1})}get nextCharacterToken(){let{cursor:$,lineLength:I}=this;if(I<=$)return null;return new rK0.Token({token:this.line[$],startCursor:$,endCursor:$})}get lineFromCursor(){return this.line.substr(this.cursor)}advancePastLine(){let $=OQ1.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}}tK0.Scanner=sK0});var jF=M(($H0)=>{Object.defineProperty($H0,"__esModule",{value:!0});$H0.ColumnFormatter=void 0;class eK0{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}}$H0.ColumnFormatter=eK0});var Gx=M((UH0)=>{Object.defineProperty(UH0,"__esModule",{value:!0});UH0.NonQuotedColumnParser=void 0;var FQ1=jF(),zH0=w7();class qH0{constructor($){this.parserOptions=$,this.columnFormatter=new FQ1.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let{parserOptions:I}=this,z=[],q=$.nextCharacterToken;for(;q;q=$.nextCharacterToken){if(zH0.Token.isTokenDelimiter(q,I)||zH0.Token.isTokenRowDelimiter(q))break;z.push(q.token),$.advancePastToken(q)}return this.columnFormatter.format(z.join(""))}}UH0.NonQuotedColumnParser=qH0});var Zx=M((QH0)=>{Object.defineProperty(QH0,"__esModule",{value:!0});QH0.QuotedColumnParser=void 0;var MQ1=jF(),xU=w7();class JH0{constructor($){this.parserOptions=$,this.columnFormatter=new MQ1.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let I=$.cursor,{foundClosingQuote:z,col:q}=this.gatherDataBetweenQuotes($);if(!z){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($),q}gatherDataBetweenQuotes($){let{parserOptions:I}=this,z=!1,q=!1,U=[],Y=$.nextCharacterToken;for(;!q&&Y!==null;Y=$.nextCharacterToken){let J=xU.Token.isTokenQuote(Y,I);if(!z&&J)z=!0;else if(z)if(xU.Token.isTokenEscapeCharacter(Y,I)){$.advancePastToken(Y);let Q=$.nextCharacterToken;if(Q!==null&&(xU.Token.isTokenQuote(Q,I)||xU.Token.isTokenEscapeCharacter(Q,I)))U.push(Q.token),Y=Q;else if(J)q=!0;else U.push(Y.token)}else if(J)q=!0;else U.push(Y.token);$.advancePastToken(Y)}return{col:this.columnFormatter.format(U.join("")),foundClosingQuote:q}}checkForMalformedColumn($){let{parserOptions:I}=this,{nextNonSpaceToken:z}=$;if(z){let q=xU.Token.isTokenDelimiter(z,I),U=xU.Token.isTokenRowDelimiter(z);if(!(q||U)){let Y=$.lineFromCursor.substr(0,10).replace(/[\r\n]/g,"\\n'");throw Error(`Parse Error: expected: '${I.escapedDelimiter}' OR new line got: '${z.token}'. at '${Y}`)}$.advanceToToken(z)}else if(!$.hasMoreData)$.advancePastLine()}}QH0.QuotedColumnParser=JH0});var WH0=M((GH0)=>{Object.defineProperty(GH0,"__esModule",{value:!0});GH0.ColumnParser=void 0;var NQ1=Gx(),DQ1=Zx(),AQ1=w7();class HH0{constructor($){this.parserOptions=$,this.quotedColumnParser=new DQ1.QuotedColumnParser($),this.nonQuotedColumnParser=new NQ1.NonQuotedColumnParser($)}parse($){let{nextNonSpaceToken:I}=$;if(I!==null&&AQ1.Token.isTokenQuote(I,this.parserOptions))return $.advanceToToken(I),this.quotedColumnParser.parse($);return this.nonQuotedColumnParser.parse($)}}GH0.ColumnParser=HH0});var Wx=M((uU)=>{Object.defineProperty(uU,"__esModule",{value:!0});uU.ColumnFormatter=uU.QuotedColumnParser=uU.NonQuotedColumnParser=uU.ColumnParser=void 0;var PQ1=WH0();Object.defineProperty(uU,"ColumnParser",{enumerable:!0,get:function(){return PQ1.ColumnParser}});var BQ1=Gx();Object.defineProperty(uU,"NonQuotedColumnParser",{enumerable:!0,get:function(){return BQ1.NonQuotedColumnParser}});var TQ1=Zx();Object.defineProperty(uU,"QuotedColumnParser",{enumerable:!0,get:function(){re Line truncated
%s`,k,k,X,q);let h=X.type==="*"?jx:X.type==="?"?Rx:"\\"+X.type;U=!0,q=q.slice(0,X.reStart)+h+"\\("+k}if(P(),Y)q+="\\\\";let A=LK1[q.charAt(0)];for(let k=Q.length-1;k>-1;k--){let h=Q[k],f=q.slice(0,h.reStart),C=q.slice(h.reStart,h.reEnd-8),b=q.slice(h.reEnd),i=q.slice(h.reEnd-8,h.reEnd)+b,v=f.split(")").length,y=f.split("(").length-v,c=b;for(let R=0;R<y;R++)c=c.replace(/\)[+*?]?/,"");b=c;let $0=b===""&&I!==Cx?"(?:$|\\/)":"";q=f+C+b+$0+i}if(q!==""&&U)q="(?=.)"+q;if(A)q=F()+q;if(I===Cx)return[q,U];if(z.nocase&&!U)U=$.toUpperCase()!==$.toLowerCase();if(!U)return FK1($);let T=z.nocase?"i":"";try{return Object.assign(new RegExp("^"+q+"$",T),{_glob:$,_src:q})}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,z=I.noglobstar?jx:I.dot?VK1:wK1,q=I.nocase?"i":"",U=$.map((Y)=>{return Y=Y.map((J)=>typeof J==="string"?NK1(J):J===O8?O8:J._src).reduce((J,Q)=>{if(!(J[J.length-1]===O8&&Q===O8))J.push(Q);return J},[]),Y.forEach((J,Q)=>{if(J!==O8||Y[Q-1]===O8)return;if(Q===0)if(Y.length>1)Y[Q+1]="(?:\\/|"+z+"\\/)?"+Y[Q+1];else Y[Q]=z;else if(Q===Y.length-1)Y[Q-1]+="(?:\\/|"+z+")?";else Y[Q-1]+="(?:\\/|\\/"+z+"\\/)"+Y[Q+1],Y[Q+1]=O8}),Y.filter((J)=>J!==O8).join("/")}).join("|");if(U="^(?:"+U+")$",this.negate)U="^(?!"+U+").*$";try{this.regexp=new RegExp(U,q)}catch(Y){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 z=this.options;if(_x.sep!=="/")$=$.split(_x.sep).join("/");$=$.split(YG0),this.debug(this.pattern,"split",$);let q=this.set;this.debug(this.pattern,"set",q);let U;for(let Y=$.length-1;Y>=0;Y--)if(U=$[Y],U)break;for(let Y=0;Y<q.length;Y++){let J=q[Y],Q=$;if(z.matchBase&&J.length===1)Q=[U];if(this.matchOne(Q,J,I)){if(z.flipNegate)return!0;return!this.negate}}if(z.flipNegate)return!1;return this.negate}static defaults($){return q$.defaults($).Minimatch}}q$.Minimatch=RH});var XG0=M((C64,WG0)=>{WG0.exports=ZG0;var gx=d("fs"),{EventEmitter:AK1}=d("events"),{Minimatch:hx}=KG0(),{resolve:PK1}=d("path");function BK1($,I){return new Promise((z,q)=>{gx.readdir($,{withFileTypes:!0},(U,Y)=>{if(U)switch(U.code){case"ENOTDIR":if(I)q(U);else z([]);break;case"ENOTSUP":case"ENOENT":case"ENAMETOOLONG":case"UNKNOWN":z([]);break;case"ELOOP":default:q(U);break}else z(Y)})})}function HG0($,I){return new Promise((z,q)=>{(I?gx.stat:gx.lstat)($,(Y,J)=>{if(Y)switch(Y.code){case"ENOENT":if(I)z(HG0($,!1));else z(null);break;default:z(null);break}else z(J)})})}async function*GG0($,I,z,q,U,Y){let J=await BK1(I+$,Y);for(let Q of J){let K=Q.name;if(K===void 0)K=Q,q=!0;let H=$+"/"+K,G=H.slice(1),Z=I+"/"+G,W=null;if(q||z)W=await HG0(Z,z);if(!W&&Q.name!==void 0)W=Q;if(W===null)W={isDirectory:()=>!1};if(W.isDirectory()){if(!U(G))yield{relative:G,absolute:Z,stats:W},yield*GG0(H,I,z,q,U,!1)}else yield{relative:G,absolute:Z,stats:W}}}async function*TK1($,I,z,q){yield*GG0("",$,I,z,q,!0)}function EK1($){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 Sx extends AK1{constructor($,I,z){super();if(typeof I==="function")z=I,I=null;if(this.options=EK1(I||{}),this.matchers=[],this.options.pattern){let q=Array.isArray(this.options.pattern)?this.options.pattern:[this.options.pattern];this.matchers=q.map((U)=>new hx(U,{dot:this.options.dot,noglobstar:this.options.noglobstar,matchBase:this.options.matchBase,nocase:this.options.nocase}))}if(this.ignoreMatchers=[],this.options.ignore){let q=Array.isArray(this.options.ignore)?this.options.ignore:[this.options.ignore];this.ignoreMatchers=q.map((U)=>new hx(U,{dot:!0}))}if(this.skipMatchers=[],this.options.skip){let q=Array.isArray(this.options.skip)?this.options.skip:[this.options.skip];this.skipMatchers=q.map((U)=>new hx(U,{dot:!0}))}if(this.iterator=TK1(PK1($||"."),this.options.follow,this.options.stat,this._shouldSkipDirectory.bind(this)),this.paused=!1,this.inactive=!1,this.aborted=!1,z)this._matches=[],this.on("match",(q)=>this._matches.push(this.options.absolute?q.absolute:q.relative)),this.on("error",(q)=>z(q)),this.on("end",()=>z(null,this._matches));setTimeout(()=>this._next(),0)}_shouldSkipDirectory($){return this.skipMatchers.some((I)=>I.match($))}_fileMatches($,I){let z=$+(I?"/":"");return(this.matchers.length===0||this.matchers.some((q)=>q.match(z)))&&!this.ignoreMatchers.some((q)=>q.match(z))&&(!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 z=$.value.relative,q=$.value.absolute;if(this.options.mark&&I)z+="/",q+="/";if(this.options.stat)this.emit("match",{relative:z,absolute:q,stat:$.value.stats});else this.emit("match",{relative:z,ab Line truncated
`,x);x=q0===-1?j.length:q0}else if(m!==-1&&j[x]==="/"&&j[x+1]==="*"){let q0=j.indexOf("*/",x);if(q0!==-1)x=q0+2,m=j.indexOf("*/",x);else g+=j[x],x++}else g+=j[x],x++;return g}function W$(j){let g=J8(j.toString()),x=g.match(k4);if(!x)x=g.match(t4);if(!x)throw Error(`could not parse args in autoInject
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let I of $.seen.entries()){let K=I[1];if(Y===I[0]){J(I);continue}if($.external){let W=$.external.registry.get(I[0])?.id;if(Y!==I[0]&&W){J(I);continue}}if($.metadataRegistry.get(I[0])?.id){J(I);continue}if(K.cycle){J(I);continue}if(K.count>1){if($.reused==="ref"){J(I);continue}}}}function Z3($,Y){let z=$.seen.get(Y);if(!z)throw Error("Unprocessed schema. This is a bug in Zod.");let U=(K)=>{let G=$.seen.get(K);if(G.ref===null)return;let W=G.def??G.schema,H={...W},X=G.ref;if(G.ref=null,X){U(X);let q=$.seen.get(X),V=q.schema;if(V.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))W.allOf=W.allOf??[],W.allOf.push(V);else Object.assign(W,V);if(Object.assign(W,H),K._zod.parent===X)for(let M in W){if(M==="$ref"||M==="allOf")continue;if(!(M in H))delete W[M]}if(V.$ref&&q.def)for(let M in W){if(M==="$ref"||M==="allOf")continue;if(M in q.def&&JSON.stringify(W[M])===JSON.stringify(q.def[M]))delete W[M]}}let Z=K._zod.parent;if(Z&&Z!==X){U(Z);let q=$.seen.get(Z);if(q?.schema.$ref){if(W.$ref=q.schema.$ref,q.def)for(let V in W){if(V==="$ref"||V==="allOf")continue;if(V in q.def&&JSON.stringify(W[V])===JSON.stringify(q.def[V]))delete W[V]}}}$.override({zodSchema:K,jsonSchema:W,path:G.path??[]})};for(let K of[...$.seen.entries()].reverse())U(K[0]);let Q={};if($.target==="draft-2020-12")Q.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")Q.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")Q.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let K=$.external.registry.get(Y)?.id;if(!K)throw Error("Schema is missing an `id` property");Q.$id=$.external.uri(K)}Object.assign(Q,z.def??z.schema);let J=$.metadataRegistry.get(Y)?.id;if(J!==void 0&&Q.id===J)delete Q.id;let I=$.external?.defs??{};for(let K of $.seen.entries()){let G=K[1];if(G.def&&G.defId){if(G.def.id===G.defId)delete G.def.id;I[G.defId]=G.def}}if($.external);else if(Object.keys(I).length>0)if($.target==="draft-2020-12")Q.$defs=I;else Q.definitions=I;try{let K=JSON.parse(JSON.stringify(Q));return Object.defineProperty(K,"~standard",{value:{...Y["~standard"],jsonSchema:{input:JQ(Y,"input",$.processors),output:JQ(Y,"output",$.processors)}},enumerable:!1,writable:!1}),K}catch(K){throw Error("Error converting schema to JSON.")}}function A8($,Y){let z=Y??{seen:new Set};if(z.seen.has($))return!1;z.seen.add($);let U=$._zod.def;if(U.type==="transform")return!0;if(U.type==="array")return A8(U.element,z);if(U.type==="set")return A8(U.valueType,z);if(U.type==="lazy")return A8(U.getter(),z);if(U.type==="promise"||U.type==="optional"||U.type==="nonoptional"||U.type==="nullable"||U.type==="readonly"||U.type==="default"||U.type==="prefault")return A8(U.innerType,z);if(U.type==="intersection")return A8(U.left,z)||A8(U.right,z);if(U.type==="record"||U.type==="map")return A8(U.keyType,z)||A8(U.valueType,z);if(U.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return A8(U.in,z)||A8(U.out,z)}if(U.type==="object"){for(let Q in U.shape)if(A8(U.shape[Q],z))return!0;return!1}if(U.type==="union"){for(let Q of U.options)if(A8(Q,z))return!0;return!1}if(U.type==="tuple"){for(let Q of U.items)if(A8(Q,z))return!0;if(U.rest&&A8(U.rest,z))return!0;return!1}return!1}var $_=($,Y={})=>(z)=>{let U=H3({...z,processors:Y});return I4($,U),X3(U,$),Z3(U,$)},JQ=($,Y,z={})=>(U)=>{let{libraryOptions:Q,target:J}=U??{},I=H3({...Q??{},target:J,io:Y,processors:z});return I4($,I),X3(I,$),Z3(I,$)};var VG=o(()=>{XG()});function RY($,Y){if("_idmap"in $){let U=$,Q=H3({...Y,processors:kV}),J={};for(let G of U._idmap.entries()){let[W,H]=G;I4(H,Q)}let I={},K={registry:U,uri:Y?.uri,defs:J};Q.external=K;for(let G of U._idmap.entries()){let[W,H]=G;X3(Q,H),I[W]=Z3(Q,H)}if(Object.keys(J).length>0){let G=Q.target==="draft-2020-12"?"$defs":"definitions";I.__shared={[G]:J}}return{schemas:I}}let z=H3({...Y,processors:kV});return I4($,z),X3(z,$),Z3(z,$)}var Zx0,Y_=($,Y,z,U)=>{let Q=z;Q.type="string";let{minimum:J,maximum:I,format:K,patterns:G,contentEncoding:W}=$._zod.bag;if(typeof J==="number")Q.minLength=J;if(typeof I==="number")Q.maxLength=I;if(K){if(Q.format=Zx0[K]??K,Q.format==="")delete Q.format;if(K==="time")delete Q.format}if(W)Q.contentEncoding=W;if(G&&G.size>0){let H=[...G];if(H.length===1)Q.pattern=H[0].source;else if(H.length>1)Q.allOf=[...H.map((X)=>({...Y.target==="draft-07"||Y.target==="draft-04"||Y.target==="openapi-3.0"?{type:"string"}:{},pattern:X.source}))]}},z_=($,Y,z,U)=>{let Q=z,{minimum:J,maximum:I,format:K,multipleOf:G,exclusiveMaximum:W,exclusiveMinimum:H}=$._zod.bag;if(typeof K==="string"&&K.includes("int"))Q.type="integer";else Q.type="number";let X=typeof H==="number"&&H>=(J??Number.NEGATIVE_INFINITY),Z=typeof W==="number"&&W<=(I??Number.POSITIVE_INFINITY),q=Y.target==="draft-04"||Y.target==="openapi-3.0";if(X)if(q)Q.minimum=H,Q.exclusiveMinimum=!0;else Q.exclusiveMinimuLine truncated
`}function mf0($){let Y=[];if($.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if($.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${$.length})`]};if($.includes(" "))Y.push("Tool name contains spaces, which may cause parsing issues");if($.includes(","))Y.push("Tool name contains commas, which may cause parsing issues");if($.startsWith("-")||$.endsWith("-"))Y.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if($.startsWith(".")||$.endsWith("."))Y.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!df0.test($)){let z=[...$].filter((U)=>!/[A-Za-z0-9._-]/.test(U)).filter((U,Q,J)=>J.indexOf(U)===Q);return Y.push(`Tool name contains invalid characters: ${z.map((U)=>`"${U}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:Y}}return{isValid:!0,warnings:Y}}function lf0($,Y){if(Y.length>0){console.warn(`Tool name validation warning for "${$}":`);for(let z of Y)console.warn(` - ${z}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function ah($){let Y=mf0($);return lf0($,Y.warnings),Y.isValid}function of0($){return typeof $==="object"&&$!==null&&"_zod"in $}function rf0($){return typeof $==="object"&&$!==null&&!("_zod"in $)&&"_def"in $&&typeof $._def?.typeName==="string"}function sf0($){if(typeof $!=="object"||$===null)return!1;if(CQ($))return!1;let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return!1;return Object.values($).every((z)=>of0(z))}function Bw($){if($===void 0)return;if(sf0($))return z0($);if(typeof $==="object"&&$!==null&&!CQ($)&&Object.values($).some((Y)=>rf0(Y)))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!CQ($))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return $}var Th,Cx0,B1,V1,Rx0,ta="2026-07-28",T3,Yt,hx0,Sx0,gx0,Qt,Jt,kx0,Iw,kx1,xx1,ba,Sh,cx0,nx0,jQ,n0,J1,Lw,Gt,_Q,Fw,mx0=0,lx0="private",ox0,zf0,Gw,xh,Xt,fx1,ux1,Gf0,Wf0,fh,Ww,WW="2026-07-28",Vt,Zf0,D$=($)=>yG.safeParse($).success,j3=($)=>kG.safeParse($).success,KW=($)=>LQ.safeParse($).success,Nw=($)=>FQ.safeParse($).success,r9=($)=>typeof $==="object"&&$!==null&&!Array.isArray($)&&$.resultType==="input_required",da="x-mcp-header",qf0,Vf0,Lf0,Ff0,Zw=-32020,bx1,wf0,ma=!1,Eh="draft-2020-12",Nf0,Tf0,jf0,la,Ef0,Sf0,wt=250,gf0,yf0,Dt,Bt,kf0,xf0,At=60000,uf0,bf0,if0,Tt,lh,pf0,ix1,jt=10485760,rh=class{_buffer;_maxBufferSize;constructor($){this._maxBufferSize=$?.maxBufferSize??jt}append($){if((this._buffer?.length??0)+$.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){while(this._buffer){let $=this._buffer.indexOf(`
`);if($===-1)return null;let Y=this._buffer.toString("utf8",0,$).replace(/\r$/,"");this._buffer=this._buffer.subarray($+1);try{return Et(Y)}catch(z){if(z instanceof SyntaxError)continue;throw z}}return null}clear(){this._buffer=void 0}},df0;var Pw=o(()=>{cT();nT();xa();pv();Th=Symbol.for("mcp.sdk.errorBrands");Cx0=class $ extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](Y){return EQ(this,Y)}static isInstance(Y){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return EQ(this,Y)}constructor(Y,z,U){super(z);this.code=Y,this.errorUri=U,this.name="OAuthError",Rh(this,new.target)}toResponseObject(){let Y={error:this.code,error_description:this.message};if(this.errorUri)Y.error_uri=this.errorUri;return Y}static fromResponse(Y){return new $(Y.error,Y.error_description??Y.error,Y.error_uri)}},B1=function($){return $.NotConnected="NOT_CONNECTED",$.AlreadyConnected="ALREADY_CONNECTED",$.NotInitialized="NOT_INITIALIZED",$.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",$.RequestTimeout="REQUEST_TIMEOUT",$.ConnectionClosed="CONNECTION_CLOSED",$.SendFailed="SEND_FAILED",$.InvalidResult="INVALID_RESULT",$.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",$.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",$.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",$.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",$.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",$.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",$.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",$.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",$.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",$.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",$.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",$}({}),V1=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance]($){return EQ(this,$)}static isInstance($){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return EQ(this,$)}constructor($,Y,z){super(Y);this.code=$,this.data=z,this.name="SdkError",Rh(this,new.target)}},Rx0=class extends V1{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor($,Y,z){super($,Y,z);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};T3=[ta];Yt=["task","inputRequests","requestState"];Sx0=new Set(["const","enum","default","examples"]),gx0=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);Qt={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Jt={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},kx0={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};kx1=Object.keys(Qt),xx1=Object.keys(Jt);ba={ok:!1,reason:"not-in-era"};Sh={era:"2025-11-25",hasRequestMethod:It,hasNotificationMethod:Kt,validateRequest:($,Y)=>Kw(ux0($),Y),validateResult:($,Y)=>Kw(fx0($),Y),validateNotification:($,Y)=>Kw(bx0($),Y),hasInputRequestMethod:()=>!1,validateInputRequest:()=>ba,validateInputResponse:()=>ba,samplingResultVariant:($,Y)=>{let z=zt();return Kw($?z.CreateMessageResultWithToolsSchema:z.CreateMessageResultSchema,Y)},outboundEnvelope:($)=>{return},validateEnvelopeMeta:($)=>[],projectCallToolResult($,Y){let z=$t($),U=z.structuredContent;if(U===void 0)return z;let Q=typeof U!=="object"||U===null||Array.isArray(U),J=Y!==void 0&&Ut(Y);if(!Q&&!J)return z;return{...z,structuredContent:{result:U}}},decodeResult($,Y){if(jh(Y)&&"resultType"in Y){let z={...Y};return delete z.resultType,{kind:"complete",result:ca(z)}}return{kind:"complete",result:ca(Y)}},encodeResult($,Y){if($!=="tools/list")return Y;l Line truncated
* content-type
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/pf0=R0(($)=>{var Y=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,z=/\\([\u000b\u0020-\u00ff])/g,U=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;$.parse=Q;function Q(K){if(!K)throw TypeError("argument string is required");var G=typeof K==="object"?J(K):K;if(typeof G!=="string")throw TypeError("argument string is required to be a string");var W=G.indexOf(";"),H=W!==-1?G.slice(0,W).trim():G.trim();if(!U.test(H))throw TypeError("invalid media type");var X=new I(H.toLowerCase());if(W!==-1){var Z,q,V;Y.lastIndex=W;while(q=Y.exec(G)){if(q.index!==W)throw TypeError("invalid parameter format");if(W+=q[0].length,Z=q[1].toLowerCase(),V=q[2],V.charCodeAt(0)===34){if(V=V.slice(1,-1),V.indexOf("\\")!==-1)V=V.replace(z,"$1")}X.parameters[Z]=V}if(W!==G.length)throw TypeError("invalid parameter format")}return X}function J(K){var G;if(typeof K.getHeader==="function")G=K.getHeader("content-type");else if(typeof K.headers==="object")G=K.headers&&K.headers["content-type"];if(typeof G!=="string")throw TypeError("content-type header is missing from object");return G}function I(K){this.parameters=Object.create(null),this.type=K}}),ix1=kq(pf0(),1);df0=/^[A-Za-z0-9._-]{1,128}$/});function th($){let Y=new $({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Zb0(Y),Y}var Aw,Ct,L1,v1,U5,jw,af0,Rt,_t,Tw,tf0,Q5,ef0,$u0,vt,Yu0,Ew,vQ,XW,hQ,Cw,zu0,ht,Uu0,Qu0,Ju0,eh,Iu0,$S,St,Ku0,Gu0,Wu0,Hu0,Xu0,Zu0,qu0,Vu0,YS,Lu0,Fu0,wu0,gt,yt,kt,Mu0,Ou0,Nu0,zS,Du0,xt,Bu0,Pu0,Au0,Tu0,ju0,Eu0,Cu0,Ru0,ft,_u0,ut,bt,it,vu0,US,hu0,ct,nt,pt,Su0,gu0,dt,yu0,ku0,xu0,mt,fu0,uu0,lt,bu0,iu0,cu0,nu0,pu0,du0,mu0,lu0,ou0,ru0,su0,au0,tu0,eu0,$b0,Yb0,zb0,Ub0,Qb0,Jb0,Ib0,Kb0,Gb0,ot,Wb0,Hb0,Xb0,Zb0,Rw=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor($){this._userAjv=$!==void 0,this._ajv=$}get ajv(){return this._ajv??=th(Hb0.Ajv2020)}_engineFor($){if(this._userAjv)return this.ajv;let Y=jo($,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");if(Y==="2020-12")return this.ajv;if(Y==="2019-09")return this._ajv2019??=th(Wb0.Ajv2019);return this._ajvDraft7??=th(ot.Ajv)}getValidator($){let Y=this._engineFor($),z="$id"in $&&typeof $.$id==="string"?Y.getSchema($.$id)??Y.compile($):Y.compile($);return(U)=>{return z(U)?{valid:!0,data:U,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:Y.errorsText(z.errors)}}}},ex1;var rt=o(()=>{cT();nT();Aw=R0(($)=>{Object.defineProperty($,"__esModule",{value:!0}),$.regexpCode=$.getEsmExportName=$.getProperty=$.safeStringify=$.stringify=$.strConcat=$.addCodeArg=$.str=$._=$.nil=$._Code=$.Name=$.IDENTIFIER=$._CodeOrName=void 0;var Y=class{};$._CodeOrName=Y,$.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var z=class extends Y{constructor(w){super();if(!$.IDENTIFIER.test(w))throw Error("CodeGen: name must be a valid identifier");this.str=w}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};$.Name=z;var U=class extends Y{constructor(w){super();this._items=typeof w==="string"?[w]:w}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let w=this._items[0];return w===""||w==='""'}get str(){var w;return(w=this._str)!==null&&w!==void 0?w:this._str=this._items.reduce((O,N)=>`${O}${N}`,"")}get names(){var w;return(w=this._names)!==null&&w!==void 0?w:this._names=this._items.reduce((O,N)=>{if(N instanceof z)O[N.str]=(O[N.str]||0)+1;return O},{})}};$._Code=U,$.nil=new U("");function Q(w,...O){let N=[w[0]],D=0;while(D<O.length)K(N,O[D]),N.push(w[++D]);return new U(N)}$._=Q;let J=new U("+");function I(w,...O){let N=[q(w[0])],D=0;while(D<O.length)N.push(J),K(N,O[D]),N.push(J,q(w[++D]));return G(N),new U(N)}$.str=I;function K(w,O){if(O instanceof U)w.push(...O._items);else if(O instanceof z)w.push(O);else w.push(X(O))}$.addCodeArg=K;function G(w){let O=1;while(O<w.length-1){if(w[O]===J){let N=W(w[O-1],w[O+1]);if(N!==void 0){w.splice(O-1,3,N);continue}w[O++]="+"}O++}}function W(w,O){if(O==='""')return w;if(w==='""')return O;if(typeof w=="string"){if(O instanceof z||w[w.length-1]!=='"')return;if(typeof O!="string")return`${w.slice(0,-1)}${O}"`;if(O[0]==='"')return w.slice(0,-1)+O.slice(1);return}if(typeof O=="string"&&O[0]==='"'&&!(w instanceof z))return`"${w}${O.slice(1)}`}function H(w,O){return O.emptyStr()?w:w.emptyStr()?O:I`${w}${O}`}$.strConcat=H;function X(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:q(Array.isArray(w)?w.join(","):w)}function Z(w){return new U(q(w))}$.stringify=Z;function q(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}$.safeStringify=q;function V(w){return typeof w=="string"&&$.IDENTIFIER.test(w)?new U(`.${w}`):Q`[${w}]`}$.getProperty=V;function F(w){if(typeof w=="string"&&$.IDENTIFIER.test(w))return new U(`${w}`);throw Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}$.getEsmExportName=F;function M(w){return new U(w.toStringLine truncated
`:""},this._extScope=y,this._scope=new z.Scope({parent:y}),this._nodes=[new F]}toString(){return this._root.render(this.opts)}name(y){return this._scope.name(y)}scopeName(y){return this._extScope.name(y)}scopeValue(y,s){let Y0=this._extScope.value(y,s);return(this._values[Y0.prefix]||(this._values[Y0.prefix]=new Set)).add(Y0),Y0}getScopeValue(y,s){return this._extScope.getValue(y,s)}scopeRefs(y){return this._extScope.scopeRefs(y,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(y,s,Y0,M0){let E0=this._scope.toName(s);if(Y0!==void 0&&M0)this._constants[E0.str]=Y0;return this._leafNode(new I(y,E0,Y0)),E0}const(y,s,Y0){return this._def(z.varKinds.const,y,s,Y0)}let(y,s,Y0){return this._def(z.varKinds.let,y,s,Y0)}var(y,s,Y0){return this._def(z.varKinds.var,y,s,Y0)}assign(y,s,Y0){return this._leafNode(new K(y,s,Y0))}add(y,s){return this._leafNode(new G(y,$.operators.ADD,s))}code(y){if(typeof y=="function")y();else if(y!==Y.nil)this._leafNode(new Z(y));return this}object(...y){let s=["{"];for(let[Y0,M0]of y){if(s.length>1)s.push(",");if(s.push(Y0),Y0!==M0||this.opts.es5)s.push(":"),(0,Y.addCodeArg)(s,M0)}return s.push("}"),new Y._Code(s)}if(y,s,Y0){if(this._blockNode(new w(y)),s&&Y0)this.code(s).else().code(Y0).endIf();else if(s)this.code(s).endIf();else if(Y0)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(y){return this._elseNode(new w(y))}else(){return this._elseNode(new M)}endIf(){return this._endBlockNode(w,M)}_for(y,s){if(this._blockNode(y),s)this.code(s).endFor();return this}for(y,s){return this._for(new N(y),s)}forRange(y,s,Y0,M0,E0=this.opts.es5?z.varKinds.var:z.varKinds.let){let G0=this._scope.toName(y);return this._for(new D(E0,G0,s,Y0),()=>M0(G0))}forOf(y,s,Y0,M0=z.varKinds.const){let E0=this._scope.toName(y);if(this.opts.es5){let G0=s instanceof Y.Name?s:this.var("_arr",s);return this.forRange("_i",0,Y._`${G0}.length`,(T0)=>{this.var(E0,Y._`${G0}[${T0}]`),Y0(E0)})}return this._for(new T("of",M0,E0,s),()=>Y0(E0))}forIn(y,s,Y0,M0=this.opts.es5?z.varKinds.var:z.varKinds.const){if(this.opts.ownProperties)return this.forOf(y,Y._`Object.keys(${s})`,Y0);let E0=this._scope.toName(y);return this._for(new T("in",M0,E0,s),()=>Y0(E0))}endFor(){return this._endBlockNode(O)}label(y){return this._leafNode(new W(y))}break(y){return this._leafNode(new H(y))}return(y){let s=new B;if(this._blockNode(s),this.code(y),s.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(B)}try(y,s,Y0){if(!s&&!Y0)throw Error('CodeGen: "try" without "catch" and "finally"');let M0=new j;if(this._blockNode(M0),this.code(y),s){let E0=this.name("e");this._currNode=M0.catch=new C(E0),s(E0)}if(Y0)this._currNode=M0.finally=new b,this.code(Y0);return this._endBlockNode(C,b)}throw(y){return this._leafNode(new X(y))}block(y,s){if(this._blockStarts.push(this._nodes.length),y)this.code(y).endBlock(s);return this}endBlock(y){let s=this._blockStarts.pop();if(s===void 0)throw Error("CodeGen: not in self-balancing block");let Y0=this._nodes.length-s;if(Y0<0||y!==void 0&&Y0!==y)throw Error(`CodeGen: wrong number of nodes: ${Y0} vs ${y} expected`);return this._nodes.length=s,this}func(y,s=Y.nil,Y0,M0){if(this._blockNode(new A(y,s,Y0)),M0)this.code(M0).endFunc();return this}endFunc(){return this._endBlockNode(A)}optimize(y=1){while(y-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(y){return this._currNode.nodes.push(y),this}_blockNode(y){this._currNode.nodes.push(y),this._nodes.push(y)}_endBlockNode(y,s){let Y0=this._currNode;if(Y0 instanceof y||s&&Y0 instanceof s)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${s?`${y.kind}/${s.kind}`:y.kind}"`)}_elseNode(y){let s=this._currNode;if(!(s instanceof w))throw Error('CodeGen: "else" without "if"');return this._currNode=s.else=y,this}get _root(){return this._nodes[0]}get _currNode(){let y=this._nodes;return y[y.length-1]}set _currNode(y){let s=this._nodes;s[s.length-1]=y}};$.CodeGen=k;function h(y,s){for(let Y0 in s)y[Y0]=(y[Y0]||0)+(s[Y0]||0);return y}function i(y,s){return s instanceof Y._CodeOrName?h(y,s.names):y}function c(y,s,Y0){if(y instanceof Y.Name)return M0(y);if(!E0(y))return y;return new Y._Code(y._items.reduce((G0,T0)=>{if(T0 instanceof Y.Name)T0=M0(T0);if(T0 instanceof Y._Code)G0.push(...T0._items);else G0.push(T0);return G0},[]));function M0(G0){let T0=Y0[G0.str];if(T0===void 0||s[G0.str]!==1)return G0;return delete s[G0.str],T0}function E0(G0){return G0 instanceof Y._Code&&G0._items.some((T0)=>T0 instanceof Y.Name&&s[T0.str]===1&&Y0[T0.str]!==void 0)}}function U0(y,s){for(let Y0 in s)y[Y0]=(y[Y0]||0)-(s[Y0]||0)}function x(y){return typeof y=="boolean"||typeof y=="number"||y===null?!y:Y._`!${e(y)}`}$.not=x;let d=p($.operators.AND);function t(...y){return y.reduce(d)}$.and=t;let $0=p($.operators.OR);function g(...y){return y.reduce($0)}$.or=g;function p(y){return(s,Y0)=>s===Y.nil?Y0:Y0===Y.nil?s:Y._`${e(s)} ${y} ${e(Y0)}`}function Line truncated
|| (${C} == "string" && ${B} && ${B} == +${B})`).assign(b,Q._`+${B}`);return;case"integer":A.elseIf(Q._`${C} === "boolean" || ${B} === null
|| (${C} === "string" && ${B} && ${B} == +${B} && !(${B} % 1))`).assign(b,Q._`+${B}`);return;case"boolean":A.elseIf(Q._`${B} === "false" || ${B} === 0 || ${B} === null`).assign(b,!1).elseIf(Q._`${B} === "true" || ${B} === 1`).assign(b,!0);return;case"null":A.elseIf(Q._`${B} === "" || ${B} === 0 || ${B} === false`),A.assign(b,null);return;case"array":A.elseIf(Q._`${C} === "string" || ${C} === "number"
|| ${C} === "boolean" || ${B} === null`).assign(b,Q._`[${B}]`)}}}function q({gen:N,parentData:D,parentDataProperty:T},A){N.if(Q._`${D} !== undefined`,()=>N.assign(Q._`${D}[${T}]`,A))}function V(N,D,T,A=I.Correct){let B=A===I.Correct?Q.operators.EQ:Q.operators.NEQ,j;switch(N){case"null":return Q._`${D} ${B} null`;case"array":j=Q._`Array.isArray(${D})`;break;case"object":j=Q._`${D} && typeof ${D} == "object" && !Array.isArray(${D})`;break;case"integer":j=C(Q._`!(${D} % 1) && !isNaN(${D})`);break;case"number":j=C();break;default:return Q._`typeof ${D} ${B} ${N}`}return A===I.Correct?j:(0,Q.not)(j);function C(b=Q.nil){return(0,Q.and)(Q._`typeof ${D} == "number"`,b,T?Q._`isFinite(${D})`:Q.nil)}}$.checkDataType=V;function F(N,D,T,A){if(N.length===1)return V(N[0],D,T,A);let B,j=(0,J.toHash)(N);if(j.array&&j.object){let C=Q._`typeof ${D} != "object"`;B=j.null?C:Q._`!${D} || ${C}`,delete j.null,delete j.array,delete j.object}else B=Q.nil;if(j.number)delete j.integer;for(let C in j)B=(0,Q.and)(B,V(C,D,T,A));return B}$.checkDataTypes=F;let M={message:({schema:N})=>`must be ${N}`,params:({schema:N,schemaValue:D})=>typeof N=="string"?Q._`{type: ${N}}`:Q._`{type: ${D}}`};function w(N){let D=O(N);(0,U.reportError)(D,M)}$.reportTypeError=w;function O(N){let{gen:D,data:T,schema:A}=N,B=(0,J.schemaRefOrVal)(N,A,"type");return{gen:D,keyword:"type",data:T,schema:A.type,schemaCode:B,schemaValue:B,parentSchema:A,params:{},it:N}}}),tf0=R0(($)=>{Object.defineProperty($,"__esModule",{value:!0}),$.assignDefaults=void 0;let Y=L1(),z=v1();function U(J,I){let{properties:K,items:G}=J.schema;if(I==="object"&&K)for(let W in K)Q(J,W,K[W].default);else if(I==="array"&&Array.isArray(G))G.forEach((W,H)=>Q(J,H,W.default))}$.assignDefaults=U;function Q(J,I,K){let{gen:G,compositeRule:W,data:H,opts:X}=J;if(K===void 0)return;let Z=Y._`${H}${(0,Y.getProperty)(I)}`;if(W){(0,z.checkStrictMode)(J,`default is ignored for: ${Z}`);return}let q=Y._`${Z} === undefined`;if(X.useDefaults==="empty")q=Y._`${q} || ${Z} === null || ${Z} === ""`;G.if(q,Y._`${Z} = ${(0,Y.stringify)(K)}`)}}),Q5=R0(($)=>{Object.defineProperty($,"__esModule",{value:!0}),$.validateUnion=$.validateArray=$.usePattern=$.callValidateCode=$.schemaProperties=$.allSchemaProperties=$.noPropertyInData=$.propertyInData=$.isOwnProperty=$.hasPropFunc=$.reportMissingProp=$.checkMissingProp=$.checkReportMissingProp=void 0;let Y=L1(),z=v1(),U=U5(),Q=v1();function J(N,D){let{gen:T,data:A,it:B}=N;T.if(X(T,A,D,B.opts.ownProperties),()=>{N.setParams({missingProperty:Y._`${D}`},!0),N.error()})}$.checkReportMissingProp=J;function I({gen:N,data:D,it:{opts:T}},A,B){return(0,Y.or)(...A.map((j)=>(0,Y.and)(X(N,D,j,T.ownProperties),Y._`${B} = ${j}`)))}$.checkMissingProp=I;function K(N,D){N.setParams({missingProperty:D},!0),N.error()}$.reportMissingProp=K;function G(N){return N.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Y._`Object.prototype.hasOwnProperty`})}$.hasPropFunc=G;function W(N,D,T){return Y._`${G(N)}.call(${D}, ${T})`}$.isOwnProperty=W;function H(N,D,T,A){let B=Y._`${D}${(0,Y.getProperty)(T)} !== undefined`;return A?Y._`${B} && ${W(N,D,T)}`:B}$.propertyInData=H;function X(N,D,T,A){let B=Y._`${D}${(0,Y.getProperty)(T)} === undefined`;return A?(0,Y.or)(B,(0,Y.not)(W(N,D,T))):B}$.noPropertyInData=X;function Z(N){return N?Object.keys(N).filter((D)=>D!=="__proto__"):[]}$.allSchemaProperties=Z;function q(N,D){return Z(D).filter((T)=>!(0,z.alwaysValidSchema)(N,D[T]))}$.schemaProperties=q;function V({schemaCode:N,data:D,it:{gen:T,topSchemaRef:A,schemaPath:B,errorPath:j},it:C},b,k,h){let i=h?Y._`${N}, ${D}, ${A}${B}`:D,c=[[U.default.instancePath,(0,Y.strConcat)(U.default.instancePath,j)],[U.default.parentData,C.parentData],[U.default.parentDataProperty,C.parentDataProperty],[U.default.rootData,U.default.rootData]];if(C.opts.dynamicRef)c.push([U.default.dynamicAnchors,U.default.dynamicAnchors]);let U0=Y._`${i}, ${T.object(...c)}`;return k!==Y.nil?Y._`${b}.call(${k}, ${U0})`:Y._`${b}(${U0})`}$.callValidateCode=V;let F=Y._`new RegExp`;function M({gen:N,it:{opts:D}},T){let A=D.unicodeRegExp?"u":"",{regExp:B}=D.code,j=B(T,A);return N.scopeValue("pattern",{key:j.toString(),ref:j,code:Y._`${B.code==="new RegExp"?F:(0,Q.useFunc)(N,B)}(${T}, ${A})`})}$.usePattern=M;function w(N){let{gen:D,data:T,keyword:A,it:B}=N,j=D.name("valid");if(B.allErrors){let b=D.let("valid",!0);return C(()=>D.assign(b,!1)),b}return D.var(j,!0),C(()=>D.break()),j;function C(b){let k=D.const("len",Y._`${T}.length`);D.forRange("i",0,k,(h)=>{N.subschema({keyword:A,dataProp:h,dataPropType:z.Type.Num},j),D.if((0,Y.not)(j),b)})}}$.validateArray=w;function O(N){let{gen:D,schema:T,keyword:A,it:B}=N;if(!Array.isArray(T))throw Error("ajv implementation error");if(T.some((b)=>(0,z.alwaysValidSchema)(B,b))&&!B.opts.unevaluated)return;let j=D.let("valid",!1),C=D.name("_valid");D.block(()=>T.forEach((b,k)=>{let h=N.subschema({keyword:A,schemaProp:k,compositeRule:!0},C);if(D.assign(j,Y._`${j} || ${C}`),!N.mergeValidEvaluated(h,C) Line truncated
missingProperty: ${X},
depsCount: ${W},
deps: ${H}}`};let Q={keyword:"dependencies",type:"object",schemaType:"object",error:$.error,code(G){let[W,H]=J(G);I(G,W),K(G,H)}};function J({schema:G}){let W={},H={};for(let X in G){if(X==="__proto__")continue;let Z=Array.isArray(G[X])?W:H;Z[X]=G[X]}return[W,H]}function I(G,W=G.schema){let{gen:H,data:X,it:Z}=G;if(Object.keys(W).length===0)return;let q=H.let("missing");for(let V in W){let F=W[V];if(F.length===0)continue;let M=(0,U.propertyInData)(H,X,V,Z.opts.ownProperties);if(G.setParams({property:V,depsCount:F.length,deps:F.join(", ")}),Z.allErrors)H.if(M,()=>{for(let w of F)(0,U.checkReportMissingProp)(G,w)});else H.if(Y._`${M} && (${(0,U.checkMissingProp)(G,F,q)})`),(0,U.reportMissingProp)(G,q),H.else()}}$.validatePropertyDeps=I;function K(G,W=G.schema){let{gen:H,data:X,keyword:Z,it:q}=G,V=H.name("valid");for(let F in W){if((0,z.alwaysValidSchema)(q,W[F]))continue;H.if((0,U.propertyInData)(H,X,F,q.opts.ownProperties),()=>{let M=G.subschema({keyword:Z,schemaProp:F},V);G.mergeValidEvaluated(M,V)},()=>H.var(V,!0)),G.ok(V)}}$.validateSchemaDeps=K,$.default=Q}),Du0=R0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=L1(),z=v1(),U={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:Q})=>Y._`{propertyName: ${Q.propertyName}}`},code(Q){let{gen:J,schema:I,data:K,it:G}=Q;if((0,z.alwaysValidSchema)(G,I))return;let W=J.name("valid");J.forIn("key",K,(H)=>{Q.setParams({propertyName:H}),Q.subschema({keyword:"propertyNames",data:H,dataTypes:["string"],propertyName:H,compositeRule:!0},W),J.if((0,Y.not)(W),()=>{if(Q.error(!0),!G.allErrors)J.break()})}),Q.ok(W)}};$.default=U}),xt=R0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=Q5(),z=L1(),U=U5(),Q=v1(),J={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:I})=>z._`{additionalProperty: ${I.additionalProperty}}`},code(I){let{gen:K,schema:G,parentSchema:W,data:H,errsCount:X,it:Z}=I;if(!X)throw Error("ajv implementation error");let{allErrors:q,opts:V}=Z;if(Z.props=!0,V.removeAdditional!=="all"&&(0,Q.alwaysValidSchema)(Z,G))return;let F=(0,Y.allSchemaProperties)(W.properties),M=(0,Y.allSchemaProperties)(W.patternProperties);w(),I.ok(z._`${X} === ${U.default.errors}`);function w(){K.forIn("key",H,(A)=>{if(!F.length&&!M.length)D(A);else K.if(O(A),()=>D(A))})}function O(A){let B;if(F.length>8){let j=(0,Q.schemaRefOrVal)(Z,W.properties,"properties");B=(0,Y.isOwnProperty)(K,j,A)}else if(F.length)B=(0,z.or)(...F.map((j)=>z._`${A} === ${j}`));else B=z.nil;if(M.length)B=(0,z.or)(B,...M.map((j)=>z._`${(0,Y.usePattern)(I,j)}.test(${A})`));return(0,z.not)(B)}function N(A){K.code(z._`delete ${H}[${A}]`)}function D(A){if(V.removeAdditional==="all"||V.removeAdditional&&G===!1){N(A);return}if(G===!1){if(I.setParams({additionalProperty:A}),I.error(),!q)K.break();return}if(typeof G=="object"&&!(0,Q.alwaysValidSchema)(Z,G)){let B=K.name("valid");if(V.removeAdditional==="failing")T(A,B,!1),K.if((0,z.not)(B),()=>{I.reset(),N(A)});else if(T(A,B),!q)K.if((0,z.not)(B),()=>K.break())}}function T(A,B,j){let C={keyword:"additionalProperties",dataProp:A,dataPropType:Q.Type.Str};if(j===!1)Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1});I.subschema(C,B)}}};$.default=J}),Bu0=R0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=vQ(),z=Q5(),U=v1(),Q=xt(),J={keyword:"properties",type:"object",schemaType:"object",code(I){let{gen:K,schema:G,parentSchema:W,data:H,it:X}=I;if(X.opts.removeAdditional==="all"&&W.additionalProperties===void 0)Q.default.code(new Y.KeywordCxt(X,Q.default,"additionalProperties"));let Z=(0,z.allSchemaProperties)(G);for(let w of Z)X.definedProperties.add(w);if(X.opts.unevaluated&&Z.length&&X.props!==!0)X.props=U.mergeEvaluated.props(K,(0,U.toHash)(Z),X.props);let q=Z.filter((w)=>!(0,U.alwaysValidSchema)(X,G[w]));if(q.length===0)return;let V=K.name("valid");for(let w of q){if(F(w))M(w);else{if(K.if((0,z.propertyInData)(K,H,w,X.opts.ownProperties)),M(w),!X.allErrors)K.else().var(V,!0);K.endIf()}I.it.definedProperties.add(w),I.ok(V)}function F(w){return X.opts.useDefaults&&!X.compositeRule&&G[w].default!==void 0}function M(w){I.subschema({keyword:"properties",schemaProp:w,dataProp:w},V)}}};$.default=J}),Pu0=R0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=Q5(),z=L1(),U=v1(),Q=v1(),J={keyword:"patternProperties",type:"object",schemaType:"object",code(I){let{gen:K,schema:G,data:W,parentSchema:H,it:X}=I,{opts:Z}=X,q=(0,Y.allSchemaProperties)(G),V=q.filter((T)=>(0,U.alwaysValidSchema)(X,G[T]));if(q.length===0||V.length===q.length&&(!X.opts.unevaluated||X.props===!0))return;let F=Z.strictSchema&&!Z.allowMatchingProperties&&H.properties,M=K.name("valid");if(X.props!==!0&&!(X.props instanceof z.Name))X.props=(0,Q.evaluatedPropsToName)(K,X.props);let{props:w}=X;O();function O(){for(let T of q){if(F)N(T);if(X.allErrors) Line truncated
\x00`,k+=O4(j,2),k+=K.magic,k+=O4(M,2),k+=O4(w,2),k+=O4(B.crc32,4),k+=O4(B.compressedSize,4),k+=O4(B.uncompressedSize,4),k+=O4(W.length,2),k+=O4(O.length,2);var h=ZO.LOCAL_FILE_HEADER+k+W+O,i=ZO.CENTRAL_FILE_HEADER+O4(b,2)+k+O4(Z.length,2)+"\x00\x00\x00\x00"+O4(C,4)+O4(U,4)+W+O+Z;return{fileRecord:h,dirRecord:i}},jo0=function($,Y,z,U,Q){var J="",I=qJ.transformTo("string",Q(U));return J=ZO.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+O4($,2)+O4($,2)+O4(Y,4)+O4(z,4)+O4(I.length,2)+I,J},Eo0=function($){var Y="";return Y=ZO.DATA_DESCRIPTOR+O4($.crc32,4)+O4($.compressedSize,4)+O4($.uncompressedSize,4),Y};function X5($,Y,z,U){VJ.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=Y,this.zipPlatform=z,this.encodeFileName=U,this.streamFiles=$,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}qJ.inherits(X5,VJ);X5.prototype.push=function($){var Y=$.meta.percent||0,z=this.entriesCount,U=this._sources.length;if(this.accumulate)this.contentBuffer.push($);else this.bytesWritten+=$.data.length,VJ.prototype.push.call(this,{data:$.data,meta:{currentFile:this.currentFile,percent:z?(Y+100*(z-U-1))/z:100}})};X5.prototype.openedSource=function($){this.currentSourceOffset=this.bytesWritten,this.currentFile=$.file.name;var Y=this.streamFiles&&!$.file.dir;if(Y){var z=V50($,Y,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:z.fileRecord,meta:{percent:0}})}else this.accumulate=!0};X5.prototype.closedSource=function($){this.accumulate=!1;var Y=this.streamFiles&&!$.file.dir,z=V50($,Y,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(z.dirRecord),Y)this.push({data:Eo0($),meta:{percent:100}});else{this.push({data:z.fileRecord,meta:{percent:0}});while(this.contentBuffer.length)this.push(this.contentBuffer.shift())}this.currentFile=null};X5.prototype.flush=function(){var $=this.bytesWritten;for(var Y=0;Y<this.dirRecords.length;Y++)this.push({data:this.dirRecords[Y],meta:{percent:100}});var z=this.bytesWritten-$,U=jo0(this.dirRecords.length,z,$,this.zipComment,this.encodeFileName);this.push({data:U,meta:{percent:100}})};X5.prototype.prepareNextSource=function(){if(this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused)this.previous.pause();else this.previous.resume()};X5.prototype.registerPrevious=function($){this._sources.push($);var Y=this;return $.on("data",function(z){Y.processChunk(z)}),$.on("end",function(){if(Y.closedSource(Y.previous.streamInfo),Y._sources.length)Y.prepareNextSource();else Y.end()}),$.on("error",function(z){Y.error(z)}),this};X5.prototype.resume=function(){if(!VJ.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};X5.prototype.error=function($){var Y=this._sources;if(!VJ.prototype.error.call(this,$))return!1;for(var z=0;z<Y.length;z++)try{Y[z].error($)}catch(U){}return!0};X5.prototype.lock=function(){VJ.prototype.lock.call(this);var $=this._sources;for(var Y=0;Y<$.length;Y++)$[Y].lock()};L50.exports=X5});var w50=E((vo0)=>{var Co0=yy(),Ro0=F50(),_o0=function($,Y){var z=$||Y,U=Co0[z];if(!U)throw Error(z+" is not a valid compression method !");return U};vo0.generateWorker=function($,Y,z){var U=new Ro0(Y.streamFiles,z,Y.platform,Y.encodeFileName),Q=0;try{$.forEach(function(J,I){Q++;var K=_o0(I.options.compression,Y.compression),G=I.options.compressionOptions||Y.compressionOptions||{},W=I.dir,H=I.date;I._compressWorker(K,G).withStreamInfo("file",{name:J,dir:W,date:H,comment:I.comment||"",unixPermissions:I.unixPermissions,dosPermissions:I.dosPermissions}).pipe(U)}),U.entriesCount=Q}catch(J){U.error(J)}return U}});var O50=E((nn1,M50)=>{var So0=c4(),qO=I$();function qH($,Y){qO.call(this,"Nodejs stream input adapter for "+$),this._upstreamEnded=!1,this._bindStream(Y)}So0.inherits(qH,qO);qH.prototype._bindStream=function($){var Y=this;this._stream=$,$.pause(),$.on("data",function(z){Y.push({data:z,meta:{percent:0}})}).on("error",function(z){if(Y.isPaused)this.generatedError=z;else Y.error(z)}).on("end",function(){if(Y.isPaused)Y._upstreamEnded=!0;else Y.end()})};qH.prototype.pause=function(){if(!qO.prototype.pause.call(this))return!1;return this._stream.pause(),!0};qH.prototype.resume=function(){if(!qO.prototype.resume.call(this))return!1;if(this._upstreamEnded)this.end();else this._stream.resume();return!0};M50.exports=qH});var R50=E((pn1,C50)=>{var go0=UJ(),VH=c4(),P50=I$(),yo0=ig(),A50=cg(),N50=oM(),ko0=D80(),xo0=w50(),D50=mW(),fo0=O50(),T50=function($,Y,z){var U=VH.getTypeOf(Y),Q,J=VH.extend(z||{},A50);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.dosPermission Line truncated
`)}openNode($,Y){let z=this.tos,U=this._xml;if(z&&this.open)U.push(">");this._stack.push($),U.push("<"),U.push($),Mk(U,Y),this.leaf=!0,this.open=!0}addAttribute($,Y){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(Y!==void 0)O70(this._xml,$,Y)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");Mk(this._xml,$)}writeText($){let Y=this._xml;if(this.open)Y.push(">"),this.open=!1;this.leaf=!1,Y.push(M70.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),Y=this._xml;if(this.leaf)Y.push("/>");else Y.push("</"),Y.push($),Y.push(">");this.open=!1,this.leaf=!1}leafNode($,Y,z){if(this.openNode($,Y),z!==void 0)this.writeText(z);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("")}}Ok.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};N70.exports=Ok});var Nk=E((Ra0)=>{var D70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function Ca0($){if(typeof $==="string")return $;if(D70)return D70.decode($);return $.toString()}Ra0.bufferToString=Ca0});var j70=E((P70)=>{Object.defineProperty(P70,"__esModule",{value:!0});P70.CHAR=`
\r -퟿-�\uD800\uDC00-\uDBFF\uDFFF`;P70.S=` \r
`;P70.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";P70.NAME_CHAR="-"+P70.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";P70.CHAR_RE=new RegExp("^["+P70.CHAR+"]$","u");P70.S_RE=new RegExp("^["+P70.S+"]+$","u");P70.NAME_START_CHAR_RE=new RegExp("^["+P70.NAME_START_CHAR+"]$","u");P70.NAME_CHAR_RE=new RegExp("^["+P70.NAME_CHAR+"]$","u");P70.NAME_RE=new RegExp("^["+P70.NAME_START_CHAR+"]["+P70.NAME_CHAR+"]*$","u");P70.NMTOKEN_RE=new RegExp("^["+P70.NAME_CHAR+"]+$","u");var Dk=9,Bk=10,Pk=13,Ak=32;P70.S_LIST=[Ak,Bk,Pk,Dk];function va0($){return $>=Ak&&$<=55295||$===Bk||$===Pk||$===Dk||$>=57344&&$<=65533||$>=65536&&$<=1114111}P70.isChar=va0;function ha0($){return $===Ak||$===Bk||$===Pk||$===Dk}P70.isS=ha0;function B70($){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}P70.isNameStartChar=B70;function Sa0($){return B70($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}P70.isNameChar=Sa0});var k70=E((h70)=>{Object.defineProperty(h70,"__esModule",{value:!0});h70.CHAR="\x01-퟿-�\uD800\uDC00-\uDBFF\uDFFF";h70.RESTRICTED_CHAR="\x01-\b\v\f\x0E-\x1F-„†-Ÿ";h70.S=` \r
`;h70.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";h70.NAME_CHAR="-"+h70.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";h70.CHAR_RE=new RegExp("^["+h70.CHAR+"]$","u");h70.RESTRICTED_CHAR_RE=new RegExp("^["+h70.RESTRICTED_CHAR+"]$","u");h70.S_RE=new RegExp("^["+h70.S+"]+$","u");h70.NAME_START_CHAR_RE=new RegExp("^["+h70.NAME_START_CHAR+"]$","u");h70.NAME_CHAR_RE=new RegExp("^["+h70.NAME_CHAR+"]$","u");h70.NAME_RE=new RegExp("^["+h70.NAME_START_CHAR+"]["+h70.NAME_CHAR+"]*$","u");h70.NMTOKEN_RE=new RegExp("^["+h70.NAME_CHAR+"]+$","u");var E70=9,C70=10,R70=13,_70=32;h70.S_LIST=[_70,C70,R70,E70];function da0($){return $>=1&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}h70.isChar=da0;function ma0($){return $>=1&&$<=8||$===11||$===12||$>=14&&$<=31||$>=127&&$<=132||$>=134&&$<=159}h70.isRestrictedChar=ma0;function la0($){return $===9||$===10||$===13||$>31&&$<127||$===133||$>159&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}h70.isCharAndNotRestricted=la0;function oa0($){return $===_70||$===C70||$===R70||$===E70}h70.isS=oa0;function v70($){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}h70.isNameStartChar=v70;function ra0($){return v70($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}h70.isNameChar=ra0});var u70=E((f70)=>{Object.defineProperty(f70,"__esModule",{value:!0});f70.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";f70.NC_NAME_CHAR="-"+f70.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";f70.NC_NAME_START_CHAR_RE=new RegExp("^["+f70.NC_NAME_START_CHAR+"]$","u");f70.NC_NAME_CHAR_RE=new RegExp("^["+f70.NC_NAME_CHAR+"]$","u");f70.NC_NAME_RE=new RegExp("^["+f70.NC_NAME_START_CHAR+"]["+f70.NC_NAME_CHAR+"]*$","u");function x70($){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}f70.isNCNameStartChar=x70;function Ht0($){return x70($)||($===45||$===46||$>=48&&$<=57||$===183||$>=768&&$<=879||$>=8255&&$<=8256)}f70.isNCNameChar=Ht0});var K30=E((I30)=>{Object.defineProperty(I30,"__esModule",{value:!0});var jJ=j70(),Ft0=k70(),fk=u70(),p8=jJ.isS,wt0=jJ.isChar,EH=jJ.isNameStartChar,b70=jJ.isNameChar,$30=jJ.S_LIST,Mt0=jJ.NAME_RE,Ot0=Ft0.isChar,Nt0=fk.isNCNameStartChar,Dt0=fk.isNCNameChar,Bt0=fk.NC_NAME_RE,cO="http://www.w3.org/XML/1998/namespace",TJ="http://www.w3.org/2000/xmlns/",Pt0={__proto__:null,xml:cO,xmlns:TJ},At0={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},k4=-1,J9=-2,i70=0,Tt0=1,jk=2,jt0=3,BJ=4,Et0=5,Ct0=6,Rt0=7,Ek=8,_t0=9,vt0=10,ht0=11,St0=12,C8=13,xO=14,Ck=15,gt0=16,Rk=17,yt0=18,kt0=19,_k=20,xt0=21,ft0=22,ut0=23,c70=24,vk=25,fO=26,n70=27,bt0=28,it0=29,p70=30,ct0=31,nt0=32,Iz=33,pt0=34,hk=35,CH=36,Sk=37,dt0=38,d70=39,m70=40,mt0=41,l70=42,lt0=43,ot0=44,gk=9,q5=10,yk=13,o70=32,r70=33,Y30=34,RH=38,z30=39,uO=45,bO=47,rt0=59,r3=60,PJ=61,A6=62,o6=63,U30=91,AJ=93,s70=133,a70=8232,iO=($)=>$===Y30||$===z30,Q30=[Y30,z30],st0=[...Q30,U30,A6],at0=[...Q30,r3,AJ],tt0=[PJ,o6,...$30],et0=[...$30,A6,RH,r3];function xk($,Y,z){switch(Y){case"xml":if(z!==cO)$.fail(`xml prefix must be bound to ${cO}.`);break;case"xmlns":if(z!==TJ)$.fail(`xmlns prefix must be bound to ${TJ}.`);break;default:}switch(z){case TJ:$.fail(Y===""?`the default namespace may not be set to ${z}.`:`may not assign a prefix (even "xmlns") to the URI ${TJ}.`);break;case cO:switch(Y){case"xml":break;case"":$.fail(`the default namespace may not be set to ${z}.`);break;default:$.fail("may not assign the xml namespace to another prefix.")}break;default:}}function $e0($,Y){for(let z of Object.keys(Y))xk($,z,Y[z])}var Ye0=($)=>Bt0.test($),ze0=($)=>Mt0.test($),Kz=0,t70=1,kk=2;I30.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var e70={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 J30{constructor($){this.opt=$!==null&&$!==void 0?$:{},this.fragmentOpt=!!this.opt.fragment;let Y=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=this.opt.position!==!1,this.fileName=this.opt.fileName,Y){this.nameStartCheck=Nt0,this.nameCheck=Dt0,this.isName=Ye0,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},Pt0);let z=this.opt.additionalNamesp Line truncated
`,Y=this.i}}captureToChar($){let{i:Y}=this,{chunk:z}=this;while(!0){let U=this.getCode();switch(U){case J9:this.text+=`${z.slice(Y,this.prevI)}
`,Y=this.i,U=q5;break;case k4:return this.text+=z.slice(Y),!1;default:}if(U===$)return this.text+=z.slice(Y,this.prevI),!0}}captureNameChars(){let{chunk:$,i:Y}=this;while(!0){let z=this.getCode();if(z===k4)return this.name+=$.slice(Y),k4;if(!b70(z))return this.name+=$.slice(Y,this.prevI),z===J9?q5:z}}skipSpaces(){while(!0){let $=this.getCodeNorm();if($===k4||!p8($))return $}}setXMLVersion($){if(this.currentXMLVersion=$,$==="1.0")this.isChar=wt0,this.getCode=this.getCode10;else this.isChar=Ot0,this.getCode=this.getCode11}sBegin(){if(this.chunk.charCodeAt(0)===65279)this.i++,this.column++;this.state=Tt0}sBeginWhitespace(){let $=this.i,Y=this.skipSpaces();if(this.prevI!==$)this.xmlDeclPossible=!1;switch(Y){case r3:if(this.state=Ck,this.text.length!==0)throw Error("no-empty text at start");break;case k4:break;default:this.unget(),this.state=C8,this.xmlDeclPossible=!1}}sDoctype(){var $;let Y=this.captureTo(st0);switch(Y){case A6:{($=this.doctypeHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=C8,this.doctype=!0;break}case k4:break;default:if(this.text+=String.fromCodePoint(Y),Y===U30)this.state=BJ;else if(iO(Y))this.state=jt0,this.q=Y}}sDoctypeQuote(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.q=null,this.state=jk}sDTD(){let $=this.captureTo(at0);if($===k4)return;if(this.text+=String.fromCodePoint($),$===AJ)this.state=jk;else if($===r3)this.state=Ct0;else if(iO($))this.state=Et0,this.q=$}sDTDQuoted(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.state=BJ,this.q=null}sDTDOpenWaka(){let $=this.getCodeNorm();switch(this.text+=String.fromCodePoint($),$){case r70:this.state=Rt0,this.openWakaBang="";break;case o6:this.state=ht0;break;default:this.state=BJ}}sDTDOpenWakaBang(){let $=String.fromCodePoint(this.getCodeNorm()),Y=this.openWakaBang+=$;if(this.text+=$,Y!=="-")this.state=Y==="--"?Ek:BJ,this.openWakaBang=""}sDTDComment(){if(this.captureToChar(uO))this.text+="-",this.state=_t0}sDTDCommentEnding(){let $=this.getCodeNorm();this.text+=String.fromCodePoint($),this.state=$===uO?vt0:Ek}sDTDCommentEnded(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===A6)this.state=BJ;else this.fail("malformed comment."),this.state=Ek}sDTDPI(){if(this.captureToChar(o6))this.text+="?",this.state=St0}sDTDPIEnding(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===A6)this.state=BJ}sText(){if(this.tags.length!==0)this.handleTextInRoot();else this.handleTextOutsideRoot()}sEntity(){let{i:$}=this,{chunk:Y}=this;$:while(!0)switch(this.getCode()){case J9:this.entity+=`${Y.slice($,this.prevI)}
`,$=this.i;break;case rt0:{let{entityReturnState:z}=this,U=this.entity+Y.slice($,this.prevI);this.state=z;let Q;if(U==="")this.fail("empty entity name."),Q="&;";else Q=this.parseEntity(U),this.entity="";if(z!==C8||this.textHandler!==void 0)this.text+=Q;break $}case k4:this.entity+=Y.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(EH($))this.state=pt0,this.unget(),this.xmlDeclPossible=!1;else switch($){case bO:this.state=lt0,this.xmlDeclPossible=!1;break;case r70:this.state=gt0,this.openWakaBang="",this.xmlDeclPossible=!1;break;case o6:this.state=ut0;break;default:this.fail("disallowed character in tag name"),this.state=C8,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=_k,this.openWakaBang="";break;case"--":this.state=Rk,this.openWakaBang="";break;case"DOCTYPE":if(this.state=jk,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(uO))this.state=yt0}sCommentEnding(){var $;let Y=this.getCodeNorm();if(Y===uO)this.state=kt0,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(Y)}`,this.state=Rk}sCommentEnded(){let $=this.getCodeNorm();if($!==A6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=Rk;else this.state=C8}sCData(){if(this.captureToChar(AJ))this.state=xt0}sCDataEnding(){let $=this.getCodeNorm();if($===AJ)this.state=ft0;else this.text+=`]${String.fromCodePoint($)}`,this.state=_k}sCDataEnding2(){var $;let Y=this.getCodeNorm();switch(Y){case A6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=C8;break}case AJ:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(Y)}`,this.state=_k}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=c70;else if($===o6||p8($))this.fail("processing instruction without a target."),this.state=$===o6?fO:vk;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=c70}sPIRest(){let{chunk:$,i:Y}=this;while(!0){let z=this.getCodeNorm();if(z===k4){this.piTarget+=$.slice(Y);return}if(!this.nameCheck(z)){this.piTarget+=$.slice(Y,this.prevI);let U=z===o6;if(U||p8(z))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=U?Iz:n70}else this.state=U?fO:vk;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(z);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===o6)this.state=fO;else if(!p8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(o6))this.state=fO}sPIEnding(){var $;let Y=this.getCodeNorm();if(Y===A6){let{piTarget:z}=this;if(z.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:z,body:this.text}),this.piTarget=this.text="",this.state=C8}else if(Y===o6)this.text+="?";else this.text+=`?${String.fromCodePoint(Y)}`,this.state=vk;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===o6){this.state=Iz;return}if($!==k4)this.state=bt0,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(tt0);if($===o6){this.state=Iz,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(p8($)||$===PJ))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=$===PJ?p70:it0}sXMLDeclEq(){let $=this.getCodeNorm();if($===o6){this.state=Iz,this.fail("XML declaration is incomplete.");return}if(p8($))return;if($!==PJ)this.fail("value required.");this.state=p70}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===o6){this.state=Iz,this.fail("XML declaration is incomplete.");return}if(p8($))return;if(!iO($))this.fail("value must be quoted."),this.q=o70;else this.q=$;this.state=ct0}sXMLDeclValue(){let $=this.captureTo([this.q,o6]);if($===o6){this.state=Iz,this.text="",this.fail("XML declaration is incomplete.");return}if($===k4)return;let Y=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let z=Y;if(this.xmlDecl.version=z,!/^1\.[0-9]+$/.test(z))this.fail("ver Line truncated
`;$=this.i,Y=Kz;break;case k4:if(U!==void 0)this.text+=z.slice($);break $;default:Y=Kz}this.forbiddenState=Y}handleTextOutsideRoot(){let{i:$}=this,{chunk:Y,textHandler:z}=this,U=!1;$:while(!0){let Q=this.getCode();switch(Q){case r3:{if(this.state=Ck,z!==void 0){let{text:J}=this,I=Y.slice($,this.prevI);if(J.length!==0)z(J+I),this.text="";else if(I.length!==0)z(I)}break $}case RH:if(this.state=xO,this.entityReturnState=C8,z!==void 0)this.text+=Y.slice($,this.prevI);U=!0;break $;case J9:if(z!==void 0)this.text+=`${Y.slice($,this.prevI)}
`;$=this.i;break;case k4:if(z!==void 0)this.text+=Y.slice($);break $;default:if(!p8(Q))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($,Y){var z;let{prefix:U,local:Q}=this.qname($),J={name:$,prefix:U,local:Q,value:Y};if(this.attribList.push(J),(z=this.attributeHandler)===null||z===void 0||z.call(this,J),U==="xmlns"){let I=Y.trim();if(this.currentXMLVersion==="1.0"&&I==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[Q]=I,xk(this,Q,I)}else if($==="xmlns"){let I=Y.trim();this.topNS[""]=I,xk(this,"",I)}}pushAttribPlain($,Y){var z;let U={name:$,value:Y};this.attribList.push(U),(z=this.attributeHandler)===null||z===void 0||z.call(this,U)}end(){var $,Y;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:z}=this;while(z.length>0){let Q=z.pop();this.fail(`unclosed tag: ${Q.name}`)}if(this.state!==i70&&this.state!==C8)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,(Y=this.endHandler)===null||Y===void 0||Y.call(this),this._init(),this}resolve($){var Y,z;let U=this.topNS[$];if(U!==void 0)return U;let{tags:Q}=this;for(let J=Q.length-1;J>=0;J--)if(U=Q[J].ns[$],U!==void 0)return U;if(U=this.ns[$],U!==void 0)return U;return(z=(Y=this.opt).resolvePrefix)===null||z===void 0?void 0:z.call(Y,$)}qname($){let Y=$.indexOf(":");if(Y===-1)return{prefix:"",local:$};let z=$.slice(Y+1),U=$.slice(0,Y);if(U===""||z===""||z.includes(":"))this.fail(`malformed name: ${$}.`);return{prefix:U,local:z}}processAttribsNS(){var $;let{attribList:Y}=this,z=this.tag;{let{prefix:J,local:I}=this.qname(z.name);z.prefix=J,z.local=I;let K=z.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)}.`),z.uri=J}}if(Y.length===0)return;let{attributes:U}=z,Q=new Set;for(let J of Y){let{name:I,prefix:K,local:G}=J,W,H;if(K==="")W=I==="xmlns"?TJ:"",H=I;else{if(W=this.resolve(K),W===void 0)this.fail(`unbound namespace prefix: ${JSON.stringify(K)}.`),W=K;H=`{${W}}${G}`}if(Q.has(H))this.fail(`duplicate attribute: ${H}.`);Q.add(H),J.uri=W,U[I]=J}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,Y=this.tag.attributes;for(let{name:z,value:U}of $){if(Y[z]!==void 0)this.fail(`duplicate attribute: ${z}.`);Y[z]=U}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:Y}=this,z=this.tag;z.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,z),Y.push(z),this.state=C8,this.name=""}openSelfClosingTag(){var $,Y,z;this.processAttribs();let{tags:U}=this,Q=this.tag;if(Q.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,Q),(Y=this.closeTagHandler)===null||Y===void 0||Y.call(this,Q),(this.tag=(z=U[U.length-1])!==null&&z!==void 0?z:null)===null)this.closedRoot=!0;this.state=C8,this.name=""}closeTag(){let{tags:$,name:Y}=this;if(this.state=C8,this.name="",Y===""){this.fail("weird empty close tag."),this.text+="</>";return}let z=this.closeTagHandler,U=$.length;while(U-- >0){let Q=this.tag=$.pop();if(this.topNS=Q.ns,z===null||z===void 0||z(Q),Q.name===Y)break;this.fail("unexpected close tag.")}if(U===0)this.closedRoot=!0;else if(U<0)this.fail(`unmatched closing tag: ${Y}.`),this.text+=`</${Y}>`}parseEntity($){if($[0]!=="#"){let z=this.ENTITIES[$];if(z!==void 0)return z;return this.fail(this.isName($)?"undefined entity.":"disallowed character in entity name."),`&${$};`}let Y=NaN;if($[1]==="x"&&/^#x[0-9a-f]+$/i.test($))Y=parseInt($.slice(2),16);else if(/^#[0-9]+$/.test($))Y=parseInt($.slice(1),10);if(!this.isChar(Y))return this.fail("malformed character entity."),`&${$};`;return String.fromCodePoint(Y)}}I30.SaxesParser=J30});var _H=E((Ep1,G30)=>{var{SaxesParser:Je0}=K30(),{PassThrough:Ie0}=E8(),{bufferToString:Ke0}=Nk();G30.exports=async function*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(new Ie0);let Y=new Je0,z;Y.on("error",(Q)=>{z=Q});let U=[];Y.on("opentag",(Q)=>U.push({eventType:"opentag",value:Q})),Y.on("text",(Q)=>U.push({eventType:"text",value:Q})),Y.on("closetag",(Q)=>U.push({eventType:"closetag",value:Q}));for await(let Q of $){if(Y.write(Ke0(Q)),z)throw z;yield U,U=[]}}});var g0=E((Cp1,W30)=>{var Ge0=_H(),We0=l6();class EJ{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,Y){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($ instanceof EJ)$.reset();else if($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}async parse($){for await(let Y of $)for(let{eventType:z,value:U}of Y)if(z==="opentag")this.parseOpen(U);else if(z==="text")this.parseText(U);else if(z==="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&&((Y=$.writeHeaders)!==null&&Y!==void 0?Y:!0),this.headers=Array.isArray(this.headers)?this.headers:null,this.escapedQuote=`${this.escape}${this.quote}`}}uJ0.FormatterOptions=fJ0});var DN=E((em1,pJ0)=>{var O$1="[object AsyncFunction]",N$1="[object Function]",D$1="[object GeneratorFunction]",B$1="[object Null]",P$1="[object Proxy]",A$1="[object Undefined]",T$1=typeof global=="object"&&global&&global.Object===Object&&global,j$1=typeof self=="object"&&self&&self.Object===Object&&self,E$1=T$1||j$1||Function("return this")(),cJ0=Object.prototype,C$1=cJ0.hasOwnProperty,nJ0=cJ0.toString,iJ0=E$1.Symbol,Vz=iJ0?iJ0.toStringTag:void 0;function R$1($){if($==null)return $===void 0?A$1:B$1;return Vz&&Vz in Object($)?_$1($):v$1($)}function _$1($){var Y=C$1.call($,Vz),z=$[Vz];try{$[Vz]=void 0;var U=!0}catch(J){}var Q=nJ0.call($);if(U)if(Y)$[Vz]=z;else delete $[Vz];return Q}function v$1($){return nJ0.call($)}function h$1($){if(!S$1($))return!1;var Y=R$1($);return Y==N$1||Y==D$1||Y==O$1||Y==P$1}function S$1($){var Y=typeof $;return $!=null&&(Y=="object"||Y=="function")}pJ0.exports=h$1});var TI0=E((BN,xJ)=>{var g$1=200,Kf="__lodash_hash_undefined__",_N=1,zI0=2,UI0=9007199254740991,PN="[object Arguments]",$f="[object Array]",y$1="[object AsyncFunction]",QI0="[object Boolean]",JI0="[object Date]",II0="[object Error]",KI0="[object Function]",k$1="[object GeneratorFunction]",AN="[object Map]",GI0="[object Number]",x$1="[object Null]",kJ="[object Object]",dJ0="[object Promise]",f$1="[object Proxy]",WI0="[object RegExp]",TN="[object Set]",HI0="[object String]",u$1="[object Symbol]",b$1="[object Undefined]",Yf="[object WeakMap]",XI0="[object ArrayBuffer]",jN="[object DataView]",i$1="[object Float32Array]",c$1="[object Float64Array]",n$1="[object Int8Array]",p$1="[object Int16Array]",d$1="[object Int32Array]",m$1="[object Uint8Array]",l$1="[object Uint8ClampedArray]",o$1="[object Uint16Array]",r$1="[object Uint32Array]",s$1=/[\\^$.*+?()[\]{}|]/g,a$1=/^\[object .+?Constructor\]$/,t$1=/^(?:0|[1-9]\d*)$/,A4={};A4[i$1]=A4[c$1]=A4[n$1]=A4[p$1]=A4[d$1]=A4[m$1]=A4[l$1]=A4[o$1]=A4[r$1]=!0;A4[PN]=A4[$f]=A4[XI0]=A4[QI0]=A4[jN]=A4[JI0]=A4[II0]=A4[KI0]=A4[AN]=A4[GI0]=A4[kJ]=A4[WI0]=A4[TN]=A4[HI0]=A4[Yf]=!1;var ZI0=typeof global=="object"&&global&&global.Object===Object&&global,e$1=typeof self=="object"&&self&&self.Object===Object&&self,Z7=ZI0||e$1||Function("return this")(),qI0=typeof BN=="object"&&BN&&!BN.nodeType&&BN,mJ0=qI0&&typeof xJ=="object"&&xJ&&!xJ.nodeType&&xJ,VI0=mJ0&&mJ0.exports===qI0,ax=VI0&&ZI0.process,lJ0=function(){try{return ax&&ax.binding&&ax.binding("util")}catch($){}}(),oJ0=lJ0&&lJ0.isTypedArray;function $51($,Y){var z=-1,U=$==null?0:$.length,Q=0,J=[];while(++z<U){var I=$[z];if(Y(I,z,$))J[Q++]=I}return J}function Y51($,Y){var z=-1,U=Y.length,Q=$.length;while(++z<U)$[Q+z]=Y[z];return $}function z51($,Y){var z=-1,U=$==null?0:$.length;while(++z<U)if(Y($[z],z,$))return!0;return!1}function U51($,Y){var z=-1,U=Array($);while(++z<$)U[z]=Y(z);return U}function Q51($){return function(Y){return $(Y)}}function J51($,Y){return $.has(Y)}function I51($,Y){return $==null?void 0:$[Y]}function K51($){var Y=-1,z=Array($.size);return $.forEach(function(U,Q){z[++Y]=[Q,U]}),z}function G51($,Y){return function(z){return $(Y(z))}}function W51($){var Y=-1,z=Array($.size);return $.forEach(function(U){z[++Y]=U}),z}var H51=Array.prototype,X51=Function.prototype,vN=Object.prototype,tx=Z7["__core-js_shared__"],LI0=X51.toString,K9=vN.hasOwnProperty,rJ0=function(){var $=/[^.]+$/.exec(tx&&tx.keys&&tx.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),FI0=vN.toString,Z51=RegExp("^"+LI0.call(K9).replace(s$1,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),sJ0=VI0?Z7.Buffer:void 0,EN=Z7.Symbol,aJ0=Z7.Uint8Array,wI0=vN.propertyIsEnumerable,q51=H51.splice,Lz=EN?EN.toStringTag:void 0,tJ0=Object.getOwnPropertySymbols,V51=sJ0?sJ0.isBuffer:void 0,L51=G51(Object.keys,Object),zf=fJ(Z7,"DataView"),xH=fJ(Z7,"Map"),Uf=fJ(Z7,"Promise"),Qf=fJ(Z7,"Set"),Jf=fJ(Z7,"WeakMap"),fH=fJ(Object,"create"),F51=Mz(zf),w51=Mz(xH),M51=Mz(Uf),O51=Mz(Qf),N51=Mz(Jf),eJ0=EN?EN.prototype:void 0,ex=eJ0?eJ0.valueOf:void 0;function Fz($){var Y=-1,z=$==null?0:$.length;this.clear();while(++Y<z){var U=$[Y];this.set(U[0],U[1])}}function D51(){this.__data__=fH?fH(null):{},this.size=0}function B51($){var Y=this.has($)&&delete this.__data__[$];return this.size-=Y?1:0,Y}function P51($){var Y=this.__data Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(Y)}set headers($){this._headers=$}shouldQuote($,Y){let z=Y?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(R91.default(z))return z;if(Array.isArray(z))return z[$];if(this._headers!==null)return z[this._headers[$]];return!1}format($,Y,z){let U=`${_91.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:Q}=this;if(Q.quote!==""){if(U.indexOf(Q.quote)!==-1)return this.quoteField(U.replace(this.REPLACE_REGEXP,Q.escapedQuote))}if(U.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(Y,z))return this.quoteField(U);return U}quoteField($){let{quote:Y}=this.formatterOptions;return`${Y}${$}${Y}`}}uJ.FieldFormatter=gI0});var Zf=E((yI0)=>{Object.defineProperty(yI0,"__esModule",{value:!0});yI0.isSyncTransform=void 0;yI0.isSyncTransform=($)=>$.length===1});var fI0=E((bJ)=>{var xI0=bJ&&bJ.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(bJ,"__esModule",{value:!0});bJ.RowFormatter=void 0;var h91=xI0(DN()),S91=xI0(TI0()),g91=Xf(),y91=Zf();class Oz{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new g91.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(Oz.isRowHashArray($))return $.map((Y)=>Y[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(y91.isSyncTransform($))return(Y,z)=>{let U=null;try{U=$(Y)}catch(Q){return z(Q)}return z(null,U)};return(Y,z)=>{$(Y,z)}}set rowTransform($){if(!h91.default($))throw TypeError("The transform should be a function");this._rowTransform=Oz.createTransform($)}format($,Y){this.callTransformer($,(z,U)=>{if(z)return Y(z);if(!$)return Y(null);let Q=[];if(U){let{shouldFormatColumns:J,headers:I}=this.checkHeaders(U);if(this.shouldWriteHeaders&&I&&!this.hasWrittenHeaders)Q.push(this.formatColumns(I,!0)),this.hasWrittenHeaders=!0;if(J){let K=this.gatherColumns(U);Q.push(this.formatColumns(K,!1))}}return Y(null,Q)})}finish($){let Y=[];if(this.formatterOptions.alwaysWriteHeaders&&this.rowCount===0){if(!this.headers)return $(Error("`alwaysWriteHeaders` option is set to true but `headers` option not provided."));Y.push(this.formatColumns(this.headers,!0))}if(this.formatterOptions.includeEndRowDelimiter)Y.push(this.formatterOptions.rowDelimiter);return $(null,Y)}checkHeaders($){if(this.headers)return{shouldFormatColumns:!0,headers:this.headers};let Y=Oz.gatherHeaders($);if(this.headers=Y,this.fieldFormatter.headers=Y,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!S91.default(Y,$),headers:Y}}gatherColumns($){if(this.headers===null)throw Error("Headers is currently null");if(!Array.isArray($))return this.headers.map((Y)=>$[Y]);if(Oz.isRowHashArray($))return this.headers.map((Y,z)=>{let U=$[z];if(U)return U[1];return""});if(Oz.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((Y,z)=>$[z])}callTransformer($,Y){if(!this._rowTransform)return Y(null,$);return this._rowTransform($,Y)}formatColumns($,Y){let z=$.map((Q,J)=>this.fieldFormatter.format(Q,J,Y)).join(this.formatterOptions.delimiter),{rowCount:U}=this;if(this.rowCount+=1,U)return[this.formatterOptions.rowDelimiter,z].join("");return z}}bJ.RowFormatter=Oz});var uI0=E((gN)=>{Object.defineProperty(gN,"__esModule",{value:!0});gN.FieldFormatter=gN.RowFormatter=void 0;var k91=fI0();Object.defineProperty(gN,"RowFormatter",{enumerable:!0,get:function(){return k91.RowFormatter}});var x91=Xf();Object.defineProperty(gN,"FieldFormatter",{enumerable:!0,get:function(){return x91.FieldFormatter}})});var qf=E((iI0)=>{Object.defineProperty(iI0,"__esModule",{value:!0});iI0.CsvFormatterStream=void 0;var u91=I0("stream"),b91=uI0();class bI0 extends u91.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new b91.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,Y,z){let U=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(Q,J)=>{if(Q)return U=!0,z(Q);if(J)J.forEach((I)=>{this.push(Buffer.from(I,"utf8"))});return U=!0,z()})}catch(Q){if(U)throw Q;z(Q)}}_flush($){this.rowFormatter.finish((Y,z)=>{if(Y)return $(Y);if(z)z.forEach((U)=>{this.push(Buffer.from(U,"utf8"))});return $()})}}iI0.CsvFormatterStream=bI0});var pI0=E((s1)=>{var nI0=s1&&s1.__createBinding||(Object.create?function($,Y,z,U){if(U===void 0)U=z;Object.defineProperty($,U,{enumerable:!0,get:function(){return Y[z]}})}:function($,Y,z,U){if(U===void 0)U=z;$[U]=Y[z]}),i91=s1&&s1.__setModuleDefault||(Object.create?function($,Y){O Line truncated
`||Y===`\r
`}static isTokenCarriageReturn($,Y){return $.token===Y.carriageReturn}static isTokenComment($,Y){return Y.supportsComments&&!!$&&$.token===Y.comment}static isTokenEscapeCharacter($,Y){return $.token===Y.escapeChar}static isTokenQuote($,Y){return $.token===Y.quote}static isTokenDelimiter($,Y){return $.token===Y.delimiter}}dK0.Token=pK0});var xf=E((rK0)=>{Object.defineProperty(rK0,"__esModule",{value:!0});rK0.Scanner=void 0;var lK0=I2(),r21=/((?:\r\n)|\n|\r)/;class oK0{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,Y=this.parserOptions.NEXT_TOKEN_REGEXP;if($.search(Y)===-1)return null;let z=Y.exec($);if(z==null)return null;let U=z[1],Q=this.cursor+(z.index||0);return new lK0.Token({token:U,startCursor:Q,endCursor:Q+U.length-1})}get nextCharacterToken(){let{cursor:$,lineLength:Y}=this;if(Y<=$)return null;return new lK0.Token({token:this.line[$],startCursor:$,endCursor:$})}get lineFromCursor(){return this.line.substr(this.cursor)}advancePastLine(){let $=r21.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}}rK0.Scanner=oK0});var UD=E((tK0)=>{Object.defineProperty(tK0,"__esModule",{value:!0});tK0.ColumnFormatter=void 0;class aK0{constructor($){if($.trim)this.format=(Y)=>Y.trim();else if($.ltrim)this.format=(Y)=>Y.trimLeft();else if($.rtrim)this.format=(Y)=>Y.trimRight();else this.format=(Y)=>Y}}tK0.ColumnFormatter=aK0});var ff=E((zG0)=>{Object.defineProperty(zG0,"__esModule",{value:!0});zG0.NonQuotedColumnParser=void 0;var s21=UD(),$G0=I2();class YG0{constructor($){this.parserOptions=$,this.columnFormatter=new s21.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let{parserOptions:Y}=this,z=[],U=$.nextCharacterToken;for(;U;U=$.nextCharacterToken){if($G0.Token.isTokenDelimiter(U,Y)||$G0.Token.isTokenRowDelimiter(U))break;z.push(U.token),$.advancePastToken(U)}return this.columnFormatter.format(z.join(""))}}zG0.NonQuotedColumnParser=YG0});var uf=E((JG0)=>{Object.defineProperty(JG0,"__esModule",{value:!0});JG0.QuotedColumnParser=void 0;var a21=UD(),aJ=I2();class QG0{constructor($){this.parserOptions=$,this.columnFormatter=new a21.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let Y=$.cursor,{foundClosingQuote:z,col:U}=this.gatherDataBetweenQuotes($);if(!z){if($.advanceTo(Y),!$.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:Y}=this,z=!1,U=!1,Q=[],J=$.nextCharacterToken;for(;!U&&J!==null;J=$.nextCharacterToken){let I=aJ.Token.isTokenQuote(J,Y);if(!z&&I)z=!0;else if(z)if(aJ.Token.isTokenEscapeCharacter(J,Y)){$.advancePastToken(J);let K=$.nextCharacterToken;if(K!==null&&(aJ.Token.isTokenQuote(K,Y)||aJ.Token.isTokenEscapeCharacter(K,Y)))Q.push(K.token),J=K;else if(I)U=!0;else Q.push(J.token)}else if(I)U=!0;else Q.push(J.token);$.advancePastToken(J)}return{col:this.columnFormatter.format(Q.join("")),foundClosingQuote:U}}checkForMalformedColumn($){let{parserOptions:Y}=this,{nextNonSpaceToken:z}=$;if(z){let U=aJ.Token.isTokenDelimiter(z,Y),Q=aJ.Token.isTokenRowDelimiter(z);if(!(U||Q)){let J=$.lineFromCursor.substr(0,10).replace(/[\r\n]/g,"\\n'");throw Error(`Parse Error: expected: '${Y.escapedDelimiter}' OR new line got: '${z.token}'. at '${J}`)}$.advanceToToken(z)}else if(!$.hasMoreData)$.advancePastLine()}}JG0.QuotedColumnParser=QG0});var HG0=E((GG0)=>{Object.defineProperty(GG0,"__esModule",{value:!0});GG0.ColumnParser=void 0;var t21=ff(),e21=uf(),$Y1=I2();class KG0{constructor($){this.parserOptions=$,this.quotedColumnParser=new e21.QuotedColumnParser($),this.nonQuotedColumnParser=new t21.NonQuotedColumnParser($)}parse($){let{nextNonSpaceToken:Y}=$;if(Y!==null&&$Y1.Token.isTokenQuote(Y,this.parserOptions))return $.advanceToToken(Y),this.quotedColumnParser.parse($);return this.nonQuotedColumnParser.parse($)}}GG0.ColumnParser=KG0});var bf=E((tJ)=>{Object.defineProperty(tJ,"__esModule",{value:!0});tJ.ColumnFormatter=tJ.QuotedColumnParser=tJ.NonQuotedColumnParser=tJ.ColumnParser=void 0;var YY1=HG0();Object.defineProperty(tJ,"ColumnParser",{enumerable:!0,get:function(){return YY1.ColumnParser}});var zY1=ff();Object.defineProperty(tJ,"NonQuotedColumnParser",{enumerable:!0,get:function(){return zY1.NonQuotedColumnParser}});var UY1=uf();Object.defineProperty(tJ,"QuotedColumnParser",{enumerable:!0,get:function(){re Line truncated
%s`,A,A,q,U);let B=q.type==="*"?zu:q.type==="?"?Ju:"\\"+q.type;Q=!0,U=U.slice(0,q.reStart)+B+"\\("+A}if(N(),J)U+="\\\\";let D=oY1[U.charAt(0)];for(let A=K.length-1;A>-1;A--){let B=K[A],j=U.slice(0,B.reStart),C=U.slice(B.reStart,B.reEnd-8),b=U.slice(B.reEnd),k=U.slice(B.reEnd-8,B.reEnd)+b,h=j.split(")").length,i=j.split("(").length-h,c=b;for(let x=0;x<i;x++)c=c.replace(/\)[+*?]?/,"");b=c;let U0=b===""&&Y!==Uu?"(?:$|\\/)":"";U=j+C+b+U0+k}if(U!==""&&Q)U="(?=.)"+U;if(D)U=w()+U;if(Y===Uu)return[U,Q];if(z.nocase&&!Q)Q=$.toUpperCase()!==$.toLowerCase();if(!Q)return sY1($);let T=z.nocase?"i":"";try{return Object.assign(new RegExp("^"+U+"$",T),{_glob:$,_src:U})}catch(A){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 Y=this.options,z=Y.noglobstar?zu:Y.dot?mY1:lY1,U=Y.nocase?"i":"",Q=$.map((J)=>{return J=J.map((I)=>typeof I==="string"?tY1(I):I===R8?R8:I._src).reduce((I,K)=>{if(!(I[I.length-1]===R8&&K===R8))I.push(K);return I},[]),J.forEach((I,K)=>{if(I!==R8||J[K-1]===R8)return;if(K===0)if(J.length>1)J[K+1]="(?:\\/|"+z+"\\/)?"+J[K+1];else J[K]=z;else if(K===J.length-1)J[K-1]+="(?:\\/|"+z+")?";else J[K-1]+="(?:\\/|\\/"+z+"\\/)"+J[K+1],J[K+1]=R8}),J.filter((I)=>I!==R8).join("/")}).join("|");if(Q="^(?:"+Q+")$",this.negate)Q="^(?!"+Q+").*$";try{this.regexp=new RegExp(Q,U)}catch(J){this.regexp=!1}return this.regexp}match($,Y=this.partial){if(this.debug("match",$,this.pattern),this.comment)return!1;if(this.empty)return $==="";if($==="/"&&Y)return!0;let z=this.options;if(Qu.sep!=="/")$=$.split(Qu.sep).join("/");$=$.split(UW0),this.debug(this.pattern,"split",$);let U=this.set;this.debug(this.pattern,"set",U);let Q;for(let J=$.length-1;J>=0;J--)if(Q=$[J],Q)break;for(let J=0;J<U.length;J++){let I=U[J],K=$;if(z.matchBase&&I.length===1)K=[Q];if(this.matchOne(K,I,Y)){if(z.flipNegate)return!0;return!this.negate}}if(z.flipNegate)return!1;return this.negate}static defaults($){return W$.defaults($).Minimatch}}W$.Minimatch=mH});var XW0=E((Go1,HW0)=>{HW0.exports=WW0;var Gu=I0("fs"),{EventEmitter:$z1}=I0("events"),{Minimatch:Ku}=IW0(),{resolve:Yz1}=I0("path");function zz1($,Y){return new Promise((z,U)=>{Gu.readdir($,{withFileTypes:!0},(Q,J)=>{if(Q)switch(Q.code){case"ENOTDIR":if(Y)U(Q);else z([]);break;case"ENOTSUP":case"ENOENT":case"ENAMETOOLONG":case"UNKNOWN":z([]);break;case"ELOOP":default:U(Q);break}else z(J)})})}function KW0($,Y){return new Promise((z,U)=>{(Y?Gu.stat:Gu.lstat)($,(J,I)=>{if(J)switch(J.code){case"ENOENT":if(Y)z(KW0($,!1));else z(null);break;default:z(null);break}else z(I)})})}async function*GW0($,Y,z,U,Q,J){let I=await zz1(Y+$,J);for(let K of I){let G=K.name;if(G===void 0)G=K,U=!0;let W=$+"/"+G,H=W.slice(1),X=Y+"/"+H,Z=null;if(U||z)Z=await KW0(X,z);if(!Z&&K.name!==void 0)Z=K;if(Z===null)Z={isDirectory:()=>!1};if(Z.isDirectory()){if(!Q(H))yield{relative:H,absolute:X,stats:Z},yield*GW0(W,Y,z,U,Q,!1)}else yield{relative:H,absolute:X,stats:Z}}}async function*Uz1($,Y,z,U){yield*GW0("",$,Y,z,U,!0)}function Qz1($){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 Wu extends $z1{constructor($,Y,z){super();if(typeof Y==="function")z=Y,Y=null;if(this.options=Qz1(Y||{}),this.matchers=[],this.options.pattern){let U=Array.isArray(this.options.pattern)?this.options.pattern:[this.options.pattern];this.matchers=U.map((Q)=>new Ku(Q,{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((Q)=>new Ku(Q,{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((Q)=>new Ku(Q,{dot:!0}))}if(this.iterator=Uz1(Yz1($||"."),this.options.follow,this.options.stat,this._shouldSkipDirectory.bind(this)),this.paused=!1,this.inactive=!1,this.aborted=!1,z)this._matches=[],this.on("match",(U)=>this._matches.push(this.options.absolute?U.absolute:U.relative)),this.on("error",(U)=>z(U)),this.on("end",()=>z(null,this._matches));setTimeout(()=>this._next(),0)}_shouldSkipDirectory($){return this.skipMatchers.some((Y)=>Y.match($))}_fileMatches($,Y){let z=$+(Y?"/":"");return(this.matchers.length===0||this.matchers.some((U)=>U.match(z)))&&!this.ignoreMatchers.some((U)=>U.match(z))&&(!this.options.nodir||!Y)}_next(){if(!this.paused&&!this.aborted)this.iterator.next().then(($)=>{if(!$.done){let Y=$.value.stats.isDirectory();if(this._fileMatches($.value.relative,Y)){let z=$.value.relative,U=$.value.absolute;if(this.options.mark&&Y)z+="/",U+="/";if(this.options.stat)this.emit("match",{relative:z,absolute:U,stat:$.value.stats});else this.emit("match",{relative:z Line truncated
`,m);m=w0===-1?f.length:w0}else if(K0!==-1&&f[m]==="/"&&f[m+1]==="*"){let w0=f.indexOf("*/",m);if(w0!==-1)m=w0+2,K0=f.indexOf("*/",m);else n+=f[m],m++}else n+=f[m],m++;return n}function i0(f){let n=u0(f.toString()),m=n.match(a);if(!m)m=n.match(H0);if(!m)throw Error(`could not parse args in autoInject
Source:
`+g);let[,m]=x;return m.replace(/\s/g,"").split(Z$).map((q0)=>q0.replace(T8,"").trim())}function m8(j,g){var x={};return Object.keys(j).forEach((m)=>{var q0=j[m],J0,G0=X(q0),Z0=!G0&&q0.length===1||G0&&q0.length===0;if(Array.isArray(q0))J0=[...q0],q0=J0.pop(),x[m]=J0.concat(J0.length>0?L0:q0);else if(Z0)x[m]=q0;else{if(J0=W$(q0),q0.length===0&&!G0&&J0.length===0)throw Error("autoInject task functions require explicit parameters.");if(!G0)J0.pop();x[m]=J0.concat(L0)}function L0(S0,F1){var _1=J0.map((D1)=>S0[D1]);_1.push(F1),O(q0)(..._1)}}),L1(x,g)}class J2{constructor(){this.head=this.tail=null,this.length=0}removeLink(j){if(j.prev)j.prev.next=j.next;else this.head=j.next;if(j.next)j.next.prev=j.prev;else this.tail=j.prev;return j.prev=j.next=null,this.length-=1,j}empty(){while(this.head)this.shift();return this}insertAfter(j,g){if(g.prev=j,g.next=j.next,j.next)j.next.prev=g;else this.tail=g;j.next=g,this.length+=1}insertBefore(j,g){if(g.prev=j.prev,g.next=j,j.prev)j.prev.next=g;else this.head=g;j.prev=g,this.length+=1}unshift(j){if(this.head)this.insertBefore(this.head,j);else l8(this,j)}push(j){if(this.tail)this.insertAfter(this.tail,j);else l8(this,j)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){var j=this.head;while(j)yield j.data,j=j.next}remove(j){var g=this.head;while(g){var{next:x}=g;if(j(g))this.removeLink(g);g=x}return this}}function l8(j,g){j.length=1,j.head=j.tail=g}function V3(j,g,x){if(g==null)g=1;else if(g===0)throw RangeError("Concurrency must not be zero");var m=O(j),q0=0,J0=[];let G0={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};function Z0(b0,v0){G0[b0].push(v0)}function L0(b0,v0){let i0=(...A1)=>{S0(b0,i0),v0(...A1)};G0[b0].push(i0)}function S0(b0,v0){if(!b0)return Object.keys(G0).forEach((i0)=>G0[i0]=[]);if(!v0)return G0[b0]=[];G0[b0]=G0[b0].filter((i0)=>i0!==v0)}function F1(b0,...v0){G0[b0].forEach((i0)=>i0(...v0))}var _1=!1;function D1(b0,v0,i0,A1){if(A1!=null&&typeof A1!=="function")throw Error("task callback must be a function");R1.started=!0;var A4,O6;function V$(K2,...TJ){if(K2)return i0?O6(K2):A4();if(TJ.length<=1)return A4(TJ[0]);A4(TJ)}var Pz=R1._createTaskItem(b0,i0?V$:A1||V$);if(v0)R1._tasks.unshift(Pz);else R1._tasks.push(Pz);if(!_1)_1=!0,H(()=>{_1=!1,R1.process()});if(i0||!A1)return new Promise((K2,TJ)=>{A4=K2,O6=TJ})}function X$(b0){return function(v0,...i0){q0-=1;for(var A1=0,A4=b0.length;A1<A4;A1++){var O6=b0[A1],V$=J0.indexOf(O6);if(V$===0)J0.shift();else if(V$>0)J0.splice(V$,1);if(O6.callback(v0,...i0),v0!=null)F1("error",v0,O6.data)}if(q0<=R1.concurrency-R1.buffer)F1("unsaturated");if(R1.idle())F1("drain");R1.process()}}function Az(b0){if(b0.length===0&&R1.idle())return H(()=>F1("drain")),!0;return!1}let Q2=(b0)=>(v0)=>{if(!v0)return new Promise((i0,A1)=>{L0(b0,(A4,O6)=>{if(A4)return A1(A4);i0(O6)})});S0(b0),Z0(b0,v0)};var BJ=!1,R1={_tasks:new J2,_createTaskItem(b0,v0){return{data:b0,callback:v0}},*[Symbol.iterator](){yield*R1._tasks[Symbol.iterator]()},concurrency:g,payload:x,buffer:g/4,started:!1,paused:!1,push(b0,v0){if(Array.isArray(b0)){if(Az(b0))return;return b0.map((i0)=>D1(i0,!1,!1,v0))}return D1(b0,!1,!1,v0)},pushAsync(b0,v0){if(Array.isArray(b0)){if(Az(b0))return;return b0.map((i0)=>D1(i0,!1,!0,v0))}return D1(b0,!1,!0,v0)},kill(){S0(),R1._tasks.empty()},unshift(b0,v0){if(Array.isArray(b0)){if(Az(b0))return;return b0.map((i0)=>D1(i0,!0,!1,v0))}return D1(b0,!0,!1,v0)},unshiftAsync(b0,v0){if(Array.isArray(b0)){if(Az(b0))return;return b0.map((i0)=>D1(i0,!0,!0,v0))}return D1(b0,!0,!0,v0)},remove(b0){R1._tasks.remove(b0)},process(){if(BJ)return;BJ=!0;while(!R1.paused&&q0<R1.concurrency&&R1._tasks.length){var b0=[],v0=[],i0=R1._tasks.length;if(R1.payload)i0=Math.min(i0,R1.payload);for(var A1=0;A1<i0;A1++){var A4=R1._tasks.shift();b0.push(A4),J0.push(A4),v0.push(A4.data)}if(q0+=1,R1._tasks.length===0)F1("empty");if(q0===R1.concurrency)F1("saturated");var O6=v(X$(b0));m(v0,O6)}BJ=!1},length(){return R1._tasks.length},running(){return q0},workersList(){return J0},idle(){return R1._tasks.length+q0===0},pause(){R1.paused=!0},resume(){if(R1.paused===!1)return;R1.paused=!1,H(R1.process)}};return Object.defineProperties(R1,{saturated:{writable:!1,value:Q2("saturated")},unsaturated:{writable:!1,value:Q2("unsaturated")},empty:{writable:!1,value:Q2("empty")},drain:{writable:!1,value:Q2("drain")},error:{writable:!1,value:Q2("error")}}),R1}function C0(j,g){return V3(j,1,g)}function a(j,g,x){return V3(j,g,x)}function N(j,g,x,m){m=k(m);var q0=O(x);return u0(j,(J0,G0,Z0)=>{q0(g,J0,(L0,S0)=>{g=S0,Z0(L0)})},(J0)=>m(J0,g))}var B=F(N,4);function S(...j){var g=j.map(O);return function(...x){var m=this,q0=x[x.length-1];if(typeof q0=="function")x.pop();else q0=k0();return B(g,x,(J0,G0,Z0)=>{G0.apply(m,J0.concat((L0,...S0)=>{Z0(L0,S0)}))},(J0,G0)=>q0(J0,...G0)),q0[E0]}}function n(...j){return S(...j.reverse())}function I0(j,g,x,m){return P(c(g),j,x,m)}var r=F(I0,4);function Line truncated
GFS4: `),console.error($)};if(!v4[k6]){if(xx=global[k6]||[],PG0(v4,xx),v4.close=function($){function I(z,q){return $.call(v4,z,function(U){if(!U)AG0();if(typeof q==="function")q.apply(this,arguments)})}return Object.defineProperty(I,uF,{value:$}),I}(v4.close),v4.closeSync=function($){function I(z){$.apply(v4,arguments),AG0()}return Object.defineProperty(I,uF,{value:$}),I}(v4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){ZI(v4[k6]),d("assert").equal(v4[k6].length,0)})}var xx;if(!global[k6])PG0(global,v4[k6]);fx.exports=ux(yK1(v4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!v4.__patched)fx.exports=ux(v4),v4.__patched=!0;function ux($){gK1($),$.gracefulify=ux,$.createReadStream=T,$.createWriteStream=k;var I=$.readFile;$.readFile=z;function z(C,b,i){if(typeof b==="function")i=b,b=null;return v(C,b,i);function v(y,c,$0,R){return I(y,c,function(u){if(u&&(u.code==="EMFILE"||u.code==="ENFILE"))bU([v,[y,c,$0],u,R||Date.now(),Date.now()]);else if(typeof $0==="function")$0.apply(this,arguments)})}}var q=$.writeFile;$.writeFile=U;function U(C,b,i,v){if(typeof i==="function")v=i,i=null;return y(C,b,i,v);function y(c,$0,R,u,p){return q(c,$0,R,function(s){if(s&&(s.code==="EMFILE"||s.code==="ENFILE"))bU([y,[c,$0,R,u],s,p||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var Y=$.appendFile;if(Y)$.appendFile=J;function J(C,b,i,v){if(typeof i==="function")v=i,i=null;return y(C,b,i,v);function y(c,$0,R,u,p){return Y(c,$0,R,function(s){if(s&&(s.code==="EMFILE"||s.code==="ENFILE"))bU([y,[c,$0,R,u],s,p||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var Q=$.copyFile;if(Q)$.copyFile=K;function K(C,b,i,v){if(typeof i==="function")v=i,i=0;return y(C,b,i,v);function y(c,$0,R,u,p){return Q(c,$0,R,function(s){if(s&&(s.code==="EMFILE"||s.code==="ENFILE"))bU([y,[c,$0,R,u],s,p||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var H=$.readdir;$.readdir=Z;var G=/^v[0-5]\./;function Z(C,b,i){if(typeof b==="function")i=b,b=null;var v=G.test(process.version)?function($0,R,u,p){return H($0,y($0,R,u,p))}:function($0,R,u,p){return H($0,R,y($0,R,u,p))};return v(C,b,i);function y(c,$0,R,u){return function(p,s){if(p&&(p.code==="EMFILE"||p.code==="ENFILE"))bU([v,[c,$0,R],p,u||Date.now(),Date.now()]);else{if(s&&s.sort)s.sort();if(typeof R==="function")R.call(this,p,s)}}}}if(process.version.substr(0,4)==="v0.8"){var W=SK1($);F=W.ReadStream,P=W.WriteStream}var X=$.ReadStream;if(X)F.prototype=Object.create(X.prototype),F.prototype.open=D;var w=$.WriteStream;if(w)P.prototype=Object.create(w.prototype),P.prototype.open=A;Object.defineProperty($,"ReadStream",{get:function(){return F},set:function(C){F=C},enumerable:!0,configurable:!0}),Object.defineProperty($,"WriteStream",{get:function(){return P},set:function(C){P=C},enumerable:!0,configurable:!0});var L=F;Object.defineProperty($,"FileReadStream",{get:function(){return L},set:function(C){L=C},enumerable:!0,configurable:!0});var O=P;Object.defineProperty($,"FileWriteStream",{get:function(){return O},set:function(C){O=C},enumerable:!0,configurable:!0});function F(C,b){if(this instanceof F)return X.apply(this,arguments),this;else return F.apply(Object.create(F.prototype),arguments)}function D(){var C=this;f(C.path,C.flags,C.mode,function(b,i){if(b){if(C.autoClose)C.destroy();C.emit("error",b)}else C.fd=i,C.emit("open",i),C.read()})}function P(C,b){if(this instanceof P)return w.apply(this,arguments),this;else return P.apply(Object.create(P.prototype),arguments)}function A(){var C=this;f(C.path,C.flags,C.mode,function(b,i){if(b)C.destroy(),C.emit("error",b);else C.fd=i,C.emit("open",i)})}function T(C,b){return new $.ReadStream(C,b)}function k(C,b){return new $.WriteStream(C,b)}var h=$.open;$.open=f;function f(C,b,i,v){if(typeof i==="function")v=i,i=null;return y(C,b,i,v);function y(c,$0,R,u,p){return h(c,$0,R,function(s,U0){if(s&&(s.code==="EMFILE"||s.code==="ENFILE"))bU([y,[c,$0,R,u],s,p||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}return $}function bU($){ZI("ENQUEUE",$[0].name,$[1]),v4[k6].push($),kx()}var xF;function AG0(){var $=Date.now();for(var I=0;I<v4[k6].length;++I)if(v4[k6][I].length>2)v4[k6][I][3]=$,v4[k6][I][4]=$;kx()}function kx(){if(clearTimeout(xF),xF=void 0,v4[k6].length===0)return;var $=v4[k6].shift(),I=$[0],z=$[1],q=$[2],U=$[3],Y=$[4];if(U===void 0)ZI("RETRY",I.name,z),I.apply(null,z);else if(Date.now()-U>=60000){ZI("TIMEOUT",I.name,z);var J=z.pop();if(typeof J==="function")J.call(null,q)}else{var Q=Date.now()-Y,K=Math.max(Y-U,1),H=Math.min(K*1.2,100);if(Q>=H)ZI("RETRY",I.name,z),I.apply(null,z.concat([U]));else v4[k6].push($)}if(xF===void 0)xF=setTimeout(kx,0)}});var TG0=M((g64,bx)=>{function uK1($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var BG0=l4().Buffer,vH=d("util");function kK1($,I,z){$.copy(I,z)}bx.exports=function(){function $(){uK1(this,$),this.head=null,this.tail=null,th Line truncated
`+n);let[,K0]=m;return K0.replace(/\s/g,"").split(L0).map((w0)=>w0.replace(f0,"").trim())}function D1(f,n){var m={};return Object.keys(f).forEach((K0)=>{var w0=f[K0],D0,A0=q(w0),j0=!A0&&w0.length===1||A0&&w0.length===0;if(Array.isArray(w0))D0=[...w0],w0=D0.pop(),m[K0]=D0.concat(D0.length>0?h0:w0);else if(j0)m[K0]=w0;else{if(D0=i0(w0),w0.length===0&&!A0&&D0.length===0)throw Error("autoInject task functions require explicit parameters.");if(!A0)D0.pop();m[K0]=D0.concat(h0)}function h0(z1,x1){var m1=D0.map((i1)=>z1[i1]);m1.push(x1),M(w0)(...m1)}}),Y1(m,n)}class k1{constructor(){this.head=this.tail=null,this.length=0}removeLink(f){if(f.prev)f.prev.next=f.next;else this.head=f.next;if(f.next)f.next.prev=f.prev;else this.tail=f.prev;return f.prev=f.next=null,this.length-=1,f}empty(){while(this.head)this.shift();return this}insertAfter(f,n){if(n.prev=f,n.next=f.next,f.next)f.next.prev=n;else this.tail=n;f.next=n,this.length+=1}insertBefore(f,n){if(n.prev=f.prev,n.next=f,f.prev)f.prev.next=n;else this.head=n;f.prev=n,this.length+=1}unshift(f){if(this.head)this.insertBefore(this.head,f);else u1(this,f)}push(f){if(this.tail)this.insertAfter(this.tail,f);else u1(this,f)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){var f=this.head;while(f)yield f.data,f=f.next}remove(f){var n=this.head;while(n){var{next:m}=n;if(f(n))this.removeLink(n);n=m}return this}}function u1(f,n){f.length=1,f.head=f.tail=n}function b1(f,n,m){if(n==null)n=1;else if(n===0)throw RangeError("Concurrency must not be zero");var K0=M(f),w0=0,D0=[];let A0={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};function j0(G1,e0){A0[G1].push(e0)}function h0(G1,e0){let W1=(...c1)=>{z1(G1,W1),e0(...c1)};A0[G1].push(W1)}function z1(G1,e0){if(!G1)return Object.keys(A0).forEach((W1)=>A0[W1]=[]);if(!e0)return A0[G1]=[];A0[G1]=A0[G1].filter((W1)=>W1!==e0)}function x1(G1,...e0){A0[G1].forEach((W1)=>W1(...e0))}var m1=!1;function i1(G1,e0,W1,c1){if(c1!=null&&typeof c1!=="function")throw Error("task callback must be a function");l1.started=!0;var g4,v6;function O$(OY,...nK){if(OY)return W1?v6(OY):g4();if(nK.length<=1)return g4(nK[0]);g4(nK)}var kU=l1._createTaskItem(G1,W1?O$:c1||O$);if(e0)l1._tasks.unshift(kU);else l1._tasks.push(kU);if(!m1)m1=!0,W(()=>{m1=!1,l1.process()});if(W1||!c1)return new Promise((OY,nK)=>{g4=OY,v6=nK})}function M$(G1){return function(e0,...W1){w0-=1;for(var c1=0,g4=G1.length;c1<g4;c1++){var v6=G1[c1],O$=D0.indexOf(v6);if(O$===0)D0.shift();else if(O$>0)D0.splice(O$,1);if(v6.callback(e0,...W1),e0!=null)x1("error",e0,v6.data)}if(w0<=l1.concurrency-l1.buffer)x1("unsaturated");if(l1.idle())x1("drain");l1.process()}}function yU(G1){if(G1.length===0&&l1.idle())return W(()=>x1("drain")),!0;return!1}let MY=(G1)=>(e0)=>{if(!e0)return new Promise((W1,c1)=>{h0(G1,(g4,v6)=>{if(g4)return c1(g4);W1(v6)})});z1(G1),j0(G1,e0)};var cK=!1,l1={_tasks:new k1,_createTaskItem(G1,e0){return{data:G1,callback:e0}},*[Symbol.iterator](){yield*l1._tasks[Symbol.iterator]()},concurrency:n,payload:m,buffer:n/4,started:!1,paused:!1,push(G1,e0){if(Array.isArray(G1)){if(yU(G1))return;return G1.map((W1)=>i1(W1,!1,!1,e0))}return i1(G1,!1,!1,e0)},pushAsync(G1,e0){if(Array.isArray(G1)){if(yU(G1))return;return G1.map((W1)=>i1(W1,!1,!0,e0))}return i1(G1,!1,!0,e0)},kill(){z1(),l1._tasks.empty()},unshift(G1,e0){if(Array.isArray(G1)){if(yU(G1))return;return G1.map((W1)=>i1(W1,!0,!1,e0))}return i1(G1,!0,!1,e0)},unshiftAsync(G1,e0){if(Array.isArray(G1)){if(yU(G1))return;return G1.map((W1)=>i1(W1,!0,!0,e0))}return i1(G1,!0,!0,e0)},remove(G1){l1._tasks.remove(G1)},process(){if(cK)return;cK=!0;while(!l1.paused&&w0<l1.concurrency&&l1._tasks.length){var G1=[],e0=[],W1=l1._tasks.length;if(l1.payload)W1=Math.min(W1,l1.payload);for(var c1=0;c1<W1;c1++){var g4=l1._tasks.shift();G1.push(g4),D0.push(g4),e0.push(g4.data)}if(w0+=1,l1._tasks.length===0)x1("empty");if(w0===l1.concurrency)x1("saturated");var v6=h(M$(G1));K0(e0,v6)}cK=!1},length(){return l1._tasks.length},running(){return w0},workersList(){return D0},idle(){return l1._tasks.length+w0===0},pause(){l1.paused=!0},resume(){if(l1.paused===!1)return;l1.paused=!1,W(l1.process)}};return Object.defineProperties(l1,{saturated:{writable:!1,value:MY("saturated")},unsaturated:{writable:!1,value:MY("unsaturated")},empty:{writable:!1,value:MY("empty")},drain:{writable:!1,value:MY("drain")},error:{writable:!1,value:MY("error")}}),l1}function B0(f,n){return b1(f,1,n)}function Q0(f,n,m){return b1(f,n,m)}function P(f,n,m,K0){K0=A(K0);var w0=M(m);return Y0(f,(D0,A0,j0)=>{w0(n,D0,(h0,z1)=>{n=z1,j0(h0)})},(D0)=>K0(D0,n))}var v=w(P,4);function u(...f){var n=f.map(M);return function(...m){var K0=this,w0=m[m.length-1];if(typeof w0=="function")m.pop();else w0=b0();return v(n,m,(D0,A0,j0)=>{A0.apply(K0,D0.concat((h0,...z1)=>{j0(h0,z1)}))},(D0,A0)=>w0(D0,...A0)),w0[T0]}}function r(...f){return u(...f.reverse())}function X0(f,n,m,K0){return N(c(n),f,m,K0)}var J Line truncated
GFS4: `),console.error($)};if(!p4[s6]){if(Xu=global[s6]||[],DW0(p4,Xu),p4.close=function($){function Y(z,U){return $.call(p4,z,function(Q){if(!Q)NW0();if(typeof U==="function")U.apply(this,arguments)})}return Object.defineProperty(Y,qD,{value:$}),Y}(p4.close),p4.closeSync=function($){function Y(z){$.apply(p4,arguments),NW0()}return Object.defineProperty(Y,qD,{value:$}),Y}(p4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){Pz(p4[s6]),I0("assert").equal(p4[s6].length,0)})}var Xu;if(!global[s6])DW0(global,p4[s6]);Vu.exports=Zu(qz1(p4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!p4.__patched)Vu.exports=Zu(p4),p4.__patched=!0;function Zu($){Xz1($),$.gracefulify=Zu,$.createReadStream=T,$.createWriteStream=A;var Y=$.readFile;$.readFile=z;function z(C,b,k){if(typeof b==="function")k=b,b=null;return h(C,b,k);function h(i,c,U0,x){return Y(i,c,function(d){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))YI([h,[i,c,U0],d,x||Date.now(),Date.now()]);else if(typeof U0==="function")U0.apply(this,arguments)})}}var U=$.writeFile;$.writeFile=Q;function Q(C,b,k,h){if(typeof k==="function")h=k,k=null;return i(C,b,k,h);function i(c,U0,x,d,t){return U(c,U0,x,function($0){if($0&&($0.code==="EMFILE"||$0.code==="ENFILE"))YI([i,[c,U0,x,d],$0,t||Date.now(),Date.now()]);else if(typeof d==="function")d.apply(this,arguments)})}}var J=$.appendFile;if(J)$.appendFile=I;function I(C,b,k,h){if(typeof k==="function")h=k,k=null;return i(C,b,k,h);function i(c,U0,x,d,t){return J(c,U0,x,function($0){if($0&&($0.code==="EMFILE"||$0.code==="ENFILE"))YI([i,[c,U0,x,d],$0,t||Date.now(),Date.now()]);else if(typeof d==="function")d.apply(this,arguments)})}}var K=$.copyFile;if(K)$.copyFile=G;function G(C,b,k,h){if(typeof k==="function")h=k,k=0;return i(C,b,k,h);function i(c,U0,x,d,t){return K(c,U0,x,function($0){if($0&&($0.code==="EMFILE"||$0.code==="ENFILE"))YI([i,[c,U0,x,d],$0,t||Date.now(),Date.now()]);else if(typeof d==="function")d.apply(this,arguments)})}}var W=$.readdir;$.readdir=X;var H=/^v[0-5]\./;function X(C,b,k){if(typeof b==="function")k=b,b=null;var h=H.test(process.version)?function(U0,x,d,t){return W(U0,i(U0,x,d,t))}:function(U0,x,d,t){return W(U0,x,i(U0,x,d,t))};return h(C,b,k);function i(c,U0,x,d){return function(t,$0){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))YI([h,[c,U0,x],t,d||Date.now(),Date.now()]);else{if($0&&$0.sort)$0.sort();if(typeof x==="function")x.call(this,t,$0)}}}}if(process.version.substr(0,4)==="v0.8"){var Z=Zz1($);w=Z.ReadStream,N=Z.WriteStream}var q=$.ReadStream;if(q)w.prototype=Object.create(q.prototype),w.prototype.open=O;var V=$.WriteStream;if(V)N.prototype=Object.create(V.prototype),N.prototype.open=D;Object.defineProperty($,"ReadStream",{get:function(){return w},set:function(C){w=C},enumerable:!0,configurable:!0}),Object.defineProperty($,"WriteStream",{get:function(){return N},set:function(C){N=C},enumerable:!0,configurable:!0});var F=w;Object.defineProperty($,"FileReadStream",{get:function(){return F},set:function(C){F=C},enumerable:!0,configurable:!0});var M=N;Object.defineProperty($,"FileWriteStream",{get:function(){return M},set:function(C){M=C},enumerable:!0,configurable:!0});function w(C,b){if(this instanceof w)return q.apply(this,arguments),this;else return w.apply(Object.create(w.prototype),arguments)}function O(){var C=this;j(C.path,C.flags,C.mode,function(b,k){if(b){if(C.autoClose)C.destroy();C.emit("error",b)}else C.fd=k,C.emit("open",k),C.read()})}function N(C,b){if(this instanceof N)return V.apply(this,arguments),this;else return N.apply(Object.create(N.prototype),arguments)}function D(){var C=this;j(C.path,C.flags,C.mode,function(b,k){if(b)C.destroy(),C.emit("error",b);else C.fd=k,C.emit("open",k)})}function T(C,b){return new $.ReadStream(C,b)}function A(C,b){return new $.WriteStream(C,b)}var B=$.open;$.open=j;function j(C,b,k,h){if(typeof k==="function")h=k,k=null;return i(C,b,k,h);function i(c,U0,x,d,t){return B(c,U0,x,function($0,g){if($0&&($0.code==="EMFILE"||$0.code==="ENFILE"))YI([i,[c,U0,x,d],$0,t||Date.now(),Date.now()]);else if(typeof d==="function")d.apply(this,arguments)})}}return $}function YI($){Pz("ENQUEUE",$[0].name,$[1]),p4[s6].push($),qu()}var ZD;function NW0(){var $=Date.now();for(var Y=0;Y<p4[s6].length;++Y)if(p4[s6][Y].length>2)p4[s6][Y][3]=$,p4[s6][Y][4]=$;qu()}function qu(){if(clearTimeout(ZD),ZD=void 0,p4[s6].length===0)return;var $=p4[s6].shift(),Y=$[0],z=$[1],U=$[2],Q=$[3],J=$[4];if(Q===void 0)Pz("RETRY",Y.name,z),Y.apply(null,z);else if(Date.now()-Q>=60000){Pz("TIMEOUT",Y.name,z);var I=z.pop();if(typeof I==="function")I.call(null,U)}else{var K=Date.now()-J,G=Math.max(J-Q,1),W=Math.min(G*1.2,100);if(K>=W)Pz("RETRY",Y.name,z),Y.apply(null,z.concat([Q]));else p4[s6].push($)}if(ZD===void 0)ZD=setTimeout(qu,0)}});var PW0=E((qo1,Lu)=>{function Lz1($,Y){if(!($ instanceof Y))throw TypeError("Cannot call a class as a function")}var BW0=K6().Buffer,lH=I0("util");function Fz1($,Y,z){$.copy(Y,z)}Lu.exports=function(){function $(){Lz1(this,$),this.h Line truncated
* normalize-path <https://github.com/jonschlinkert/normalize-path>
*
* Copyright (c) 2014-2018, Jon Schlinkert.
* Released under the MIT License.
*/ZZ0.exports=function($,I){if(typeof $!=="string")throw TypeError("expected path to be a string");if($==="\\"||$==="/")return"/";var z=$.length;if(z<=1)return $;var q="";if(z>4&&$[3]==="\\"){var U=$[2];if((U==="?"||U===".")&&$.slice(0,2)==="\\\\")$=$.slice(2),q="//"}var Y=$.split(/[/\\]+/);if(I!==!1&&Y[Y.length-1]==="")Y.pop();return q+Y.join("/")}});var Yu=M((d64,FZ0)=>{var XZ0=9007199254740991,pH1="[object Arguments]",dH1="[object Function]",mH1="[object GeneratorFunction]",lH1=/^(?:0|[1-9]\d*)$/;function VZ0($,I,z){switch(z.length){case 0:return $.call(I);case 1:return $.call(I,z[0]);case 2:return $.call(I,z[0],z[1]);case 3:return $.call(I,z[0],z[1],z[2])}return $.apply(I,z)}function oH1($,I){var z=-1,q=Array($);while(++z<$)q[z]=I(z);return q}var bH=Object.prototype,iH=bH.hasOwnProperty,wZ0=bH.toString,rH1=bH.propertyIsEnumerable,WZ0=Math.max;function sH1($,I){var z=JG1($)||YG1($)?oH1($.length,String):[],q=z.length,U=!!q;for(var Y in $)if((I||iH.call($,Y))&&!(U&&(Y=="length"||OZ0(Y,q))))z.push(Y);return z}function tH1($,I,z,q){if($===void 0||zu($,bH[z])&&!iH.call(q,z))return I;return $}function aH1($,I,z){var q=$[I];if(!(iH.call($,I)&&zu(q,z))||z===void 0&&!(I in $))$[I]=z}function eH1($){if(!Uu($))return UG1($);var I=qG1($),z=[];for(var q in $)if(!(q=="constructor"&&(I||!iH.call($,q))))z.push(q);return z}function LZ0($,I){return I=WZ0(I===void 0?$.length-1:I,0),function(){var z=arguments,q=-1,U=WZ0(z.length-I,0),Y=Array(U);while(++q<U)Y[q]=z[I+q];q=-1;var J=Array(I+1);while(++q<I)J[q]=z[q];return J[I]=Y,VZ0($,this,J)}}function $G1($,I,z,q){z||(z={});var U=-1,Y=I.length;while(++U<Y){var J=I[U],Q=q?q(z[J],$[J],J,z,$):void 0;aH1(z,J,Q===void 0?$[J]:Q)}return z}function IG1($){return LZ0(function(I,z){var q=-1,U=z.length,Y=U>1?z[U-1]:void 0,J=U>2?z[2]:void 0;if(Y=$.length>3&&typeof Y=="function"?(U--,Y):void 0,J&&zG1(z[0],z[1],J))Y=U<3?void 0:Y,U=1;I=Object(I);while(++q<U){var Q=z[q];if(Q)$(I,Q,q,Y)}return I})}function OZ0($,I){return I=I==null?XZ0:I,!!I&&(typeof $=="number"||lH1.test($))&&($>-1&&$%1==0&&$<I)}function zG1($,I,z){if(!Uu(z))return!1;var q=typeof I;if(q=="number"?qu(z)&&OZ0(I,z.length):q=="string"&&(I in z))return zu(z[I],$);return!1}function qG1($){var I=$&&$.constructor,z=typeof I=="function"&&I.prototype||bH;return $===z}function UG1($){var I=[];if($!=null)for(var z in Object($))I.push(z);return I}function zu($,I){return $===I||$!==$&&I!==I}function YG1($){return QG1($)&&iH.call($,"callee")&&(!rH1.call($,"callee")||wZ0.call($)==pH1)}var JG1=Array.isArray;function qu($){return $!=null&&HG1($.length)&&!KG1($)}function QG1($){return GG1($)&&qu($)}function KG1($){var I=Uu($)?wZ0.call($):"";return I==dH1||I==mH1}function HG1($){return typeof $=="number"&&$>-1&&$%1==0&&$<=XZ0}function Uu($){var I=typeof $;return!!$&&(I=="object"||I=="function")}function GG1($){return!!$&&typeof $=="object"}var ZG1=IG1(function($,I,z,q){$G1(I,XG1(I),$,q)}),WG1=LZ0(function($){return $.push(void 0,tH1),VZ0(ZG1,void 0,$)});function XG1($){return qu($)?sH1($,!0):eH1($)}FZ0.exports=WG1});var NZ0=M((m64,Ju)=>{function VG1($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var MZ0=l4().Buffer,nH=d("util");function wG1($,I,z){$.copy(I,z)}Ju.exports=function(){function $(){VG1(this,$),this.head=null,this.tail=null,this.length=0}return $.prototype.push=function(z){var q={data:z,next:null};if(this.length>0)this.tail.next=q;else this.head=q;this.tail=q,++this.length},$.prototype.unshift=function(z){var q={data:z,next:this.head};if(this.length===0)this.tail=q;this.head=q,++this.length},$.prototype.shift=function(){if(this.length===0)return;var z=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,z},$.prototype.clear=function(){this.head=this.tail=null,this.length=0},$.prototype.join=function(z){if(this.length===0)return"";var q=this.head,U=""+q.data;while(q=q.next)U+=z+q.data;return U},$.prototype.concat=function(z){if(this.length===0)return MZ0.alloc(0);var q=MZ0.allocUnsafe(z>>>0),U=this.head,Y=0;while(U)wG1(U.data,q,Y),Y+=U.data.length,U=U.next;return q},$}();if(nH&&nH.inspect&&nH.inspect.custom)Ju.exports.prototype[nH.inspect.custom]=function(){var $=nH.inspect({length:this.length});return this.constructor.name+" "+$}});var Qu=M((l64,DZ0)=>{var sF=m4();function LG1($,I){var z=this,q=this._readableState&&this._readableState.destroyed,U=this._writableState&&this._writableState.destroyed;if(q||U){if(I)I($);else if($){if(!this._writableState)sF.nextTick(tF,this,$);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,sF.nextTick(tF,this,$)}return this}if(this._readableState)this._readableState.destroyed=!0;if(this._writableState)this._writableState.destroyed=!0;return this._destroy($||null,function(Y){if(!I&&Y){if(!z._writableState)sF.nextTick(tF,z,Y);else if(!z._writableState.errorEmitted)z._writableState.errorEmitted=!0,sF.nextTick(tF,z,Y)}else if(I)I(Y)}),this}function OG1(){if(this._readableState)this._readable Line truncated
%s`,T,T,D,q);var k=D.type==="*"?du:D.type==="?"?pu:"\\"+D.type;U=!0,q=q.slice(0,D.reStart)+k+"\\("+T}if(w(),Y)q+="\\\\";var h=!1;switch(q.charAt(0)){case"[":case".":case"(":h=!0}for(var f=Q.length-1;f>-1;f--){var C=Q[f],b=q.slice(0,C.reStart),i=q.slice(C.reStart,C.reEnd-8),v=q.slice(C.reEnd-8,C.reEnd),y=q.slice(C.reEnd);v+=y;var c=b.split("(").length-1,$0=y;for(L=0;L<c;L++)$0=$0.replace(/\)[+*?]?/,"");y=$0;var R="";if(y===""&&I!==XM)R="$";var u=b+i+y+R+v;q=u}if(q!==""&&U)q="(?=.)"+q;if(h)q=W+q;if(I===XM)return[q,U];if(!U)return xV1($);var p=z.nocase?"i":"";try{var s=new RegExp("^"+q+"$",p)}catch(U0){return new RegExp("$.")}return s._glob=$,s._src=q,s}U$.makeRe=function($,I){return new q6($,I||{}).makeRe()};q6.prototype.makeRe=yV1;function yV1(){if(this.regexp||this.regexp===!1)return this.regexp;var $=this.set;if(!$.length)return this.regexp=!1,this.regexp;var I=this.options,z=I.noglobstar?du:I.dot?jV1:CV1,q=I.nocase?"i":"",U=$.map(function(Y){return Y.map(function(J){return J===NI?z:typeof J==="string"?uV1(J):J._src}).join("\\/")}).join("|");if(U="^(?:"+U+")$",this.negate)U="^(?!"+U+").*$";try{this.regexp=new RegExp(U,q)}catch(Y){this.regexp=!1}return this.regexp}U$.match=function($,I,z){z=z||{};var q=new q6(I,z);if($=$.filter(function(U){return q.match(U)}),q.options.nonull&&!$.length)$.push(I);return $};q6.prototype.match=function(I,z){if(typeof z>"u")z=this.partial;if(this.debug("match",I,this.pattern),this.comment)return!1;if(this.empty)return I==="";if(I==="/"&&z)return!0;var q=this.options;if($G.sep!=="/")I=I.split($G.sep).join("/");I=I.split($X0),this.debug(this.pattern,"split",I);var U=this.set;this.debug(this.pattern,"set",U);var Y,J;for(J=I.length-1;J>=0;J--)if(Y=I[J],Y)break;for(J=0;J<U.length;J++){var Q=U[J],K=I;if(q.matchBase&&Q.length===1)K=[Y];var H=this.matchOne(K,Q,z);if(H){if(q.flipNegate)return!0;return!this.negate}}if(q.flipNegate)return!1;return this.negate};q6.prototype.matchOne=function($,I,z){if(I.indexOf(NI)!==-1)return this._matchGlobstar($,I,z,0,0);return this._matchOne($,I,z,0,0)};q6.prototype._matchGlobstar=function($,I,z,q,U){var Y,J=-1;for(Y=U;Y<I.length;Y++)if(I[Y]===NI){J=Y;break}var Q=-1;for(Y=I.length-1;Y>=0;Y--)if(I[Y]===NI){Q=Y;break}var K=I.slice(U,J),H=z?I.slice(J+1):I.slice(J+1,Q),G=z?[]:I.slice(Q+1);if(K.length){var Z=$.slice(q,q+K.length);if(!this._matchOne(Z,K,z,0,0))return!1;q+=K.length}var W=0;if(G.length){if(G.length+q>$.length)return!1;var X=$.length-G.length;if(this._matchOne($,G,z,X,0))W=G.length;else{if($[$.length-1]!==""||q+G.length===$.length)return!1;if(X--,!this._matchOne($,G,z,X,0))return!1;W=G.length+1}}if(!H.length){var w=!!W;for(Y=q;Y<$.length-W;Y++){var L=String($[Y]);if(w=!0,L==="."||L===".."||!this.options.dot&&L.charAt(0)===".")return!1}return z||w}var O=[[[],0]],F=O[0],D=0,P=[0];for(var A=0;A<H.length;A++){var T=H[A];if(T===NI)P.push(D),F=[[],0],O.push(F);else F[0].push(T),D++}var k=O.length-1,h=$.length-W;for(var f=0;f<O.length;f++)O[f][1]=h-(P[k--]+O[f][0].length);return!!this._matchGlobStarBodySections($,O,q,0,z,0,!!W)};q6.prototype._matchGlobStarBodySections=function($,I,z,q,U,Y,J){var Q=I[q];if(!Q){for(var K=z;K<$.length;K++){J=!0;var H=$[K];if(H==="."||H===".."||!this.options.dot&&H.charAt(0)===".")return!1}return J}var G=Q[0],Z=Q[1];while(z<=Z){var W=this._matchOne($.slice(0,z+G.length),G,U,z,0);if(W&&Y<this.maxGlobstarRecursion){var X=this._matchGlobStarBodySections($,I,z+G.length,q+1,U,Y+1,J);if(X!==!1)return X}var H=$[z];if(H==="."||H===".."||!this.options.dot&&H.charAt(0)===".")return!1;z++}return U||null};q6.prototype._matchOne=function($,I,z,q,U){var Y,J,Q,K;for(Y=q,J=U,Q=$.length,K=I.length;Y<Q&&J<K;Y++,J++){this.debug("matchOne loop");var H=I[J],G=$[Y];if(this.debug(I,H,G),H===!1||H===NI)return!1;var Z;if(typeof H==="string")Z=G===H,this.debug("string match",H,G,Z);else Z=G.match(H),this.debug("pattern match",H,G,Z);if(!Z)return!1}if(Y===Q&&J===K)return!0;else if(Y===Q)return z;else if(J===K)return Y===Q-1&&$[Y]==="";throw Error("wtf?")};function xV1($){return $.replace(/\\(.)/g,"$1")}function uV1($){return $.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var OM=M((X84,LM)=>{function qX0($){return $.charAt(0)==="/"}function UX0($){var I=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,z=I.exec($),q=z[1]||"",U=Boolean(q&&q.charAt(1)!==":");return Boolean(z[2]||U)}LM.exports=process.platform==="win32"?UX0:qX0;LM.exports.posix=qX0;LM.exports.win32=UX0});var lu=M((lV1)=>{lV1.setopts=cV1;lV1.ownProp=YX0;lV1.makeAbs=IG;lV1.finish=pV1;lV1.mark=dV1;lV1.isIgnored=QX0;lV1.childrenIgnored=mV1;function YX0($,I){return Object.prototype.hasOwnProperty.call($,I)}var kV1=d("fs"),eU=d("path"),fV1=wM(),JX0=OM(),mu=fV1.Minimatch;function bV1($,I){return $.localeCompare(I,"en")}function iV1($,I){if($.ignore=I.ignore||[],!Array.isArray($.ignore))$.ignore=[$.ignore];if($.ignore.length)$.ignore=$.ignore.map(nV1)}function nV1($){var I=null;if($.slice(-3)==="/**"){var z=$.replace(/(\/\*\*)+$/,"");I=new mu(z,{dot:!0})}return{matcher Line truncated
See: https://github.com/isaacs/node-glob/issues/167`);return new Z6($,I).found}function Z6($,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 Z6))return new Z6($,I);if(zw1(this,$,I),this.noprocess)return this;var z=this.minimatch.set.length;this.matches=Array(z);for(var q=0;q<z;q++)this._process(this.minimatch.set[q],q,!1);this._finish()}Z6.prototype._finish=function(){if(HX0.ok(this instanceof Z6),this.realpath){var $=this;this.matches.forEach(function(I,z){var q=$.matches[z]=Object.create(null);for(var U in I)try{U=$._makeAbs(U);var Y=Iw1.realpathSync(U,$.realpathCache);q[Y]=!0}catch(J){if(J.syscall==="stat")q[$._makeAbs(U)]=!0;else throw J}})}DI.finish(this)};Z6.prototype._process=function($,I,z){HX0.ok(this instanceof Z6);var q=0;while(typeof $[q]==="string")q++;var U;switch(q){case $.length:this._processSimple($.join("/"),I);return;case 0:U=null;break;default:U=$.slice(0,q).join("/");break}var Y=$.slice(q),J;if(U===null)J=".";else if(FM(U)||FM($.map(function(H){return typeof H==="string"?H:"[*]"}).join("/"))){if(!U||!FM(U))U="/"+U;J=U}else J=U;var Q=this._makeAbs(J);if(qw1(this,J))return;var K=Y[0]===KX0.GLOBSTAR;if(K)this._processGlobStar(U,J,Q,Y,I,z);else this._processReaddir(U,J,Q,Y,I,z)};Z6.prototype._processReaddir=function($,I,z,q,U,Y){var J=this._readdir(z,Y);if(!J)return;var Q=q[0],K=!!this.minimatch.negate,H=Q._glob,G=this.dot||H.charAt(0)===".",Z=[];for(var W=0;W<J.length;W++){var X=J[W];if(X.charAt(0)!=="."||G){var w;if(K&&!$)w=!X.match(Q);else w=X.match(Q);if(w)Z.push(X)}}var L=Z.length;if(L===0)return;if(q.length===1&&!this.mark&&!this.stat){if(!this.matches[U])this.matches[U]=Object.create(null);for(var W=0;W<L;W++){var X=Z[W];if($)if($.slice(-1)!=="/")X=$+"/"+X;else X=$+X;if(X.charAt(0)==="/"&&!this.nomount)X=ou.join(this.root,X);this._emitMatch(U,X)}return}q.shift();for(var W=0;W<L;W++){var X=Z[W],O;if($)O=[$,X];else O=[X];this._process(O.concat(q),U,Y)}};Z6.prototype._emitMatch=function($,I){if(Uw1(this,I))return;var z=this._makeAbs(I);if(this.mark)I=this._mark(I);if(this.absolute)I=z;if(this.matches[$][I])return;if(this.nodir){var q=this.cache[z];if(q==="DIR"||Array.isArray(q))return}if(this.matches[$][I]=!0,this.stat)this._stat(I)};Z6.prototype._readdirInGlobStar=function($){if(this.follow)return this._readdir($,!1);var I,z,q;try{z=this.fs.lstatSync($)}catch(Y){if(Y.code==="ENOENT")return null}var U=z&&z.isSymbolicLink();if(this.symlinks[$]=U,!U&&z&&!z.isDirectory())this.cache[$]="FILE";else I=this._readdir($,!1);return I};Z6.prototype._readdir=function($,I){var z;if(I&&!ru(this.symlinks,$))return this._readdirInGlobStar($);if(ru(this.cache,$)){var q=this.cache[$];if(!q||q==="FILE")return null;if(Array.isArray(q))return q}try{return this._readdirEntries($,this.fs.readdirSync($))}catch(U){return this._readdirError($,U),null}};Z6.prototype._readdirEntries=function($,I){if(!this.mark&&!this.stat)for(var z=0;z<I.length;z++){var q=I[z];if($==="/")q=$+q;else q=$+"/"+q;this.cache[q]=!0}return this.cache[$]=I,I};Z6.prototype._readdirError=function($,I){switch(I.code){case"ENOTSUP":case"ENOTDIR":var z=this._makeAbs($);if(this.cache[z]="FILE",z===this.cwdAbs){var q=Error(I.code+" invalid cwd "+this.cwd);throw q.path=this.cwd,q.code=I.code,q}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}};Z6.prototype._processGlobStar=function($,I,z,q,U,Y){var J=this._readdir(z,Y);if(!J)return;var Q=q.slice(1),K=$?[$]:[],H=K.concat(Q);this._process(H,U,!1);var G=J.length,Z=this.symlinks[z];if(Z&&Y)return;for(var W=0;W<G;W++){var X=J[W];if(X.charAt(0)==="."&&!this.dot)continue;var w=K.concat(J[W],Q);this._process(w,U,!0);var L=K.concat(J[W],q);this._process(L,U,!0)}};Z6.prototype._processSimple=function($,I){var z=this._stat($);if(!this.matches[I])this.matches[I]=Object.create(null);if(!z)return;if($&&FM($)&&!this.nomount){var q=/[\/\\]$/.test($);if($.charAt(0)==="/")$=ou.join(this.root,$);else if($=ou.resolve(this.root,$),q)$+="/"}if(process.platform==="win32")$=$.replace(/\\/g,"/");this._emitMatch(I,$)};Z6.prototype._stat=function($){var I=this._makeAbs($),z=$.slice(-1)==="/";if($.length>this.maxLength)return!1;if(!this.stat&&ru(this.cache,I)){var J=this.cache[I];if(Array.isArray(J))J="DIR";if(!z||J==="DIR")return J;if(z&&J==="FILE")return!1}var q,U=this.statCache[I];if(!U){var Y;try{Y=this.fs.lstatSync(I)}catch(Q){if(Q&&(Q.code==="ENOENT"||Q.code==="ENOTDIR"))return this.statCache[I]=!1,!1}if(Y&&Y.isSymbolicLink())try{U=this.fs.statSync(I)}catch(Q){U=Y}else U=Y}this.statCache[I]=U;var J=!0;if(U)J=U.isDirectory()?"DIR":"FILE";if(this.cache[I]=this.cache[I]||J,z&&J==="FILE")return!1;return J};Z6.prototype._mark=function($){return DI.mark(this,$)};Z6.prototype._makeAbs=function($){return DI.makeAbs(this,$)}});var su=M((M84,VX0)=>{VX0.exports=XX0;function XX0($,I){if($&&I)return XX0($)(I);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(q){z[q]=$[q]}),z;f Line truncated
`);if($.linkname)I+=ok(" linkpath="+$.linkname+`
`);var z=$.pax;if(z)for(var q in z)I+=ok(" "+q+"="+z[q]+`
`);return Buffer.from(I)};VF1.decodePax=function($){var I={};while($.length){var z=0;while(z<$.length&&$[z]!==32)z++;var q=parseInt($.slice(0,z).toString(),10);if(!q)return I;var U=$.slice(z+1,q-1).toString(),Y=U.indexOf("=");if(Y===-1)return I;I[U.slice(0,Y)]=U.slice(Y+1),$=$.slice(q)}return I};VF1.encode=function($){var I=qF1(512),z=$.name,q="";if($.typeflag===5&&z[z.length-1]!=="/")z+="/";if(Buffer.byteLength(z)!==z.length)return null;while(Buffer.byteLength(z)>100){var U=z.indexOf("/");if(U===-1)return null;q+=q?"/"+z.slice(0,U):z.slice(0,U),z=z.slice(U+1)}if(Buffer.byteLength(z)>100||Buffer.byteLength(q)>155)return null;if($.linkname&&Buffer.byteLength($.linkname)>100)return null;if(I.write(z),I.write(R7($.mode&HF1,6),100),I.write(R7($.uid,6),108),I.write(R7($.gid,6),116),I.write(R7($.size,11),124),I.write(R7($.mtime.getTime()/1000|0,11),136),I[156]=Cw0+WF1($.type),$.linkname)I.write($.linkname,157);if(_w0.copy(I,OG),JF1.copy(I,rk),$.uname)I.write($.uname,265);if($.gname)I.write($.gname,297);if(I.write(R7($.devmajor||0,6),329),I.write(R7($.devminor||0,6),337),q)I.write(q,345);return I.write(R7(vw0(I),6),148),I};VF1.decode=function($,I,z){var q=$[156]===0?0:$[156]-Cw0,U=KY($,0,100,I),Y=v7($,100,8),J=v7($,108,8),Q=v7($,116,8),K=v7($,124,12),H=v7($,136,12),G=ZF1(q),Z=$[157]===0?null:KY($,157,100,I),W=KY($,265,32),X=KY($,297,32),w=v7($,329,8),L=v7($,337,8),O=vw0($);if(O===256)return null;if(O!==v7($,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(_w0.compare($,OG,OG+6)===0){if($[345])U=KY($,345,155,I)+"/"+U}else if(QF1.compare($,OG,OG+6)===0&&KF1.compare($,rk,rk+2)===0);else if(!z)throw Error("Invalid tar header: unknown format.");if(q===0&&U&&U[U.length-1]==="/")q=5;return{name:U,mode:Y,uid:J,gid:Q,size:K,mtime:new Date(1000*H),type:G,linkname:Z,uname:W,gname:X,devmajor:w,devminor:L}}});var kw0=M((X$4,uw0)=>{var gw0=d("util"),NF1=jw0(),FG=sk(),Sw0=w8().Writable,yw0=w8().PassThrough,xw0=function(){},hw0=function($){return $&=511,$&&512-$},DF1=function($,I){var z=new kM($,I);return z.end(),z},AF1=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,$},kM=function($,I){this._parent=$,this.offset=I,yw0.call(this,{autoDestroy:!1})};gw0.inherits(kM,yw0);kM.prototype.destroy=function($){this._parent.destroy($)};var c9=function($){if(!(this instanceof c9))return new c9($);Sw0.call(this,$),$=$||{},this._offset=0,this._buffer=NF1(),this._missing=0,this._partial=!1,this._onparse=xw0,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,z=I._buffer,q=function(){I._continue()},U=function(W){if(I._locked=!1,W)return I.destroy(W);if(!I._stream)q()},Y=function(){I._stream=null;var W=hw0(I._header.size);if(W)I._parse(W,J);else I._parse(512,Z);if(!I._locked)q()},J=function(){I._buffer.consume(hw0(I._header.size)),I._parse(512,Z),q()},Q=function(){var W=I._header.size;I._paxGlobal=FG.decodePax(z.slice(0,W)),z.consume(W),Y()},K=function(){var W=I._header.size;if(I._pax=FG.decodePax(z.slice(0,W)),I._paxGlobal)I._pax=Object.assign({},I._paxGlobal,I._pax);z.consume(W),Y()},H=function(){var W=I._header.size;this._gnuLongPath=FG.decodeLongPath(z.slice(0,W),$.filenameEncoding),z.consume(W),Y()},G=function(){var W=I._header.size;this._gnuLongLinkPath=FG.decodeLongPath(z.slice(0,W),$.filenameEncoding),z.consume(W),Y()},Z=function(){var W=I._offset,X;try{X=I._header=FG.decode(z.slice(0,512),$.filenameEncoding,$.allowUnknownFormat)}catch(w){I.emit("error",w)}if(z.consume(512),!X){I._parse(512,Z),q();return}if(X.type==="gnu-long-path"){I._parse(X.size,H),q();return}if(X.type==="gnu-long-link-path"){I._parse(X.size,G),q();return}if(X.type==="pax-global-header"){I._parse(X.size,Q),q();return}if(X.type==="pax-header"){I._parse(X.size,K),q();return}if(I._gnuLongPath)X.name=I._gnuLongPath,I._gnuLongPath=null;if(I._gnuLongLinkPath)X.linkname=I._gnuLongLinkPath,I._gnuLongLinkPath=null;if(I._pax)I._header=X=AF1(X,I._pax),I._pax=null;if(I._locked=!0,!X.size||X.type==="directory"){I._parse(512,Z),I.emit("entry",X,DF1(I,W),U);return}I._stream=new kM(I,W),I.emit("entry",X,I._stream,U),I._parse(X.size,Y),q()};this._onheader=Z,this._parse(512,Z)};gw0.inherits(c9,Sw0);c9.prototype.destroy=function($){if(this._destroyed)return;if(this._destroyed=!0,$)this.emit("error",$);if(this.emit("close"),this._stream)this._stream.emit("close")};c9.prototype._parse=function($,I){if(this._destroyed)return;if(this._offset+=$,this._missing=$,I===this._onheader)this._partial=!1;this._onparse=I};c9.prototype._continue=function(){if(this._destroyed)return;var $=this._cb;if(this._cb=xw0,this._overflow)this._write(this._overflow,void 0,$);else $()};c9.prototype._write=function($,I,z){if(this._destroyed)return;var q=this._stream,U=this._buffer,Y=this._missing;if($.length)this._partial=!0;if($.length<Y){ 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="${iF1.xmlEncode($.Target)}" TargetMode="${$.TargetMode}"/>`);else this.stream.write(`<Relationship Id="${I}" Type="${$.Type}" Target="${$.Target}"/>`);return I}_writeClose(){this.stream.write("</Relationships>")}}GL0.exports=HL0});var LL0=M((P$4,wL0)=>{var WL0=y6(),XL0=K7(),cF1=C4(),pF1=Gy(),dF1=Wy();class VL0{constructor($,I,z){this.id=z.id,this.count=0,this._worksheet=$,this._workbook=z.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:XL0.Comments,Target:`../comments${this.id}.xml`};this._sheetRelsWriter.addRelationship($);let I={Type:XL0.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 z=new pF1,q=new WL0;z.render(q,$),this.commentsStream.write(q.xml);let U=new dF1,Y=new WL0;U.render(Y,$,I),this.vmlStream.write(Y.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=cF1.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()}}wL0.exports=VL0});var AL0=M((B$4,DL0)=>{var mF1=b4(),lF1=K7(),ek=C4(),OL0=_v(),FL0=N9(),oF1=cg(),ML0=cw(),$f=dw(),rF1=ZL0(),sF1=LL0(),tF1=jv(),M6=new oF1,If=Y7(),aF1=kS(),eF1=fS(),$M1=bS(),IM1=SS(),zM1=hS(),qM1=yS(),UM1=iS(),YM1=nS(),JM1=cS(),QM1=pS(),KM1=dS(),HM1=mS(),GM1=tS(),ZM1=oS(),WM1=lS(),N6={dataValidations:new aF1,sheetProperties:new eF1,sheetFormatProperties:new $M1,columns:new If({tag:"cols",length:!1,childXform:new IM1}),row:new zM1,hyperlinks:new If({tag:"hyperlinks",length:!1,childXform:new qM1}),sheetViews:new If({tag:"sheetViews",length:!1,childXform:new UM1}),sheetProtection:new YM1,pageMargins:new JM1,pageSeteup:new QM1,autoFilter:new KM1,picture:new HM1,conditionalFormattings:new GM1,headerFooter:new ZM1,rowBreaks:new WM1};class NL0{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 rF1($),this._sheetCommentsWriter=new sF1(this,this._sheetRelsWriter,$),this._dimensions=new FL0,this._rowZero=1,this.committed=!1,this.dataValidations=new tF1,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
*/WH0.exports=function($,Y){if(typeof $!=="string")throw TypeError("expected path to be a string");if($==="\\"||$==="/")return"/";var z=$.length;if(z<=1)return $;var U="";if(z>4&&$[3]==="\\"){var Q=$[2];if((Q==="?"||Q===".")&&$.slice(0,2)==="\\\\")$=$.slice(2),U="//"}var J=$.split(/[/\\]+/);if(Y!==!1&&J[J.length-1]==="")J.pop();return U+J.join("/")}});var gu=E((To1,FH0)=>{var XH0=9007199254740991,BU1="[object Arguments]",PU1="[object Function]",AU1="[object GeneratorFunction]",TU1=/^(?:0|[1-9]\d*)$/;function ZH0($,Y,z){switch(z.length){case 0:return $.call(Y);case 1:return $.call(Y,z[0]);case 2:return $.call(Y,z[0],z[1]);case 3:return $.call(Y,z[0],z[1],z[2])}return $.apply(Y,z)}function jU1($,Y){var z=-1,U=Array($);while(++z<$)U[z]=Y(z);return U}var zX=Object.prototype,UX=zX.hasOwnProperty,qH0=zX.toString,EU1=zX.propertyIsEnumerable,HH0=Math.max;function CU1($,Y){var z=fU1($)||xU1($)?jU1($.length,String):[],U=z.length,Q=!!U;for(var J in $)if((Y||UX.call($,J))&&!(Q&&(J=="length"||LH0(J,U))))z.push(J);return z}function RU1($,Y,z,U){if($===void 0||vu($,zX[z])&&!UX.call(U,z))return Y;return $}function _U1($,Y,z){var U=$[Y];if(!(UX.call($,Y)&&vu(U,z))||z===void 0&&!(Y in $))$[Y]=z}function vU1($){if(!Su($))return kU1($);var Y=yU1($),z=[];for(var U in $)if(!(U=="constructor"&&(Y||!UX.call($,U))))z.push(U);return z}function VH0($,Y){return Y=HH0(Y===void 0?$.length-1:Y,0),function(){var z=arguments,U=-1,Q=HH0(z.length-Y,0),J=Array(Q);while(++U<Q)J[U]=z[Y+U];U=-1;var I=Array(Y+1);while(++U<Y)I[U]=z[U];return I[Y]=J,ZH0($,this,I)}}function hU1($,Y,z,U){z||(z={});var Q=-1,J=Y.length;while(++Q<J){var I=Y[Q],K=U?U(z[I],$[I],I,z,$):void 0;_U1(z,I,K===void 0?$[I]:K)}return z}function SU1($){return VH0(function(Y,z){var U=-1,Q=z.length,J=Q>1?z[Q-1]:void 0,I=Q>2?z[2]:void 0;if(J=$.length>3&&typeof J=="function"?(Q--,J):void 0,I&&gU1(z[0],z[1],I))J=Q<3?void 0:J,Q=1;Y=Object(Y);while(++U<Q){var K=z[U];if(K)$(Y,K,U,J)}return Y})}function LH0($,Y){return Y=Y==null?XH0:Y,!!Y&&(typeof $=="number"||TU1.test($))&&($>-1&&$%1==0&&$<Y)}function gU1($,Y,z){if(!Su(z))return!1;var U=typeof Y;if(U=="number"?hu(z)&&LH0(Y,z.length):U=="string"&&(Y in z))return vu(z[Y],$);return!1}function yU1($){var Y=$&&$.constructor,z=typeof Y=="function"&&Y.prototype||zX;return $===z}function kU1($){var Y=[];if($!=null)for(var z in Object($))Y.push(z);return Y}function vu($,Y){return $===Y||$!==$&&Y!==Y}function xU1($){return uU1($)&&UX.call($,"callee")&&(!EU1.call($,"callee")||qH0.call($)==BU1)}var fU1=Array.isArray;function hu($){return $!=null&&iU1($.length)&&!bU1($)}function uU1($){return cU1($)&&hu($)}function bU1($){var Y=Su($)?qH0.call($):"";return Y==PU1||Y==AU1}function iU1($){return typeof $=="number"&&$>-1&&$%1==0&&$<=XH0}function Su($){var Y=typeof $;return!!$&&(Y=="object"||Y=="function")}function cU1($){return!!$&&typeof $=="object"}var nU1=SU1(function($,Y,z,U){hU1(Y,dU1(Y),$,U)}),pU1=VH0(function($){return $.push(void 0,RU1),ZH0(nU1,void 0,$)});function dU1($){return hu($)?CU1($,!0):vU1($)}FH0.exports=pU1});var MH0=E((jo1,yu)=>{function mU1($,Y){if(!($ instanceof Y))throw TypeError("Cannot call a class as a function")}var wH0=K6().Buffer,QX=I0("util");function lU1($,Y,z){$.copy(Y,z)}yu.exports=function(){function $(){mU1(this,$),this.head=null,this.tail=null,this.length=0}return $.prototype.push=function(z){var U={data:z,next:null};if(this.length>0)this.tail.next=U;else this.head=U;this.tail=U,++this.length},$.prototype.unshift=function(z){var U={data:z,next:this.head};if(this.length===0)this.tail=U;this.head=U,++this.length},$.prototype.shift=function(){if(this.length===0)return;var z=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,z},$.prototype.clear=function(){this.head=this.tail=null,this.length=0},$.prototype.join=function(z){if(this.length===0)return"";var U=this.head,Q=""+U.data;while(U=U.next)Q+=z+U.data;return Q},$.prototype.concat=function(z){if(this.length===0)return wH0.alloc(0);var U=wH0.allocUnsafe(z>>>0),Q=this.head,J=0;while(Q)lU1(Q.data,U,J),J+=Q.data.length,Q=Q.next;return U},$}();if(QX&&QX.inspect&&QX.inspect.custom)yu.exports.prototype[QX.inspect.custom]=function(){var $=QX.inspect({length:this.length});return this.constructor.name+" "+$}});var ku=E((Eo1,OH0)=>{var jD=I6();function oU1($,Y){var z=this,U=this._readableState&&this._readableState.destroyed,Q=this._writableState&&this._writableState.destroyed;if(U||Q){if(Y)Y($);else if($){if(!this._writableState)jD.nextTick(ED,this,$);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,jD.nextTick(ED,this,$)}return this}if(this._readableState)this._readableState.destroyed=!0;if(this._writableState)this._writableState.destroyed=!0;return this._destroy($||null,function(J){if(!Y&&J){if(!z._writableState)jD.nextTick(ED,z,J);else if(!z._writableState.errorEmitted)z._writableState.errorEmitted=!0,jD.nextTick(ED,z,J)}else if(Y)Y(J)}),this}function rU1(){if(this._readableState)this._readabl Line truncated
%s`,T,T,O,U);var A=O.type==="*"?Nb:O.type==="?"?Ob:"\\"+O.type;Q=!0,U=U.slice(0,O.reStart)+A+"\\("+T}if(V(),J)U+="\\\\";var B=!1;switch(U.charAt(0)){case"[":case".":case"(":B=!0}for(var j=K.length-1;j>-1;j--){var C=K[j],b=U.slice(0,C.reStart),k=U.slice(C.reStart,C.reEnd-8),h=U.slice(C.reEnd-8,C.reEnd),i=U.slice(C.reEnd);h+=i;var c=b.split("(").length-1,U0=i;for(F=0;F<c;F++)U0=U0.replace(/\)[+*?]?/,"");i=U0;var x="";if(i===""&&Y!==nD)x="$";var d=b+k+i+x+h;U=d}if(U!==""&&Q)U="(?=.)"+U;if(B)U=Z+U;if(Y===nD)return[U,Q];if(!Q)return VG1($);var t=z.nocase?"i":"";try{var $0=new RegExp("^"+U+"$",t)}catch(g){return new RegExp("$.")}return $0._glob=$,$0._src=U,$0}H$.makeRe=function($,Y){return new L6($,Y||{}).makeRe()};L6.prototype.makeRe=qG1;function qG1(){if(this.regexp||this.regexp===!1)return this.regexp;var $=this.set;if(!$.length)return this.regexp=!1,this.regexp;var Y=this.options,z=Y.noglobstar?Nb:Y.dot?JG1:IG1,U=Y.nocase?"i":"",Q=$.map(function(J){return J.map(function(I){return I===hz?z:typeof I==="string"?LG1(I):I._src}).join("\\/")}).join("|");if(Q="^(?:"+Q+")$",this.negate)Q="^(?!"+Q+").*$";try{this.regexp=new RegExp(Q,U)}catch(J){this.regexp=!1}return this.regexp}H$.match=function($,Y,z){z=z||{};var U=new L6(Y,z);if($=$.filter(function(Q){return U.match(Q)}),U.options.nonull&&!$.length)$.push(Y);return $};L6.prototype.match=function(Y,z){if(typeof z>"u")z=this.partial;if(this.debug("match",Y,this.pattern),this.comment)return!1;if(this.empty)return Y==="";if(Y==="/"&&z)return!0;var U=this.options;if(FX.sep!=="/")Y=Y.split(FX.sep).join("/");Y=Y.split(tX0),this.debug(this.pattern,"split",Y);var Q=this.set;this.debug(this.pattern,"set",Q);var J,I;for(I=Y.length-1;I>=0;I--)if(J=Y[I],J)break;for(I=0;I<Q.length;I++){var K=Q[I],G=Y;if(U.matchBase&&K.length===1)G=[J];var W=this.matchOne(G,K,z);if(W){if(U.flipNegate)return!0;return!this.negate}}if(U.flipNegate)return!1;return this.negate};L6.prototype.matchOne=function($,Y,z){if(Y.indexOf(hz)!==-1)return this._matchGlobstar($,Y,z,0,0);return this._matchOne($,Y,z,0,0)};L6.prototype._matchGlobstar=function($,Y,z,U,Q){var J,I=-1;for(J=Q;J<Y.length;J++)if(Y[J]===hz){I=J;break}var K=-1;for(J=Y.length-1;J>=0;J--)if(Y[J]===hz){K=J;break}var G=Y.slice(Q,I),W=z?Y.slice(I+1):Y.slice(I+1,K),H=z?[]:Y.slice(K+1);if(G.length){var X=$.slice(U,U+G.length);if(!this._matchOne(X,G,z,0,0))return!1;U+=G.length}var Z=0;if(H.length){if(H.length+U>$.length)return!1;var q=$.length-H.length;if(this._matchOne($,H,z,q,0))Z=H.length;else{if($[$.length-1]!==""||U+H.length===$.length)return!1;if(q--,!this._matchOne($,H,z,q,0))return!1;Z=H.length+1}}if(!W.length){var V=!!Z;for(J=U;J<$.length-Z;J++){var F=String($[J]);if(V=!0,F==="."||F===".."||!this.options.dot&&F.charAt(0)===".")return!1}return z||V}var M=[[[],0]],w=M[0],O=0,N=[0];for(var D=0;D<W.length;D++){var T=W[D];if(T===hz)N.push(O),w=[[],0],M.push(w);else w[0].push(T),O++}var A=M.length-1,B=$.length-Z;for(var j=0;j<M.length;j++)M[j][1]=B-(N[A--]+M[j][0].length);return!!this._matchGlobStarBodySections($,M,U,0,z,0,!!Z)};L6.prototype._matchGlobStarBodySections=function($,Y,z,U,Q,J,I){var K=Y[U];if(!K){for(var G=z;G<$.length;G++){I=!0;var W=$[G];if(W==="."||W===".."||!this.options.dot&&W.charAt(0)===".")return!1}return I}var H=K[0],X=K[1];while(z<=X){var Z=this._matchOne($.slice(0,z+H.length),H,Q,z,0);if(Z&&J<this.maxGlobstarRecursion){var q=this._matchGlobStarBodySections($,Y,z+H.length,U+1,Q,J+1,I);if(q!==!1)return q}var W=$[z];if(W==="."||W===".."||!this.options.dot&&W.charAt(0)===".")return!1;z++}return Q||null};L6.prototype._matchOne=function($,Y,z,U,Q){var J,I,K,G;for(J=U,I=Q,K=$.length,G=Y.length;J<K&&I<G;J++,I++){this.debug("matchOne loop");var W=Y[I],H=$[J];if(this.debug(Y,W,H),W===!1||W===hz)return!1;var X;if(typeof W==="string")X=H===W,this.debug("string match",W,H,X);else X=H.match(W),this.debug("pattern match",W,H,X);if(!X)return!1}if(J===K&&I===G)return!0;else if(J===K)return z;else if(I===G)return J===K-1&&$[J]==="";throw Error("wtf?")};function VG1($){return $.replace(/\\(.)/g,"$1")}function LG1($){return $.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var lD=E((lo1,mD)=>{function YZ0($){return $.charAt(0)==="/"}function zZ0($){var Y=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,z=Y.exec($),U=z[1]||"",Q=Boolean(U&&U.charAt(1)!==":");return Boolean(z[2]||Q)}mD.exports=process.platform==="win32"?zZ0:YZ0;mD.exports.posix=YZ0;mD.exports.win32=zZ0});var Bb=E((TG1)=>{TG1.setopts=DG1;TG1.ownProp=UZ0;TG1.makeAbs=wX;TG1.finish=BG1;TG1.mark=PG1;TG1.isIgnored=JZ0;TG1.childrenIgnored=AG1;function UZ0($,Y){return Object.prototype.hasOwnProperty.call($,Y)}var FG1=I0("fs"),VI=I0("path"),wG1=dD(),QZ0=lD(),Db=wG1.Minimatch;function MG1($,Y){return $.localeCompare(Y,"en")}function OG1($,Y){if($.ignore=Y.ignore||[],!Array.isArray($.ignore))$.ignore=[$.ignore];if($.ignore.length)$.ignore=$.ignore.map(NG1)}function NG1($){var Y=null;if($.slice(-3)==="/**"){var z=$.replace(/(\/\*\*)+$/,"");Y=new Db(z,{dot:!0})}return{ma Line truncated
See: https://github.com/isaacs/node-glob/issues/167`);return new T6($,Y).found}function T6($,Y){if(!$)throw Error("must provide pattern");if(typeof Y==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof T6))return new T6($,Y);if(gG1(this,$,Y),this.noprocess)return this;var z=this.minimatch.set.length;this.matches=Array(z);for(var U=0;U<z;U++)this._process(this.minimatch.set[U],U,!1);this._finish()}T6.prototype._finish=function(){if(KZ0.ok(this instanceof T6),this.realpath){var $=this;this.matches.forEach(function(Y,z){var U=$.matches[z]=Object.create(null);for(var Q in Y)try{Q=$._makeAbs(Q);var J=SG1.realpathSync(Q,$.realpathCache);U[J]=!0}catch(I){if(I.syscall==="stat")U[$._makeAbs(Q)]=!0;else throw I}})}Sz.finish(this)};T6.prototype._process=function($,Y,z){KZ0.ok(this instanceof T6);var U=0;while(typeof $[U]==="string")U++;var Q;switch(U){case $.length:this._processSimple($.join("/"),Y);return;case 0:Q=null;break;default:Q=$.slice(0,U).join("/");break}var J=$.slice(U),I;if(Q===null)I=".";else if(oD(Q)||oD($.map(function(W){return typeof W==="string"?W:"[*]"}).join("/"))){if(!Q||!oD(Q))Q="/"+Q;I=Q}else I=Q;var K=this._makeAbs(I);if(yG1(this,I))return;var G=J[0]===IZ0.GLOBSTAR;if(G)this._processGlobStar(Q,I,K,J,Y,z);else this._processReaddir(Q,I,K,J,Y,z)};T6.prototype._processReaddir=function($,Y,z,U,Q,J){var I=this._readdir(z,J);if(!I)return;var K=U[0],G=!!this.minimatch.negate,W=K._glob,H=this.dot||W.charAt(0)===".",X=[];for(var Z=0;Z<I.length;Z++){var q=I[Z];if(q.charAt(0)!=="."||H){var V;if(G&&!$)V=!q.match(K);else V=q.match(K);if(V)X.push(q)}}var F=X.length;if(F===0)return;if(U.length===1&&!this.mark&&!this.stat){if(!this.matches[Q])this.matches[Q]=Object.create(null);for(var Z=0;Z<F;Z++){var q=X[Z];if($)if($.slice(-1)!=="/")q=$+"/"+q;else q=$+q;if(q.charAt(0)==="/"&&!this.nomount)q=Pb.join(this.root,q);this._emitMatch(Q,q)}return}U.shift();for(var Z=0;Z<F;Z++){var q=X[Z],M;if($)M=[$,q];else M=[q];this._process(M.concat(U),Q,J)}};T6.prototype._emitMatch=function($,Y){if(kG1(this,Y))return;var z=this._makeAbs(Y);if(this.mark)Y=this._mark(Y);if(this.absolute)Y=z;if(this.matches[$][Y])return;if(this.nodir){var U=this.cache[z];if(U==="DIR"||Array.isArray(U))return}if(this.matches[$][Y]=!0,this.stat)this._stat(Y)};T6.prototype._readdirInGlobStar=function($){if(this.follow)return this._readdir($,!1);var Y,z,U;try{z=this.fs.lstatSync($)}catch(J){if(J.code==="ENOENT")return null}var Q=z&&z.isSymbolicLink();if(this.symlinks[$]=Q,!Q&&z&&!z.isDirectory())this.cache[$]="FILE";else Y=this._readdir($,!1);return Y};T6.prototype._readdir=function($,Y){var z;if(Y&&!Ab(this.symlinks,$))return this._readdirInGlobStar($);if(Ab(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(Q){return this._readdirError($,Q),null}};T6.prototype._readdirEntries=function($,Y){if(!this.mark&&!this.stat)for(var z=0;z<Y.length;z++){var U=Y[z];if($==="/")U=$+U;else U=$+"/"+U;this.cache[U]=!0}return this.cache[$]=Y,Y};T6.prototype._readdirError=function($,Y){switch(Y.code){case"ENOTSUP":case"ENOTDIR":var z=this._makeAbs($);if(this.cache[z]="FILE",z===this.cwdAbs){var U=Error(Y.code+" invalid cwd "+this.cwd);throw U.path=this.cwd,U.code=Y.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 Y;if(!this.silent)console.error("glob error",Y);break}};T6.prototype._processGlobStar=function($,Y,z,U,Q,J){var I=this._readdir(z,J);if(!I)return;var K=U.slice(1),G=$?[$]:[],W=G.concat(K);this._process(W,Q,!1);var H=I.length,X=this.symlinks[z];if(X&&J)return;for(var Z=0;Z<H;Z++){var q=I[Z];if(q.charAt(0)==="."&&!this.dot)continue;var V=G.concat(I[Z],K);this._process(V,Q,!0);var F=G.concat(I[Z],U);this._process(F,Q,!0)}};T6.prototype._processSimple=function($,Y){var z=this._stat($);if(!this.matches[Y])this.matches[Y]=Object.create(null);if(!z)return;if($&&oD($)&&!this.nomount){var U=/[\/\\]$/.test($);if($.charAt(0)==="/")$=Pb.join(this.root,$);else if($=Pb.resolve(this.root,$),U)$+="/"}if(process.platform==="win32")$=$.replace(/\\/g,"/");this._emitMatch(Y,$)};T6.prototype._stat=function($){var Y=this._makeAbs($),z=$.slice(-1)==="/";if($.length>this.maxLength)return!1;if(!this.stat&&Ab(this.cache,Y)){var I=this.cache[Y];if(Array.isArray(I))I="DIR";if(!z||I==="DIR")return I;if(z&&I==="FILE")return!1}var U,Q=this.statCache[Y];if(!Q){var J;try{J=this.fs.lstatSync(Y)}catch(K){if(K&&(K.code==="ENOENT"||K.code==="ENOTDIR"))return this.statCache[Y]=!1,!1}if(J&&J.isSymbolicLink())try{Q=this.fs.statSync(Y)}catch(K){Q=J}else Q=J}this.statCache[Y]=Q;var I=!0;if(Q)I=Q.isDirectory()?"DIR":"FILE";if(this.cache[Y]=this.cache[Y]||I,z&&I==="FILE")return!1;return I};T6.prototype._mark=function($){return Sz.mark(this,$)};T6.prototype._makeAbs=function($){return Sz.makeAbs(this,$)}});var Tb=E((eo1,ZZ0)=>{ZZ0.exports=XZ0;function XZ0($,Y){if($&&Y)return XZ0($)(Y);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(U){z[U]=$[U]}),z;f Line truncated
`);if($.linkname)Y+=Pi(" linkpath="+$.linkname+`
`);var z=$.pax;if(z)for(var U in z)Y+=Pi(" "+U+"="+z[U]+`
`);return Buffer.from(Y)};mX1.decodePax=function($){var Y={};while($.length){var z=0;while(z<$.length&&$[z]!==32)z++;var U=parseInt($.slice(0,z).toString(),10);if(!U)return Y;var Q=$.slice(z+1,U-1).toString(),J=Q.indexOf("=");if(J===-1)return Y;Y[Q.slice(0,J)]=Q.slice(J+1),$=$.slice(U)}return Y};mX1.encode=function($){var Y=yX1(512),z=$.name,U="";if($.typeflag===5&&z[z.length-1]!=="/")z+="/";if(Buffer.byteLength(z)!==z.length)return null;while(Buffer.byteLength(z)>100){var Q=z.indexOf("/");if(Q===-1)return null;U+=U?"/"+z.slice(0,Q):z.slice(0,Q),z=z.slice(Q+1)}if(Buffer.byteLength(z)>100||Buffer.byteLength(U)>155)return null;if($.linkname&&Buffer.byteLength($.linkname)>100)return null;if(Y.write(z),Y.write(D2($.mode&iX1,6),100),Y.write(D2($.uid,6),108),Y.write(D2($.gid,6),116),Y.write(D2($.size,11),124),Y.write(D2($.mtime.getTime()/1000|0,11),136),Y[156]=jV0+pX1($.type),$.linkname)Y.write($.linkname,157);if(EV0.copy(Y,SX),fX1.copy(Y,Ai),$.uname)Y.write($.uname,265);if($.gname)Y.write($.gname,297);if(Y.write(D2($.devmajor||0,6),329),Y.write(D2($.devminor||0,6),337),U)Y.write(U,345);return Y.write(D2(RV0(Y),6),148),Y};mX1.decode=function($,Y,z){var U=$[156]===0?0:$[156]-jV0,Q=PI($,0,100,Y),J=B2($,100,8),I=B2($,108,8),K=B2($,116,8),G=B2($,124,12),W=B2($,136,12),H=nX1(U),X=$[157]===0?null:PI($,157,100,Y),Z=PI($,265,32),q=PI($,297,32),V=B2($,329,8),F=B2($,337,8),M=RV0($);if(M===256)return null;if(M!==B2($,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(EV0.compare($,SX,SX+6)===0){if($[345])Q=PI($,345,155,Y)+"/"+Q}else if(uX1.compare($,SX,SX+6)===0&&bX1.compare($,Ai,Ai+2)===0);else if(!z)throw Error("Invalid tar header: unknown format.");if(U===0&&Q&&Q[Q.length-1]==="/")U=5;return{name:Q,mode:J,uid:I,gid:K,size:G,mtime:new Date(1000*W),type:H,linkname:X,uname:Z,gname:q,devmajor:V,devminor:F}}});var kV0=E((lr1,yV0)=>{var vV0=I0("util"),tX1=TV0(),gX=Ti(),hV0=E8().Writable,SV0=E8().PassThrough,gV0=function(){},_V0=function($){return $&=511,$&&512-$},eX1=function($,Y){var z=new VB($,Y);return z.end(),z},$Z1=function($,Y){if(Y.path)$.name=Y.path;if(Y.linkpath)$.linkname=Y.linkpath;if(Y.size)$.size=parseInt(Y.size,10);return $.pax=Y,$},VB=function($,Y){this._parent=$,this.offset=Y,SV0.call(this,{autoDestroy:!1})};vV0.inherits(VB,SV0);VB.prototype.destroy=function($){this._parent.destroy($)};var P7=function($){if(!(this instanceof P7))return new P7($);hV0.call(this,$),$=$||{},this._offset=0,this._buffer=tX1(),this._missing=0,this._partial=!1,this._onparse=gV0,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 Y=this,z=Y._buffer,U=function(){Y._continue()},Q=function(Z){if(Y._locked=!1,Z)return Y.destroy(Z);if(!Y._stream)U()},J=function(){Y._stream=null;var Z=_V0(Y._header.size);if(Z)Y._parse(Z,I);else Y._parse(512,X);if(!Y._locked)U()},I=function(){Y._buffer.consume(_V0(Y._header.size)),Y._parse(512,X),U()},K=function(){var Z=Y._header.size;Y._paxGlobal=gX.decodePax(z.slice(0,Z)),z.consume(Z),J()},G=function(){var Z=Y._header.size;if(Y._pax=gX.decodePax(z.slice(0,Z)),Y._paxGlobal)Y._pax=Object.assign({},Y._paxGlobal,Y._pax);z.consume(Z),J()},W=function(){var Z=Y._header.size;this._gnuLongPath=gX.decodeLongPath(z.slice(0,Z),$.filenameEncoding),z.consume(Z),J()},H=function(){var Z=Y._header.size;this._gnuLongLinkPath=gX.decodeLongPath(z.slice(0,Z),$.filenameEncoding),z.consume(Z),J()},X=function(){var Z=Y._offset,q;try{q=Y._header=gX.decode(z.slice(0,512),$.filenameEncoding,$.allowUnknownFormat)}catch(V){Y.emit("error",V)}if(z.consume(512),!q){Y._parse(512,X),U();return}if(q.type==="gnu-long-path"){Y._parse(q.size,W),U();return}if(q.type==="gnu-long-link-path"){Y._parse(q.size,H),U();return}if(q.type==="pax-global-header"){Y._parse(q.size,K),U();return}if(q.type==="pax-header"){Y._parse(q.size,G),U();return}if(Y._gnuLongPath)q.name=Y._gnuLongPath,Y._gnuLongPath=null;if(Y._gnuLongLinkPath)q.linkname=Y._gnuLongLinkPath,Y._gnuLongLinkPath=null;if(Y._pax)Y._header=q=$Z1(q,Y._pax),Y._pax=null;if(Y._locked=!0,!q.size||q.type==="directory"){Y._parse(512,X),Y.emit("entry",q,eX1(Y,Z),Q);return}Y._stream=new VB(Y,Z),Y.emit("entry",q,Y._stream,Q),Y._parse(q.size,J),U()};this._onheader=X,this._parse(512,X)};vV0.inherits(P7,hV0);P7.prototype.destroy=function($){if(this._destroyed)return;if(this._destroyed=!0,$)this.emit("error",$);if(this.emit("close"),this._stream)this._stream.emit("close")};P7.prototype._parse=function($,Y){if(this._destroyed)return;if(this._offset+=$,this._missing=$,Y===this._onheader)this._partial=!1;this._onparse=Y};P7.prototype._continue=function(){if(this._destroyed)return;var $=this._cb;if(this._cb=gV0,this._overflow)this._write(this._overflow,void 0,$);else $()};P7.prototype._write=function($,Y,z){if(this._destroyed)return;var U=this._stream,Q=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 Y=`rId${++this.count}`;if($.TargetMode)this.stream.write(`<Relationship Id="${Y}" Type="${$.Type}" Target="${OZ1.xmlEncode($.Target)}" TargetMode="${$.TargetMode}"/>`);else this.stream.write(`<Relationship Id="${Y}" Type="${$.Type}" Target="${$.Target}"/>`);return Y}_writeClose(){this.stream.write("</Relationships>")}}GL0.exports=KL0});var VL0=E((Us1,qL0)=>{var HL0=l6(),XL0=e3(),DZ1=i4(),BZ1=fx(),PZ1=bx();class ZL0{constructor($,Y,z){this.id=z.id,this.count=0,this._worksheet=$,this._workbook=z.workbook,this._sheetRelsWriter=Y}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:XL0.Comments,Target:`../comments${this.id}.xml`};this._sheetRelsWriter.addRelationship($);let Y={Type:XL0.VmlDrawing,Target:`../drawings/vmlDrawing${this.id}.vml`};this.vmlRelId=this._sheetRelsWriter.addRelationship(Y)}_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($,Y){let z=new BZ1,U=new HL0;z.render(U,$),this.commentsStream.write(U.xml);let Q=new PZ1,J=new HL0;Q.render(J,$,Y),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((Y)=>{Y.refAddress=DZ1.decodeAddress(Y.ref)}),$.forEach((Y)=>{this._writeComment(Y,this.count),this.count+=1})}}commit(){if(this.count)this._writeClose(),this.commentsStream.end(),this.vmlStream.end()}}qL0.exports=ZL0});var NL0=E((Qs1,OL0)=>{var AZ1=Y6(),TZ1=e3(),Ci=i4(),LL0=Ug(),FL0=$7(),jZ1=wk(),wL0=OM(),Ri=DM(),EZ1=WL0(),CZ1=VL0(),RZ1=Yg(),y6=new jZ1,_i=s3(),_Z1=Zx(),vZ1=qx(),hZ1=Vx(),SZ1=Gx(),gZ1=Ix(),yZ1=Wx(),kZ1=Lx(),xZ1=Fx(),fZ1=wx(),uZ1=Mx(),bZ1=Ox(),iZ1=Nx(),cZ1=Tx(),nZ1=Bx(),pZ1=Dx(),k6={dataValidations:new _Z1,sheetProperties:new vZ1,sheetFormatProperties:new hZ1,columns:new _i({tag:"cols",length:!1,childXform:new SZ1}),row:new gZ1,hyperlinks:new _i({tag:"hyperlinks",length:!1,childXform:new yZ1}),sheetViews:new _i({tag:"sheetViews",length:!1,childXform:new kZ1}),sheetProtection:new xZ1,pageMargins:new fZ1,pageSeteup:new uZ1,autoFilter:new bZ1,picture:new iZ1,conditionalFormattings:new cZ1,headerFooter:new nZ1,rowBreaks:new pZ1};class ML0{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 EZ1($),this._sheetCommentsWriter=new CZ1(this,this._sheetRelsWriter,$),this._dimensions=new FL0,this._rowZero=1,this.committed=!1,this.dataValidations=new RZ1,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
`)},Mf=Nf.getNativePromise();if(Nf.isNode&&typeof MutationObserver>"u")Df=global.setImmediate,Af=process.nextTick,gI=Nf.isRecentNode?function($){Df.call(global,$)}:function($){Af.call(process,$)};else if(typeof Mf==="function"&&typeof Mf.resolve==="function")Pf=Mf.resolve(),gI=function($){Pf.then($)};else if(typeof MutationObserver<"u"&&!(typeof window<"u"&&window.navigator&&(window.navigator.standalone||window.cordova)))gI=function(){var $=document.createElement("div"),I={attributes:!0},z=!1,q=document.createElement("div"),U=new MutationObserver(function(){$.classList.toggle("foo"),z=!1});U.observe(q,I);var Y=function(){if(z)return;z=!0,q.classList.toggle("foo")};return function(Q){var K=new MutationObserver(function(){K.disconnect(),Q()});K.observe($,I),Y()}}();else if(typeof setImmediate<"u")gI=function($){setImmediate($)};else if(typeof setTimeout<"u")gI=function($){setTimeout($,0)};else gI=qN1;var Df,Af,Pf;IO0.exports=gI});var UO0=M((x$4,qO0)=>{function UN1($,I,z,q,U){for(var Y=0;Y<U;++Y)z[Y+q]=$[Y+I],$[Y+I]=void 0}function S7($){this._capacity=$,this._length=0,this._front=0}S7.prototype._willBeOverCapacity=function($){return this._capacity<$};S7.prototype._pushOne=function($){var I=this.length();this._checkCapacity(I+1);var z=this._front+I&this._capacity-1;this[z]=$,this._length=I+1};S7.prototype.push=function($,I,z){var q=this.length()+3;if(this._willBeOverCapacity(q)){this._pushOne($),this._pushOne(I),this._pushOne(z);return}var U=this._front+q-3;this._checkCapacity(q);var Y=this._capacity-1;this[U+0&Y]=$,this[U+1&Y]=I,this[U+2&Y]=z,this._length=q};S7.prototype.shift=function(){var $=this._front,I=this[$];return this[$]=void 0,this._front=$+1&this._capacity-1,this._length--,I};S7.prototype.length=function(){return this._length};S7.prototype._checkCapacity=function($){if(this._capacity<$)this._resizeTo(this._capacity<<1)};S7.prototype._resizeTo=function($){var I=this._capacity;this._capacity=$;var z=this._front,q=this._length,U=z+q&I-1;UN1(this,0,this,I,U)};qO0.exports=S7});var ZO0=M((u$4,Bf)=>{var HO0;try{throw Error()}catch($){HO0=$}var YN1=zO0(),YO0=UO0(),GO0=q4();function D6(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new YO0(16),this._normalQueue=new YO0(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var $=this;this.drainQueues=function(){$._drainQueues()},this._schedule=YN1}D6.prototype.setScheduler=function($){var I=this._schedule;return this._schedule=$,this._customScheduler=!0,I};D6.prototype.hasCustomScheduler=function(){return this._customScheduler};D6.prototype.enableTrampoline=function(){this._trampolineEnabled=!0};D6.prototype.disableTrampolineIfNecessary=function(){if(GO0.hasDevTools)this._trampolineEnabled=!1};D6.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};D6.prototype.fatalError=function($,I){if(I)process.stderr.write("Fatal "+($ instanceof Error?$.stack:$)+`
`),process.exit(2);else this.throwLater($)};D6.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(z){throw Error(`No async scheduler available
`)},oi=ri.getNativePromise();if(ri.isNode&&typeof MutationObserver>"u")si=global.setImmediate,ai=process.nextTick,dz=ri.isRecentNode?function($){si.call(global,$)}:function($){ai.call(process,$)};else if(typeof oi==="function"&&typeof oi.resolve==="function")ti=oi.resolve(),dz=function($){ti.then($)};else if(typeof MutationObserver<"u"&&!(typeof window<"u"&&window.navigator&&(window.navigator.standalone||window.cordova)))dz=function(){var $=document.createElement("div"),Y={attributes:!0},z=!1,U=document.createElement("div"),Q=new MutationObserver(function(){$.classList.toggle("foo"),z=!1});Q.observe(U,Y);var J=function(){if(z)return;z=!0,U.classList.toggle("foo")};return function(K){var G=new MutationObserver(function(){G.disconnect(),K()});G.observe($,Y),J()}}();else if(typeof setImmediate<"u")dz=function($){setImmediate($)};else if(typeof setTimeout<"u")dz=function($){setTimeout($,0)};else dz=yq1;var si,ai,ti;eL0.exports=dz});var zF0=E((Fs1,YF0)=>{function kq1($,Y,z,U,Q){for(var J=0;J<Q;++J)z[J+U]=$[J+Y],$[J+Y]=void 0}function T2($){this._capacity=$,this._length=0,this._front=0}T2.prototype._willBeOverCapacity=function($){return this._capacity<$};T2.prototype._pushOne=function($){var Y=this.length();this._checkCapacity(Y+1);var z=this._front+Y&this._capacity-1;this[z]=$,this._length=Y+1};T2.prototype.push=function($,Y,z){var U=this.length()+3;if(this._willBeOverCapacity(U)){this._pushOne($),this._pushOne(Y),this._pushOne(z);return}var Q=this._front+U-3;this._checkCapacity(U);var J=this._capacity-1;this[Q+0&J]=$,this[Q+1&J]=Y,this[Q+2&J]=z,this._length=U};T2.prototype.shift=function(){var $=this._front,Y=this[$];return this[$]=void 0,this._front=$+1&this._capacity-1,this._length--,Y};T2.prototype.length=function(){return this._length};T2.prototype._checkCapacity=function($){if(this._capacity<$)this._resizeTo(this._capacity<<1)};T2.prototype._resizeTo=function($){var Y=this._capacity;this._capacity=$;var z=this._front,U=this._length,Q=z+U&Y-1;kq1(this,0,this,Y,Q)};YF0.exports=T2});var WF0=E((ws1,ei)=>{var KF0;try{throw Error()}catch($){KF0=$}var xq1=$F0(),UF0=zF0(),GF0=F4();function x6(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new UF0(16),this._normalQueue=new UF0(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var $=this;this.drainQueues=function(){$._drainQueues()},this._schedule=xq1}x6.prototype.setScheduler=function($){var Y=this._schedule;return this._schedule=$,this._customScheduler=!0,Y};x6.prototype.hasCustomScheduler=function(){return this._customScheduler};x6.prototype.enableTrampoline=function(){this._trampolineEnabled=!0};x6.prototype.disableTrampolineIfNecessary=function(){if(GF0.hasDevTools)this._trampolineEnabled=!1};x6.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};x6.prototype.fatalError=function($,Y){if(Y)process.stderr.write("Fatal "+($ instanceof Error?$.stack:$)+`
`),process.exit(2);else this.throwLater($)};x6.prototype.throwLater=function($,Y){if(arguments.length===1)Y=$,$=function(){throw Y};if(typeof setTimeout<"u")setTimeout(function(){$(Y)},0);else try{this._schedule(function(){$(Y)})}catch(z){throw Error(`No async scheduler available
See http://goo.gl/MqrFmX
`)}};function JO0($,I,z){this._lateQueue.push($,I,z),this._queueTick()}function QO0($,I,z){this._normalQueue.push($,I,z),this._queueTick()}function KO0($){this._normalQueue._pushOne($),this._queueTick()}if(!GO0.hasDevTools)D6.prototype.invokeLater=JO0,D6.prototype.invoke=QO0,D6.prototype.settlePromises=KO0;else D6.prototype.invokeLater=function($,I,z){if(this._trampolineEnabled)JO0.call(this,$,I,z);else this._schedule(function(){setTimeout(function(){$.call(I,z)},100)})},D6.prototype.invoke=function($,I,z){if(this._trampolineEnabled)QO0.call(this,$,I,z);else this._schedule(function(){$.call(I,z)})},D6.prototype.settlePromises=function($){if(this._trampolineEnabled)KO0.call(this,$);else this._schedule(function(){$._settlePromises()})};D6.prototype._drainQueue=function($){while($.length()>0){var I=$.shift();if(typeof I!=="function"){I._settlePromises();continue}var z=$.shift(),q=$.shift();I.call(z,q)}};D6.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)};D6.prototype._queueTick=function(){if(!this._isTickUsed)this._isTickUsed=!0,this._schedule(this.drainQueues)};D6.prototype._reset=function(){this._isTickUsed=!1};Bf.exports=D6;Bf.exports.firstLineError=HO0});var d9=M((k$4,VO0)=>{var jf=hI(),JN1=jf.freeze,WO0=q4(),XO0=WO0.inherits,XY=WO0.notEnumerableProp;function VY($,I){function z(q){if(!(this instanceof z))return new z(q);if(XY(this,"message",typeof q==="string"?q:I),XY(this,"name",$),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else Error.call(this)}return XO0(z,Error),z}var Tf,Ef,QN1=VY("Warning","warning"),KN1=VY("CancellationError","cancellation error"),HN1=VY("TimeoutError","timeout error"),BG=VY("AggregateError","aggregate error");try{Tf=TypeError,Ef=RangeError}catch($){Tf=VY("TypeError","type error"),Ef=VY("RangeError","range error")}var lM="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" ");for(SI=0;SI<lM.length;++SI)if(typeof Array.prototype[lM[SI]]==="function")BG.prototype[lM[SI]]=Array.prototype[lM[SI]];var SI;jf.defineProperty(BG.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0});BG.prototype.isOperational=!0;var oM=0;BG.prototype.toString=function(){var $=Array(oM*4+1).join(" "),I=`
`)}};function QF0($,Y,z){this._lateQueue.push($,Y,z),this._queueTick()}function JF0($,Y,z){this._normalQueue.push($,Y,z),this._queueTick()}function IF0($){this._normalQueue._pushOne($),this._queueTick()}if(!GF0.hasDevTools)x6.prototype.invokeLater=QF0,x6.prototype.invoke=JF0,x6.prototype.settlePromises=IF0;else x6.prototype.invokeLater=function($,Y,z){if(this._trampolineEnabled)QF0.call(this,$,Y,z);else this._schedule(function(){setTimeout(function(){$.call(Y,z)},100)})},x6.prototype.invoke=function($,Y,z){if(this._trampolineEnabled)JF0.call(this,$,Y,z);else this._schedule(function(){$.call(Y,z)})},x6.prototype.settlePromises=function($){if(this._trampolineEnabled)IF0.call(this,$);else this._schedule(function(){$._settlePromises()})};x6.prototype._drainQueue=function($){while($.length()>0){var Y=$.shift();if(typeof Y!=="function"){Y._settlePromises();continue}var z=$.shift(),U=$.shift();Y.call(z,U)}};x6.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)};x6.prototype._queueTick=function(){if(!this._isTickUsed)this._isTickUsed=!0,this._schedule(this.drainQueues)};x6.prototype._reset=function(){this._isTickUsed=!1};ei.exports=x6;ei.exports.firstLineError=KF0});var T7=E((Ms1,ZF0)=>{var zc=pz(),fq1=zc.freeze,HF0=F4(),XF0=HF0.inherits,CI=HF0.notEnumerableProp;function RI($,Y){function z(U){if(!(this instanceof z))return new z(U);if(CI(this,"message",typeof U==="string"?U:Y),CI(this,"name",$),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else Error.call(this)}return XF0(z,Error),z}var $c,Yc,uq1=RI("Warning","warning"),bq1=RI("CancellationError","cancellation error"),iq1=RI("TimeoutError","timeout error"),bX=RI("AggregateError","aggregate error");try{$c=TypeError,Yc=RangeError}catch($){$c=RI("TypeError","type error"),Yc=RI("RangeError","range error")}var PB="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" ");for(mz=0;mz<PB.length;++mz)if(typeof Array.prototype[PB[mz]]==="function")bX.prototype[PB[mz]]=Array.prototype[PB[mz]];var mz;zc.defineProperty(bX.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0});bX.prototype.isOperational=!0;var AB=0;bX.prototype.toString=function(){var $=Array(AB*4+1).join(" "),Y=`
`+$+`AggregateError of:
`;oM++,$=Array(oM*4+1).join(" ");for(var z=0;z<this.length;++z){var q=this[z]===this?"[Circular AggregateError]":this[z]+"",U=q.split(`
`);for(var Y=0;Y<U.length;++Y)U[Y]=$+U[Y];q=U.join(`
`),I+=q+`
`}return oM--,I};function PG($){if(!(this instanceof PG))return new PG($);if(XY(this,"name","OperationalError"),XY(this,"message",$),this.cause=$,this.isOperational=!0,$ instanceof Error)XY(this,"message",$.message),XY(this,"stack",$.stack);else if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}XO0(PG,Error);var yI=Error.__BluebirdErrorTypes__;if(!yI)yI=JN1({CancellationError:KN1,TimeoutError:HN1,OperationalError:PG,RejectionError:PG,AggregateError:BG}),jf.defineProperty(Error,"__BluebirdErrorTypes__",{value:yI,writable:!1,enumerable:!1,configurable:!1});VO0.exports={Error,TypeError:Tf,RangeError:Ef,CancellationError:yI.CancellationError,OperationalError:yI.OperationalError,TimeoutError:yI.TimeoutError,AggregateError:yI.AggregateError,Warning:QN1}});var LO0=M((f$4,wO0)=>{wO0.exports=function($,I){var z=q4(),q=z.errorObj,U=z.isObject;function Y(Z,W){if(U(Z)){if(Z instanceof $)return Z;var X=Q(Z);if(X===q){if(W)W._pushContext();var w=$.reject(X.e);if(W)W._popContext();return w}else if(typeof X==="function"){if(H(Z)){var w=new $(I);return Z._then(w._fulfill,w._reject,void 0,w,null),w}return G(Z,X,W)}}return Z}function J(Z){return Z.then}function Q(Z){try{return J(Z)}catch(W){return q.e=W,q}}var K={}.hasOwnProperty;function H(Z){try{return K.call(Z,"_promise0")}catch(W){return!1}}function G(Z,W,X){var w=new $(I),L=w;if(X)X._pushContext();if(w._captureStackTrace(),X)X._popContext();var O=!0,F=z.tryCatch(W).call(Z,D,P);if(O=!1,w&&F===q)w._rejectCallback(F.e,!0,!0),w=null;function D(A){if(!w)return;w._resolveCallback(A),w=null}function P(A){if(!w)return;w._rejectCallback(A,O,!0),w=null}return L}return Y}});var FO0=M((b$4,OO0)=>{OO0.exports=function($,I,z,q,U){var Y=q4(),J=Y.isArray;function Q(H){switch(H){case-2:return[];case-3:return{}}}function K(H){var G=this._promise=new $(I);if(H instanceof $)G._propagateFrom(H,3);G._setOnCancel(this),this._values=H,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return Y.inherits(K,U),K.prototype.length=function(){return this._length},K.prototype.promise=function(){return this._promise},K.prototype._init=function H(G,Z){var W=z(this._values,this._promise);if(W instanceof $){W=W._target();var X=W._bitField;if(this._values=W,(X&50397184)===0)return this._promise._setAsyncGuaranteed(),W._then(H,this._reject,void 0,this,Z);else if((X&33554432)!==0)W=W._value();else if((X&16777216)!==0)return this._reject(W._reason());else return this._cancel()}if(W=Y.asArray(W),W===null){var w=q("expecting an array or an iterable object but got "+Y.classString(W)).reason();this._promise._rejectCallback(w,!1);return}if(W.length===0){if(Z===-5)this._resolveEmptyArray();else this._resolve(Q(Z));return}this._iterate(W)},K.prototype._iterate=function(H){var G=this.getActualLength(H.length);this._length=G,this._values=this.shouldCopyValues()?Array(G):this._values;var Z=this._promise,W=!1,X=null;for(var w=0;w<G;++w){var L=z(H[w],Z);if(L instanceof $)L=L._target(),X=L._bitField;else X=null;if(W){if(X!==null)L.suppressUnhandledRejections()}else if(X!==null)if((X&50397184)===0)L._proxy(this,w),this._values[w]=L;else if((X&33554432)!==0)W=this._promiseFulfilled(L._value(),w);else if((X&16777216)!==0)W=this._promiseRejected(L._reason(),w);else W=this._promiseCancelled(w);else W=this._promiseFulfilled(L,w)}if(!W)Z._setAsyncGuaranteed()},K.prototype._isResolved=function(){return this._values===null},K.prototype._resolve=function(H){this._values=null,this._promise._fulfill(H)},K.prototype._cancel=function(){if(this._isResolved()||!this._promise._isCancellable())return;this._values=null,this._promise._cancel()},K.prototype._reject=function(H){this._values=null,this._promise._rejectCallback(H,!1)},K.prototype._promiseFulfilled=function(H,G){this._values[G]=H;var Z=++this._totalResolved;if(Z>=this._length)return this._resolve(this._values),!0;return!1},K.prototype._promiseCancelled=function(){return this._cancel(),!0},K.prototype._promiseRejected=function(H){return this._totalResolved++,this._reject(H),!0},K.prototype._resultCancelled=function(){if(this._isResolved())return;var H=this._values;if(this._cancel(),H instanceof $)H.cancel();else for(var G=0;G<H.length;++G)if(H[G]instanceof $)H[G].cancel()},K.prototype.shouldCopyValues=function(){return!0},K.prototype.getActualLength=function(H){return H},K}});var NO0=M((i$4,MO0)=>{MO0.exports=function($){var I=!1,z=[];$.prototype._promiseCreated=function(){},$.prototype._pushContext=function(){},$.prototype._popContext=function(){return null},$._peekContext=$.prototype._peekContext=function(){};function q(){this._trace=new q.CapturedTrace(Y())}q.prototype._pushContext=function(){if(this._trace!==void 0)this._trace._promiseCreated=null,z.push(this._trace)},q.prototype._popContext=function(){if(this._trace!==void 0){var J=z.pop(),Q=J._promiseCreated;return J._promiseCreated=null,Q}return null};function U(){if(I)return new q}function Y(){var J=z.length-1;if(J>=0)return z[J];return}return q.CapturedTrace=null,q.create=U,q.deactivateLong Line truncated
`;AB++,$=Array(AB*4+1).join(" ");for(var z=0;z<this.length;++z){var U=this[z]===this?"[Circular AggregateError]":this[z]+"",Q=U.split(`
`);for(var J=0;J<Q.length;++J)Q[J]=$+Q[J];U=Q.join(`
`),Y+=U+`
`}return AB--,Y};function uX($){if(!(this instanceof uX))return new uX($);if(CI(this,"name","OperationalError"),CI(this,"message",$),this.cause=$,this.isOperational=!0,$ instanceof Error)CI(this,"message",$.message),CI(this,"stack",$.stack);else if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}XF0(uX,Error);var lz=Error.__BluebirdErrorTypes__;if(!lz)lz=fq1({CancellationError:bq1,TimeoutError:iq1,OperationalError:uX,RejectionError:uX,AggregateError:bX}),zc.defineProperty(Error,"__BluebirdErrorTypes__",{value:lz,writable:!1,enumerable:!1,configurable:!1});ZF0.exports={Error,TypeError:$c,RangeError:Yc,CancellationError:lz.CancellationError,OperationalError:lz.OperationalError,TimeoutError:lz.TimeoutError,AggregateError:lz.AggregateError,Warning:uq1}});var VF0=E((Os1,qF0)=>{qF0.exports=function($,Y){var z=F4(),U=z.errorObj,Q=z.isObject;function J(X,Z){if(Q(X)){if(X instanceof $)return X;var q=K(X);if(q===U){if(Z)Z._pushContext();var V=$.reject(q.e);if(Z)Z._popContext();return V}else if(typeof q==="function"){if(W(X)){var V=new $(Y);return X._then(V._fulfill,V._reject,void 0,V,null),V}return H(X,q,Z)}}return X}function I(X){return X.then}function K(X){try{return I(X)}catch(Z){return U.e=Z,U}}var G={}.hasOwnProperty;function W(X){try{return G.call(X,"_promise0")}catch(Z){return!1}}function H(X,Z,q){var V=new $(Y),F=V;if(q)q._pushContext();if(V._captureStackTrace(),q)q._popContext();var M=!0,w=z.tryCatch(Z).call(X,O,N);if(M=!1,V&&w===U)V._rejectCallback(w.e,!0,!0),V=null;function O(D){if(!V)return;V._resolveCallback(D),V=null}function N(D){if(!V)return;V._rejectCallback(D,M,!0),V=null}return F}return J}});var FF0=E((Ns1,LF0)=>{LF0.exports=function($,Y,z,U,Q){var J=F4(),I=J.isArray;function K(W){switch(W){case-2:return[];case-3:return{}}}function G(W){var H=this._promise=new $(Y);if(W instanceof $)H._propagateFrom(W,3);H._setOnCancel(this),this._values=W,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return J.inherits(G,Q),G.prototype.length=function(){return this._length},G.prototype.promise=function(){return this._promise},G.prototype._init=function W(H,X){var Z=z(this._values,this._promise);if(Z instanceof $){Z=Z._target();var q=Z._bitField;if(this._values=Z,(q&50397184)===0)return this._promise._setAsyncGuaranteed(),Z._then(W,this._reject,void 0,this,X);else if((q&33554432)!==0)Z=Z._value();else if((q&16777216)!==0)return this._reject(Z._reason());else return this._cancel()}if(Z=J.asArray(Z),Z===null){var V=U("expecting an array or an iterable object but got "+J.classString(Z)).reason();this._promise._rejectCallback(V,!1);return}if(Z.length===0){if(X===-5)this._resolveEmptyArray();else this._resolve(K(X));return}this._iterate(Z)},G.prototype._iterate=function(W){var H=this.getActualLength(W.length);this._length=H,this._values=this.shouldCopyValues()?Array(H):this._values;var X=this._promise,Z=!1,q=null;for(var V=0;V<H;++V){var F=z(W[V],X);if(F instanceof $)F=F._target(),q=F._bitField;else q=null;if(Z){if(q!==null)F.suppressUnhandledRejections()}else if(q!==null)if((q&50397184)===0)F._proxy(this,V),this._values[V]=F;else if((q&33554432)!==0)Z=this._promiseFulfilled(F._value(),V);else if((q&16777216)!==0)Z=this._promiseRejected(F._reason(),V);else Z=this._promiseCancelled(V);else Z=this._promiseFulfilled(F,V)}if(!Z)X._setAsyncGuaranteed()},G.prototype._isResolved=function(){return this._values===null},G.prototype._resolve=function(W){this._values=null,this._promise._fulfill(W)},G.prototype._cancel=function(){if(this._isResolved()||!this._promise._isCancellable())return;this._values=null,this._promise._cancel()},G.prototype._reject=function(W){this._values=null,this._promise._rejectCallback(W,!1)},G.prototype._promiseFulfilled=function(W,H){this._values[H]=W;var X=++this._totalResolved;if(X>=this._length)return this._resolve(this._values),!0;return!1},G.prototype._promiseCancelled=function(){return this._cancel(),!0},G.prototype._promiseRejected=function(W){return this._totalResolved++,this._reject(W),!0},G.prototype._resultCancelled=function(){if(this._isResolved())return;var W=this._values;if(this._cancel(),W instanceof $)W.cancel();else for(var H=0;H<W.length;++H)if(W[H]instanceof $)W[H].cancel()},G.prototype.shouldCopyValues=function(){return!0},G.prototype.getActualLength=function(W){return W},G}});var MF0=E((Ds1,wF0)=>{wF0.exports=function($){var Y=!1,z=[];$.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,z.push(this._trace)},U.prototype._popContext=function(){if(this._trace!==void 0){var I=z.pop(),K=I._promiseCreated;return I._promiseCreated=null,K}return null};function Q(){if(Y)return new U}function J(){var I=z.length-1;if(I>=0)return z[I];return}return U.CapturedTrace=null,U.create=Q,U.deactivateLong Line truncated
See http://goo.gl/MqrFmX
`);if(!C0.longStackTraces&&T8()){var a=$.prototype._captureStackTrace,N=$.prototype._attachExtraTrace;C0.longStackTraces=!0,A=function(){if(q.haveItemsQueued()&&!C0.longStackTraces)throw Error(`cannot enable long stack traces after promises have been created
`);if(!B0.longStackTraces&&f0()){var Q0=$.prototype._captureStackTrace,P=$.prototype._attachExtraTrace;B0.longStackTraces=!0,D=function(){if(U.haveItemsQueued()&&!B0.longStackTraces)throw Error(`cannot enable long stack traces after promises have been created
See http://goo.gl/MqrFmX
`);$.prototype._captureStackTrace=a,$.prototype._attachExtraTrace=N,I.deactivateLongStackTraces(),q.enableTrampoline(),C0.longStackTraces=!1},$.prototype._captureStackTrace=U0,$.prototype._attachExtraTrace=H0,I.activateLongStackTraces(),q.disableTrampolineIfNecessary()}},$.hasLongStackTraces=function(){return C0.longStackTraces&&T8()};var T=function(){try{if(typeof CustomEvent==="function"){var a=new CustomEvent("CustomEvent");return Y.global.dispatchEvent(a),function(N,B){var S=new CustomEvent(N.toLowerCase(),{detail:B,cancelable:!0});return!Y.global.dispatchEvent(S)}}else if(typeof Event==="function"){var a=new Event("CustomEvent");return Y.global.dispatchEvent(a),function(B,S){var n=new Event(B.toLowerCase(),{cancelable:!0});return n.detail=S,!Y.global.dispatchEvent(n)}}else{var a=document.createEvent("CustomEvent");return a.initCustomEvent("testingtheevent",!1,!0,{}),Y.global.dispatchEvent(a),function(B,S){var n=document.createEvent("CustomEvent");return n.initCustomEvent(B.toLowerCase(),!1,!0,S),!Y.global.dispatchEvent(n)}}}catch(N){}return function(){return!1}}(),k=function(){if(Y.isNode)return function(){return process.emit.apply(process,arguments)};else{if(!Y.global)return function(){return!1};return function(a){var N="on"+a.toLowerCase(),B=Y.global[N];if(!B)return!1;return B.apply(Y.global,[].slice.call(arguments,1)),!0}}}();function h(a,N){return{promise:N}}var f={promiseCreated:h,promiseFulfilled:h,promiseRejected:h,promiseResolved:h,promiseCancelled:h,promiseChained:function(a,N,B){return{promise:N,child:B}},warning:function(a,N){return{warning:N}},unhandledRejection:function(a,N,B){return{reason:N,promise:B}},rejectionHandled:h},C=function(a){var N=!1;try{N=k.apply(null,arguments)}catch(S){q.throwLater(S),N=!0}var B=!1;try{B=T(a,f[a].apply(null,arguments))}catch(S){q.throwLater(S),B=!0}return B||N};$.config=function(a){if(a=Object(a),"longStackTraces"in a){if(a.longStackTraces)$.longStackTraces();else if(!a.longStackTraces&&$.hasLongStackTraces())A()}if("warnings"in a){var N=a.warnings;if(C0.warnings=!!N,P=C0.warnings,Y.isObject(N)){if("wForgottenReturn"in N)P=!!N.wForgottenReturn}}if("cancellation"in a&&a.cancellation&&!C0.cancellation){if(q.haveItemsQueued())throw Error("cannot enable cancellation after promises are in use");$.prototype._clearCancellationData=$0,$.prototype._propagateFrom=R,$.prototype._onCancel=y,$.prototype._setOnCancel=c,$.prototype._attachCancellationCallback=v,$.prototype._execute=i,p=R,C0.cancellation=!0}if("monitoring"in a){if(a.monitoring&&!C0.monitoring)C0.monitoring=!0,$.prototype._fireEvent=C;else if(!a.monitoring&&C0.monitoring)C0.monitoring=!1,$.prototype._fireEvent=b}return $};function b(){return!1}$.prototype._fireEvent=b,$.prototype._execute=function(a,N,B){try{a(N,B)}catch(S){return S}},$.prototype._onCancel=function(){},$.prototype._setOnCancel=function(a){},$.prototype._attachCancellationCallback=function(a){},$.prototype._captureStackTrace=function(){},$.prototype._attachExtraTrace=function(){},$.prototype._clearCancellationData=function(){},$.prototype._propagateFrom=function(a,N){};function i(a,N,B){var S=this;try{a(N,B,function(n){if(typeof n!=="function")throw TypeError("onCancel must be a function, got: "+Y.toString(n));S._attachCancellationCallback(n)})}catch(n){return n}}function v(a){if(!this._isCancellable())return this;var N=this._onCancel();if(N!==void 0)if(Y.isArray(N))N.push(a);else this._setOnCancel([N,a]);else this._setOnCancel(a)}function y(){return this._onCancelField}function c(a){this._onCancelField=a}function $0(){this._cancellationParent=void 0,this._onCancelField=void 0}function R(a,N){if((N&1)!==0){this._cancellationParent=a;var B=a._branchesRemainingToCancel;if(B===void 0)B=0;a._branchesRemainingToCancel=B+1}if((N&2)!==0&&a._isBound())this._setBoundTo(a._boundTo)}function u(a,N){if((N&2)!==0&&a._isBound())this._setBoundTo(a._boundTo)}var p=u;function s(){var a=this._boundTo;if(a!==void 0){if(a instanceof $)if(a.isFulfilled())return a.value();else return}return a}function U0(){this._trace=new l8(this._peekContext())}function H0(a,N){if(J(a)){var B=this._trace;if(B!==void 0){if(N)B=B._parent}if(B!==void 0)B.attachExtraTrace(a);else if(!a.__stackCleaned__){var S=k0(a);Y.notEnumerableProp(a,"stack",S.message+`
`+S.stack.join(`
`)),Y.notEnumerableProp(a,"__stackCleaned__",!0)}}}function D0(a,N,B,S,n){if(a===void 0&&N!==null&&P){if(n!==void 0&&n._returnedNonUndefined())return;if((S._bitField&65535)===0)return;if(B)B=B+" ";var I0="",r="";if(N._trace){var z0=N._trace.stack.split(`
`),Q0=o(z0);for(var W0=Q0.length-1;W0>=0;--W0){var g0=Q0[W0];if(!G.test(g0)){var d0=g0.match(Z);if(d0)I0="at "+d0[1]+":"+d0[2]+":"+d0[3]+" ";break}}if(Q0.length>0){var c0=Q0[0];for(var W0=0;W0<z0.length;++W0)if(z0[W0]===c0){if(W0>0)r=`
`+z0[W0-1];break}}}var O1="a promise was created in a "+B+"handler "+I0+"but was not returned from it, see http://goo.gl/rRqMUw"+r;S._warn(O1,!0,N)}}function _0(a,N){var B=a+" is deprecated and will be removed in a future version.";if(N)B+=" Use "+N+" instead.";return Y1(B)}function Y1(a,N,B){if(!C0.warnings)return;var S=new U(a),n;if(N)B._attachExtraTrace(S);else if(C0.longStackTraces&&(n=$._peekContext()))n.attachExtraTrace(S);else{var I0=k0(S);S.stack=I0.message+`
`+I0.stack.join(`
`)}if(!C("warning",S))L1(S,"",!0)}function u0(a,N){for(var B=0;B<N.length-1;++B)N[B].push("From previous event:"),N[B]=N[B].join(`
`);if(B<N.length)N[B]=N[B].join(`
`);return a+`
`+N.join(`
`)}function r0(a){for(var N=0;N<a.length;++N)if(a[N].length===0||N+1<a.length&&a[N][0]===a[N+1][0])a.splice(N,1),N--}function I1(a){var N=a[0];for(var B=1;B<a.length;++B){var S=a[B],n=N.length-1,I0=N[n],r=-1;for(var z0=S.length-1;z0>=0;--z0)if(S[z0]===I0){r=z0;break}for(var z0=r;z0>=0;--z0){var Q0=S[z0];if(N[n]===Q0)N.pop(),n--;else break}N=S}}function o(a){var N=[];for(var B=0;B<a.length;++B){var S=a[B],n=S===" (No stack trace)"||W.test(S),I0=n&&J8(S);if(n&&!I0){if(w&&S.charAt(0)!==" ")S=" "+S;N.push(S)}}return N}function E0(a){var N=a.stack.replace(/\s+$/g,"").split(`
`);for(var B=0;B<N.length;++B){var S=N[B];if(S===" (No stack trace)"||W.test(S))break}if(B>0&&a.name!="SyntaxError")N=N.slice(B);return N}function k0(a){var N=a.stack,B=a.toString();return N=typeof N==="string"&&N.length>0?E0(a):[" (No stack trace)"],{message:B,stack:a.name=="SyntaxError"?N:o(N)}}function L1(a,N,B){if(typeof console<"u"){var S;if(Y.isObject(a)){var n=a.stack;S=N+X(n,a)}else S=N+String(a);if(typeof L==="function")L(S,B);else if(typeof console.log==="function"||typeof console.log==="object")console.log(S)}}function k4(a,N,B,S){var n=!1;try{if(typeof N==="function")if(n=!0,a==="rejectionHandled")N(S);else N(B,S)}catch(I0){q.throwLater(I0)}if(a==="unhandledRejection"){if(!C(a,B,S)&&!n)L1(B,"Unhandled rejection ")}else C(a,S)}function t4(a){var N;if(typeof a==="function")N="[function "+(a.name||"anonymous")+"]";else{N=a&&typeof a.toString==="function"?a.toString():Y.toString(a);var B=/\[object [a-zA-Z0-9$_]+\]/;if(B.test(N))try{var S=JSON.stringify(a);N=S}catch(n){}if(N.length===0)N="(empty array)"}return"(<"+Z$(N)+">, no stack trace)"}function Z$(a){var N=41;if(a.length<N)return a;return a.substr(0,N-3)+"..."}function T8(){return typeof V3==="function"}var J8=function(){return!1},W$=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function m8(a){var N=a.match(W$);if(N)return{fileName:N[1],line:parseInt(N[2],10)}}function J2(a,N){if(!T8())return;var B=a.stack.split(`
`),S=N.stack.split(`
`),n=-1,I0=-1,r,z0;for(var Q0=0;Q0<B.length;++Q0){var W0=m8(B[Q0]);if(W0){r=W0.fileName,n=W0.line;break}}for(var Q0=0;Q0<S.length;++Q0){var W0=m8(S[Q0]);if(W0){z0=W0.fileName,I0=W0.line;break}}if(n<0||I0<0||!r||!z0||r!==z0||n>=I0)return;J8=function(g0){if(H.test(g0))return!0;var d0=m8(g0);if(d0){if(d0.fileName===r&&(n<=d0.line&&d0.line<=I0))return!0}return!1}}function l8(a){this._parent=a,this._promisesCreated=0;var N=this._length=1+(a===void 0?0:a._length);if(V3(this,l8),N>32)this.uncycle()}Y.inherits(l8,Error),I.CapturedTrace=l8,l8.prototype.uncycle=function(){var a=this._length;if(a<2)return;var N=[],B={};for(var S=0,n=this;n!==void 0;++S)N.push(n),n=n._parent;a=this._length=S;for(var S=a-1;S>=0;--S){var I0=N[S].stack;if(B[I0]===void 0)B[I0]=S}for(var S=0;S<a;++S){var r=N[S].stack,z0=B[r];if(z0!==void 0&&z0!==S){if(z0>0)N[z0-1]._parent=void 0,N[z0-1]._length=1;N[S]._parent=void 0,N[S]._length=1;var Q0=S>0?N[S-1]:this;if(z0<a-1)Q0._parent=N[z0+1],Q0._parent.uncycle(),Q0._length=Q0._parent._length+1;else Q0._parent=void 0,Q0._length=1;var W0=Q0._length+1;for(var g0=S-2;g0>=0;--g0)N[g0]._length=W0,W0++;return}}},l8.prototype.attachExtraTrace=function(a){if(a.__stackCleaned__)return;this.uncycle();var N=k0(a),B=N.message,S=[N.stack],n=this;while(n!==void 0)S.push(o(n.stack.split(`
`))),n=n._parent;I1(S),r0(S),Y.notEnumerableProp(a,"stack",u0(B,S)),Y.notEnumerableProp(a,"__stackCleaned__",!0)};var V3=function(){var N=/^\s*at\s*/,B=function(r,z0){if(typeof r==="string")return r;if(z0.name!==void 0&&z0.message!==void 0)return z0.toString();return t4(z0)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6,W=N,X=B;var S=Error.captureStackTrace;return J8=function(r){return H.test(r)},function(r,z0){Error.stackTraceLimit+=6,S(r,z0),Error.stackTraceLimit-=6}}var n=Error();if(typeof n.stack==="string"&&n.stack.split(`
`)[0].indexOf("stackDetection@")>=0)return W=/@/,X=B,w=!0,function(z0){z0.stack=Error().stack};var I0;try{throw Error()}catch(r){I0="stack"in r}if(!("stack"in n)&&I0&&typeof Error.stackTraceLimit==="number")return W=N,X=B,function(z0){Error.stackTraceLimit+=6;try{throw Error()}catch(Q0){z0.stack=Q0.stack}Error.stackTraceLimit-=6};return X=function(r,z0){if(typeof r==="string")return r;if((typeof z0==="object"||typeof z0==="function")&&z0.name!==void 0&&z0.message!==void 0)return z0.toString();return t4(z0)},null}([]);if(typeof console<"u"&&typeof console.warn<"u"){if(L=function(a){console.warn(a)},Y.isNode&&process.stderr.isTTY)L=function(a,N){var B=N?"\x1B[33m":"\x1B[31m";console.warn(B+a+`\x1B[0m
`)};else if(!Y.isNode&&typeof Error().stack==="string")L=function(a,N){console.warn("%c"+a,N?"color: darkorange":"color: red")}}var C0={warnings:F,longStackTraces:!1,cancellation:!1,monitoring:!1};if(D)$.longStackTraces();return{longStackTraces:function(){return C0.longStackTraces},warnings:function(){return C0.warnings},cancellation:function(){return C0.cancellation},monitoring:function(){return C0.monitoring},propagateFromFunction:function(){return p},boundValueFunction:function(){return s},checkForgottenReturns:D0,setBounds:J2,warn:Y1,deprecated:_0,CapturedTrace:l8,fireDomEvent:T,fireGlobalEvent:k}}});var BO0=M((c$4,PO0)=>{PO0.exports=function($,I){var z=q4(),q=$.CancellationError,U=z.errorObj;function Y(Z,W,X){this.promise=Z,this.type=W,this.handler=X,this.called=!1,this.cancelPromise=null}Y.prototype.isFinallyHandler=function(){return this.type===0};function J(Z){this.finallyHandler=Z}J.prototype._resultCancelled=function(){Q(this.finallyHandler)};function Q(Z,W){if(Z.cancelPromise!=null){if(arguments.length>1)Z.cancelPromise._reject(W);else Z.cancelPromise._cancel();return Z.cancelPromise=null,!0}return!1}function K(){return G.call(this,this.promise._target()._settledValue())}function H(Z){if(Q(this,Z))return;return U.e=Z,U}function G(Z){var W=this.promise,X=this.handler;if(!this.called){this.called=!0;var w=this.isFinallyHandler()?X.call(W._boundValue()):X.call(W._boundValue(),Z);if(w!==void 0){W._setReturnedNonUndefined();var L=I(w,W);if(L instanceof $){if(this.cancelPromise!=null){if(L._isCancelled()){var O=new q("late cancellation observer");return W._attachExtraTrace(O),U.e=O,U}else if(L.isPending())L._attachCancellationCallback(new J(this))}return L._then(K,H,void 0,this,void 0)}}}if(W.isRejected())return Q(this),U.e=Z,U;else return Q(this),Z}return $.prototype._passThrough=function(Z,W,X,w){if(typeof Z!=="function")return this.then();return this._then(X,w,void 0,new Y(this,W,Z),void 0)},$.prototype.lastly=$.prototype.finally=function(Z){return this._passThrough(Z,0,G,G)},$.prototype.tap=function(Z){return this._passThrough(Z,1,G)},Y}});var EO0=M((p$4,TO0)=>{TO0.exports=function($){var I=q4(),z=hI().keys,q=I.tryCatch,U=I.errorObj;function Y(J,Q,K){return function(H){var G=K._boundValue();$:for(var Z=0;Z<J.length;++Z){var W=J[Z];if(W===Error||W!=null&&W.prototype instanceof Error){if(H instanceof W)return q(Q).call(G,H)}else if(typeof W==="function"){var X=q(W).call(G,H);if(X===U)return X;else if(X)return q(Q).call(G,H)}else if(I.isObject(H)){var w=z(W);for(var L=0;L<w.length;++L){var O=w[L];if(W[O]!=H[O])continue $}return q(Q).call(G,H)}}return $}}return Y}});var Cf=M((d$4,_O0)=>{var jO0=q4(),GN1=jO0.maybeWrapAsError,ZN1=d9(),WN1=ZN1.OperationalError,CO0=hI();function XN1($){return $ instanceof Error&&CO0.getPrototypeOf($)===Error.prototype}var VN1=/^(?:name|message|stack|cause)$/;function wN1($){var I;if(XN1($)){I=new WN1($),I.name=$.name,I.message=$.message,I.stack=$.stack;var z=CO0.keys($);for(var q=0;q<z.length;++q){var U=z[q];if(!VN1.test(U))I[U]=$[U]}return I}return jO0.markAsOriginatingFromRejection($),$}function LN1($,I){return function(z,q){if($===null)return;if(z){var U=wN1(GN1(z));$._attachExtraTrace(U),$._reject(U)}else if(!I)$._fulfill(q);else{var Y=arguments.length,J=Array(Math.max(Y-1,0));for(var Q=1;Q<Y;++Q)J[Q-1]=arguments[Q];$._fulfill(J)}$=null}}_O0.exports=LN1});var vO0=M((m$4,RO0)=>{RO0.exports=function($,I,z,q,U){var Y=q4(),J=Y.tryCatch;$.method=function(Q){if(typeof Q!=="function")throw new $.TypeError("expecting a function but got "+Y.classString(Q));return function(){var K=new $(I);K._captureStackTrace(),K._pushContext();var H=J(Q).apply(this,arguments),G=K._popContext();return U.checkForgottenReturns(H,G,"Promise.method",K),K._resolveFromSyncValue(H),K}},$.attempt=$.try=function(Q){if(typeof Q!=="function")return q("expecting a function but got "+Y.classString(Q));var K=new $(I);K._captureStackTrace(),K._pushContext();var H;if(arguments.length>1){U.deprecated("calling Promise.try with more than 1 argument");var G=arguments[1],Z=arguments[2];H=Y.isArray(G)?J(Q).apply(Z,G):J(Q).call(Z,G)}else H=J(Q)();var W=K._popContext();return U.checkForgottenReturns(H,W,"Promise.try",K),K._resolveFromSyncValue(H),K},$.prototype._resolveFromSyncValue=function(Q){if(Q===Y.errorObj)this._rejectCallback(Q.e,!1);else this._resolveCallback(Q,!0)}}});var gO0=M((l$4,hO0)=>{hO0.exports=function($,I,z,q){var U=!1,Y=function(H,G){this._reject(G)},J=function(H,G){G.promiseRejectionQueued=!0,G.bindingPromise._then(Y,Y,null,this,H)},Q=function(H,G){if((this._bitField&50397184)===0)this._resolveCallback(G.target)},K=function(H,G){if(!G.promiseRejectionQueued)this._reject(H)};$.prototype.bind=function(H){if(!U)U=!0,$.prototype._propagateFrom=q.propagateFromFunction(),$.prototype._boundValue=q.boundValueFunction();var G=z(H),Z=new $(I);Z._propagateFrom(this,1);var W=this._target();if(Z._setBoundTo(G),G instanceof $){var X={promiseRejectionQueued:!1,promise:Z,target:W,bindingPromise:G};W._then(I,J,voi Line truncated
`);$.prototype._captureStackTrace=Q0,$.prototype._attachExtraTrace=P,Y.deactivateLongStackTraces(),U.enableTrampoline(),B0.longStackTraces=!1},$.prototype._captureStackTrace=g,$.prototype._attachExtraTrace=p,Y.activateLongStackTraces(),U.disableTrampolineIfNecessary()}},$.hasLongStackTraces=function(){return B0.longStackTraces&&f0()};var T=function(){try{if(typeof CustomEvent==="function"){var Q0=new CustomEvent("CustomEvent");return J.global.dispatchEvent(Q0),function(P,v){var u=new CustomEvent(P.toLowerCase(),{detail:v,cancelable:!0});return!J.global.dispatchEvent(u)}}else if(typeof Event==="function"){var Q0=new Event("CustomEvent");return J.global.dispatchEvent(Q0),function(v,u){var r=new Event(v.toLowerCase(),{cancelable:!0});return r.detail=u,!J.global.dispatchEvent(r)}}else{var Q0=document.createEvent("CustomEvent");return Q0.initCustomEvent("testingtheevent",!1,!0,{}),J.global.dispatchEvent(Q0),function(v,u){var r=document.createEvent("CustomEvent");return r.initCustomEvent(v.toLowerCase(),!1,!0,u),!J.global.dispatchEvent(r)}}}catch(P){}return function(){return!1}}(),A=function(){if(J.isNode)return function(){return process.emit.apply(process,arguments)};else{if(!J.global)return function(){return!1};return function(Q0){var P="on"+Q0.toLowerCase(),v=J.global[P];if(!v)return!1;return v.apply(J.global,[].slice.call(arguments,1)),!0}}}();function B(Q0,P){return{promise:P}}var j={promiseCreated:B,promiseFulfilled:B,promiseRejected:B,promiseResolved:B,promiseCancelled:B,promiseChained:function(Q0,P,v){return{promise:P,child:v}},warning:function(Q0,P){return{warning:P}},unhandledRejection:function(Q0,P,v){return{reason:P,promise:v}},rejectionHandled:B},C=function(Q0){var P=!1;try{P=A.apply(null,arguments)}catch(u){U.throwLater(u),P=!0}var v=!1;try{v=T(Q0,j[Q0].apply(null,arguments))}catch(u){U.throwLater(u),v=!0}return v||P};$.config=function(Q0){if(Q0=Object(Q0),"longStackTraces"in Q0){if(Q0.longStackTraces)$.longStackTraces();else if(!Q0.longStackTraces&&$.hasLongStackTraces())D()}if("warnings"in Q0){var P=Q0.warnings;if(B0.warnings=!!P,N=B0.warnings,J.isObject(P)){if("wForgottenReturn"in P)N=!!P.wForgottenReturn}}if("cancellation"in Q0&&Q0.cancellation&&!B0.cancellation){if(U.haveItemsQueued())throw Error("cannot enable cancellation after promises are in use");$.prototype._clearCancellationData=U0,$.prototype._propagateFrom=x,$.prototype._onCancel=i,$.prototype._setOnCancel=c,$.prototype._attachCancellationCallback=h,$.prototype._execute=k,t=x,B0.cancellation=!0}if("monitoring"in Q0){if(Q0.monitoring&&!B0.monitoring)B0.monitoring=!0,$.prototype._fireEvent=C;else if(!Q0.monitoring&&B0.monitoring)B0.monitoring=!1,$.prototype._fireEvent=b}return $};function b(){return!1}$.prototype._fireEvent=b,$.prototype._execute=function(Q0,P,v){try{Q0(P,v)}catch(u){return u}},$.prototype._onCancel=function(){},$.prototype._setOnCancel=function(Q0){},$.prototype._attachCancellationCallback=function(Q0){},$.prototype._captureStackTrace=function(){},$.prototype._attachExtraTrace=function(){},$.prototype._clearCancellationData=function(){},$.prototype._propagateFrom=function(Q0,P){};function k(Q0,P,v){var u=this;try{Q0(P,v,function(r){if(typeof r!=="function")throw TypeError("onCancel must be a function, got: "+J.toString(r));u._attachCancellationCallback(r)})}catch(r){return r}}function h(Q0){if(!this._isCancellable())return this;var P=this._onCancel();if(P!==void 0)if(J.isArray(P))P.push(Q0);else this._setOnCancel([P,Q0]);else this._setOnCancel(Q0)}function i(){return this._onCancelField}function c(Q0){this._onCancelField=Q0}function U0(){this._cancellationParent=void 0,this._onCancelField=void 0}function x(Q0,P){if((P&1)!==0){this._cancellationParent=Q0;var v=Q0._branchesRemainingToCancel;if(v===void 0)v=0;Q0._branchesRemainingToCancel=v+1}if((P&2)!==0&&Q0._isBound())this._setBoundTo(Q0._boundTo)}function d(Q0,P){if((P&2)!==0&&Q0._isBound())this._setBoundTo(Q0._boundTo)}var t=d;function $0(){var Q0=this._boundTo;if(Q0!==void 0){if(Q0 instanceof $)if(Q0.isFulfilled())return Q0.value();else return}return Q0}function g(){this._trace=new u1(this._peekContext())}function p(Q0,P){if(I(Q0)){var v=this._trace;if(v!==void 0){if(P)v=v._parent}if(v!==void 0)v.attachExtraTrace(Q0);else if(!Q0.__stackCleaned__){var u=b0(Q0);J.notEnumerableProp(Q0,"stack",u.message+`
`+u.stack.join(`
`)),J.notEnumerableProp(Q0,"__stackCleaned__",!0)}}}function e(Q0,P,v,u,r){if(Q0===void 0&&P!==null&&N){if(r!==void 0&&r._returnedNonUndefined())return;if((u._bitField&65535)===0)return;if(v)v=v+" ";var X0="",J0="";if(P._trace){var Z0=P._trace.stack.split(`
`),O0=G0(Z0);for(var P0=O0.length-1;P0>=0;--P0){var r0=O0[P0];if(!H.test(r0)){var I1=r0.match(X);if(I1)X0="at "+I1[1]+":"+I1[2]+":"+I1[3]+" ";break}}if(O0.length>0){var U1=O0[0];for(var P0=0;P0<Z0.length;++P0)if(Z0[P0]===U1){if(P0>0)J0=`
`+Z0[P0-1];break}}}var N1="a promise was created in a "+v+"handler "+X0+"but was not returned from it, see http://goo.gl/rRqMUw"+J0;u._warn(N1,!0,P)}}function y(Q0,P){var v=Q0+" is deprecated and will be removed in a future version.";if(P)v+=" Use "+P+" instead.";return s(v)}function s(Q0,P,v){if(!B0.warnings)return;var u=new Q(Q0),r;if(P)v._attachExtraTrace(u);else if(B0.longStackTraces&&(r=$._peekContext()))r.attachExtraTrace(u);else{var X0=b0(u);u.stack=X0.message+`
`+X0.stack.join(`
`)}if(!C("warning",u))Y1(u,"",!0)}function Y0(Q0,P){for(var v=0;v<P.length-1;++v)P[v].push("From previous event:"),P[v]=P[v].join(`
`);if(v<P.length)P[v]=P[v].join(`
`);return Q0+`
`+P.join(`
`)}function M0(Q0){for(var P=0;P<Q0.length;++P)if(Q0[P].length===0||P+1<Q0.length&&Q0[P][0]===Q0[P+1][0])Q0.splice(P,1),P--}function E0(Q0){var P=Q0[0];for(var v=1;v<Q0.length;++v){var u=Q0[v],r=P.length-1,X0=P[r],J0=-1;for(var Z0=u.length-1;Z0>=0;--Z0)if(u[Z0]===X0){J0=Z0;break}for(var Z0=J0;Z0>=0;--Z0){var O0=u[Z0];if(P[r]===O0)P.pop(),r--;else break}P=u}}function G0(Q0){var P=[];for(var v=0;v<Q0.length;++v){var u=Q0[v],r=u===" (No stack trace)"||Z.test(u),X0=r&&u0(u);if(r&&!X0){if(V&&u.charAt(0)!==" ")u=" "+u;P.push(u)}}return P}function T0(Q0){var P=Q0.stack.replace(/\s+$/g,"").split(`
`);for(var v=0;v<P.length;++v){var u=P[v];if(u===" (No stack trace)"||Z.test(u))break}if(v>0&&Q0.name!="SyntaxError")P=P.slice(v);return P}function b0(Q0){var P=Q0.stack,v=Q0.toString();return P=typeof P==="string"&&P.length>0?T0(Q0):[" (No stack trace)"],{message:v,stack:Q0.name=="SyntaxError"?P:G0(P)}}function Y1(Q0,P,v){if(typeof console<"u"){var u;if(J.isObject(Q0)){var r=Q0.stack;u=P+q(r,Q0)}else u=P+String(Q0);if(typeof F==="function")F(u,v);else if(typeof console.log==="function"||typeof console.log==="object")console.log(u)}}function a(Q0,P,v,u){var r=!1;try{if(typeof P==="function")if(r=!0,Q0==="rejectionHandled")P(u);else P(v,u)}catch(X0){U.throwLater(X0)}if(Q0==="unhandledRejection"){if(!C(Q0,v,u)&&!r)Y1(v,"Unhandled rejection ")}else C(Q0,u)}function H0(Q0){var P;if(typeof Q0==="function")P="[function "+(Q0.name||"anonymous")+"]";else{P=Q0&&typeof Q0.toString==="function"?Q0.toString():J.toString(Q0);var v=/\[object [a-zA-Z0-9$_]+\]/;if(v.test(P))try{var u=JSON.stringify(Q0);P=u}catch(r){}if(P.length===0)P="(empty array)"}return"(<"+L0(P)+">, no stack trace)"}function L0(Q0){var P=41;if(Q0.length<P)return Q0;return Q0.substr(0,P-3)+"..."}function f0(){return typeof b1==="function"}var u0=function(){return!1},i0=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function D1(Q0){var P=Q0.match(i0);if(P)return{fileName:P[1],line:parseInt(P[2],10)}}function k1(Q0,P){if(!f0())return;var v=Q0.stack.split(`
`),u=P.stack.split(`
`),r=-1,X0=-1,J0,Z0;for(var O0=0;O0<v.length;++O0){var P0=D1(v[O0]);if(P0){J0=P0.fileName,r=P0.line;break}}for(var O0=0;O0<u.length;++O0){var P0=D1(u[O0]);if(P0){Z0=P0.fileName,X0=P0.line;break}}if(r<0||X0<0||!J0||!Z0||J0!==Z0||r>=X0)return;u0=function(r0){if(W.test(r0))return!0;var I1=D1(r0);if(I1){if(I1.fileName===J0&&(r<=I1.line&&I1.line<=X0))return!0}return!1}}function u1(Q0){this._parent=Q0,this._promisesCreated=0;var P=this._length=1+(Q0===void 0?0:Q0._length);if(b1(this,u1),P>32)this.uncycle()}J.inherits(u1,Error),Y.CapturedTrace=u1,u1.prototype.uncycle=function(){var Q0=this._length;if(Q0<2)return;var P=[],v={};for(var u=0,r=this;r!==void 0;++u)P.push(r),r=r._parent;Q0=this._length=u;for(var u=Q0-1;u>=0;--u){var X0=P[u].stack;if(v[X0]===void 0)v[X0]=u}for(var u=0;u<Q0;++u){var J0=P[u].stack,Z0=v[J0];if(Z0!==void 0&&Z0!==u){if(Z0>0)P[Z0-1]._parent=void 0,P[Z0-1]._length=1;P[u]._parent=void 0,P[u]._length=1;var O0=u>0?P[u-1]:this;if(Z0<Q0-1)O0._parent=P[Z0+1],O0._parent.uncycle(),O0._length=O0._parent._length+1;else O0._parent=void 0,O0._length=1;var P0=O0._length+1;for(var r0=u-2;r0>=0;--r0)P[r0]._length=P0,P0++;return}}},u1.prototype.attachExtraTrace=function(Q0){if(Q0.__stackCleaned__)return;this.uncycle();var P=b0(Q0),v=P.message,u=[P.stack],r=this;while(r!==void 0)u.push(G0(r.stack.split(`
`))),r=r._parent;E0(u),M0(u),J.notEnumerableProp(Q0,"stack",Y0(v,u)),J.notEnumerableProp(Q0,"__stackCleaned__",!0)};var b1=function(){var P=/^\s*at\s*/,v=function(J0,Z0){if(typeof J0==="string")return J0;if(Z0.name!==void 0&&Z0.message!==void 0)return Z0.toString();return H0(Z0)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6,Z=P,q=v;var u=Error.captureStackTrace;return u0=function(J0){return W.test(J0)},function(J0,Z0){Error.stackTraceLimit+=6,u(J0,Z0),Error.stackTraceLimit-=6}}var r=Error();if(typeof r.stack==="string"&&r.stack.split(`
`)[0].indexOf("stackDetection@")>=0)return Z=/@/,q=v,V=!0,function(Z0){Z0.stack=Error().stack};var X0;try{throw Error()}catch(J0){X0="stack"in J0}if(!("stack"in r)&&X0&&typeof Error.stackTraceLimit==="number")return Z=P,q=v,function(Z0){Error.stackTraceLimit+=6;try{throw Error()}catch(O0){Z0.stack=O0.stack}Error.stackTraceLimit-=6};return q=function(J0,Z0){if(typeof J0==="string")return J0;if((typeof Z0==="object"||typeof Z0==="function")&&Z0.name!==void 0&&Z0.message!==void 0)return Z0.toString();return H0(Z0)},null}([]);if(typeof console<"u"&&typeof console.warn<"u"){if(F=function(Q0){console.warn(Q0)},J.isNode&&process.stderr.isTTY)F=function(Q0,P){var v=P?"\x1B[33m":"\x1B[31m";console.warn(v+Q0+`\x1B[0m
`)};else if(!J.isNode&&typeof Error().stack==="string")F=function(Q0,P){console.warn("%c"+Q0,P?"color: darkorange":"color: red")}}var B0={warnings:w,longStackTraces:!1,cancellation:!1,monitoring:!1};if(O)$.longStackTraces();return{longStackTraces:function(){return B0.longStackTraces},warnings:function(){return B0.warnings},cancellation:function(){return B0.cancellation},monitoring:function(){return B0.monitoring},propagateFromFunction:function(){return t},boundValueFunction:function(){return $0},checkForgottenReturns:e,setBounds:k1,warn:s,deprecated:y,CapturedTrace:u1,fireDomEvent:T,fireGlobalEvent:A}}});var BF0=E((Ps1,DF0)=>{DF0.exports=function($,Y){var z=F4(),U=$.CancellationError,Q=z.errorObj;function J(X,Z,q){this.promise=X,this.type=Z,this.handler=q,this.called=!1,this.cancelPromise=null}J.prototype.isFinallyHandler=function(){return this.type===0};function I(X){this.finallyHandler=X}I.prototype._resultCancelled=function(){K(this.finallyHandler)};function K(X,Z){if(X.cancelPromise!=null){if(arguments.length>1)X.cancelPromise._reject(Z);else X.cancelPromise._cancel();return X.cancelPromise=null,!0}return!1}function G(){return H.call(this,this.promise._target()._settledValue())}function W(X){if(K(this,X))return;return Q.e=X,Q}function H(X){var Z=this.promise,q=this.handler;if(!this.called){this.called=!0;var V=this.isFinallyHandler()?q.call(Z._boundValue()):q.call(Z._boundValue(),X);if(V!==void 0){Z._setReturnedNonUndefined();var F=Y(V,Z);if(F instanceof $){if(this.cancelPromise!=null){if(F._isCancelled()){var M=new U("late cancellation observer");return Z._attachExtraTrace(M),Q.e=M,Q}else if(F.isPending())F._attachCancellationCallback(new I(this))}return F._then(G,W,void 0,this,void 0)}}}if(Z.isRejected())return K(this),Q.e=X,Q;else return K(this),X}return $.prototype._passThrough=function(X,Z,q,V){if(typeof X!=="function")return this.then();return this._then(q,V,void 0,new J(this,Z,X),void 0)},$.prototype.lastly=$.prototype.finally=function(X){return this._passThrough(X,0,H,H)},$.prototype.tap=function(X){return this._passThrough(X,1,H)},J}});var AF0=E((As1,PF0)=>{PF0.exports=function($){var Y=F4(),z=pz().keys,U=Y.tryCatch,Q=Y.errorObj;function J(I,K,G){return function(W){var H=G._boundValue();$:for(var X=0;X<I.length;++X){var Z=I[X];if(Z===Error||Z!=null&&Z.prototype instanceof Error){if(W instanceof Z)return U(K).call(H,W)}else if(typeof Z==="function"){var q=U(Z).call(H,W);if(q===Q)return q;else if(q)return U(K).call(H,W)}else if(Y.isObject(W)){var V=z(Z);for(var F=0;F<V.length;++F){var M=V[F];if(Z[M]!=W[M])continue $}return U(K).call(H,W)}}return $}}return J}});var Uc=E((Ts1,EF0)=>{var TF0=F4(),cq1=TF0.maybeWrapAsError,nq1=T7(),pq1=nq1.OperationalError,jF0=pz();function dq1($){return $ instanceof Error&&jF0.getPrototypeOf($)===Error.prototype}var mq1=/^(?:name|message|stack|cause)$/;function lq1($){var Y;if(dq1($)){Y=new pq1($),Y.name=$.name,Y.message=$.message,Y.stack=$.stack;var z=jF0.keys($);for(var U=0;U<z.length;++U){var Q=z[U];if(!mq1.test(Q))Y[Q]=$[Q]}return Y}return TF0.markAsOriginatingFromRejection($),$}function oq1($,Y){return function(z,U){if($===null)return;if(z){var Q=lq1(cq1(z));$._attachExtraTrace(Q),$._reject(Q)}else if(!Y)$._fulfill(U);else{var J=arguments.length,I=Array(Math.max(J-1,0));for(var K=1;K<J;++K)I[K-1]=arguments[K];$._fulfill(I)}$=null}}EF0.exports=oq1});var RF0=E((js1,CF0)=>{CF0.exports=function($,Y,z,U,Q){var J=F4(),I=J.tryCatch;$.method=function(K){if(typeof K!=="function")throw new $.TypeError("expecting a function but got "+J.classString(K));return function(){var G=new $(Y);G._captureStackTrace(),G._pushContext();var W=I(K).apply(this,arguments),H=G._popContext();return Q.checkForgottenReturns(W,H,"Promise.method",G),G._resolveFromSyncValue(W),G}},$.attempt=$.try=function(K){if(typeof K!=="function")return U("expecting a function but got "+J.classString(K));var G=new $(Y);G._captureStackTrace(),G._pushContext();var W;if(arguments.length>1){Q.deprecated("calling Promise.try with more than 1 argument");var H=arguments[1],X=arguments[2];W=J.isArray(H)?I(K).apply(X,H):I(K).call(X,H)}else W=I(K)();var Z=G._popContext();return Q.checkForgottenReturns(W,Z,"Promise.try",G),G._resolveFromSyncValue(W),G},$.prototype._resolveFromSyncValue=function(K){if(K===J.errorObj)this._rejectCallback(K.e,!1);else this._resolveCallback(K,!0)}}});var vF0=E((Es1,_F0)=>{_F0.exports=function($,Y,z,U){var Q=!1,J=function(W,H){this._reject(H)},I=function(W,H){H.promiseRejectionQueued=!0,H.bindingPromise._then(J,J,null,this,W)},K=function(W,H){if((this._bitField&50397184)===0)this._resolveCallback(H.target)},G=function(W,H){if(!H.promiseRejectionQueued)this._reject(W)};$.prototype.bind=function(W){if(!Q)Q=!0,$.prototype._propagateFrom=U.propagateFromFunction(),$.prototype._boundValue=U.boundValueFunction();var H=z(W),X=new $(Y);X._propagateFrom(this,1);var Z=this._target();if(X._setBoundTo(H),H instanceof $){var q={promiseRejectionQueued:!1,promise:X,target:Z,bindingPromise:H};Z._then(Y,I,voi Line truncated
See http://goo.gl/MqrFmX
`);return this._settledValue()},q=I.prototype.error=I.prototype.reason=function(){if(!this.isRejected())throw TypeError(`cannot get rejection reason of a non-rejected promise
`);return this._settledValue()},U=Y.prototype.error=Y.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()},U=I.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0},Y=I.prototype.isRejected=function(){return(this._bitField&16777216)!==0},J=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 J.call(this._target())},$.prototype.isRejected=function(){return Y.call(this._target())},$.prototype.isFulfilled=function(){return U.call(this._target())},$.prototype.isResolved=function(){return Q.call(this._target())},$.prototype.value=function(){return z.call(this._target())},$.prototype.reason=function(){var K=this._target();return K._unsetRejectionIsUnhandled(),q.call(K)},$.prototype._value=function(){return this._settledValue()},$.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},$.PromiseInspection=I}});var iO0=M((t$4,bO0)=>{bO0.exports=function($,I,z,q,U,Y){var J=q4(),Q=J.canEvaluate,K=J.tryCatch,H=J.errorObj,G;if(Q){var Z=function(D){return Function("value","holder",`
`);return this._settledValue()},Q=Y.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0},J=Y.prototype.isRejected=function(){return(this._bitField&16777216)!==0},I=Y.prototype.isPending=function(){return(this._bitField&50397184)===0},K=Y.prototype.isResolved=function(){return(this._bitField&50331648)!==0};Y.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 I.call(this._target())},$.prototype.isRejected=function(){return J.call(this._target())},$.prototype.isFulfilled=function(){return Q.call(this._target())},$.prototype.isResolved=function(){return K.call(this._target())},$.prototype.value=function(){return z.call(this._target())},$.prototype.reason=function(){var G=this._target();return G._unsetRejectionIsUnhandled(),U.call(G)},$.prototype._value=function(){return this._settledValue()},$.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},$.PromiseInspection=Y}});var uF0=E((vs1,fF0)=>{fF0.exports=function($,Y,z,U,Q,J){var I=F4(),K=I.canEvaluate,G=I.tryCatch,W=I.errorObj,H;if(K){var X=function(O){return Function("value","holder",`
'use strict';
holder.pIndex = value;
holder.checkFulfillment(this);
`.replace(/Index/g,D))},W=function(D){return Function("promise","holder",`
`.replace(/Index/g,O))},Z=function(O){return Function("promise","holder",`
'use strict';
holder.pIndex = promise;
`.replace(/Index/g,D))},X=function(D){var P=Array(D);for(var A=0;A<P.length;++A)P[A]="this.p"+(A+1);var T=P.join(" = ")+" = null;",k=`var promise;
`+P.map(function(b){return`
`.replace(/Index/g,O))},q=function(O){var N=Array(O);for(var D=0;D<N.length;++D)N[D]="this.p"+(D+1);var T=N.join(" = ")+" = null;",A=`var promise;
`+N.map(function(b){return`
promise = `+b+`;
if (promise instanceof Promise) {
promise.cancel();
}
`}).join(`
`),h=P.join(", "),f="Holder$"+D,C=`return function(tryCatch, errorObj, Promise, async) {
`),B=N.join(", "),j="Holder$"+O,C=`return function(tryCatch, errorObj, Promise, async) {
'use strict';
function [TheName](fn) {
[TheProperties]
@@ -193,7 +199,7 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof Z6))r
return [TheName];
}(tryCatch, errorObj, Promise, async);
`;return C=C.replace(/\[TheName\]/g,f).replace(/\[TheTotal\]/g,D).replace(/\[ThePassedArguments\]/g,h).replace(/\[TheProperties\]/g,T).replace(/\[CancellationCode\]/g,k),Function("tryCatch","errorObj","Promise","async",C)(K,H,$,U)},w=[],L=[],O=[];for(var F=0;F<8;++F)w.push(X(F+1)),L.push(Z(F+1)),O.push(W(F+1));G=function(D){this._reject(D)}}$.join=function(){var D=arguments.length-1,P;if(D>0&&typeof arguments[D]==="function"){if(P=arguments[D],D<=8&&Q){var c=new $(q);c._captureStackTrace();var A=w[D-1],T=new A(P),k=L;for(var h=0;h<D;++h){var f=z(arguments[h],c);if(f instanceof $){f=f._target();var C=f._bitField;if((C&50397184)===0)f._then(k[h],G,void 0,c,T),O[h](f,T),T.asyncNeeded=!1;else if((C&33554432)!==0)k[h].call(c,f._value(),T);else if((C&16777216)!==0)c._reject(f._reason());else c._cancel()}else k[h].call(c,f,T)}if(!c._isFateSealed()){if(T.asyncNeeded){var b=Y();if(b!==null)T.fn=J.domainBind(b,T.fn)}c._setAsyncGuaranteed(),c._setOnCancel(T)}return c}}var i=arguments.length,v=Array(i);for(var y=0;y<i;++y)v[y]=arguments[y];if(P)v.pop();var c=new I(v).promise();return P!==void 0?c.spread(P):c}}});var cO0=M((a$4,nO0)=>{nO0.exports=function($,I,z,q,U,Y){var J=$._getDomain,Q=q4(),K=Q.tryCatch,H=Q.errorObj,G=$._async;function Z(X,w,L,O){this.constructor$(X),this._promise._captureStackTrace();var F=J();this._callback=F===null?w:Q.domainBind(F,w),this._preservedValues=O===U?Array(this.length()):null,this._limit=L,this._inFlight=0,this._queue=[],G.invoke(this._asyncInit,this,void 0)}Q.inherits(Z,I),Z.prototype._asyncInit=function(){this._init$(void 0,-2)},Z.prototype._init=function(){},Z.prototype._promiseFulfilled=function(X,w){var L=this._values,O=this.length(),F=this._preservedValues,D=this._limit;if(w<0){if(w=w*-1-1,L[w]=X,D>=1){if(this._inFlight--,this._drainQueue(),this._isResolved())return!0}}else{if(D>=1&&this._inFlight>=D)return L[w]=X,this._queue.push(w),!1;if(F!==null)F[w]=X;var P=this._promise,A=this._callback,T=P._boundValue();P._pushContext();var k=K(A).call(T,X,w,O),h=P._popContext();if(Y.checkForgottenReturns(k,h,F!==null?"Promise.filter":"Promise.map",P),k===H)return this._reject(k.e),!0;var f=q(k,this._promise);if(f instanceof $){f=f._target();var C=f._bitField;if((C&50397184)===0){if(D>=1)this._inFlight++;return L[w]=f,f._proxy(this,(w+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[w]=k}var b=++this._totalResolved;if(b>=O){if(F!==null)this._filter(L,F);else this._resolve(L);return!0}return!1},Z.prototype._drainQueue=function(){var X=this._queue,w=this._limit,L=this._values;while(X.length>0&&this._inFlight<w){if(this._isResolved())return;var O=X.pop();this._promiseFulfilled(L[O],O)}},Z.prototype._filter=function(X,w){var L=w.length,O=Array(L),F=0;for(var D=0;D<L;++D)if(X[D])O[F++]=w[D];O.length=F,this._resolve(O)},Z.prototype.preservedValues=function(){return this._preservedValues};function W(X,w,L,O){if(typeof w!=="function")return z("expecting a function but got "+Q.classString(w));var F=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)));F=L.concurrency}else return $.reject(TypeError("options argument must be an object but it is "+Q.classString(L)));return F=typeof F==="number"&&isFinite(F)&&F>=1?F:0,new Z(X,w,F,O).promise()}$.prototype.map=function(X,w){return W(this,X,w,null)},$.map=function(X,w,L,O){return W(X,w,L,O)}}});var dO0=M((e$4,pO0)=>{var _f=Object.create;if(_f)rM=_f(null),sM=_f(null),rM[" size"]=sM[" size"]=0;var rM,sM;pO0.exports=function($){var I=q4(),z=I.canEvaluate,q=I.isIdentifier,U,Y,J=function(X){return Function("ensureMethod",`
`;return C=C.replace(/\[TheName\]/g,j).replace(/\[TheTotal\]/g,O).replace(/\[ThePassedArguments\]/g,B).replace(/\[TheProperties\]/g,T).replace(/\[CancellationCode\]/g,A),Function("tryCatch","errorObj","Promise","async",C)(G,W,$,Q)},V=[],F=[],M=[];for(var w=0;w<8;++w)V.push(q(w+1)),F.push(X(w+1)),M.push(Z(w+1));H=function(O){this._reject(O)}}$.join=function(){var O=arguments.length-1,N;if(O>0&&typeof arguments[O]==="function"){if(N=arguments[O],O<=8&&K){var c=new $(U);c._captureStackTrace();var D=V[O-1],T=new D(N),A=F;for(var B=0;B<O;++B){var j=z(arguments[B],c);if(j instanceof $){j=j._target();var C=j._bitField;if((C&50397184)===0)j._then(A[B],H,void 0,c,T),M[B](j,T),T.asyncNeeded=!1;else if((C&33554432)!==0)A[B].call(c,j._value(),T);else if((C&16777216)!==0)c._reject(j._reason());else c._cancel()}else A[B].call(c,j,T)}if(!c._isFateSealed()){if(T.asyncNeeded){var b=J();if(b!==null)T.fn=I.domainBind(b,T.fn)}c._setAsyncGuaranteed(),c._setOnCancel(T)}return c}}var k=arguments.length,h=Array(k);for(var i=0;i<k;++i)h[i]=arguments[i];if(N)h.pop();var c=new Y(h).promise();return N!==void 0?c.spread(N):c}}});var iF0=E((hs1,bF0)=>{bF0.exports=function($,Y,z,U,Q,J){var I=$._getDomain,K=F4(),G=K.tryCatch,W=K.errorObj,H=$._async;function X(q,V,F,M){this.constructor$(q),this._promise._captureStackTrace();var w=I();this._callback=w===null?V:K.domainBind(w,V),this._preservedValues=M===Q?Array(this.length()):null,this._limit=F,this._inFlight=0,this._queue=[],H.invoke(this._asyncInit,this,void 0)}K.inherits(X,Y),X.prototype._asyncInit=function(){this._init$(void 0,-2)},X.prototype._init=function(){},X.prototype._promiseFulfilled=function(q,V){var F=this._values,M=this.length(),w=this._preservedValues,O=this._limit;if(V<0){if(V=V*-1-1,F[V]=q,O>=1){if(this._inFlight--,this._drainQueue(),this._isResolved())return!0}}else{if(O>=1&&this._inFlight>=O)return F[V]=q,this._queue.push(V),!1;if(w!==null)w[V]=q;var N=this._promise,D=this._callback,T=N._boundValue();N._pushContext();var A=G(D).call(T,q,V,M),B=N._popContext();if(J.checkForgottenReturns(A,B,w!==null?"Promise.filter":"Promise.map",N),A===W)return this._reject(A.e),!0;var j=U(A,this._promise);if(j instanceof $){j=j._target();var C=j._bitField;if((C&50397184)===0){if(O>=1)this._inFlight++;return F[V]=j,j._proxy(this,(V+1)*-1),!1}else if((C&33554432)!==0)A=j._value();else if((C&16777216)!==0)return this._reject(j._reason()),!0;else return this._cancel(),!0}F[V]=A}var b=++this._totalResolved;if(b>=M){if(w!==null)this._filter(F,w);else this._resolve(F);return!0}return!1},X.prototype._drainQueue=function(){var q=this._queue,V=this._limit,F=this._values;while(q.length>0&&this._inFlight<V){if(this._isResolved())return;var M=q.pop();this._promiseFulfilled(F[M],M)}},X.prototype._filter=function(q,V){var F=V.length,M=Array(F),w=0;for(var O=0;O<F;++O)if(q[O])M[w++]=V[O];M.length=w,this._resolve(M)},X.prototype.preservedValues=function(){return this._preservedValues};function Z(q,V,F,M){if(typeof V!=="function")return z("expecting a function but got "+K.classString(V));var w=0;if(F!==void 0)if(typeof F==="object"&&F!==null){if(typeof F.concurrency!=="number")return $.reject(TypeError("'concurrency' must be a number but it is "+K.classString(F.concurrency)));w=F.concurrency}else return $.reject(TypeError("options argument must be an object but it is "+K.classString(F)));return w=typeof w==="number"&&isFinite(w)&&w>=1?w:0,new X(q,V,w,M).promise()}$.prototype.map=function(q,V){return Z(this,q,V,null)},$.map=function(q,V,F,M){return Z(q,V,F,M)}}});var nF0=E((Ss1,cF0)=>{var Qc=Object.create;if(Qc)TB=Qc(null),jB=Qc(null),TB[" size"]=jB[" size"]=0;var TB,jB;cF0.exports=function($){var Y=F4(),z=Y.canEvaluate,U=Y.isIdentifier,Q,J,I=function(q){return Function("ensureMethod",`
return function(obj) {
'use strict'
var len = this.length;
@@ -207,29 +213,29 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof Z6))r
return obj.methodName.apply(obj, this);
}
};
`.replace(/methodName/g,X))(H)},Q=function(X){return Function("obj",`
`.replace(/methodName/g,q))(W)},K=function(q){return Function("obj",`
'use strict';
return obj.propertyName;
`.replace("propertyName",X))},K=function(X,w,L){var O=L[X];if(typeof O!=="function"){if(!q(X))return null;if(O=w(X),L[X]=O,L[" size"]++,L[" size"]>512){var F=Object.keys(L);for(var D=0;D<256;++D)delete L[F[D]];L[" size"]=F.length-256}}return O};U=function(X){return K(X,J,rM)},Y=function(X){return K(X,Q,sM)};function H(X,w){var L;if(X!=null)L=X[w];if(typeof L!=="function"){var O="Object "+I.classString(X)+" has no method '"+I.toString(w)+"'";throw new $.TypeError(O)}return L}function G(X){var w=this.pop(),L=H(X,w);return L.apply(X,this)}$.prototype.call=function(X){var w=arguments.length,L=Array(Math.max(w-1,0));for(var O=1;O<w;++O)L[O-1]=arguments[O];if(z){var F=U(X);if(F!==null)return this._then(F,void 0,void 0,L,void 0)}return L.push(X),this._then(G,void 0,void 0,L,void 0)};function Z(X){return X[this]}function W(X){var w=+this;if(w<0)w=Math.max(0,w+X.length);return X[w]}$.prototype.get=function(X){var w=typeof X==="number",L;if(!w)if(z){var O=Y(X);L=O!==null?O:Z}else L=Z;else L=W;return this._then(L,void 0,void 0,X,void 0)}}});var lO0=M(($54,mO0)=>{mO0.exports=function($,I,z,q,U,Y){var J=q4(),Q=d9().TypeError,K=q4().inherits,H=J.errorObj,G=J.tryCatch,Z={};function W(P){setTimeout(function(){throw P},0)}function X(P){var A=z(P);if(A!==P&&typeof P._isDisposable==="function"&&typeof P._getDisposer==="function"&&P._isDisposable())A._setDisposable(P._getDisposer());return A}function w(P,A){var T=0,k=P.length,h=new $(U);function f(){if(T>=k)return h._fulfill();var C=X(P[T++]);if(C instanceof $&&C._isDisposable()){try{C=z(C._getDisposer().tryDispose(A),P.promise)}catch(b){return W(b)}if(C instanceof $)return C._then(f,W,null,null,null)}f()}return f(),h}function L(P,A,T){this._data=P,this._promise=A,this._context=T}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 Z},L.prototype.tryDispose=function(P){var A=this.resource(),T=this._context;if(T!==void 0)T._pushContext();var k=A!==Z?this.doDispose(A,P):null;if(T!==void 0)T._popContext();return this._promise._unsetDisposable(),this._data=null,k},L.isDisposer=function(P){return P!=null&&typeof P.resource==="function"&&typeof P.tryDispose==="function"};function O(P,A,T){this.constructor$(P,A,T)}K(O,L),O.prototype.doDispose=function(P,A){var T=this.data();return T.call(P,P,A)};function F(P){if(L.isDisposer(P))return this.resources[this.index]._setDisposable(P),P.promise();return P}function D(P){this.length=P,this.promise=null,this[P-1]=null}D.prototype._resultCancelled=function(){var P=this.length;for(var A=0;A<P;++A){var T=this[A];if(T instanceof $)T.cancel()}},$.using=function(){var P=arguments.length;if(P<2)return I("you must pass at least 2 arguments to Promise.using");var A=arguments[P-1];if(typeof A!=="function")return I("expecting a function but got "+J.classString(A));var T,k=!0;if(P===2&&Array.isArray(arguments[0]))T=arguments[0],P=T.length,k=!1;else T=arguments,P--;var h=new D(P);for(var f=0;f<P;++f){var C=T[f];if(L.isDisposer(C)){var b=C;C=C.promise(),C._setDisposable(b)}else{var i=z(C);if(i instanceof $)C=i._then(F,null,null,{resources:h,index:f},void 0)}h[f]=C}var v=Array(h.length);for(var f=0;f<v.length;++f)v[f]=$.resolve(h[f]).reflect();var y=$.all(v).then(function($0){for(var R=0;R<$0.length;++R){var u=$0[R];if(u.isRejected())return H.e=u.error(),H;else if(!u.isFulfilled()){y.cancel();return}$0[R]=u.value()}c._pushContext(),A=G(A);var p=k?A.apply(void 0,$0):A($0),s=c._popContext();return Y.checkForgottenReturns(p,s,"Promise.using",c),p}),c=y.lastly(function(){var $0=new $.PromiseInspection(y);return w(h,$0)});return h.promise=c,c._setOnCancel(h),c},$.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,q());throw new Q}}});var rO0=M((I54,oO0)=>{oO0.exports=function($,I,z){var q=q4(),U=$.TimeoutError;function Y(Z){this.handle=Z}Y.prototype._resultCancelled=function(){clearTimeout(this.handle)};var J=function(Z){return Q(+this).thenReturn(Z)},Q=$.delay=function(Z,W){var X,w;if(W!==void 0){if(X=$.resolve(W)._then(J,null,null,Z,void 0),z.cancellation()&&W instanceof $)X._setOnCancel(W)}else{if(X=new $(I),w=setTimeout(function(){X._fulfill()},+Z),z.cancellation())X._setOnCancel(new Y(w));X._captureStackTrace()}return X._setAsyncGuaranteed(),X};$.prototype.delay=function(Z){return Q(Z,this)};var K=function(Z,W,X){var w;if(typeof W!=="string")if(W instanceof Error)w=W;else w=new U("operation timed out");else w=new U(W);if(q.markAsOriginatingFromRejection(w),Z._attachExtraTrace(w),Z._reject(w),X!=null)X.cancel()};function H(Z){return clearTimeout(this.handle),Z}f Line truncated
`.replace("propertyName",q))},G=function(q,V,F){var M=F[q];if(typeof M!=="function"){if(!U(q))return null;if(M=V(q),F[q]=M,F[" size"]++,F[" size"]>512){var w=Object.keys(F);for(var O=0;O<256;++O)delete F[w[O]];F[" size"]=w.length-256}}return M};Q=function(q){return G(q,I,TB)},J=function(q){return G(q,K,jB)};function W(q,V){var F;if(q!=null)F=q[V];if(typeof F!=="function"){var M="Object "+Y.classString(q)+" has no method '"+Y.toString(V)+"'";throw new $.TypeError(M)}return F}function H(q){var V=this.pop(),F=W(q,V);return F.apply(q,this)}$.prototype.call=function(q){var V=arguments.length,F=Array(Math.max(V-1,0));for(var M=1;M<V;++M)F[M-1]=arguments[M];if(z){var w=Q(q);if(w!==null)return this._then(w,void 0,void 0,F,void 0)}return F.push(q),this._then(H,void 0,void 0,F,void 0)};function X(q){return q[this]}function Z(q){var V=+this;if(V<0)V=Math.max(0,V+q.length);return q[V]}$.prototype.get=function(q){var V=typeof q==="number",F;if(!V)if(z){var M=J(q);F=M!==null?M:X}else F=X;else F=Z;return this._then(F,void 0,void 0,q,void 0)}}});var dF0=E((gs1,pF0)=>{pF0.exports=function($,Y,z,U,Q,J){var I=F4(),K=T7().TypeError,G=F4().inherits,W=I.errorObj,H=I.tryCatch,X={};function Z(N){setTimeout(function(){throw N},0)}function q(N){var D=z(N);if(D!==N&&typeof N._isDisposable==="function"&&typeof N._getDisposer==="function"&&N._isDisposable())D._setDisposable(N._getDisposer());return D}function V(N,D){var T=0,A=N.length,B=new $(Q);function j(){if(T>=A)return B._fulfill();var C=q(N[T++]);if(C instanceof $&&C._isDisposable()){try{C=z(C._getDisposer().tryDispose(D),N.promise)}catch(b){return Z(b)}if(C instanceof $)return C._then(j,Z,null,null,null)}j()}return j(),B}function F(N,D,T){this._data=N,this._promise=D,this._context=T}F.prototype.data=function(){return this._data},F.prototype.promise=function(){return this._promise},F.prototype.resource=function(){if(this.promise().isFulfilled())return this.promise().value();return X},F.prototype.tryDispose=function(N){var D=this.resource(),T=this._context;if(T!==void 0)T._pushContext();var A=D!==X?this.doDispose(D,N):null;if(T!==void 0)T._popContext();return this._promise._unsetDisposable(),this._data=null,A},F.isDisposer=function(N){return N!=null&&typeof N.resource==="function"&&typeof N.tryDispose==="function"};function M(N,D,T){this.constructor$(N,D,T)}G(M,F),M.prototype.doDispose=function(N,D){var T=this.data();return T.call(N,N,D)};function w(N){if(F.isDisposer(N))return this.resources[this.index]._setDisposable(N),N.promise();return N}function O(N){this.length=N,this.promise=null,this[N-1]=null}O.prototype._resultCancelled=function(){var N=this.length;for(var D=0;D<N;++D){var T=this[D];if(T instanceof $)T.cancel()}},$.using=function(){var N=arguments.length;if(N<2)return Y("you must pass at least 2 arguments to Promise.using");var D=arguments[N-1];if(typeof D!=="function")return Y("expecting a function but got "+I.classString(D));var T,A=!0;if(N===2&&Array.isArray(arguments[0]))T=arguments[0],N=T.length,A=!1;else T=arguments,N--;var B=new O(N);for(var j=0;j<N;++j){var C=T[j];if(F.isDisposer(C)){var b=C;C=C.promise(),C._setDisposable(b)}else{var k=z(C);if(k instanceof $)C=k._then(w,null,null,{resources:B,index:j},void 0)}B[j]=C}var h=Array(B.length);for(var j=0;j<h.length;++j)h[j]=$.resolve(B[j]).reflect();var i=$.all(h).then(function(U0){for(var x=0;x<U0.length;++x){var d=U0[x];if(d.isRejected())return W.e=d.error(),W;else if(!d.isFulfilled()){i.cancel();return}U0[x]=d.value()}c._pushContext(),D=H(D);var t=A?D.apply(void 0,U0):D(U0),$0=c._popContext();return J.checkForgottenReturns(t,$0,"Promise.using",c),t}),c=i.lastly(function(){var U0=new $.PromiseInspection(i);return V(B,U0)});return B.promise=c,c._setOnCancel(B),c},$.prototype._setDisposable=function(N){this._bitField=this._bitField|131072,this._disposer=N},$.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(N){if(typeof N==="function")return new M(N,this,U());throw new K}}});var lF0=E((ys1,mF0)=>{mF0.exports=function($,Y,z){var U=F4(),Q=$.TimeoutError;function J(X){this.handle=X}J.prototype._resultCancelled=function(){clearTimeout(this.handle)};var I=function(X){return K(+this).thenReturn(X)},K=$.delay=function(X,Z){var q,V;if(Z!==void 0){if(q=$.resolve(Z)._then(I,null,null,X,void 0),z.cancellation()&&Z instanceof $)q._setOnCancel(Z)}else{if(q=new $(Y),V=setTimeout(function(){q._fulfill()},+X),z.cancellation())q._setOnCancel(new J(V));q._captureStackTrace()}return q._setAsyncGuaranteed(),q};$.prototype.delay=function(X){return K(X,this)};var G=function(X,Z,q){var V;if(typeof Z!=="string")if(Z instanceof Error)V=Z;else V=new Q("operation timed out");else V=new Q(Z);if(U.markAsOriginatingFromRejection(V),X._attachExtraTrace(V),X._reject(V),q!=null)q.cancel()};function W(X){return clearTimeout(this.handle),X Line truncated
See http://goo.gl/MqrFmX
`.replace("%s",O)+`From coroutine:
`.replace("%s",M)+`From coroutine:
`+this._stack.split(`
`).slice(1,-7).join(`
`)));return}}F=F._target();var D=F._bitField;if((D&50397184)===0)this._yieldedPromise=F,F._proxy(this,null);else if((D&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,F._value());else if((D&16777216)!==0)$._async.invoke(this._promiseRejected,this,F._reason());else this._promiseCancelled()}},$.coroutine=function(w,L){if(typeof w!=="function")throw new Q(`generatorFunction must be a function
`)));return}}w=w._target();var O=w._bitField;if((O&50397184)===0)this._yieldedPromise=w,w._proxy(this,null);else if((O&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,w._value());else if((O&16777216)!==0)$._async.invoke(this._promiseRejected,this,w._reason());else this._promiseCancelled()}},$.coroutine=function(V,F){if(typeof V!=="function")throw new K(`generatorFunction must be a function
See http://goo.gl/MqrFmX
`);var O=Object(L).yieldHandler,F=X,D=Error().stack;return function(){var P=w.apply(this,arguments),A=new F(void 0,void 0,O,D),T=A.promise();return A._generator=P,A._promiseFulfilled(void 0),T}},$.coroutine.addYieldHandler=function(w){if(typeof w!=="function")throw new Q("expecting a function but got "+K.classString(w));Z.push(w)},$.spawn=function(w){if(Y.deprecated("Promise.spawn()","Promise.coroutine()"),typeof w!=="function")return I(`generatorFunction must be a function
`);var M=Object(F).yieldHandler,w=q,O=Error().stack;return function(){var N=V.apply(this,arguments),D=new w(void 0,void 0,M,O),T=D.promise();return D._generator=N,D._promiseFulfilled(void 0),T}},$.coroutine.addYieldHandler=function(V){if(typeof V!=="function")throw new K("expecting a function but got "+G.classString(V));X.push(V)},$.spawn=function(V){if(J.deprecated("Promise.spawn()","Promise.coroutine()"),typeof V!=="function")return Y(`generatorFunction must be a function
See http://goo.gl/MqrFmX
`);var L=new X(w,this),O=L.promise();return L._run($.spawn),O}}});var eO0=M((q54,aO0)=>{aO0.exports=function($){var I=q4(),z=$._async,q=I.tryCatch,U=I.errorObj;function Y(K,H){var G=this;if(!I.isArray(K))return J.call(G,K,H);var Z=q(H).apply(G._boundValue(),[null].concat(K));if(Z===U)z.throwLater(Z.e)}function J(K,H){var G=this,Z=G._boundValue(),W=K===void 0?q(H).call(Z,null):q(H).call(Z,null,K);if(W===U)z.throwLater(W.e)}function Q(K,H){var G=this;if(!K){var Z=Error(K+"");Z.cause=K,K=Z}var W=q(H).call(G._boundValue(),K);if(W===U)z.throwLater(W.e)}$.prototype.asCallback=$.prototype.nodeify=function(K,H){if(typeof K=="function"){var G=J;if(H!==void 0&&Object(H).spread)G=Y;this._then(G,Q,void 0,this,K)}return this}}});var IF0=M((U54,$F0)=>{$F0.exports=function($,I){var z={},q=q4(),U=Cf(),Y=q.withAppended,J=q.maybeWrapAsError,Q=q.canEvaluate,K=d9().TypeError,H="Async",G={__isPromisified__:!0},Z=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],W=new RegExp("^(?:"+Z.join("|")+")$"),X=function(y){return q.isIdentifier(y)&&y.charAt(0)!=="_"&&y!=="constructor"};function w(y){return!W.test(y)}function L(y){try{return y.__isPromisified__===!0}catch(c){return!1}}function O(y,c,$0){var R=q.getDataPropertyOrDefault(y,c+$0,G);return R?L(R):!1}function F(y,c,$0){for(var R=0;R<y.length;R+=2){var u=y[R];if($0.test(u)){var p=u.replace($0,"");for(var s=0;s<y.length;s+=2)if(y[s]===p)throw new K(`Cannot promisify an API that has normal methods with '%s'-suffix
`);var F=new q(V,this),M=F.promise();return F._run($.spawn),M}}});var aF0=E((xs1,sF0)=>{sF0.exports=function($){var Y=F4(),z=$._async,U=Y.tryCatch,Q=Y.errorObj;function J(G,W){var H=this;if(!Y.isArray(G))return I.call(H,G,W);var X=U(W).apply(H._boundValue(),[null].concat(G));if(X===Q)z.throwLater(X.e)}function I(G,W){var H=this,X=H._boundValue(),Z=G===void 0?U(W).call(X,null):U(W).call(X,null,G);if(Z===Q)z.throwLater(Z.e)}function K(G,W){var H=this;if(!G){var X=Error(G+"");X.cause=G,G=X}var Z=U(W).call(H._boundValue(),G);if(Z===Q)z.throwLater(Z.e)}$.prototype.asCallback=$.prototype.nodeify=function(G,W){if(typeof G=="function"){var H=I;if(W!==void 0&&Object(W).spread)H=J;this._then(H,K,void 0,this,G)}return this}}});var eF0=E((fs1,tF0)=>{tF0.exports=function($,Y){var z={},U=F4(),Q=Uc(),J=U.withAppended,I=U.maybeWrapAsError,K=U.canEvaluate,G=T7().TypeError,W="Async",H={__isPromisified__:!0},X=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],Z=new RegExp("^(?:"+X.join("|")+")$"),q=function(i){return U.isIdentifier(i)&&i.charAt(0)!=="_"&&i!=="constructor"};function V(i){return!Z.test(i)}function F(i){try{return i.__isPromisified__===!0}catch(c){return!1}}function M(i,c,U0){var x=U.getDataPropertyOrDefault(i,c+U0,H);return x?F(x):!1}function w(i,c,U0){for(var x=0;x<i.length;x+=2){var d=i[x];if(U0.test(d)){var t=d.replace(U0,"");for(var $0=0;$0<i.length;$0+=2)if(i[$0]===t)throw new G(`Cannot promisify an API that has normal methods with '%s'-suffix
See http://goo.gl/MqrFmX
`.replace("%s",c))}}}function D(y,c,$0,R){var u=q.inheritedDataKeys(y),p=[];for(var s=0;s<u.length;++s){var U0=u[s],H0=y[U0],D0=R===X?!0:X(U0,H0,y);if(typeof H0==="function"&&!L(H0)&&!O(y,U0,c)&&R(U0,H0,y,D0))p.push(U0,H0)}return F(p,c,$0),p}var P=function(y){return y.replace(/([$])/,"\\$")},A,T=function(y){var c=[y],$0=Math.max(0,y-1-3);for(var R=y-1;R>=$0;--R)c.push(R);for(var R=y+1;R<=3;++R)c.push(R);return c},k=function(y){return q.filledRange(y,"_arg","")},h=function(y){return q.filledRange(Math.max(y,3),"_arg","")},f=function(y){if(typeof y.length==="number")return Math.max(Math.min(y.length,1024),0);return 0};A=function(y,c,$0,R,u,p){var s=Math.max(0,f(R)-1),U0=T(s),H0=typeof y==="string"||c===z;function D0(r0){var I1=k(r0).join(", "),o=r0>0?", ":"",E0;if(H0)E0=`ret = callback.call(this, {{args}}, nodeback); break;
`;else E0=c===void 0?`ret = callback({{args}}, nodeback); break;
`.replace("%s",c))}}}function O(i,c,U0,x){var d=U.inheritedDataKeys(i),t=[];for(var $0=0;$0<d.length;++$0){var g=d[$0],p=i[g],e=x===q?!0:q(g,p,i);if(typeof p==="function"&&!F(p)&&!M(i,g,c)&&x(g,p,i,e))t.push(g,p)}return w(t,c,U0),t}var N=function(i){return i.replace(/([$])/,"\\$")},D,T=function(i){var c=[i],U0=Math.max(0,i-1-3);for(var x=i-1;x>=U0;--x)c.push(x);for(var x=i+1;x<=3;++x)c.push(x);return c},A=function(i){return U.filledRange(i,"_arg","")},B=function(i){return U.filledRange(Math.max(i,3),"_arg","")},j=function(i){if(typeof i.length==="number")return Math.max(Math.min(i.length,1024),0);return 0};D=function(i,c,U0,x,d,t){var $0=Math.max(0,j(x)-1),g=T($0),p=typeof i==="string"||c===z;function e(M0){var E0=A(M0).join(", "),G0=M0>0?", ":"",T0;if(p)T0=`ret = callback.call(this, {{args}}, nodeback); break;
`;else T0=c===void 0?`ret = callback({{args}}, nodeback); break;
`:`ret = callback.call(receiver, {{args}}, nodeback); break;
`;return E0.replace("{{args}}",I1).replace(", ",o)}function _0(){var r0="";for(var I1=0;I1<U0.length;++I1)r0+="case "+U0[I1]+":"+D0(U0[I1]);return r0+=`
`;return T0.replace("{{args}}",E0).replace(", ",G0)}function y(){var M0="";for(var E0=0;E0<g.length;++E0)M0+="case "+g[E0]+":"+e(g[E0]);return M0+=`
default:
var args = new Array(len + 1);
var i = 0;
@@ -239,15 +245,15 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof Z6))r
args[i] = nodeback;
[CodeForCall]
break;
`.replace("[CodeForCall]",H0?`ret = callback.apply(this, args);
`.replace("[CodeForCall]",p?`ret = callback.apply(this, args);
`:`ret = callback.apply(receiver, args);
`),r0}var Y1=typeof y==="string"?"this != null ? this['"+y+"'] : fn":"fn",u0=`'use strict';
`),M0}var s=typeof i==="string"?"this != null ? this['"+i+"'] : fn":"fn",Y0=`'use strict';
var ret = function (Parameters) {
'use strict';
var len = arguments.length;
var promise = new Promise(INTERNAL);
promise._captureStackTrace();
var nodeback = nodebackForPromise(promise, `+p+`);
var nodeback = nodebackForPromise(promise, `+t+`);
var ret;
var callback = tryCatch([GetFunctionCode]);
switch(len) {
@@ -261,25 +267,25 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof Z6))r
};
notEnumerableProp(ret, '__isPromisified__', true);
return ret;
`.replace("[CodeForSwitchCase]",_0()).replace("[GetFunctionCode]",Y1);return u0=u0.replace("Parameters",h(s)),Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",u0)($,R,c,Y,J,U,q.tryCatch,q.errorObj,q.notEnumerableProp,I)};function C(y,c,$0,R,u,p){var s=function(){return this}(),U0=y;if(typeof U0==="string")y=R;function H0(){var D0=c;if(c===z)D0=this;var _0=new $(I);_0._captureStackTrace();var Y1=typeof U0==="string"&&this!==s?this[U0]:y,u0=U(_0,p);try{Y1.apply(D0,Y(arguments,u0))}catch(r0){_0._rejectCallback(J(r0),!0,!0)}if(!_0._isFateSealed())_0._setAsyncGuaranteed();return _0}return q.notEnumerableProp(H0,"__isPromisified__",!0),H0}var b=Q?A:C;function i(y,c,$0,R,u){var p=new RegExp(P(c)+"$"),s=D(y,c,p,$0);for(var U0=0,H0=s.length;U0<H0;U0+=2){var D0=s[U0],_0=s[U0+1],Y1=D0+c;if(R===b)y[Y1]=b(D0,z,D0,_0,c,u);else{var u0=R(_0,function(){return b(D0,z,D0,_0,c,u)});q.notEnumerableProp(u0,"__isPromisified__",!0),y[Y1]=u0}}return q.toFastProperties(y),y}function v(y,c,$0){return b(y,c,void 0,y,null,$0)}$.promisify=function(y,c){if(typeof y!=="function")throw new K("expecting a function but got "+q.classString(y));if(L(y))return y;c=Object(c);var $0=c.context===void 0?z:c.context,R=!!c.multiArgs,u=v(y,$0,R);return q.copyDescriptors(y,u,w),u},$.promisifyAll=function(y,c){if(typeof y!=="function"&&typeof y!=="object")throw new K(`the target of promisifyAll must be an object or a function
`.replace("[CodeForSwitchCase]",y()).replace("[GetFunctionCode]",s);return Y0=Y0.replace("Parameters",B($0)),Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",Y0)($,x,c,J,I,Q,U.tryCatch,U.errorObj,U.notEnumerableProp,Y)};function C(i,c,U0,x,d,t){var $0=function(){return this}(),g=i;if(typeof g==="string")i=x;function p(){var e=c;if(c===z)e=this;var y=new $(Y);y._captureStackTrace();var s=typeof g==="string"&&this!==$0?this[g]:i,Y0=Q(y,t);try{s.apply(e,J(arguments,Y0))}catch(M0){y._rejectCallback(I(M0),!0,!0)}if(!y._isFateSealed())y._setAsyncGuaranteed();return y}return U.notEnumerableProp(p,"__isPromisified__",!0),p}var b=K?D:C;function k(i,c,U0,x,d){var t=new RegExp(N(c)+"$"),$0=O(i,c,t,U0);for(var g=0,p=$0.length;g<p;g+=2){var e=$0[g],y=$0[g+1],s=e+c;if(x===b)i[s]=b(e,z,e,y,c,d);else{var Y0=x(y,function(){return b(e,z,e,y,c,d)});U.notEnumerableProp(Y0,"__isPromisified__",!0),i[s]=Y0}}return U.toFastProperties(i),i}function h(i,c,U0){return b(i,c,void 0,i,null,U0)}$.promisify=function(i,c){if(typeof i!=="function")throw new G("expecting a function but got "+U.classString(i));if(F(i))return i;c=Object(c);var U0=c.context===void 0?z:c.context,x=!!c.multiArgs,d=h(i,U0,x);return U.copyDescriptors(i,d,V),d},$.promisifyAll=function(i,c){if(typeof i!=="function"&&typeof i!=="object")throw new G(`the target of promisifyAll must be an object or a function
See http://goo.gl/MqrFmX
`);c=Object(c);var $0=!!c.multiArgs,R=c.suffix;if(typeof R!=="string")R=H;var u=c.filter;if(typeof u!=="function")u=X;var p=c.promisifier;if(typeof p!=="function")p=b;if(!q.isIdentifier(R))throw RangeError(`suffix must be a valid identifier
`);c=Object(c);var U0=!!c.multiArgs,x=c.suffix;if(typeof x!=="string")x=W;var d=c.filter;if(typeof d!=="function")d=q;var t=c.promisifier;if(typeof t!=="function")t=b;if(!U.isIdentifier(x))throw RangeError(`suffix must be a valid identifier
See http://goo.gl/MqrFmX
`);var s=q.inheritedDataKeys(y);for(var U0=0;U0<s.length;++U0){var H0=y[s[U0]];if(s[U0]!=="constructor"&&q.isClass(H0))i(H0.prototype,R,u,p,$0),i(H0,R,u,p,$0)}return i(y,R,u,p,$0)}}});var qF0=M((Y54,zF0)=>{zF0.exports=function($,I,z,q){var U=q4(),Y=U.isObject,J=hI(),Q;if(typeof Map==="function")Q=Map;var K=function(){var W=0,X=0;function w(L,O){this[W]=L,this[W+X]=O,W++}return function(O){X=O.size,W=0;var F=Array(O.size*2);return O.forEach(w,F),F}}(),H=function(W){var X=new Q,w=W.length/2|0;for(var L=0;L<w;++L){var O=W[w+L],F=W[L];X.set(O,F)}return X};function G(W){var X=!1,w;if(Q!==void 0&&W instanceof Q)w=K(W),X=!0;else{var L=J.keys(W),O=L.length;w=Array(O*2);for(var F=0;F<O;++F){var D=L[F];w[F]=W[D],w[F+O]=D}}this.constructor$(w),this._isMap=X,this._init$(void 0,-3)}U.inherits(G,I),G.prototype._init=function(){},G.prototype._promiseFulfilled=function(W,X){this._values[X]=W;var w=++this._totalResolved;if(w>=this._length){var L;if(this._isMap)L=H(this._values);else{L={};var O=this.length();for(var F=0,D=this.length();F<D;++F)L[this._values[F+O]]=this._values[F]}return this._resolve(L),!0}return!1},G.prototype.shouldCopyValues=function(){return!1},G.prototype.getActualLength=function(W){return W>>1};function Z(W){var X,w=z(W);if(!Y(w))return q(`cannot await properties of a non-object
`);var $0=U.inheritedDataKeys(i);for(var g=0;g<$0.length;++g){var p=i[$0[g]];if($0[g]!=="constructor"&&U.isClass(p))k(p.prototype,x,d,t,U0),k(p,x,d,t,U0)}return k(i,x,d,t,U0)}}});var Yw0=E((us1,$w0)=>{$w0.exports=function($,Y,z,U){var Q=F4(),J=Q.isObject,I=pz(),K;if(typeof Map==="function")K=Map;var G=function(){var Z=0,q=0;function V(F,M){this[Z]=F,this[Z+q]=M,Z++}return function(M){q=M.size,Z=0;var w=Array(M.size*2);return M.forEach(V,w),w}}(),W=function(Z){var q=new K,V=Z.length/2|0;for(var F=0;F<V;++F){var M=Z[V+F],w=Z[F];q.set(M,w)}return q};function H(Z){var q=!1,V;if(K!==void 0&&Z instanceof K)V=G(Z),q=!0;else{var F=I.keys(Z),M=F.length;V=Array(M*2);for(var w=0;w<M;++w){var O=F[w];V[w]=Z[O],V[w+M]=O}}this.constructor$(V),this._isMap=q,this._init$(void 0,-3)}Q.inherits(H,Y),H.prototype._init=function(){},H.prototype._promiseFulfilled=function(Z,q){this._values[q]=Z;var V=++this._totalResolved;if(V>=this._length){var F;if(this._isMap)F=W(this._values);else{F={};var M=this.length();for(var w=0,O=this.length();w<O;++w)F[this._values[w+M]]=this._values[w]}return this._resolve(F),!0}return!1},H.prototype.shouldCopyValues=function(){return!1},H.prototype.getActualLength=function(Z){return Z>>1};function X(Z){var q,V=z(Z);if(!J(V))return U(`cannot await properties of a non-object
See http://goo.gl/MqrFmX
`);else if(w instanceof $)X=w._then($.props,void 0,void 0,void 0,void 0);else X=new G(w).promise();if(w instanceof $)X._propagateFrom(w,2);return X}$.prototype.props=function(){return Z(this)},$.props=function(W){return Z(W)}}});var YF0=M((J54,UF0)=>{UF0.exports=function($,I,z,q){var U=q4(),Y=function(Q){return Q.then(function(K){return J(K,Q)})};function J(Q,K){var H=z(Q);if(H instanceof $)return Y(H);else if(Q=U.asArray(Q),Q===null)return q("expecting an array or an iterable object but got "+U.classString(Q));var G=new $(I);if(K!==void 0)G._propagateFrom(K,3);var{_fulfill:Z,_reject:W}=G;for(var X=0,w=Q.length;X<w;++X){var L=Q[X];if(L===void 0&&!(X in Q))continue;$.cast(L)._then(Z,W,void 0,G,null)}return G}$.race=function(Q){return J(Q,void 0)},$.prototype.race=function(){return J(this,void 0)}}});var QF0=M((Q54,JF0)=>{JF0.exports=function($,I,z,q,U,Y){var J=$._getDomain,Q=q4(),K=Q.tryCatch;function H(w,L,O,F){this.constructor$(w);var D=J();if(this._fn=D===null?L:Q.domainBind(D,L),O!==void 0)O=$.resolve(O),O._attachCancellationCallback(this);if(this._initialValue=O,this._currentCancellable=null,F===U)this._eachValues=Array(this._length);else if(F===0)this._eachValues=null;else this._eachValues=void 0;this._promise._captureStackTrace(),this._init$(void 0,-5)}Q.inherits(H,I),H.prototype._gotAccum=function(w){if(this._eachValues!==void 0&&this._eachValues!==null&&w!==U)this._eachValues.push(w)},H.prototype._eachComplete=function(w){if(this._eachValues!==null)this._eachValues.push(w);return this._eachValues},H.prototype._init=function(){},H.prototype._resolveEmptyArray=function(){this._resolve(this._eachValues!==void 0?this._eachValues:this._initialValue)},H.prototype.shouldCopyValues=function(){return!1},H.prototype._resolve=function(w){this._promise._resolveCallback(w),this._values=null},H.prototype._resultCancelled=function(w){if(w===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()},H.prototype._iterate=function(w){this._values=w;var L,O,F=w.length;if(this._initialValue!==void 0)L=this._initialValue,O=0;else L=$.resolve(w[0]),O=1;if(this._currentCancellable=L,!L.isRejected())for(;O<F;++O){var D={accum:null,value:w[O],index:O,length:F,array:this};L=L._then(W,void 0,void 0,D,void 0)}if(this._eachValues!==void 0)L=L._then(this._eachComplete,void 0,void 0,this,void 0);L._then(G,G,void 0,L,this)},$.prototype.reduce=function(w,L){return Z(this,w,L,null)},$.reduce=function(w,L,O,F){return Z(w,L,O,F)};function G(w,L){if(this.isFulfilled())L._resolve(w);else L._reject(w)}function Z(w,L,O,F){if(typeof L!=="function")return z("expecting a function but got "+Q.classString(L));var D=new H(w,L,O,F);return D.promise()}function W(w){this.accum=w,this.array._gotAccum(w);var L=q(this.value,this.array._promise);if(L instanceof $)return this.array._currentCancellable=L,L._then(X,void 0,void 0,this,void 0);else return X.call(this,L)}function X(w){var L=this.array,O=L._promise,F=K(L._fn);O._pushContext();var D;if(L._eachValues!==void 0)D=F.call(O._boundValue(),w,this.index,this.length);else D=F.call(O._boundValue(),this.accum,w,this.index,this.length);if(D instanceof $)L._currentCancellable=D;var P=O._popContext();return Y.checkForgottenReturns(D,P,L._eachValues!==void 0?"Promise.each":"Promise.reduce",O),D}}});var HF0=M((K54,KF0)=>{KF0.exports=function($,I,z){var q=$.PromiseInspection,U=q4();function Y(J){this.constructor$(J)}U.inherits(Y,I),Y.prototype._promiseResolved=function(J,Q){this._values[J]=Q;var K=++this._totalResolved;if(K>=this._length)return this._resolve(this._values),!0;return!1},Y.prototype._promiseFulfilled=function(J,Q){var K=new q;return K._bitField=33554432,K._settledValueField=J,this._promiseResolved(Q,K)},Y.prototype._promiseRejected=function(J,Q){var K=new q;return K._bitField=16777216,K._settledValueField=J,this._promiseResolved(Q,K)},$.settle=function(J){return z.deprecated(".settle()",".reflect()"),new Y(J).promise()},$.prototype.settle=function(){return $.settle(this)}}});var ZF0=M((H54,GF0)=>{GF0.exports=function($,I,z){var q=q4(),U=d9().RangeError,Y=d9().AggregateError,J=q.isArray,Q={};function K(G){this.constructor$(G),this._howMany=0,this._unwrap=!1,this._initialized=!1}q.inherits(K,I),K.prototype._init=function(){if(!this._initialized)return;if(this._howMany===0){this._resolve([]);return}this._init$(void 0,-5);var G=J(this._values);if(!this._isResolved()&&G&&this._howMany>this._canPossiblyFulfill())this._reject(this._getRangeError(this.length()))},K.prototype.init=function(){this._initialized=!0,this._init()},K.prototype.setUnwrap=function(){this._unwrap=!0},K.prototype.howMany=function(){return this._howMany},K.prototype.setHowMany=function(G){this._howMany=G},K.prototype._promiseFulfilled=function(G){if(this._addFulfilled(G),this._fulfilled()===this.howMany()){if(this._values.length=this.howMany(),this.howMany()= Line truncated
`);else if(V instanceof $)q=V._then($.props,void 0,void 0,void 0,void 0);else q=new H(V).promise();if(V instanceof $)q._propagateFrom(V,2);return q}$.prototype.props=function(){return X(this)},$.props=function(Z){return X(Z)}}});var Uw0=E((bs1,zw0)=>{zw0.exports=function($,Y,z,U){var Q=F4(),J=function(K){return K.then(function(G){return I(G,K)})};function I(K,G){var W=z(K);if(W instanceof $)return J(W);else if(K=Q.asArray(K),K===null)return U("expecting an array or an iterable object but got "+Q.classString(K));var H=new $(Y);if(G!==void 0)H._propagateFrom(G,3);var{_fulfill:X,_reject:Z}=H;for(var q=0,V=K.length;q<V;++q){var F=K[q];if(F===void 0&&!(q in K))continue;$.cast(F)._then(X,Z,void 0,H,null)}return H}$.race=function(K){return I(K,void 0)},$.prototype.race=function(){return I(this,void 0)}}});var Jw0=E((is1,Qw0)=>{Qw0.exports=function($,Y,z,U,Q,J){var I=$._getDomain,K=F4(),G=K.tryCatch;function W(V,F,M,w){this.constructor$(V);var O=I();if(this._fn=O===null?F:K.domainBind(O,F),M!==void 0)M=$.resolve(M),M._attachCancellationCallback(this);if(this._initialValue=M,this._currentCancellable=null,w===Q)this._eachValues=Array(this._length);else if(w===0)this._eachValues=null;else this._eachValues=void 0;this._promise._captureStackTrace(),this._init$(void 0,-5)}K.inherits(W,Y),W.prototype._gotAccum=function(V){if(this._eachValues!==void 0&&this._eachValues!==null&&V!==Q)this._eachValues.push(V)},W.prototype._eachComplete=function(V){if(this._eachValues!==null)this._eachValues.push(V);return this._eachValues},W.prototype._init=function(){},W.prototype._resolveEmptyArray=function(){this._resolve(this._eachValues!==void 0?this._eachValues:this._initialValue)},W.prototype.shouldCopyValues=function(){return!1},W.prototype._resolve=function(V){this._promise._resolveCallback(V),this._values=null},W.prototype._resultCancelled=function(V){if(V===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()},W.prototype._iterate=function(V){this._values=V;var F,M,w=V.length;if(this._initialValue!==void 0)F=this._initialValue,M=0;else F=$.resolve(V[0]),M=1;if(this._currentCancellable=F,!F.isRejected())for(;M<w;++M){var O={accum:null,value:V[M],index:M,length:w,array:this};F=F._then(Z,void 0,void 0,O,void 0)}if(this._eachValues!==void 0)F=F._then(this._eachComplete,void 0,void 0,this,void 0);F._then(H,H,void 0,F,this)},$.prototype.reduce=function(V,F){return X(this,V,F,null)},$.reduce=function(V,F,M,w){return X(V,F,M,w)};function H(V,F){if(this.isFulfilled())F._resolve(V);else F._reject(V)}function X(V,F,M,w){if(typeof F!=="function")return z("expecting a function but got "+K.classString(F));var O=new W(V,F,M,w);return O.promise()}function Z(V){this.accum=V,this.array._gotAccum(V);var F=U(this.value,this.array._promise);if(F instanceof $)return this.array._currentCancellable=F,F._then(q,void 0,void 0,this,void 0);else return q.call(this,F)}function q(V){var F=this.array,M=F._promise,w=G(F._fn);M._pushContext();var O;if(F._eachValues!==void 0)O=w.call(M._boundValue(),V,this.index,this.length);else O=w.call(M._boundValue(),this.accum,V,this.index,this.length);if(O instanceof $)F._currentCancellable=O;var N=M._popContext();return J.checkForgottenReturns(O,N,F._eachValues!==void 0?"Promise.each":"Promise.reduce",M),O}}});var Kw0=E((cs1,Iw0)=>{Iw0.exports=function($,Y,z){var U=$.PromiseInspection,Q=F4();function J(I){this.constructor$(I)}Q.inherits(J,Y),J.prototype._promiseResolved=function(I,K){this._values[I]=K;var G=++this._totalResolved;if(G>=this._length)return this._resolve(this._values),!0;return!1},J.prototype._promiseFulfilled=function(I,K){var G=new U;return G._bitField=33554432,G._settledValueField=I,this._promiseResolved(K,G)},J.prototype._promiseRejected=function(I,K){var G=new U;return G._bitField=16777216,G._settledValueField=I,this._promiseResolved(K,G)},$.settle=function(I){return z.deprecated(".settle()",".reflect()"),new J(I).promise()},$.prototype.settle=function(){return $.settle(this)}}});var Ww0=E((ns1,Gw0)=>{Gw0.exports=function($,Y,z){var U=F4(),Q=T7().RangeError,J=T7().AggregateError,I=U.isArray,K={};function G(H){this.constructor$(H),this._howMany=0,this._unwrap=!1,this._initialized=!1}U.inherits(G,Y),G.prototype._init=function(){if(!this._initialized)return;if(this._howMany===0){this._resolve([]);return}this._init$(void 0,-5);var H=I(this._values);if(!this._isResolved()&&H&&this._howMany>this._canPossiblyFulfill())this._reject(this._getRangeError(this.length()))},G.prototype.init=function(){this._initialized=!0,this._init()},G.prototype.setUnwrap=function(){this._unwrap=!0},G.prototype.howMany=function(){return this._howMany},G.prototype.setHowMany=function(H){this._howMany=H},G.prototype._promiseFulfilled=function(H){if(this._addFulfilled(H),this._fulfilled()===this.howMany()){if(this._values.length=this.howMany(),this.howMany()= Line truncated
See http://goo.gl/MqrFmX
`);var W=new K(G),X=W.promise();return W.setHowMany(Z),W.init(),X}$.some=function(G,Z){return H(G,Z)},$.prototype.some=function(G){return H(this,G)},$._SomePromiseArray=K}});var XF0=M((G54,WF0)=>{WF0.exports=function($,I){var z=$.map;$.prototype.filter=function(q,U){return z(this,q,U,I)},$.filter=function(q,U,Y){return z(q,U,Y,I)}}});var wF0=M((Z54,VF0)=>{VF0.exports=function($,I){var{reduce:z,all:q}=$;function U(){return q(this)}function Y(J,Q){return z(J,Q,I,I)}$.prototype.each=function(J){return z(this,J,I,0)._then(U,void 0,void 0,this,void 0)},$.prototype.mapSeries=function(J){return z(this,J,I,I)},$.each=function(J,Q){return z(J,Q,I,0)._then(U,void 0,void 0,J,void 0)},$.mapSeries=Y}});var OF0=M((W54,LF0)=>{LF0.exports=function($){var I=$._SomePromiseArray;function z(q){var U=new I(q),Y=U.promise();return U.setHowMany(1),U.setUnwrap(),U.init(),Y}$.any=function(q){return z(q)},$.prototype.any=function(){return z(this)}}});var FF0=M((X54,Rf)=>{Rf.exports=function(){var $=function(){return new Z(`circular promise resolution chain
`);var Z=new G(H),q=Z.promise();return Z.setHowMany(X),Z.init(),q}$.some=function(H,X){return W(H,X)},$.prototype.some=function(H){return W(this,H)},$._SomePromiseArray=G}});var Xw0=E((ps1,Hw0)=>{Hw0.exports=function($,Y){var z=$.map;$.prototype.filter=function(U,Q){return z(this,U,Q,Y)},$.filter=function(U,Q,J){return z(U,Q,J,Y)}}});var qw0=E((ds1,Zw0)=>{Zw0.exports=function($,Y){var{reduce:z,all:U}=$;function Q(){return U(this)}function J(I,K){return z(I,K,Y,Y)}$.prototype.each=function(I){return z(this,I,Y,0)._then(Q,void 0,void 0,this,void 0)},$.prototype.mapSeries=function(I){return z(this,I,Y,Y)},$.each=function(I,K){return z(I,K,Y,0)._then(Q,void 0,void 0,I,void 0)},$.mapSeries=J}});var Lw0=E((ms1,Vw0)=>{Vw0.exports=function($){var Y=$._SomePromiseArray;function z(U){var Q=new Y(U),J=Q.promise();return Q.setHowMany(1),Q.setUnwrap(),Q.init(),J}$.any=function(U){return z(U)},$.prototype.any=function(){return z(this)}}});var Fw0=E((ls1,Jc)=>{Jc.exports=function(){var $=function(){return new X(`circular promise resolution chain
See http://goo.gl/MqrFmX
`)},I=function(){return new v.PromiseInspection(this._target())},z=function(R){return v.reject(new Z(R))};function q(){}var U={},Y=q4(),J;if(Y.isNode)J=function(){var R=process.domain;if(R===void 0)R=null;return R};else J=function(){return null};Y.notEnumerableProp(v,"_getDomain",J);var Q=hI(),K=ZO0(),H=new K;Q.defineProperty(v,"_async",{value:H});var G=d9(),Z=v.TypeError=G.TypeError;v.RangeError=G.RangeError;var W=v.CancellationError=G.CancellationError;v.TimeoutError=G.TimeoutError,v.OperationalError=G.OperationalError,v.RejectionError=G.OperationalError,v.AggregateError=G.AggregateError;var X=function(){},w={},L={},O=LO0()(v,X),F=FO0()(v,X,O,z,q),D=NO0()(v),P=D.create,A=AO0()(v,D),T=A.CapturedTrace,k=BO0()(v,O),h=EO0()(L),f=Cf(),C=Y.errorObj,b=Y.tryCatch;function i(R,u){if(typeof u!=="function")throw new Z("expecting a function but got "+Y.classString(u));if(R.constructor!==v)throw new Z(`the promise constructor cannot be invoked directly
`)},Y=function(){return new h.PromiseInspection(this._target())},z=function(x){return h.reject(new X(x))};function U(){}var Q={},J=F4(),I;if(J.isNode)I=function(){var x=process.domain;if(x===void 0)x=null;return x};else I=function(){return null};J.notEnumerableProp(h,"_getDomain",I);var K=pz(),G=WF0(),W=new G;K.defineProperty(h,"_async",{value:W});var H=T7(),X=h.TypeError=H.TypeError;h.RangeError=H.RangeError;var Z=h.CancellationError=H.CancellationError;h.TimeoutError=H.TimeoutError,h.OperationalError=H.OperationalError,h.RejectionError=H.OperationalError,h.AggregateError=H.AggregateError;var q=function(){},V={},F={},M=VF0()(h,q),w=FF0()(h,q,M,z,U),O=MF0()(h),N=O.create,D=NF0()(h,O),T=D.CapturedTrace,A=BF0()(h,M),B=AF0()(F),j=Uc(),C=J.errorObj,b=J.tryCatch;function k(x,d){if(typeof d!=="function")throw new X("expecting a function but got "+J.classString(d));if(x.constructor!==h)throw new X(`the promise constructor cannot be invoked directly
See http://goo.gl/MqrFmX
`)}function v(R){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,R!==X)i(this,R),this._resolveFromExecutor(R);this._promiseCreated(),this._fireEvent("promiseCreated",this)}v.prototype.toString=function(){return"[object Promise]"},v.prototype.caught=v.prototype.catch=function(R){var u=arguments.length;if(u>1){var p=Array(u-1),s=0,U0;for(U0=0;U0<u-1;++U0){var H0=arguments[U0];if(Y.isObject(H0))p[s++]=H0;else return z("expecting an object but got A catch statement predicate "+Y.classString(H0))}return p.length=s,R=arguments[U0],this.then(void 0,h(p,R,this))}return this.then(void 0,R)},v.prototype.reflect=function(){return this._then(I,I,void 0,this,void 0)},v.prototype.then=function(R,u){if(A.warnings()&&arguments.length>0&&typeof R!=="function"&&typeof u!=="function"){var p=".then() only accepts functions but was passed: "+Y.classString(R);if(arguments.length>1)p+=", "+Y.classString(u);this._warn(p)}return this._then(R,u,void 0,void 0,void 0)},v.prototype.done=function(R,u){var p=this._then(R,u,void 0,void 0,void 0);p._setIsFinal()},v.prototype.spread=function(R){if(typeof R!=="function")return z("expecting a function but got "+Y.classString(R));return this.all()._then(R,void 0,void 0,w,void 0)},v.prototype.toJSON=function(){var R={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())R.fulfillmentValue=this.value(),R.isFulfilled=!0;else if(this.isRejected())R.rejectionReason=this.reason(),R.isRejected=!0;return R},v.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new F(this).promise()},v.prototype.error=function(R){return this.caught(Y.originatesFromRejection,R)},v.getNewLibraryCopy=Rf.exports,v.is=function(R){return R instanceof v},v.fromNode=v.fromCallback=function(R){var u=new v(X);u._captureStackTrace();var p=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,s=b(R)(f(u,p));if(s===C)u._rejectCallback(s.e,!0);if(!u._isFateSealed())u._setAsyncGuaranteed();return u},v.all=function(R){return new F(R).promise()},v.cast=function(R){var u=O(R);if(!(u instanceof v))u=new v(X),u._captureStackTrace(),u._setFulfilled(),u._rejectionHandler0=R;return u},v.resolve=v.fulfilled=v.cast,v.reject=v.rejected=function(R){var u=new v(X);return u._captureStackTrace(),u._rejectCallback(R,!0),u},v.setScheduler=function(R){if(typeof R!=="function")throw new Z("expecting a function but got "+Y.classString(R));return H.setScheduler(R)},v.prototype._then=function(R,u,p,s,U0){var H0=U0!==void 0,D0=H0?U0:new v(X),_0=this._target(),Y1=_0._bitField;if(!H0){if(D0._propagateFrom(this,3),D0._captureStackTrace(),s===void 0&&(this._bitField&2097152)!==0)if((Y1&50397184)!==0)s=this._boundValue();else s=_0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,D0)}var u0=J();if((Y1&50397184)!==0){var r0,I1,o=_0._settlePromiseCtx;if((Y1&33554432)!==0)I1=_0._rejectionHandler0,r0=R;else if((Y1&16777216)!==0)I1=_0._fulfillmentHandler0,r0=u,_0._unsetRejectionIsUnhandled();else o=_0._settlePromiseLateCancellationObserver,I1=new W("late cancellation observer"),_0._attachExtraTrace(I1),r0=u;H.invoke(o,_0,{handler:u0===null?r0:typeof r0==="function"&&Y.domainBind(u0,r0),promise:D0,receiver:s,value:I1})}else _0._addCallbacks(R,u,D0,s,u0);return D0},v.prototype._length=function(){return this._bitField&65535},v.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},v.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},v.prototype._setLength=function(R){this._bitField=this._bitField&-65536|R&65535},v.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},v.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},v.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},v.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},v.prototype._isFinal=function(){return(this._bitField&4194304)>0},v.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},v.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},v.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},v.prototype._setAsyncGuaranteed=function(){if(H.hasCustomScheduler())return;this._bitField=this._bitField|134217728},v.prototype._receiverAt=function(R){var u=R===0?this._receiver0:this[R*4-4+3];if(u===U)return;else if(u===void 0&&this._isBound())return this._boundValue();return u},v.prototype._promiseAt=function(R){return this[R*4-4+2]},v.prototype._fulfillmentHandlerAt=function(R){return this[R*4-4+0]},v.prototype._rejectionHandlerAt=function(R){return this[R*4-4+1]},v.prototype._boundValue=function(){},v.prototype._migrateCallback0=function(R){var{_bitFie Line truncated
`)}function h(x){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,x!==q)k(this,x),this._resolveFromExecutor(x);this._promiseCreated(),this._fireEvent("promiseCreated",this)}h.prototype.toString=function(){return"[object Promise]"},h.prototype.caught=h.prototype.catch=function(x){var d=arguments.length;if(d>1){var t=Array(d-1),$0=0,g;for(g=0;g<d-1;++g){var p=arguments[g];if(J.isObject(p))t[$0++]=p;else return z("expecting an object but got A catch statement predicate "+J.classString(p))}return t.length=$0,x=arguments[g],this.then(void 0,B(t,x,this))}return this.then(void 0,x)},h.prototype.reflect=function(){return this._then(Y,Y,void 0,this,void 0)},h.prototype.then=function(x,d){if(D.warnings()&&arguments.length>0&&typeof x!=="function"&&typeof d!=="function"){var t=".then() only accepts functions but was passed: "+J.classString(x);if(arguments.length>1)t+=", "+J.classString(d);this._warn(t)}return this._then(x,d,void 0,void 0,void 0)},h.prototype.done=function(x,d){var t=this._then(x,d,void 0,void 0,void 0);t._setIsFinal()},h.prototype.spread=function(x){if(typeof x!=="function")return z("expecting a function but got "+J.classString(x));return this.all()._then(x,void 0,void 0,V,void 0)},h.prototype.toJSON=function(){var x={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())x.fulfillmentValue=this.value(),x.isFulfilled=!0;else if(this.isRejected())x.rejectionReason=this.reason(),x.isRejected=!0;return x},h.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new w(this).promise()},h.prototype.error=function(x){return this.caught(J.originatesFromRejection,x)},h.getNewLibraryCopy=Jc.exports,h.is=function(x){return x instanceof h},h.fromNode=h.fromCallback=function(x){var d=new h(q);d._captureStackTrace();var t=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,$0=b(x)(j(d,t));if($0===C)d._rejectCallback($0.e,!0);if(!d._isFateSealed())d._setAsyncGuaranteed();return d},h.all=function(x){return new w(x).promise()},h.cast=function(x){var d=M(x);if(!(d instanceof h))d=new h(q),d._captureStackTrace(),d._setFulfilled(),d._rejectionHandler0=x;return d},h.resolve=h.fulfilled=h.cast,h.reject=h.rejected=function(x){var d=new h(q);return d._captureStackTrace(),d._rejectCallback(x,!0),d},h.setScheduler=function(x){if(typeof x!=="function")throw new X("expecting a function but got "+J.classString(x));return W.setScheduler(x)},h.prototype._then=function(x,d,t,$0,g){var p=g!==void 0,e=p?g:new h(q),y=this._target(),s=y._bitField;if(!p){if(e._propagateFrom(this,3),e._captureStackTrace(),$0===void 0&&(this._bitField&2097152)!==0)if((s&50397184)!==0)$0=this._boundValue();else $0=y===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,e)}var Y0=I();if((s&50397184)!==0){var M0,E0,G0=y._settlePromiseCtx;if((s&33554432)!==0)E0=y._rejectionHandler0,M0=x;else if((s&16777216)!==0)E0=y._fulfillmentHandler0,M0=d,y._unsetRejectionIsUnhandled();else G0=y._settlePromiseLateCancellationObserver,E0=new Z("late cancellation observer"),y._attachExtraTrace(E0),M0=d;W.invoke(G0,y,{handler:Y0===null?M0:typeof M0==="function"&&J.domainBind(Y0,M0),promise:e,receiver:$0,value:E0})}else y._addCallbacks(x,d,e,$0,Y0);return e},h.prototype._length=function(){return this._bitField&65535},h.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},h.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},h.prototype._setLength=function(x){this._bitField=this._bitField&-65536|x&65535},h.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},h.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},h.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},h.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},h.prototype._isFinal=function(){return(this._bitField&4194304)>0},h.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},h.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},h.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},h.prototype._setAsyncGuaranteed=function(){if(W.hasCustomScheduler())return;this._bitField=this._bitField|134217728},h.prototype._receiverAt=function(x){var d=x===0?this._receiver0:this[x*4-4+3];if(d===Q)return;else if(d===void 0&&this._isBound())return this._boundValue();return d},h.prototype._promiseAt=function(x){return this[x*4-4+2]},h.prototype._fulfillmentHandlerAt=function(x){return this[x*4-4+0]},h.prototype._rejectionHandlerAt=function(x){return this[x*4-4+1]},h.prototype._boundValue=function(){},h.prototype._migrateCallback0=function(x){var{_bitField:d,_fulfillmentHandler Line truncated
path = %s
syscall = %s
fstream_type = %s
@@ -288,22 +294,26 @@ fstream_unc_path = %s
fstream_class = %s
fstream_stack =
%s
`,I||"UNKNOWN",q.stack,q.path,q.syscall,q.fstream_type,q.fstream_path,q.fstream_unc_path,q.fstream_class,q.fstream_stack.join(`
`));else z.emit("warn",q)};u7.prototype.info=function($,I){this.emit("info",$,I)};u7.prototype.error=function($,I,z){var q=tM0($,I,this);if(z)throw q;else this.emit("error",q)};function tM0($,I,z){if(!($ instanceof Error))$=Error($);if($.code=$.code||I,$.path=$.path||z.path,$.fstream_type=$.fstream_type||z.type,$.fstream_path=$.fstream_path||z.path,z._path!==z.path)$.fstream_unc_path=$.fstream_unc_path||z._path;if(z.linkpath)$.fstream_linkpath=$.fstream_linkpath||z.linkpath;return $.fstream_class=$.fstream_class||z.constructor.name,$.fstream_stack=$.fstream_stack||Error().stack.split(/\n/).slice(3).map(function(q){return q.replace(/^ {4}at /,"")}),$}});var lG=M((c54,eM0)=>{eM0.exports=rA1;function rA1($){var I=["Directory","File","SymbolicLink","Link","BlockDevice","CharacterDevice","FIFO","Socket"],z;if($.type&&I.indexOf($.type)!==-1)return $[$.type]=!0,$.type;for(var q=0,U=I.length;q<U;q++){z=I[q];var Y=$[z]||$["is"+z];if(typeof Y==="function")Y=Y.call($);if(Y)return $[z]=!0,$.type=z,z}return null}});var Ob=M((p54,$N0)=>{$N0.exports=oG;var sA1=b8(),tA1=n0(),Lb=iI();tA1(oG,Lb);function oG($){var I=this;if(!(I instanceof oG))throw Error("LinkReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="SymbolicLink"&&$.SymbolicLink))throw Error("Non-link type "+$.type);Lb.call(I,$)}oG.prototype._stat=function($){var I=this;sA1.readlink(I._path,function(z,q){if(z)return I.error(z);I.linkpath=I.props.linkpath=q,I.emit("linkpath",q),Lb.prototype._stat.call(I,$)})};oG.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var Mb=M((d54,qN0)=>{qN0.exports=s5;var zN0=b8(),aA1=n0(),rG=d("path"),Fb=iI(),IN0=d("assert").ok;aA1(s5,Fb);function s5($){var I=this;if(!(I instanceof s5))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;Fb.call(this,$)}s5.prototype._getEntries=function(){var $=this;if($._gotEntries)return;$._gotEntries=!0,zN0.readdir($._path,function(I,z){if(I)return $.error(I);if($.entries=z,$.emit("entries",z),$._paused)$.once("resume",q);else q();function q(){if($._length=$.entries.length,typeof $.sort==="function")$.entries=$.entries.sort($.sort.bind($));$._read()}})};s5.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=rG.resolve($._path,$.entries[$._index]);IN0(I!==$._path),IN0($.entries[$._index]),$._currentEntry=I,zN0[$.props.follow?"stat":"lstat"](I,function(z,q){if(z)return $.error(z);var U=$._proxy||$;q.path=I,q.basename=rG.basename(I),q.dirname=rG.dirname(I);var Y=$.getChildProps.call(U,q);Y.path=I,Y.basename=rG.basename(I),Y.dirname=rG.dirname(I);var J=Fb(Y,q);$._currentEntry=J,J.on("pause",function(H){if(!$._paused&&!J._disowned)$.pause(H)}),J.on("resume",function(H){if($._paused&&!J._disowned)$.resume(H)}),J.on("stat",function(H){if($.emit("_entryStat",J,H),J._aborted)return;if(J._paused)J.once("resume",function(){$.emit("entryStat",J,H)});else $.emit("entryStat",J,H)}),J.on("ready",function H(){if($._paused)return J.pause($),$.once("resume",H);if(J.type==="Socket")$.emit("socket",J);else $.emitEntry(J)});var Q=!1;J.on("close",K),J.on("disown",K);function K(){if(Q)return;if(Q=!0,$.emit("childEnd",J),$.emit("entryEnd",J),$._currentEntry=null,!$._paused)$._read()}J.on("error",function(H){if(J._swallowErrors)$.warn(H),J.emit("end"),J.emit("close");else $.emit("error",H)}),["child","childEnd","warn"].forEach(function(H){J.on(H,$.emit.bind($,H))})})};s5.prototype.disown=function($){if($.emit("beforeDisown"),$._disowned=!0,$.parent=$.root=null,$===this._currentEntry)this._currentEntry=null;$.emit("disown")};s5.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}};s5.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",$)};s5.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()};s5.prototype.emitEntry=function($){this.emit("entry",$),this.emit("child",$)}});var Nb=M((m54,QN0)=>{QN0.exports=nI;var eA1=b8(),$P1=n0(),UN0=iI(),YN0={EOF:!0},JN0={CLOSE:!0};$P1(nI,UN0);function nI($){var I=this;if(!(I instanceof nI))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,UN0.call(I,$)}nI.prototype._getStream=function(){var $=this,I=$._stream=eA1.createReadStream($._path,$.pro Line truncated
`,Y||"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 z.emit("warn",U)};C2.prototype.info=function($,Y){this.emit("info",$,Y)};C2.prototype.error=function($,Y,z){var U=rM0($,Y,this);if(z)throw U;else this.emit("error",U)};function rM0($,Y,z){if(!($ instanceof Error))$=Error($);if($.code=$.code||Y,$.path=$.path||z.path,$.fstream_type=$.fstream_type||z.type,$.fstream_path=$.fstream_path||z.path,z._path!==z.path)$.fstream_unc_path=$.fstream_unc_path||z._path;if(z.linkpath)$.fstream_linkpath=$.fstream_linkpath||z.linkpath;return $.fstream_class=$.fstream_class||z.constructor.name,$.fstream_stack=$.fstream_stack||Error().stack.split(/\n/).slice(3).map(function(U){return U.replace(/^ {4}at /,"")}),$}});var WZ=E((Pa1,aM0)=>{aM0.exports=EF1;function EF1($){var Y=["Directory","File","SymbolicLink","Link","BlockDevice","CharacterDevice","FIFO","Socket"],z;if($.type&&Y.indexOf($.type)!==-1)return $[$.type]=!0,$.type;for(var U=0,Q=Y.length;U<Q;U++){z=Y[U];var J=$[z]||$["is"+z];if(typeof J==="function")J=J.call($);if(J)return $[z]=!0,$.type=z,z}return null}});var dc=E((Aa1,tM0)=>{tM0.exports=HZ;var CF1=l8(),RF1=X1(),pc=ez();RF1(HZ,pc);function HZ($){var Y=this;if(!(Y instanceof HZ))throw Error("LinkReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="SymbolicLink"&&$.SymbolicLink))throw Error("Non-link type "+$.type);pc.call(Y,$)}HZ.prototype._stat=function($){var Y=this;CF1.readlink(Y._path,function(z,U){if(z)return Y.error(z);Y.linkpath=Y.props.linkpath=U,Y.emit("linkpath",U),pc.prototype._stat.call(Y,$)})};HZ.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var lc=E((Ta1,YO0)=>{YO0.exports=w9;var $O0=l8(),_F1=X1(),XZ=I0("path"),mc=ez(),eM0=I0("assert").ok;_F1(w9,mc);function w9($){var Y=this;if(!(Y instanceof w9))throw Error("DirReader must be called as constructor.");if($.type!=="Directory"||!$.Directory)throw Error("Non-directory type "+$.type);if(Y.entries=null,Y._index=-1,Y._paused=!1,Y._length=-1,$.sort)this.sort=$.sort;mc.call(this,$)}w9.prototype._getEntries=function(){var $=this;if($._gotEntries)return;$._gotEntries=!0,$O0.readdir($._path,function(Y,z){if(Y)return $.error(Y);if($.entries=z,$.emit("entries",z),$._paused)$.once("resume",U);else U();function U(){if($._length=$.entries.length,typeof $.sort==="function")$.entries=$.entries.sort($.sort.bind($));$._read()}})};w9.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 Y=XZ.resolve($._path,$.entries[$._index]);eM0(Y!==$._path),eM0($.entries[$._index]),$._currentEntry=Y,$O0[$.props.follow?"stat":"lstat"](Y,function(z,U){if(z)return $.error(z);var Q=$._proxy||$;U.path=Y,U.basename=XZ.basename(Y),U.dirname=XZ.dirname(Y);var J=$.getChildProps.call(Q,U);J.path=Y,J.basename=XZ.basename(Y),J.dirname=XZ.dirname(Y);var I=mc(J,U);$._currentEntry=I,I.on("pause",function(W){if(!$._paused&&!I._disowned)$.pause(W)}),I.on("resume",function(W){if($._paused&&!I._disowned)$.resume(W)}),I.on("stat",function(W){if($.emit("_entryStat",I,W),I._aborted)return;if(I._paused)I.once("resume",function(){$.emit("entryStat",I,W)});else $.emit("entryStat",I,W)}),I.on("ready",function W(){if($._paused)return I.pause($),$.once("resume",W);if(I.type==="Socket")$.emit("socket",I);else $.emitEntry(I)});var K=!1;I.on("close",G),I.on("disown",G);function G(){if(K)return;if(K=!0,$.emit("childEnd",I),$.emit("entryEnd",I),$._currentEntry=null,!$._paused)$._read()}I.on("error",function(W){if(I._swallowErrors)$.warn(W),I.emit("end"),I.emit("close");else $.emit("error",W)}),["child","childEnd","warn"].forEach(function(W){I.on(W,$.emit.bind($,W))})})};w9.prototype.disown=function($){if($.emit("beforeDisown"),$._disowned=!0,$.parent=$.root=null,$===this._currentEntry)this._currentEntry=null;$.emit("disown")};w9.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}};w9.prototype.pause=function($){var Y=this;if(Y._paused)return;if($=$||Y,Y._paused=!0,Y._currentEntry&&Y._currentEntry.pause)Y._currentEntry.pause($);Y.emit("pause",$)};w9.prototype.resume=function($){var Y=this;if(!Y._paused)return;if($=$||Y,Y._paused=!1,Y.emit("resume",$),Y._paused)return;if(Y._currentEntry){if(Y._currentEntry.resume)Y._currentEntry.resume($)}else Y._read()};w9.prototype.emitEntry=function($){this.emit("entry",$),this.emit("child",$)}});var oc=E((ja1,JO0)=>{JO0.exports=$U;var vF1=l8(),hF1=X1(),zO0=ez(),UO0={EOF:!0},QO0={CLOSE:!0};hF1($U,zO0);function $U($){var Y=this;if(!(Y instanceof $U))throw Error("FileReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="File"&&$.File))throw Error("Non-file type "+$.type);Y._buffer=[],Y._bytesEmitted=0,zO0.call(Y,$)}$U.prototype._getStream=function(){var $=this,Y=$._stream=vF1.createReadStream($._path,$.p Line truncated
expect: `+$.props.size+`
actual: `+$._bytesEmitted)}),I.on("close",function(){if($._paused||$._buffer.length)$._buffer.push(JN0),$._read();else $.emit("close")}),I.on("error",function(z){$.emit("error",z)}),$._read()};nI.prototype._read=function(){var $=this;if($._paused)return;if(!$._stream)return $._getStream();if($._buffer.length){var I=$._buffer;for(var z=0,q=I.length;z<q;z++){var U=I[z];if(U===YN0)$.emit("end");else if(U===JN0)$.emit("close");else $.emit("data",U);if($._paused){$._buffer=I.slice(z);return}}$._buffer.length=0}};nI.prototype.pause=function($){var I=this;if(I._paused)return;if($=$||I,I._paused=!0,I._stream)I._stream.pause();I.emit("pause",$)};nI.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 GN0=M((l54,HN0)=>{HN0.exports=AN;var IP1=n0(),KN0=iI();IP1(AN,KN0);function AN($){var I=this;if(!(I instanceof AN))throw Error("SocketReader must be called as constructor.");if(!($.type==="Socket"&&$.Socket))throw Error("Non-socket type "+$.type);KN0.call(I,$)}AN.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var Ab=M((o54,ZN0)=>{ZN0.exports=cI;var Db=iI(),zP1=lG(),qP1=n0(),UP1=b8();qP1(cI,Db);function cI($){var I=this;if(!(I instanceof cI))throw Error("ProxyReader must be called as constructor.");I.props=$,I._buffer=[],I.ready=!1,Db.call(I,$)}cI.prototype._stat=function(){var $=this,I=$.props,z=I.follow?"stat":"lstat";UP1[z](I.path,function(q,U){var Y;if(q||!U)Y="File";else Y=zP1(U);I[Y]=!0,I.type=$.type=Y,$._old=U,$._addProxy(Db(I,U))})};cI.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(q){$.on(q,I.emit.bind(I,q))}),I.emit("proxy",$),$.on("ready",function(){I.ready=!0,I.emit("ready")});var z=I._buffer;I._buffer.length=0,z.forEach(function(q){$[q[0]].apply($,q[1])})};cI.prototype.pause=function(){return this._proxyTarget?this._proxyTarget.pause():!1};cI.prototype.resume=function(){return this._proxyTarget?this._proxyTarget.resume():!1}});var iI=M((r54,VN0)=>{VN0.exports=Z5;var YP1=b8(),JP1=d("stream").Stream,QP1=n0(),Pb=d("path"),Bb=lG(),PN=Z5.hardLinks={},WN0=DN();QP1(Z5,WN0);var XN0=Ob();function Z5($,I){var z=this;if(!(z instanceof Z5))return new Z5($,I);if(typeof $==="string")$={path:$};var q,U;if($.type&&typeof $.type==="function")q=$.type,U=q;else q=Bb($),U=Z5;if(I&&!q)q=Bb(I),$[q]=!0,$.type=q;switch(q){case"Directory":U=Mb();break;case"Link":case"File":U=Nb();break;case"SymbolicLink":U=XN0;break;case"Socket":U=GN0();break;case null:U=Ab();break}if(!(z instanceof U))return new U($);if(WN0.call(z),!$.path)z.error("Must provide a path",null,!0);if(z.readable=!0,z.writable=!1,z.type=q,z.props=$,z.depth=$.depth=$.depth||0,z.parent=$.parent||null,z.root=$.root||$.parent&&$.parent.root||z,z._path=z.path=Pb.resolve($.path),process.platform==="win32"){if(z.path=z._path=z.path.replace(/\?/g,"_"),z._path.length>=260)z._swallowErrors=!0,z._path="\\\\?\\"+z.path.replace(/\//g,"\\")}if(z.basename=$.basename=Pb.basename(z.path),z.dirname=$.dirname=Pb.dirname(z.path),$.parent=$.root=null,z.size=$.size,z.filter=typeof $.filter==="function"?$.filter:null,$.sort==="alpha")$.sort=KP1;z._stat(I)}function KP1($,I){return $===I?0:$.toLowerCase()>I.toLowerCase()?1:$.toLowerCase()<I.toLowerCase()?-1:$>I?1:-1}Z5.prototype._stat=function($){var I=this,z=I.props,q=z.follow?"stat":"lstat";if($)process.nextTick(U.bind(null,null,$));else YP1[q](I._path,U);function U(Y,J){if(Y)return I.error(Y);if(Object.keys(J).forEach(function(X){z[X]=J[X]}),I.size!==void 0&&z.size!==I.size)return I.error("incorrect size");I.size=z.size;var Q=Bb(z),K=z.hardlinks!==!1;if(K&&Q!=="Directory"&&z.nlink&&z.nlink>1){var H=z.dev+":"+z.ino;if(PN[H]===I._path||!PN[H])PN[H]=I._path;else Q=I.type=I.props.type="Link",I.Link=I.props.Link=!0,I.linkpath=I.props.linkpath=PN[H],I._stat=I._read=XN0.prototype._read}if(I.type&&I.type!==Q)I.error("Unexpected type: "+Q);if(I.filter){var G=I._proxy||I;if(!I.filter.call(G,G,z)){if(!I._disowned)I.abort(),I.emit("end"),I.emit("close");return}}var Z=["_stat","stat","ready"],W=0;(function X(){if(I._aborted){I.emit("end"),I.emit("close");return}if(I._paused&&I.type!=="Directory"){I.once("resume",X);return}var w=Z[W++];if(!w)return I._read();I.emit(w,z),X()})()}};Z5.prototype.pipe=function($){var I=this;if(typeof $.add==="function")I.on("entry",function(z){var q=$.add(z);if(q===!1)I.pause()});return JP1.prototype.pipe.apply(this,arguments)};Z5.prototype.pause=function($){if(this._paused=!0,$=$||this,this.emit("pause",$),this._stream)this._stream.pause($)};Z5.prototype.resume=function($){if(this._paused=!1,$=$||this,this.emit("resume",$),this._stream)this._stream.resume($);this._read()};Z5.prototype._read=function(){this.error("Cannot read unknown type: "+this.type)}});var Cb=M((s54,AN0)=>{A Line truncated
actual: `+$._bytesEmitted)}),Y.on("close",function(){if($._paused||$._buffer.length)$._buffer.push(QO0),$._read();else $.emit("close")}),Y.on("error",function(z){$.emit("error",z)}),$._read()};$U.prototype._read=function(){var $=this;if($._paused)return;if(!$._stream)return $._getStream();if($._buffer.length){var Y=$._buffer;for(var z=0,U=Y.length;z<U;z++){var Q=Y[z];if(Q===UO0)$.emit("end");else if(Q===QO0)$.emit("close");else $.emit("data",Q);if($._paused){$._buffer=Y.slice(z);return}}$._buffer.length=0}};$U.prototype.pause=function($){var Y=this;if(Y._paused)return;if($=$||Y,Y._paused=!0,Y._stream)Y._stream.pause();Y.emit("pause",$)};$U.prototype.resume=function($){var Y=this;if(!Y._paused)return;if($=$||Y,Y.emit("resume",$),Y._paused=!1,Y._stream)Y._stream.resume();Y._read()}});var GO0=E((Ea1,KO0)=>{KO0.exports=tB;var SF1=X1(),IO0=ez();SF1(tB,IO0);function tB($){var Y=this;if(!(Y instanceof tB))throw Error("SocketReader must be called as constructor.");if(!($.type==="Socket"&&$.Socket))throw Error("Non-socket type "+$.type);IO0.call(Y,$)}tB.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var sc=E((Ca1,WO0)=>{WO0.exports=YU;var rc=ez(),gF1=WZ(),yF1=X1(),kF1=l8();yF1(YU,rc);function YU($){var Y=this;if(!(Y instanceof YU))throw Error("ProxyReader must be called as constructor.");Y.props=$,Y._buffer=[],Y.ready=!1,rc.call(Y,$)}YU.prototype._stat=function(){var $=this,Y=$.props,z=Y.follow?"stat":"lstat";kF1[z](Y.path,function(U,Q){var J;if(U||!Q)J="File";else J=gF1(Q);Y[J]=!0,Y.type=$.type=J,$._old=Q,$._addProxy(rc(Y,Q))})};YU.prototype._addProxy=function($){var Y=this;if(Y._proxyTarget)return Y.error("proxy already set");Y._proxyTarget=$,$._proxy=Y,["error","data","end","close","linkpath","entry","entryEnd","child","childEnd","warn","stat"].forEach(function(U){$.on(U,Y.emit.bind(Y,U))}),Y.emit("proxy",$),$.on("ready",function(){Y.ready=!0,Y.emit("ready")});var z=Y._buffer;Y._buffer.length=0,z.forEach(function(U){$[U[0]].apply($,U[1])})};YU.prototype.pause=function(){return this._proxyTarget?this._proxyTarget.pause():!1};YU.prototype.resume=function(){return this._proxyTarget?this._proxyTarget.resume():!1}});var ez=E((Ra1,ZO0)=>{ZO0.exports=O5;var xF1=l8(),fF1=I0("stream").Stream,uF1=X1(),ac=I0("path"),tc=WZ(),eB=O5.hardLinks={},HO0=aB();uF1(O5,HO0);var XO0=dc();function O5($,Y){var z=this;if(!(z instanceof O5))return new O5($,Y);if(typeof $==="string")$={path:$};var U,Q;if($.type&&typeof $.type==="function")U=$.type,Q=U;else U=tc($),Q=O5;if(Y&&!U)U=tc(Y),$[U]=!0,$.type=U;switch(U){case"Directory":Q=lc();break;case"Link":case"File":Q=oc();break;case"SymbolicLink":Q=XO0;break;case"Socket":Q=GO0();break;case null:Q=sc();break}if(!(z instanceof Q))return new Q($);if(HO0.call(z),!$.path)z.error("Must provide a path",null,!0);if(z.readable=!0,z.writable=!1,z.type=U,z.props=$,z.depth=$.depth=$.depth||0,z.parent=$.parent||null,z.root=$.root||$.parent&&$.parent.root||z,z._path=z.path=ac.resolve($.path),process.platform==="win32"){if(z.path=z._path=z.path.replace(/\?/g,"_"),z._path.length>=260)z._swallowErrors=!0,z._path="\\\\?\\"+z.path.replace(/\//g,"\\")}if(z.basename=$.basename=ac.basename(z.path),z.dirname=$.dirname=ac.dirname(z.path),$.parent=$.root=null,z.size=$.size,z.filter=typeof $.filter==="function"?$.filter:null,$.sort==="alpha")$.sort=bF1;z._stat(Y)}function bF1($,Y){return $===Y?0:$.toLowerCase()>Y.toLowerCase()?1:$.toLowerCase()<Y.toLowerCase()?-1:$>Y?1:-1}O5.prototype._stat=function($){var Y=this,z=Y.props,U=z.follow?"stat":"lstat";if($)process.nextTick(Q.bind(null,null,$));else xF1[U](Y._path,Q);function Q(J,I){if(J)return Y.error(J);if(Object.keys(I).forEach(function(q){z[q]=I[q]}),Y.size!==void 0&&z.size!==Y.size)return Y.error("incorrect size");Y.size=z.size;var K=tc(z),G=z.hardlinks!==!1;if(G&&K!=="Directory"&&z.nlink&&z.nlink>1){var W=z.dev+":"+z.ino;if(eB[W]===Y._path||!eB[W])eB[W]=Y._path;else K=Y.type=Y.props.type="Link",Y.Link=Y.props.Link=!0,Y.linkpath=Y.props.linkpath=eB[W],Y._stat=Y._read=XO0.prototype._read}if(Y.type&&Y.type!==K)Y.error("Unexpected type: "+K);if(Y.filter){var H=Y._proxy||Y;if(!Y.filter.call(H,H,z)){if(!Y._disowned)Y.abort(),Y.emit("end"),Y.emit("close");return}}var X=["_stat","stat","ready"],Z=0;(function q(){if(Y._aborted){Y.emit("end"),Y.emit("close");return}if(Y._paused&&Y.type!=="Directory"){Y.once("resume",q);return}var V=X[Z++];if(!V)return Y._read();Y.emit(V,z),q()})()}};O5.prototype.pipe=function($){var Y=this;if(typeof $.add==="function")Y.on("entry",function(z){var U=$.add(z);if(U===!1)Y.pause()});return fF1.prototype.pipe.apply(this,arguments)};O5.prototype.pause=function($){if(this._paused=!0,$=$||this,this.emit("pause",$),this._stream)this._stream.pause($)};O5.prototype.resume=function($){if(this._paused=!1,$=$||this,this.emit("resume",$),this._stream)this._stream.resume($);this._read()};O5.prototype._read=function(){this.error("Cannot read unknown type: "+this.type)}});var zn=E((_a1,NO0)=> Line truncated
expect: `+$.size+`
actual: `+$._bytesWritten);SN.prototype._finish.call($)}});var fb=M((V94,ZD0)=>{ZD0.exports=n7;var kb=EY(),yP1=lG(),xP1=n0(),uP1=hN(),kP1=d("fs");xP1(n7,kb);function n7($){var I=this;if(!(I instanceof n7))throw Error("ProxyWriter must be called as constructor.");I.props=$,I._needDrain=!1,kb.call(I,$)}n7.prototype._stat=function(){var $=this,I=$.props,z=I.follow?"stat":"lstat";kP1[z](I.path,function(q,U){var Y;if(q||!U)Y="File";else Y=yP1(U);I[Y]=!0,I.type=$.type=Y,$._old=U,$._addProxy(kb(I,U))})};n7.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(q){$.on(q,I.emit.bind(I,q))}),I.emit("proxy",$);var z=I._buffer;if(z.forEach(function(q){$[q[0]].apply($,q[1])}),I._buffer.length=0,I._needsDrain)I.emit("drain")};n7.prototype.add=function($){if(uP1($),!this._proxy)return this._buffer.push(["add",[$]]),this._needDrain=!0,!1;return this._proxy.add($)};n7.prototype.write=function($){if(!this._proxy)return this._buffer.push(["write",[$]]),this._needDrain=!0,!1;return this._proxy.write($)};n7.prototype.end=function($){if(!this._proxy)return this._buffer.push(["end",[$]]),!1;return this._proxy.end($)}});var EY=M((w94,ND0)=>{ND0.exports=S$;var g$=b8(),fP1=n0(),bP1=Cb(),iP1=gb(),eG=d("path"),XD0=process.platform==="win32"?0:process.umask(),VD0=lG(),wD0=DN();fP1(S$,wD0);S$.dirmode=parseInt("0777",8)&~XD0;S$.filemode=parseInt("0666",8)&~XD0;var nP1=yb(),cP1=xb(),pP1=ub(),dP1=fb();function S$($,I){var z=this;if(typeof $==="string")$={path:$};var q=VD0($),U=S$;switch(q){case"Directory":U=nP1;break;case"File":U=pP1;break;case"Link":case"SymbolicLink":U=cP1;break;case null:default:U=dP1;break}if(!(z instanceof U))return new U($);if(wD0.call(z),!$.path)z.error("Must provide a path",null,!0);if(z.type=$.type,z.props=$,z.depth=$.depth||0,z.clobber=$.clobber===!1?$.clobber:!0,z.parent=$.parent||null,z.root=$.root||$.parent&&$.parent.root||z,z._path=z.path=eG.resolve($.path),process.platform==="win32"){if(z.path=z._path=z.path.replace(/\?/g,"_"),z._path.length>=260)z._swallowErrors=!0,z._path="\\\\?\\"+z.path.replace(/\//g,"\\")}if(z.basename=eG.basename($.path),z.dirname=eG.dirname($.path),z.linkpath=$.linkpath||null,$.parent=$.root=null,z.size=$.size,typeof $.mode==="string")$.mode=parseInt($.mode,8);z.readable=!1,z.writable=!0,z._buffer=[],z.ready=!1,z.filter=typeof $.filter==="function"?$.filter:null,z._stat(I)}S$.prototype._create=function(){var $=this;g$[$.props.follow?"stat":"lstat"]($._path,function(I){if(I)return $.warn("Cannot create "+$._path+`
Unsupported type: `+$.type,"ENOTSUP");$._finish()})};S$.prototype._stat=function($){var I=this,z=I.props,q=z.follow?"stat":"lstat",U=I._proxy||I;if($)Y(null,$);else g$[q](I._path,Y);function Y(J,Q){if(I.filter&&!I.filter.call(U,U,Q)){I._aborted=!0,I.emit("end"),I.emit("close");return}if(J||!Q)return bb(I);I._old=Q;var K=VD0(Q);if(K!==I.type||I.type==="File"&&Q.nlink>1)return bP1(I._path,function(H){if(H)return I.error(H);I._old=null,bb(I)});bb(I)}};function bb($){iP1(eG.dirname($._path),S$.dirmode,function(I,z){if(I)return $.error(I);return $._madeDir=z,$._create()})}function LD0($,I,z,q,U){var Y=I.mode,J=I.follow||$.type!=="SymbolicLink"?"chmod":"lchmod";if(!g$[J])return U();if(typeof Y!=="number")return U();var Q=z.mode&parseInt("0777",8);if(Y=Y&parseInt("0777",8),Y===Q)return U();g$[J](q,Y,U)}function OD0($,I,z,q,U){if(process.platform==="win32")return U();if(!process.getuid||process.getuid()!==0)return U();if(typeof I.uid!=="number"&&typeof I.gid!=="number")return U();if(z.uid===I.uid&&z.gid===I.gid)return U();var Y=$.props.follow||$.type!=="SymbolicLink"?"chown":"lchown";if(!g$[Y])return U();if(typeof I.uid!=="number")I.uid=z.uid;if(typeof I.gid!=="number")I.gid=z.gid;g$[Y](q,I.uid,I.gid,U)}function FD0($,I,z,q,U){if(!g$.utimes||process.platform==="win32")return U();var Y=I.follow||$.type!=="SymbolicLink"?"utimes":"lutimes";if(Y==="lutimes"&&!g$[Y])Y="utimes";if(!g$[Y])return U();var{atime:J,mtime:Q}=z,K=I.atime,H=I.mtime;if(K===void 0)K=J;if(H===void 0)H=Q;if(!WD0(K))K=new Date(K);if(!WD0(H))K=new Date(H);if(K.getTime()===J.getTime()&&H.getTime()===Q.getTime())return U();g$[Y](q,K,H,U)}S$.prototype._finish=function(){var $=this;if($._finishing)return;$._finishing=!0;var I=0,z=null,q=!1;if($._old)$._old.atime=new Date(0),$._old.mtime=new Date(0),Y($._old);else{var U=$.props.follow?"stat":"lstat";g$[U]($._path,function(Q,K){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);Y($._old=K)})}return;function Y(Q){I+=3,LD0($,$.props,Q,$._path,J("chmod")),OD0($,$.props,Q,$._path,J("chown")),FD0($,$.props,Q,$._path,J("utimes"))}function J(Q){return function(K){if(z)return;if(K)return K.fstream_finish_call=Q,$.error(z=K);if(--I>0)return;if(q)return;if(q=!0,!$._madeDir)return H();else MD0($,$._path,H);function H(G){if(G)return G.fstream_finish_call="setupMadeDir",$.error(G);$.emit("end"),$.emit("close")}}}};function MD0($,I,z){var q=$._madeDir,U=eG.dirname(I);mP1($,U,function(Y){if(Y)return z(Y);if(U===q)return z();MD0($,U,z)})}function mP1($,I,z){var q={};Object.keys($.props).forEach(function(Q){if(q[Q]=$.props[Q],Q==="mode"&&$.type!=="Directory")q[Q]=q[Q]|parseInt("0111",8)});var U=3,Y=null;g$.stat(I,function(Q,K){if(Q)return z(Y=Q);LD0($,q,K,I,J),OD0($,q,K,I,J),FD0($,q,K,I,J)});function J(Q){if(Y)return;if(Q)return z(Y=Q);if(--U===0)return z()}}S$.prototype.pipe=function(){this.error("Can't pipe from writable stream")};S$.prototype.add=function(){this.error("Can't add to non-Directory type")};S$.prototype.write=function(){return!0};function lP1($){return Object.prototype.toString.call($)}function WD0($){return typeof $==="object"&&lP1($)==="[object Date]"}});var db=M((oP1)=>{oP1.Abstract=DN();oP1.Reader=iI();oP1.Writer=EY();oP1.File={Reader:Nb(),Writer:ub()};oP1.Dir={Reader:Mb(),Writer:yb()};oP1.Link={Reader:Ob(),Writer:xb()};oP1.Proxy={Reader:Ab(),Writer:fb()};oP1.Reader.Dir=oP1.DirReader=oP1.Dir.Reader;oP1.Reader.File=oP1.FileReader=oP1.File.Reader;oP1.Reader.Link=oP1.LinkReader=oP1.Link.Reader;oP1.Reader.Proxy=oP1.ProxyReader=oP1.Proxy.Reader;oP1.Writer.Dir=oP1.DirWriter=oP1.Dir.Writer;oP1.Writer.File=oP1.FileWriter=oP1.File.Writer;oP1.Writer.Link=oP1.LinkWriter=oP1.Link.Writer;oP1.Writer.Proxy=oP1.ProxyWriter=oP1.Proxy.Writer;oP1.collect=hN()});var AD0=M((T94,DD0)=>{DD0.exports=zB1;var tP1=WN(),aP1=db().Writer,mb=d("path"),eP1=d("stream"),$B1=Vb(),IB1=y7();function zB1($){$.path=mb.resolve(mb.normalize($.path));var I=new tP1($),z=new eP1.Writable({objectMode:!0});z._write=function(U,Y,J){if(U.type=="Directory")return J();var Q=mb.join($.path,U.path);if(Q.indexOf($.path)!=0)return J();let K=$.getWriter?$.getWriter({path:Q}):aP1({path:Q});U.pipe(K).on("error",J).on("close",J)};var q=$B1(I,z);return I.once("crx-header",function(U){q.crxHeader=U}),I.pipe(z).on("finish",function(){q.emit("close")}),q.promise=function(){return new IB1(function(U,Y){q.on("close",U),q.on("error",Y)})},q}});var PD0=M((E94,yN)=>{var W6=function($){var I=1e7,z=7,q=9007199254740992,U=W(q),Y="0123456789abcdefghijklmnopqrstuvwxyz",J=typeof BigInt==="function";function Q(N,B,S,n){if(typeof N>"u")return Q[0];if(typeof B<"u")return+B===10&&!S?C0(N):T8(N,B,S,n);return C0(N)}function K(N,B){this.value=N,this.sign=B,this.isSmall=!1}K.prototype=Object.create(Q.prototype);function H(N){this.value=N,this.sign=N<0,this.isSmall=!0}H.prototype=Object.create(Q.prototype);function G(N){th Line truncated
actual: `+$._bytesWritten);HP.prototype._finish.call($)}});var qn=E((oa1,WN0)=>{WN0.exports=S2;var Zn=iI(),qw1=WZ(),Vw1=X1(),Lw1=GP(),Fw1=I0("fs");Vw1(S2,Zn);function S2($){var Y=this;if(!(Y instanceof S2))throw Error("ProxyWriter must be called as constructor.");Y.props=$,Y._needDrain=!1,Zn.call(Y,$)}S2.prototype._stat=function(){var $=this,Y=$.props,z=Y.follow?"stat":"lstat";Fw1[z](Y.path,function(U,Q){var J;if(U||!Q)J="File";else J=qw1(Q);Y[J]=!0,Y.type=$.type=J,$._old=Q,$._addProxy(Zn(Y,Q))})};S2.prototype._addProxy=function($){var Y=this;if(Y._proxy)return Y.error("proxy already set");Y._proxy=$,["ready","error","close","pipe","drain","warn"].forEach(function(U){$.on(U,Y.emit.bind(Y,U))}),Y.emit("proxy",$);var z=Y._buffer;if(z.forEach(function(U){$[U[0]].apply($,U[1])}),Y._buffer.length=0,Y._needsDrain)Y.emit("drain")};S2.prototype.add=function($){if(Lw1($),!this._proxy)return this._buffer.push(["add",[$]]),this._needDrain=!0,!1;return this._proxy.add($)};S2.prototype.write=function($){if(!this._proxy)return this._buffer.push(["write",[$]]),this._needDrain=!0,!1;return this._proxy.write($)};S2.prototype.end=function($){if(!this._proxy)return this._buffer.push(["end",[$]]),!1;return this._proxy.end($)}});var iI=E((ra1,MN0)=>{MN0.exports=f$;var x$=l8(),ww1=X1(),Mw1=zn(),Ow1=Kn(),LZ=I0("path"),XN0=process.platform==="win32"?0:process.umask(),ZN0=WZ(),qN0=aB();ww1(f$,qN0);f$.dirmode=parseInt("0777",8)&~XN0;f$.filemode=parseInt("0666",8)&~XN0;var Nw1=Wn(),Dw1=Hn(),Bw1=Xn(),Pw1=qn();function f$($,Y){var z=this;if(typeof $==="string")$={path:$};var U=ZN0($),Q=f$;switch(U){case"Directory":Q=Nw1;break;case"File":Q=Bw1;break;case"Link":case"SymbolicLink":Q=Dw1;break;case null:default:Q=Pw1;break}if(!(z instanceof Q))return new Q($);if(qN0.call(z),!$.path)z.error("Must provide a path",null,!0);if(z.type=$.type,z.props=$,z.depth=$.depth||0,z.clobber=$.clobber===!1?$.clobber:!0,z.parent=$.parent||null,z.root=$.root||$.parent&&$.parent.root||z,z._path=z.path=LZ.resolve($.path),process.platform==="win32"){if(z.path=z._path=z.path.replace(/\?/g,"_"),z._path.length>=260)z._swallowErrors=!0,z._path="\\\\?\\"+z.path.replace(/\//g,"\\")}if(z.basename=LZ.basename($.path),z.dirname=LZ.dirname($.path),z.linkpath=$.linkpath||null,$.parent=$.root=null,z.size=$.size,typeof $.mode==="string")$.mode=parseInt($.mode,8);z.readable=!1,z.writable=!0,z._buffer=[],z.ready=!1,z.filter=typeof $.filter==="function"?$.filter:null,z._stat(Y)}f$.prototype._create=function(){var $=this;x$[$.props.follow?"stat":"lstat"]($._path,function(Y){if(Y)return $.warn("Cannot create "+$._path+`
Unsupported type: `+$.type,"ENOTSUP");$._finish()})};f$.prototype._stat=function($){var Y=this,z=Y.props,U=z.follow?"stat":"lstat",Q=Y._proxy||Y;if($)J(null,$);else x$[U](Y._path,J);function J(I,K){if(Y.filter&&!Y.filter.call(Q,Q,K)){Y._aborted=!0,Y.emit("end"),Y.emit("close");return}if(I||!K)return Vn(Y);Y._old=K;var G=ZN0(K);if(G!==Y.type||Y.type==="File"&&K.nlink>1)return Mw1(Y._path,function(W){if(W)return Y.error(W);Y._old=null,Vn(Y)});Vn(Y)}};function Vn($){Ow1(LZ.dirname($._path),f$.dirmode,function(Y,z){if(Y)return $.error(Y);return $._madeDir=z,$._create()})}function VN0($,Y,z,U,Q){var J=Y.mode,I=Y.follow||$.type!=="SymbolicLink"?"chmod":"lchmod";if(!x$[I])return Q();if(typeof J!=="number")return Q();var K=z.mode&parseInt("0777",8);if(J=J&parseInt("0777",8),J===K)return Q();x$[I](U,J,Q)}function LN0($,Y,z,U,Q){if(process.platform==="win32")return Q();if(!process.getuid||process.getuid()!==0)return Q();if(typeof Y.uid!=="number"&&typeof Y.gid!=="number")return Q();if(z.uid===Y.uid&&z.gid===Y.gid)return Q();var J=$.props.follow||$.type!=="SymbolicLink"?"chown":"lchown";if(!x$[J])return Q();if(typeof Y.uid!=="number")Y.uid=z.uid;if(typeof Y.gid!=="number")Y.gid=z.gid;x$[J](U,Y.uid,Y.gid,Q)}function FN0($,Y,z,U,Q){if(!x$.utimes||process.platform==="win32")return Q();var J=Y.follow||$.type!=="SymbolicLink"?"utimes":"lutimes";if(J==="lutimes"&&!x$[J])J="utimes";if(!x$[J])return Q();var{atime:I,mtime:K}=z,G=Y.atime,W=Y.mtime;if(G===void 0)G=I;if(W===void 0)W=K;if(!HN0(G))G=new Date(G);if(!HN0(W))G=new Date(W);if(G.getTime()===I.getTime()&&W.getTime()===K.getTime())return Q();x$[J](U,G,W,Q)}f$.prototype._finish=function(){var $=this;if($._finishing)return;$._finishing=!0;var Y=0,z=null,U=!1;if($._old)$._old.atime=new Date(0),$._old.mtime=new Date(0),J($._old);else{var Q=$.props.follow?"stat":"lstat";x$[Q]($._path,function(K,G){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=G)})}return;function J(K){Y+=3,VN0($,$.props,K,$._path,I("chmod")),LN0($,$.props,K,$._path,I("chown")),FN0($,$.props,K,$._path,I("utimes"))}function I(K){return function(G){if(z)return;if(G)return G.fstream_finish_call=K,$.error(z=G);if(--Y>0)return;if(U)return;if(U=!0,!$._madeDir)return W();else wN0($,$._path,W);function W(H){if(H)return H.fstream_finish_call="setupMadeDir",$.error(H);$.emit("end"),$.emit("close")}}}};function wN0($,Y,z){var U=$._madeDir,Q=LZ.dirname(Y);Aw1($,Q,function(J){if(J)return z(J);if(Q===U)return z();wN0($,Q,z)})}function Aw1($,Y,z){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 Q=3,J=null;x$.stat(Y,function(K,G){if(K)return z(J=K);VN0($,U,G,Y,I),LN0($,U,G,Y,I),FN0($,U,G,Y,I)});function I(K){if(J)return;if(K)return z(J=K);if(--Q===0)return z()}}f$.prototype.pipe=function(){this.error("Can't pipe from writable stream")};f$.prototype.add=function(){this.error("Can't add to non-Directory type")};f$.prototype.write=function(){return!0};function Tw1($){return Object.prototype.toString.call($)}function HN0($){return typeof $==="object"&&Tw1($)==="[object Date]"}});var On=E((jw1)=>{jw1.Abstract=aB();jw1.Reader=ez();jw1.Writer=iI();jw1.File={Reader:oc(),Writer:Xn()};jw1.Dir={Reader:lc(),Writer:Wn()};jw1.Link={Reader:dc(),Writer:Hn()};jw1.Proxy={Reader:sc(),Writer:qn()};jw1.Reader.Dir=jw1.DirReader=jw1.Dir.Reader;jw1.Reader.File=jw1.FileReader=jw1.File.Reader;jw1.Reader.Link=jw1.LinkReader=jw1.Link.Reader;jw1.Reader.Proxy=jw1.ProxyReader=jw1.Proxy.Reader;jw1.Writer.Dir=jw1.DirWriter=jw1.Dir.Writer;jw1.Writer.File=jw1.FileWriter=jw1.File.Writer;jw1.Writer.Link=jw1.LinkWriter=jw1.Link.Writer;jw1.Writer.Proxy=jw1.ProxyWriter=jw1.Proxy.Writer;jw1.collect=GP()});var NN0=E((Jt1,ON0)=>{ON0.exports=gw1;var Rw1=cB(),_w1=On().Writer,Nn=I0("path"),vw1=I0("stream"),hw1=cc(),Sw1=j2();function gw1($){$.path=Nn.resolve(Nn.normalize($.path));var Y=new Rw1($),z=new vw1.Writable({objectMode:!0});z._write=function(Q,J,I){if(Q.type=="Directory")return I();var K=Nn.join($.path,Q.path);if(K.indexOf($.path)!=0)return I();let G=$.getWriter?$.getWriter({path:K}):_w1({path:K});Q.pipe(G).on("error",I).on("close",I)};var U=hw1(Y,z);return Y.once("crx-header",function(Q){U.crxHeader=Q}),Y.pipe(z).on("finish",function(){U.emit("close")}),U.promise=function(){return new Sw1(function(Q,J){U.on("close",Q),U.on("error",J)})},U}});var DN0=E((It1,XP)=>{var j6=function($){var Y=1e7,z=7,U=9007199254740992,Q=Z(U),J="0123456789abcdefghijklmnopqrstuvwxyz",I=typeof BigInt==="function";function K(P,v,u,r){if(typeof P>"u")return K[0];if(typeof v<"u")return+v===10&&!u?B0(P):f0(P,v,u,r);return B0(P)}function G(P,v){this.value=P,this.sign=v,this.isSmall=!1}G.prototype=Object.create(K.prototype);function W(P){this.value=P,this.sign=P<0,this.isSmall=!0}W.prototype=Object.create(K.prototype);function H(P){ Line truncated
* Tmp
*
* Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>
*
* MIT Licensed
*/var a1=d("fs"),iN=d("os"),X6=d("path"),xD0=d("crypto"),t5={fs:a1.constants,os:iN.constants},bD0=/XXXXXX/,iD0=(t5.O_CREAT||t5.fs.O_CREAT)|(t5.O_EXCL||t5.fs.O_EXCL)|(t5.O_RDWR||t5.fs.O_RDWR),EB1=iN.platform()==="win32",jB1=t5.EBADF||t5.os.errno.EBADF,CB1=t5.ENOENT||t5.os.errno.ENOENT,CY=[],nD0=a1.rmdirSync.bind(a1),cD0=!1;function _B1($,I){return a1.rm($,{recursive:!0},I)}function pD0($){return a1.rmSync($,{recursive:!0})}function tb($,I){let z=_Y($,I),q=z[0],U=z[1];fB1(q,function(Y,J){if(Y)return U(Y);let Q=J.tries;(function K(){try{let H=mD0(J);a1.stat(H,function(G){if(!G){if(Q-- >0)return K();return U(Error("Could not get a unique tmp filename, max tries reached "+H))}U(null,H)})}catch(H){U(H)}})()})}function ab($){let I=_Y($),z=I[0],q=bB1(z),U=q.tries;do{let Y=mD0(q);try{a1.statSync(Y)}catch(J){return Y}}while(U-- >0);throw Error("Could not get a unique tmp filename, max tries reached")}function RB1($,I){let z=_Y($,I),q=z[0],U=z[1];tb(q,function(J,Q){if(J)return U(J);a1.open(Q,iD0,q.mode||384,function(H,G){if(H)return U(H);if(q.discardDescriptor)return a1.close(G,function(W){return U(W,Q,void 0,rb(Q,-1,q,!1))});else{let Z=q.discardDescriptor||q.detachDescriptor;U(null,Q,G,rb(Q,Z?-1:G,q,!1))}})})}function vB1($){let I=_Y($),z=I[0],q=z.discardDescriptor||z.detachDescriptor,U=ab(z),Y=a1.openSync(U,iD0,z.mode||384);if(z.discardDescriptor)a1.closeSync(Y),Y=void 0;return{name:U,fd:Y,removeCallback:rb(U,q?-1:Y,z,!0)}}function hB1($,I){let z=_Y($,I),q=z[0],U=z[1];tb(q,function(J,Q){if(J)return U(J);a1.mkdir(Q,q.mode||448,function(H){if(H)return U(H);U(null,Q,dD0(Q,q,!1))})})}function gB1($){let I=_Y($),z=I[0],q=ab(z);return a1.mkdirSync(q,z.mode||448),{name:q,removeCallback:dD0(q,z,!0)}}function SB1($,I){let z=function(q){if(q&&!sb(q))return I(q);I()};if(0<=$[0])a1.close($[0],function(){a1.unlink($[1],z)});else a1.unlink($[1],z)}function yB1($){let I=null;try{if(0<=$[0])a1.closeSync($[0])}catch(z){if(!iB1(z)&&!sb(z))throw z}finally{try{a1.unlinkSync($[1])}catch(z){if(!sb(z))I=z}}if(I!==null)throw I}function rb($,I,z,q){let U=bN(yB1,[I,$],q),Y=bN(SB1,[I,$],q,U);if(!z.keep)CY.unshift(U);return q?U:Y}function dD0($,I,z){let q=I.unsafeCleanup?_B1:a1.rmdir.bind(a1),U=I.unsafeCleanup?pD0:nD0,Y=bN(U,$,z),J=bN(q,$,z,Y);if(!I.keep)CY.unshift(Y);return z?Y:J}function bN($,I,z,q){let U=!1;return function Y(J){if(!U){let Q=q||Y,K=CY.indexOf(Q);if(K>=0)CY.splice(K,1);if(U=!0,z||$===nD0||$===pD0)return $(I);else return $(I,J||function(){})}}}function xB1(){if(!cD0)return;while(CY.length)try{CY[0]()}catch($){}}function uD0($){let I=[],z=null;try{z=xD0.randomBytes($)}catch(q){z=xD0.pseudoRandomBytes($)}for(let q=0;q<$;q++)I.push("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[z[q]%62]);return I.join("")}function n8($){return typeof $>"u"}function _Y($,I){if(typeof $==="function")return[{},$];if(n8($))return[{},I];let z={};for(let q of Object.getOwnPropertyNames($))z[q]=$[q];return[z,I]}function uB1($,I,z){let q=X6.isAbsolute($)?$:X6.join(I,$);a1.stat(q,function(U){if(U)a1.realpath(X6.dirname(q),function(Y,J){if(Y)return z(Y);z(null,X6.join(J,X6.basename(q)))});else a1.realpath(q,z)})}function kB1($,I){let z=X6.isAbsolute($)?$:X6.join(I,$);try{return a1.statSync(z),a1.realpathSync(z)}catch(q){let U=a1.realpathSync(X6.dirname(z));return X6.join(U,X6.basename(z))}}function mD0($){let I=$.tmpdir;if(!n8($.name))return X6.join(I,$.dir,$.name);if(!n8($.template))return X6.join(I,$.dir,$.template).replace(bD0,uD0(6));let z=[$.prefix?$.prefix:"tmp","-",process.pid,"-",uD0(12),$.postfix?"-"+$.postfix:""].join("");return X6.join(I,$.dir,z)}function ob($,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 lD0($){if(!n8($.name)){let I=$.name;if(X6.isAbsolute(I))throw Error(`name option must not contain an absolute path, found "${I}".`);let z=X6.basename(I);if(z===".."||z==="."||z!==I)throw Error(`name option must not contain a path, found "${I}".`)}if(!n8($.template)){if(typeof $.template!=="string")throw Error(`template option must be a string, got "${typeof $.template}".`);if(!$.template.match(bD0))throw Error(`Invalid template, found "${$.template}".`)}if(!n8($.tries)&&isNaN($.tries)||$.tries<0)throw Error(`Invalid tries, found "${$.tries}".`);$.tries=n8($.name)?$.tries||3:1,$.keep=!!$.keep,$.detachDescriptor=!!$.detachDescriptor,$.discardDescriptor=!!$.discardDescriptor,$.unsafeCleanup=!!$.unsafeCleanup,$.prefix=n8($.prefix)?"":ob("prefix",$.prefix),$.postfix=n8($.postfix)?"":ob("postfix",$.postfix),$.template=n8($.template)?void 0:ob("template",$.template)}function kD0($,I,z,q){if(n8(I))return q(null);uB1(I,z,function(U,Y){if(U)return q(U);let J=X6.relative(z,Y);if(J.startsWith("..")||X6.isAbsolute(J))return q(Error(`${$} option must be relative to "${z}", found "${J}".`));q(null,J)})}function fD0($,I,z){if(n8(I))return;let q=kB1(I,z),U=X6.relative(z,q);if(U.startsWith("..")||X6.isAbsolute(U))throw ELine truncated
`,{mode:384}),I}function Wi($){let I=hA0();for(let z of I){if(!K$(z))continue;for(let q of sN(z).filter((U)=>U.endsWith(".json")).filter((U)=>!U.startsWith("example."))){let U=a5(z,q);try{let Y=aN(U,"utf-8"),J=JSON.parse(Y);if(J&&typeof J==="object"&&J.id===$)return U}catch{}}}return}function m7($,I){let z=Wi($);if(!z)throw Error(`Enterprise config not found: ${$}`);let U={...JSON.parse(aN(z,"utf-8")),...I};for(let J of Object.keys(I))if(I[J]===void 0)delete U[J];let Y=Ki.parse(U);return EA0(z,`${JSON.stringify(Y,null,2)}
`,"utf-8"),Y}var Gi="SEAL_USE_ENTERPRISES_DIR",jA0="SEAL_HOME_ENTERPRISES_DIR",CA0="SEAL_USE_USER_ENTERPRISES_DIR",_A0="SEAL_HOME_USER_ENTERPRISES_DIR",RA0="SEAL_USE_CONFIG_FILE",vA0="SEAL_HOME_CONFIG_FILE",RY,tN,rN,BA0;var e9=e(()=>{Hi();RY=a5(eN(),".config","seal-use","enterprises"),tN=a5(eN(),".config","seal-home","enterprises"),rN=a5(eN(),".config","seal-use","config.json"),BA0=a5(eN(),".config","seal-home","config.json")});function l7($,I,z=[]){let q=I.corpId?.trim()||void 0,U=I.stateful?I.defaultCorpId?.trim()||void 0:void 0,Y=q??U;if(Y){let Q=$.find((G)=>G.id===Y);if(Q)return Q;let K=$.find((G)=>G.id.toLowerCase()===Y.toLowerCase());if(K)return K;let H=$.find((G)=>G.name.toLowerCase()===Y.toLowerCase());if(H)return H;throw Error(`No enterprise config found for ${Y}`)}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 J=$[0];if(J)return J;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(z.length?z.join(", "):"the configured enterprise directories"))}import{existsSync as Xi,mkdirSync as iT1,readFileSync as nT1,renameSync as cT1,unlinkSync as pT1,writeFileSync as dT1}from"node:fs";import{homedir as mT1}from"node:os";import{dirname as lT1,join as oT1}from"node:path";function wi(){let $=process.env[rT1]?.trim();if($)return $;return sT1}function gA0($=new Date){return $.toISOString().slice(0,10)}function SA0($=Vi,I=new Date){let z=I.getTime()-Math.max(0,$-1)*86400000;return new Date(z).toISOString().slice(0,10)}function yA0($=wi()){if(!Xi($))return{};try{let I=nT1($,"utf-8"),z=JSON.parse(I);if(z&&typeof z==="object"&&!Array.isArray(z))return z;return{}}catch{return{}}}function tT1($,I){let z={};for(let[q,U]of Object.entries($)){if(!U||typeof U!=="object")continue;let Y={},J=!1;for(let[Q,K]of Object.entries(U))if(typeof K==="number"&&K>0&&Q>=I)Y[Q]=K,J=!0;if(J)z[q]=Y}return z}function aT1($,I=wi()){let z=lT1(I);if(!Xi(z))iT1(z,{recursive:!0,mode:448});let q=`${I}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{dT1(q,JSON.stringify($,null,2),"utf-8"),cT1(q,I)}catch(U){try{if(Xi(q))pT1(q)}catch{}throw U}}function xA0($,I=new Date){if(!$||typeof $!=="string")return;try{let z=wi(),q=yA0(z),U=gA0(I),Y=SA0(Vi,I),J=tT1(q,Y);J[$]=J[$]||{},J[$][U]=(J[$][U]??0)+1,aT1(J,z)}catch{}}function eT1($,I=Vi,z=new Date){let q=new Map;try{let U=yA0(),Y=SA0(I,z),J=gA0(z),Q=$??Object.keys(U);for(let K of Q){let H=U[K];if(!H){q.set(K,0);continue}let G=0;for(let[Z,W]of Object.entries(H))if(Z>=Y&&Z<=J&&typeof W==="number")G+=W;q.set(K,G)}}catch{if($)for(let U of $)q.set(U,0)}return q}function uA0($,I,z){let q=z??eT1($.map((U)=>U.id));return[...$].sort((U,Y)=>{if(I){if(U.id===I&&Y.id!==I)return-1;if(Y.id===I&&U.id!==I)return 1}let J=q.get(U.id)??0,Q=q.get(Y.id)??0;if(J!==Q)return Q-J;let K=U.name??U.id,H=Y.name??Y.id,G=K.localeCompare(H,"zh-CN");if(G!==0)return G;return U.id.localeCompare(Y.id)})}var rT1="SEAL_USE_USAGE_FILE",sT1,Vi=7;var Li=e(()=>{sT1=oT1(mT1(),".config","seal-use","usage.json")});function $E1($,I){return $.map((z)=>z.trim()).filter(Boolean).map((z)=>I?z:z.toLowerCase())}function IE1($,I){return I?$:$.toLowerCase()}function zE1($,I,z,q){let U=IE1($,q),Y=I.filter((J)=>U.includes(J));if(z==="all"&&Y.length!==I.length)return[];return Y}function qE1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function UE1($,I){if(I.fields&&!I.fields.has($.field))return[];let z=qE1($.value),q=[];return z.forEach((U,Y)=>{let J=zE1(U,I.keywords,I.matchMode,I.caseSensitive);if(J.length===0)return;let Q=Math.max(0,Y-I.contextLines),K=Math.min(z.length,Y+I.contextLines+1),H={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:Y+1,matchedKeywords:J,matchedText:$D(U,I.maxChars),context:{before:I.snippetOnly?[]:z.slice(Q,Y).map((G)=>$D(G,I.maxChars)),line:$D(U,I.maxChars),after:I.snippetOnly?[]:z.slice(Y+1,K).map((G)=>$D(G,I.maxChars))},metadata:$.metadata};if(I.snippetOnly)H.context={before:[],line:H.context.line,after:[]};q.push(H)}),q}function $D($,I){if(!I||$.length<=I)return $;return`${$.slice(0,Math.max(0,I))}...`}function YE1($){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 fA0($){return $.rules.flatMap((I,z)=>{let q=`${$.id}:${I.description.slice(0,32)}`,U={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:z};return[{area:"rules",entityType:"rule",entityId:q,title:`${$.versionName} / ${I.scope}`,field:"history.description", Line truncated
`+"为防止测试单据污染生产审批流,禁止向生产环境重放单据。请指定测试企业 (--target-corp <testCorpId>),或在确有需要时添加 --force。",1,`seal-use webhook replay --target-corp <testCorpId>${z.id!==q.id?` --source-corp ${z.id}`:""}`);return{sourceCorp:z,targetCorp:q}}async function Mi($,I,z){let q=I.seal?.endpoints?.approvalStylePreferences??"api/v1/agent/ai-approval/config",U=await e8($,q);if(z||U.length>0)return pA0(U,z,I.id);if(I.environment==="test"||I.id.toLowerCase().includes("test")){console.error(`[webhook-replay] 测试企业「${I.name}」未配置 Webhook 通道,正在自动创建「(Seal测-回放通道)」...`);let Y=(I.seal.url??I.source?.sealUrl??`https://${I.id.toLowerCase()}.sealai.cc`).replace(/\/+$/,"");return await gw($,Y,{name:"(Seal测-回放通道)",mode:"assisted",outgoingResultWebhook:`${Y}/api/v1/integrations/webhook/replay-mock-callback`},I.seal.endpoints.approvalStylePreferences)}throw new h4(`当前租户「${I.name}」未配置任何 Webhook 集成通道。`,1,`seal-use webhook add --name <name> --result-url <url> --corp ${I.id}`)}async function vY($){let{query:I,sourceClient:z,targetClient:q,sourceCorp:U,targetCorp:Y,webhookSelector:J,snPrefix:Q,snSuffix:K,docIdPrefix:H,docIdSuffix:G,dryRun:Z,fetchFn:W=fetch}=$,X=[];if(I.recordId){let T=await z4(z,I.recordId);X.push(T)}else if(I.recordIds&&I.recordIds.length>0)for(let T of I.recordIds)X.push(await z4(z,T));else if(I.sn){let T=await a4(z,{sourceDocumentSN:I.sn,limit:1});if(!T.records.length)throw Error(`在企业「${U.name}」中未找到单据编号为「${I.sn}」的审批记录。`);X.push(T.records[0])}else if(I.sns&&I.sns.length>0)for(let T of I.sns){let k=await a4(z,{sourceDocumentSN:T,limit:1});if(!k.records.length)throw Error(`在企业「${U.name}」中未找到单据编号为「${T}」的审批记录。`);X.push(k.records[0])}else if(I.limit!==void 0){let T=await a4(z,{limit:I.limit,status:I.status,startDate:I.startDate,endDate:I.endDate});if(!T.records.length)throw Error(`在企业「${U.name}」中未检索到符合条件的审批记录。`);X=T.records}else throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let w=X.map((T)=>({run:T,doc:Oi(T,{snPrefix:Q,snSuffix:K,docIdPrefix:H,docIdSuffix:G})}));if(Z){let T={id:"preview-webhook",name:J??"预览目标通道",mode:"assisted",incomingDocumentWebhookUrl:`${Y.seal.url}/api/v1/integrations/webhook/preview`};try{let f=await e8(q,Y.seal.endpoints.approvalStylePreferences);if(f.length>0){let C=pA0(f,J,Y.id);T={id:C.id,name:C.name,mode:C.mode,incomingDocumentWebhookUrl:C.incomingDocumentWebhook.url}}}catch{}let k=w.map(({run:f,doc:C})=>({originalRecord:{id:f.id,sourceSystem:f.sourceSystem,sourceDocumentSN:f.sourceDocumentSN,sourceDocumentId:f.sourceDocumentId},document:C,success:!0})),h=k.length===1;return{dryRun:!0,success:!0,sourceCorp:{id:U.id,name:U.name,environment:U.environment},targetCorp:{id:Y.id,name:Y.name,environment:Y.environment},targetWebhook:T,totalCount:k.length,successCount:k.length,failureCount:0,originalRecord:h?k[0].originalRecord:void 0,document:h?k[0].document:void 0,records:k}}let L=await Mi(q,Y,J),O={id:L.id,name:L.name,mode:L.mode,incomingDocumentWebhookUrl:L.incomingDocumentWebhook.url},F=[],D=0,P=0;for(let{run:T,doc:k}of w){console.error(`[webhook-replay] 正在向 Webhook 通道「${L.name}」推送单据: ${k.documentSN}...`);try{let h=await Fi(L.incomingDocumentWebhook.url,L.secret,k,W,K6(Y.seal));F.push({originalRecord:{id:T.id,sourceSystem:T.sourceSystem,sourceDocumentSN:T.sourceDocumentSN,sourceDocumentId:T.sourceDocumentId},replayedDocument:{documentSN:k.documentSN,documentId:k.documentId,fieldCount:k.fields.length},pushResult:h,success:!0}),D+=1}catch(h){let f=h instanceof Error?h.message:String(h);F.push({originalRecord:{id:T.id,sourceSystem:T.sourceSystem,sourceDocumentSN:T.sourceDocumentSN,sourceDocumentId:T.sourceDocumentId},replayedDocument:{documentSN:k.documentSN,documentId:k.documentId,fieldCount:k.fields.length},error:f,success:!1}),P+=1}}let A=F.length===1;return{success:P===0,dryRun:!1,sourceCorp:{id:U.id,name:U.name,environment:U.environment},targetCorp:{id:Y.id,name:Y.name,environment:Y.environment},targetWebhook:O,totalCount:F.length,successCount:D,failureCount:P,originalRecord:A?F[0].originalRecord:void 0,replayedDocument:A?F[0].replayedDocument:void 0,pushResult:A?F[0].pushResult:void 0,records:F}}var wE1;var GZ=e(()=>{ID();H$();e4();wE1=new Set(["TEXT","NUMBER","DATE","AMOUNT","PERSON","ATTACHMENT","DATE_RANGE","DEPARTMENT","LIST","CITY","OBJECT"])});var dA0,L34,OE1,O34;var mA0=e(()=>{u3();dA0=V.object({level:V.enum(["error","warning","info"]),code:V.string(),message:V.string(),snippet:V.string().optional(),suggestion:V.string().optional()}),L34=V.object({score:V.number().min(0).max(100),passed:V.boolean(),issues:V.array(dA0)}),OE1=V.object({ruleId:V.string Line truncated
*/var q4=I0("fs"),wP=I0("os"),E6=I0("path"),gN0=I0("crypto"),M9={fs:q4.constants,os:wP.constants},fN0=/XXXXXX/,uN0=(M9.O_CREAT||M9.fs.O_CREAT)|(M9.O_EXCL||M9.fs.O_EXCL)|(M9.O_RDWR||M9.fs.O_RDWR),QM1=wP.platform()==="win32",JM1=M9.EBADF||M9.os.errno.EBADF,IM1=M9.ENOENT||M9.os.errno.ENOENT,nI=[],bN0=q4.rmdirSync.bind(q4),iN0=!1;function KM1($,Y){return q4.rm($,{recursive:!0},Y)}function cN0($){return q4.rmSync($,{recursive:!0})}function Tn($,Y){let z=pI($,Y),U=z[0],Q=z[1];wM1(U,function(J,I){if(J)return Q(J);let K=I.tries;(function G(){try{let W=pN0(I);q4.stat(W,function(H){if(!H){if(K-- >0)return G();return Q(Error("Could not get a unique tmp filename, max tries reached "+W))}Q(null,W)})}catch(W){Q(W)}})()})}function jn($){let Y=pI($),z=Y[0],U=MM1(z),Q=U.tries;do{let J=pN0(U);try{q4.statSync(J)}catch(I){return J}}while(Q-- >0);throw Error("Could not get a unique tmp filename, max tries reached")}function GM1($,Y){let z=pI($,Y),U=z[0],Q=z[1];Tn(U,function(I,K){if(I)return Q(I);q4.open(K,uN0,U.mode||384,function(W,H){if(W)return Q(W);if(U.discardDescriptor)return q4.close(H,function(Z){return Q(Z,K,void 0,Pn(K,-1,U,!1))});else{let X=U.discardDescriptor||U.detachDescriptor;Q(null,K,H,Pn(K,X?-1:H,U,!1))}})})}function WM1($){let Y=pI($),z=Y[0],U=z.discardDescriptor||z.detachDescriptor,Q=jn(z),J=q4.openSync(Q,uN0,z.mode||384);if(z.discardDescriptor)q4.closeSync(J),J=void 0;return{name:Q,fd:J,removeCallback:Pn(Q,U?-1:J,z,!0)}}function HM1($,Y){let z=pI($,Y),U=z[0],Q=z[1];Tn(U,function(I,K){if(I)return Q(I);q4.mkdir(K,U.mode||448,function(W){if(W)return Q(W);Q(null,K,nN0(K,U,!1))})})}function XM1($){let Y=pI($),z=Y[0],U=jn(z);return q4.mkdirSync(U,z.mode||448),{name:U,removeCallback:nN0(U,z,!0)}}function ZM1($,Y){let z=function(U){if(U&&!An(U))return Y(U);Y()};if(0<=$[0])q4.close($[0],function(){q4.unlink($[1],z)});else q4.unlink($[1],z)}function qM1($){let Y=null;try{if(0<=$[0])q4.closeSync($[0])}catch(z){if(!OM1(z)&&!An(z))throw z}finally{try{q4.unlinkSync($[1])}catch(z){if(!An(z))Y=z}}if(Y!==null)throw Y}function Pn($,Y,z,U){let Q=FP(qM1,[Y,$],U),J=FP(ZM1,[Y,$],U,Q);if(!z.keep)nI.unshift(Q);return U?Q:J}function nN0($,Y,z){let U=Y.unsafeCleanup?KM1:q4.rmdir.bind(q4),Q=Y.unsafeCleanup?cN0:bN0,J=FP(Q,$,z),I=FP(U,$,z,J);if(!Y.keep)nI.unshift(J);return z?J:I}function FP($,Y,z,U){let Q=!1;return function J(I){if(!Q){let K=U||J,G=nI.indexOf(K);if(G>=0)nI.splice(G,1);if(Q=!0,z||$===bN0||$===cN0)return $(Y);else return $(Y,I||function(){})}}}function VM1(){if(!iN0)return;while(nI.length)try{nI[0]()}catch($){}}function yN0($){let Y=[],z=null;try{z=gN0.randomBytes($)}catch(U){z=gN0.pseudoRandomBytes($)}for(let U=0;U<$;U++)Y.push("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[z[U]%62]);return Y.join("")}function r8($){return typeof $>"u"}function pI($,Y){if(typeof $==="function")return[{},$];if(r8($))return[{},Y];let z={};for(let U of Object.getOwnPropertyNames($))z[U]=$[U];return[z,Y]}function LM1($,Y,z){let U=E6.isAbsolute($)?$:E6.join(Y,$);q4.stat(U,function(Q){if(Q)q4.realpath(E6.dirname(U),function(J,I){if(J)return z(J);z(null,E6.join(I,E6.basename(U)))});else q4.realpath(U,z)})}function FM1($,Y){let z=E6.isAbsolute($)?$:E6.join(Y,$);try{return q4.statSync(z),q4.realpathSync(z)}catch(U){let Q=q4.realpathSync(E6.dirname(z));return E6.join(Q,E6.basename(z))}}function pN0($){let Y=$.tmpdir;if(!r8($.name))return E6.join(Y,$.dir,$.name);if(!r8($.template))return E6.join(Y,$.dir,$.template).replace(fN0,yN0(6));let z=[$.prefix?$.prefix:"tmp","-",process.pid,"-",yN0(12),$.postfix?"-"+$.postfix:""].join("");return E6.join(Y,$.dir,z)}function Bn($,Y){if(typeof Y!=="string")throw Error(`${$} option must be a string, got "${typeof Y}".`);if(Y.includes(".."))throw Error("Relative value not allowed");return Y}function dN0($){if(!r8($.name)){let Y=$.name;if(E6.isAbsolute(Y))throw Error(`name option must not contain an absolute path, found "${Y}".`);let z=E6.basename(Y);if(z===".."||z==="."||z!==Y)throw Error(`name option must not contain a path, found "${Y}".`)}if(!r8($.template)){if(typeof $.template!=="string")throw Error(`template option must be a string, got "${typeof $.template}".`);if(!$.template.match(fN0))throw Error(`Invalid template, found "${$.template}".`)}if(!r8($.tries)&&isNaN($.tries)||$.tries<0)throw Error(`Invalid tries, found "${$.tries}".`);$.tries=r8($.name)?$.tries||3:1,$.keep=!!$.keep,$.detachDescriptor=!!$.detachDescriptor,$.discardDescriptor=!!$.discardDescriptor,$.unsafeCleanup=!!$.unsafeCleanup,$.prefix=r8($.prefix)?"":Bn("prefix",$.prefix),$.postfix=r8($.postfix)?"":Bn("postfix",$.postfix),$.template=r8($.template)?void 0:Bn("template",$.template)}function kN0($,Y,z,U){if(r8(Y))return U(null);LM1(Y,z,function(Q,J){if(Q)return U(Q);let I=E6.relative(z,J);if(I.startsWith("..")||E6.isAbsolute(I))return U(Error(`${$} option must be relative to "${z}", found "${I}".`));U(null,I)})}function xN0($,Y,z){if(r8(Y))return;let U=FM1(Y,z),Q=E6.relative(z,U);if(Q.startsWith("..")||E6.isAbsolute(Q))thrLine truncated
`)}let U=[];Y.forEach((Q,J)=>{let I=$.length+J+1,K=J===0?"⏳ ":"";U.push(`${K}${I}. ${Q}`)});for(let Q=$.length-1;Q>=0;Q--){let J=Q+1;U.push(`${J}. ${$[Q]}`)}return U.join(`
`)}function xn($,Y,z,U,Q){let J=$?.operator||Y?.operator||z?.operator,I=J?.name||J?.id||z?.operatorName||"",K=($?.nodeName||Y?.fromNodeName||Y?.nodeName||z?.nodeName||"").trim();if(K==="合思审批节点"||K==="外部审批节点"||K.includes("合思审批")||K.includes("外部审批"))K="";if((!K||K==="提交人"||K==="审批节点")&&I&&U){let M=U.find((w)=>w.operator?.name===I&&w.nodeName&&w.nodeName.trim()!=="提交人"&&!w.isEbot&&w.rawAction!=="freeflow.reject");if(M?.nodeName)K=M.nodeName.trim()}let W=$?.comment||Y?.reason||z?.rejectComment||"修改";if(W.includes(":")){let M=W.split(":");if(M.length>1)W=M.slice(1).join(":").trim()}let H=W;if(K&&I)H=`${K}(${I}) ❌: ${W}`;else if(I)H=`${I} ❌: ${W}`;else if(K)H=`${K} ❌: ${W}`;else H=W;let X=$?.rejectTargetNodeName||Y?.targetNodeName||"提交人",Z=$?.rejectTargetOperator?.name||Y?.targetOperator?.name||Q?.submitter?.name,q=Z?`${X}(${Z})`:X,V=$?.resubmitRuleText||Y?.resubmitRuleText||(I?`重新提交后由${I}继续审批`:"重新提交后继续审批");return{comment:`${H}
↳ 驳回至: ${q}
↳ ${V}`,operator:J}}function CD0($){if(!$)return[];let Y=$.pending||[],z=String($.rawState||"").toUpperCase(),U=String($.state||"").toUpperCase(),Q=[];if(Y.length>0)for(let J of Y){let I=J.approver?.name||J.approver?.id||"待定",K=(J.name||$.currentNode||"").trim(),G=K?`${K}(${I})`:I,H=J.type?.toUpperCase()==="PAYING"||K.includes("支付")||z==="PAYING"||U==="支付中"?"待支付":"待审批";Q.push(`${G}: ${H}`)}else if($.currentNode?.trim()){let I=$.currentNode.includes("支付")||z==="PAYING"||U==="支付中"?"待支付":"待审批";Q.push(`${$.currentNode.trim()}: ${I}`)}return Q}function QU($,Y){let z=new Map;if(!$||$.length===0)return z;if(!Y){for(let q of $){let F=(q.result||{}).decision||q.aiDecision||"-";z.set(q.id,{recordId:q.id,sourceDocumentSN:q.sourceDocumentSN,taskMode:q.taskMode,aiDecision:ED0(typeof F==="string"?F:"-"),aiAction:"-",eHumanAction:"-",eHumanComment:"-",auditDrift:!1})}return z}let U=[...$].sort((q,V)=>(Number(q.createdAt)||0)-(Number(V.createdAt)||0)),Q=Y.history||[],J=String(Y.rawState||"").toUpperCase(),I=String(Y.state||"").toUpperCase(),K=J==="DRAFT"||J==="REVOKED"||J==="CANCELED"||J==="CANCELLED"||I==="草稿"||I==="已撤回"||I==="已取消",G=J==="REJECTED"||J==="TERMINATED"||I==="审批驳回"||I==="已驳回",W=!K&&!G&&(J==="PAID"||I==="已支付"||Q.some((q)=>!q.isEbot&&(q.rawAction==="freeflow.pay"||q.action==="支付成功"||q.action==="支付完成"))),H=!K&&!G&&!W&&(J==="PAYING"||I==="支付中"||(Y.pending||[]).some((q)=>q.isCurrent&&(q.type?.toUpperCase()==="PAYING"||q.name?.includes("支付")))||Y.currentNode?.includes("支付")===!0),Z=W||!K&&!G&&!H&&(J==="COMPLETED"||J==="APPROVED"||I==="已完成"||I==="审批通过");for(let q=0;q<U.length;q++){let V=U[q];if(!V)continue;let F=Number(V.createdAt)||0,M=V.document||{},w=V.manualApprovalRecord||V.result?.manualApprovalRecord||M.manualApprovalRecord||{},O=typeof V.sourceExtendData?.nodeId==="string"?String(V.sourceExtendData.nodeId):void 0,N=typeof w.nodeId==="string"?String(w.nodeId):void 0,D=N?decodeURIComponent(N).replace(/^hcnode_/,"").replace(/_r\d+$/,""):void 0,T=O||D,A=T?Q.find((B0)=>B0.nodeId&&(B0.nodeId===T||T.includes(B0.nodeId))):void 0,B=A?.time??F,j=U[q+1],C=j?Number(j.createdAt)||1/0:1/0,b=q===U.length-1,k=Q.find((B0)=>(B0.time??0)>B+5000&&B0.isEbot&&(B0.nodeName?.includes("智能")||B0.nodeName?.includes("AI")||B0.action?.includes("智能")||B0.comment?.includes("AI")||B0.comment?.includes("approval-result"))&&!B0.nodeName?.includes("费用标准检查")&&!B0.nodeName?.includes("标准检查")&&!B0.nodeName?.includes("预算"));if(k){if(b=!1,(k.time??1/0)<C)C=k.time}let h=V.result||{},i=h.decision||V.aiDecision||"-",c=typeof i==="string"?i:"-",U0=c.toUpperCase(),x=U0==="REJECT"||U0==="驳回",d=U0==="APPROVE"||U0==="通过",t=U0==="EXEMPT_APPROVE"||U0==="免审通过"||U0==="备注通过",$0=V.taskMode||V.finalExecutionMode||"",p=String($0).toLowerCase().includes("auto")||V.finalExecutionMode==="automatic"||$0==="automatic"||$0==="fully_automatic",e="-";if(d||t)e="添加评论";else if(x)e=p?"驳回":"添加评论";else if(U0==="REVIEW"||U0==="转交复核")e="转交复核";let y=typeof w.status==="object"&&w.status!==null?String(w.status.type||w.status.label||"").toUpperCase():"",s=typeof w.status==="object"&&w.status!==null?String(w.status.sourceStatus||""):"",Y0=M.manualApprovalStatus||h.manualApprovalStatus||V.manualApprovalStatus,M0=typeof Y0==="string"?Y0.toUpperCase():"",E0=M0==="CANCELLED"||M0==="CANCELED"||M0==="已取消"||M0==="已撤回"||M0==="REVOKED"||y==="CANCELLED"||y==="CANCELED"||s.includes("撤回")||s.includes("取消"),G0=M0==="APPROVED"||M0==="已支付/审批完成"||M0==="已通过"||M0==="已完成"||M0==="已支付"||y==="APPROVED",b0=!(s.includes("补偿")||s.includes("已支付"))&&(M0==="TERMINATED"||M0==="REJECTED"||M0==="REJECT"||M0==="已驳回"||M0==="被驳回"||y==="TERMINATED"||y==="REJECTED"||y==="已驳回"||y==="被驳回"),Y1=A?1000:60000,a=Q.filter((B0)=>{let Q0=B0.time??0;return Q0>=B-Y1&&Q0<C}),H0="-",L0="-",f0=!1,u0,i0,D1=d||t,k1=Q.filter((B0)=>(B0.time??0)>B+5000),u1=k1.some((B0)=>B0.rawAction==="freeflow.retract"||B0.action==="单据撤回"),b1=k1.some((B0)=>B0.rawAction==="freeflow.submit"||B0.action==="提交送审");if(D1&&b&&(u1||b1))f0=!0,u0="AI通过后单据发生撤回/修改重提,后续未经AI复审";if(p&&x)H0="无操作",L0="-";else{let B0=a.filter((v)=>(v.time??0)>=B-1000&&!v.isEbot&&v.rawAction!=="freeflow.submit"&&v.action!=="提交送审"&&!((v.rawAction==="freeflow.comment"||v.action==="发表评论")&&!v.comment)&&!((v.rawAction==="freeflow.print"||v.action==="打印提醒")&&!v.comment)&&!(v.rawAction==="freeflow.carbonCopy"||v.rawAction==="freeflow.cc"||v.action==="抄送通知")),Q0=B0.find((v)=>v.rawAction==="freeflow.retract"||v.action==="单据撤回"),P=B0.find((v)=>v.rawAction==="freeflow.reject"||v.action==="审批驳回");if(!b)if(P||!Y&&b0){H0="审批驳回",f0=!1,u0=void 0;let v=xn(P,void 0,w,Q,Y);L0=v.commen Line truncated
`,{mode:384}),Y}function tn($){let Y=lD0();for(let z of Y){if(!V$(z))continue;for(let U of _P(z).filter((Q)=>Q.endsWith(".json")).filter((Q)=>!Q.startsWith("example."))){let Q=N9(z,U);try{let J=hP(Q,"utf-8"),I=JSON.parse(J);if(I&&typeof I==="object"&&I.id===$)return Q}catch{}}}return}function x2($,Y){let z=tn($);if(!z)throw Error(`Enterprise config not found: ${$}`);let Q={...JSON.parse(hP(z,"utf-8")),...Y};for(let I of Object.keys(Y))if(Y[I]===void 0)delete Q[I];let J=on.parse(Q);return iD0(z,`${JSON.stringify(J,null,2)}
`,"utf-8"),J}var sn="SEAL_USE_ENTERPRISES_DIR",cD0="SEAL_HOME_ENTERPRISES_DIR",nD0="SEAL_USE_USER_ENTERPRISES_DIR",pD0="SEAL_HOME_USER_ENTERPRISES_DIR",dD0="SEAL_USE_CONFIG_FILE",mD0="SEAL_HOME_CONFIG_FILE",oI,vP,RP,uD0;var S7=o(()=>{rn();oI=N9(SP(),".config","seal-use","enterprises"),vP=N9(SP(),".config","seal-home","enterprises"),RP=N9(SP(),".config","seal-use","config.json"),uD0=N9(SP(),".config","seal-home","config.json")});function f2($,Y,z=[]){let U=Y.corpId?.trim()||void 0,Q=Y.stateful?Y.defaultCorpId?.trim()||void 0:void 0,J=U??Q;if(J){let K=$.find((H)=>H.id===J);if(K)return K;let G=$.find((H)=>H.id.toLowerCase()===J.toLowerCase());if(G)return G;let W=$.find((H)=>H.name.toLowerCase()===J.toLowerCase());if(W)return W;throw Error(`No enterprise config found for ${J}`)}if(!Y.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 I=$[0];if(I)return I;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(z.length?z.join(", "):"the configured enterprise directories"))}import{existsSync as en,mkdirSync as tO1,readFileSync as eO1,renameSync as $N1,unlinkSync as YN1,writeFileSync as zN1}from"node:fs";import{homedir as UN1}from"node:os";import{dirname as QN1,join as JN1}from"node:path";function jZ(){let $=process.env[IN1]?.trim();if($)return $;return KN1}function oD0($=new Date){return $.toISOString().slice(0,10)}function rD0($=$p,Y=new Date){let z=Y.getTime()-Math.max(0,$-1)*86400000;return new Date(z).toISOString().slice(0,10)}function sD0($=jZ()){if(!en($))return{};try{let Y=eO1($,"utf-8"),z=JSON.parse(Y);if(z&&typeof z==="object"&&!Array.isArray(z))return z;return{}}catch{return{}}}function GN1($,Y){let z={};for(let[U,Q]of Object.entries($)){if(!Q||typeof Q!=="object")continue;let J={},I=!1;for(let[K,G]of Object.entries(Q))if(typeof G==="number"&&G>0&&K>=Y)J[K]=G,I=!0;if(I)z[U]=J}return z}function WN1($,Y=jZ()){let z=QN1(Y);if(!en(z))tO1(z,{recursive:!0,mode:448});let U=`${Y}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{zN1(U,JSON.stringify($,null,2),{encoding:"utf-8",mode:384}),$N1(U,Y)}catch(Q){try{if(en(U))YN1(U)}catch{}throw Q}}function aD0($,Y=new Date){if(!$||typeof $!=="string")return;try{let z=jZ(),U=sD0(z),Q=oD0(Y),J=rD0($p,Y),I=GN1(U,J);I[$]=I[$]||{},I[$][Q]=(I[$][Q]??0)+1,WN1(I,z)}catch{}}function HN1($,Y=$p,z=new Date){let U=new Map;try{let Q=sD0(),J=rD0(Y,z),I=oD0(z),K=$??Object.keys(Q);for(let G of K){let W=Q[G];if(!W){U.set(G,0);continue}let H=0;for(let[X,Z]of Object.entries(W))if(X>=J&&X<=I&&typeof Z==="number")H+=Z;U.set(G,H)}}catch{if($)for(let Q of $)U.set(Q,0)}return U}function tD0($,Y,z){let U=z??HN1($.map((Q)=>Q.id));return[...$].sort((Q,J)=>{if(Y){if(Q.id===Y&&J.id!==Y)return-1;if(J.id===Y&&Q.id!==Y)return 1}let I=U.get(Q.id)??0,K=U.get(J.id)??0;if(I!==K)return K-I;let G=Q.name??Q.id,W=J.name??J.id,H=G.localeCompare(W,"zh-CN");if(H!==0)return H;return Q.id.localeCompare(J.id)})}var IN1="SEAL_USE_USAGE_FILE",KN1,$p=7;var gP=o(()=>{KN1=JN1(UN1(),".config","seal-use","usage.json")});function XN1($,Y){return $.map((z)=>z.trim()).filter(Boolean).map((z)=>Y?z:z.toLowerCase())}function ZN1($,Y){return Y?$:$.toLowerCase()}function qN1($,Y,z,U){let Q=ZN1($,U),J=Y.filter((I)=>Q.includes(I));if(z==="all"&&J.length!==Y.length)return[];return J}function VN1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function LN1($,Y){if(Y.fields&&!Y.fields.has($.field))return[];let z=VN1($.value),U=[];return z.forEach((Q,J)=>{let I=qN1(Q,Y.keywords,Y.matchMode,Y.caseSensitive);if(I.length===0)return;let K=Math.max(0,J-Y.contextLines),G=Math.min(z.length,J+Y.contextLines+1),W={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:J+1,matchedKeywords:I,matchedText:yP(Q,Y.maxChars),context:{before:Y.snippetOnly?[]:z.slice(K,J).map((H)=>yP(H,Y.maxChars)),line:yP(Q,Y.maxChars),after:Y.snippetOnly?[]:z.slice(J+1,G).map((H)=>yP(H,Y.maxChars))},metadata:$.metadata};if(Y.snippetOnly)W.context={before:[],line:W.context.line,after:[]};U.push(W)}),U}function yP($,Y){if(!Y||$.length<=Y)return $;return`${$.slice(0,Math.max(0,Y))}...`}function FN1($){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 $B0($){return $.rules.flatMap((Y,z)=>{let U=`${$.id}:${Y.description.slice(0,32)}`,Q={versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedByName:$.publishedByName,publishedAt:$.publishedAt,scope:Y.scope,strictness:Y.strictness,code:"code"in Y?Y.code:void 0,index:z};return[{area:"rules",entityType:"rule",entityId:U,title:`${$.versionName} / ${Y.scope}`,field:"h Line truncated
`+"为防止测试单据污染生产审批流,禁止向生产环境重放单据。请指定测试企业 (--target-corp <testCorpId>),或在确有需要时添加 --force。",1,`seal-use webhook replay --target-corp <testCorpId>${z.id!==U.id?` --source-corp ${z.id}`:""}`);return{sourceCorp:z,targetCorp:U}}async function Up($,Y,z){let U=Y.seal?.endpoints?.approvalStylePreferences??"api/v1/agent/ai-approval/config",Q=await J$($,U);if(z||Q.length>0)return JB0(Q,z,Y.id);if(Y.environment==="test"||Y.id.toLowerCase().includes("test")){console.error(`[webhook-replay] 测试企业「${Y.name}」未配置 Webhook 通道,正在自动创建「(Seal测-回放通道)」...`);let J=(Y.seal.url??Y.source?.sealUrl??`https://${Y.id.toLowerCase()}.sealai.cc`).replace(/\/+$/,"");return await WM($,J,{name:"(Seal测-回放通道)",mode:"assisted",outgoingResultWebhook:`${J}/api/v1/integrations/webhook/replay-mock-callback`},Y.seal.endpoints.approvalStylePreferences)}throw new w4(`当前租户「${Y.name}」未配置任何 Webhook 集成通道。`,1,`seal-use webhook add --name <name> --result-url <url> --corp ${Y.id}`)}async function rI($){let{query:Y,sourceClient:z,targetClient:U,sourceCorp:Q,targetCorp:J,webhookSelector:I,snPrefix:K,snSuffix:G,docIdPrefix:W,docIdSuffix:H,dryRun:X,fetchFn:Z=fetch}=$,q=[];if(Y.recordId){let T=await G4(z,Y.recordId);q.push(T)}else if(Y.recordIds&&Y.recordIds.length>0)for(let T of Y.recordIds)q.push(await G4(z,T));else if(Y.sn){let T=await b4(z,{sourceDocumentSN:Y.sn,limit:1});if(!T.records.length)throw Error(`在企业「${Q.name}」中未找到单据编号为「${Y.sn}」的审批记录。`);q.push(T.records[0])}else if(Y.sns&&Y.sns.length>0)for(let T of Y.sns){let A=await b4(z,{sourceDocumentSN:T,limit:1});if(!A.records.length)throw Error(`在企业「${Q.name}」中未找到单据编号为「${T}」的审批记录。`);q.push(A.records[0])}else if(Y.limit!==void 0){let T=await b4(z,{limit:Y.limit,status:Y.status,startDate:Y.startDate,endDate:Y.endDate});if(!T.records.length)throw Error(`在企业「${Q.name}」中未检索到符合条件的审批记录。`);q=T.records}else throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let V=q.map((T)=>({run:T,doc:Yp(T,{snPrefix:K,snSuffix:G,docIdPrefix:W,docIdSuffix:H})}));if(X){let T={id:"preview-webhook",name:I??"预览目标通道",mode:"assisted",incomingDocumentWebhookUrl:`${J.seal.url}/api/v1/integrations/webhook/preview`};try{let j=await J$(U,J.seal.endpoints.approvalStylePreferences);if(j.length>0){let C=JB0(j,I,J.id);T={id:C.id,name:C.name,mode:C.mode,incomingDocumentWebhookUrl:C.incomingDocumentWebhook.url}}}catch{}let A=V.map(({run:j,doc:C})=>({originalRecord:{id:j.id,sourceSystem:j.sourceSystem,sourceDocumentSN:j.sourceDocumentSN,sourceDocumentId:j.sourceDocumentId},document:C,success:!0})),B=A.length===1;return{dryRun:!0,success:!0,sourceCorp:{id:Q.id,name:Q.name,environment:Q.environment},targetCorp:{id:J.id,name:J.name,environment:J.environment},targetWebhook:T,totalCount:A.length,successCount:A.length,failureCount:0,originalRecord:B?A[0].originalRecord:void 0,document:B?A[0].document:void 0,records:A}}let F=await Up(U,J,I),M={id:F.id,name:F.name,mode:F.mode,incomingDocumentWebhookUrl:F.incomingDocumentWebhook.url},w=[],O=0,N=0;for(let{run:T,doc:A}of V){console.error(`[webhook-replay] 正在向 Webhook 通道「${F.name}」推送单据: ${A.documentSN}...`);try{let B=await zp(F.incomingDocumentWebhook.url,F.secret,A,Z,B6(J.seal));w.push({originalRecord:{id:T.id,sourceSystem:T.sourceSystem,sourceDocumentSN:T.sourceDocumentSN,sourceDocumentId:T.sourceDocumentId},replayedDocument:{documentSN:A.documentSN,documentId:A.documentId,fieldCount:A.fields.length},pushResult:B,success:!0}),O+=1}catch(B){let j=B instanceof Error?B.message:String(B);w.push({originalRecord:{id:T.id,sourceSystem:T.sourceSystem,sourceDocumentSN:T.sourceDocumentSN,sourceDocumentId:T.sourceDocumentId},replayedDocument:{documentSN:A.documentSN,documentId:A.documentId,fieldCount:A.fields.length},error:j,success:!1}),N+=1}}let D=w.length===1;return{success:N===0,dryRun:!1,sourceCorp:{id:Q.id,name:Q.name,environment:Q.environment},targetCorp:{id:J.id,name:J.name,environment:J.environment},targetWebhook:M,totalCount:w.length,successCount:O,failureCount:N,originalRecord:D?w[0].originalRecord:void 0,replayedDocument:D?w[0].replayedDocument:void 0,pushResult:D?w[0].pushResult:void 0,records:w}}var jN1;var RZ=o(()=>{kP();L$();X6();jN1=new Set(["TEXT","NUMBER","DATE","AMOUNT","PERSON","ATTACHMENT","DATE_RANGE","DEPARTMENT","LIST","CITY","OBJECT"])});var IB0,le1,CN1,oe1;var KB0=o(()=>{B$();IB0=L.object({level:L.enum(["error","warning","info"]),code:L.string(),message:L.string(),snippet:L.string().optional(),suggestion:L.string().optional()}),le1=L.object({score:L.number().min(0).max(100),passed:L.boolean(),issues:L.array(IB0)}),CN1=L.object({ruleId:L.string Line truncated
* ==============================================================================
* Seal 官方标准规则校验器 (Official Standard Rule Linter)
* ==============================================================================
@@ -866,55 +876,62 @@ export function lintRule(rule: RuleLintTarget): RuleLintResult {
}
export default lintRule;
`}});import{existsSync as oI,mkdirSync as vE1,readFileSync as hE1,readdirSync as tA0,rmSync as gE1,unlinkSync as SE1,writeFileSync as yE1}from"node:fs";import{homedir as xE1}from"node:os";import{isAbsolute as uE1,join as A6,resolve as kE1}from"node:path";import{pathToFileURL as rA0}from"node:url";function aA0($=x$){let I=[],z=[];try{if(!oI($))vE1($,{recursive:!0});let q=Object.keys(Pi);for(let[Y,J]of Object.entries(Pi)){let Q=A6($,Y),K=!0;if(oI(Q))try{if(hE1(Q,"utf8")===J)K=!1}catch{K=!0}if(K)yE1(Q,J,"utf8");I.push(Y)}let U=tA0($,{withFileTypes:!0});for(let Y of U)if(!q.includes(Y.name)){let J=A6($,Y.name);try{if(Y.isDirectory())gE1(J,{recursive:!0,force:!0});else SE1(J);z.push(Y.name)}catch{}}}catch{}return{synced:I,pruned:z}}function eA0($={syncOfficial:!0}){if($.syncOfficial!==!1)aA0();let I=[{name:"builtin",type:"builtin",path:A6(x$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:A6(x$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:A6(x$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],z=[y$,YD];for(let q of z)if(oI(q))try{let U=tA0(q,{withFileTypes:!0});for(let Y of U){if(Y.isDirectory())continue;let J=Y.name;if(J.endsWith(".ts")||J.endsWith(".js")||J.endsWith(".mjs")){let Q=J.replace(/\.(ts|js|mjs)$/,"");if(!I.some((K)=>K.name===Q))I.push({name:Q,type:"custom",path:A6(q,J),description:`用户自定义规则校验器 (${J})`})}}}catch{}return I}function bE1($){let I=($||"").trim();if(!I||I==="builtin"||I==="default"||I==="official/builtin"||I==="official/builtin.ts")return{path:A6(x$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(I==="strict"||I==="official/strict"||I==="official/strict.ts")return{path:A6(x$,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(I==="hlab"||I==="hlab-sop"||I==="hlab-rules"||I==="hlab-standard"||I==="official/hlab"||I==="official/hlab.ts")return{path:A6(x$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(uE1(I)||I.startsWith("./")||I.startsWith("../")){let q=kE1(I);if(oI(q))return{path:q};for(let U of[".ts",".js",".mjs"])if(oI(`${q}${U}`))return{path:`${q}${U}`}}let z=[A6(y$,`${I}.ts`),A6(y$,`${I}.js`),A6(y$,`${I}.mjs`),A6(YD,`${I}.ts`),A6(YD,`${I}.js`),A6(YD,`${I}.mjs`)];for(let q of z)if(oI(q))return{path:q};return{}}async function Ti($){aA0();let I=bE1($??"builtin");if(I.isOfficial){let q=I.officialKind==="strict"?lA0:I.officialKind==="hlab"?oA0:hY,U=I.officialKind==="builtin"?"builtin":"official",Y=I.path;if(Y&&oI(Y))try{let Q=await import(rA0(Y).href),K=Q.default??Q.lintRule??Q.linter??Q.lint;if(typeof K==="function")return{name:I.officialKind??"builtin",type:U,filePath:Y,linter:sA0(K,q)}}catch{}return{name:I.officialKind??"builtin",type:U,filePath:Y,linter:q}}let z=I.path;if(!z)return console.error(`⚠️ [linter] 未找到自定义校验器 "${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:hY};try{let U=await import(rA0(z).href),Y=U.default??U.lintRule??U.linter??U.lint;if(typeof Y!=="function")return console.error(`⚠️ [linter] 自定义校验器 "${z}" 未导出标准函数 (default / lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:hY};return{name:$??"custom",type:"custom",filePath:z,linter:sA0(Y,hY)}}catch(q){return console.error(`⚠️ [linter] 加载自定义校验器脚本 "${z}" 失败(语法错误或依赖缺失: ${q?.message??q}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:hY}}}function sA0($,I){return async(z,q)=>{try{let U=await $(z,q);if(U&&typeof U==="object"&&typeof U.score==="number"&&Array.isArray(U.issues))return U;return console.error("⚠️ [linter] 自定义校验器返回值格式不符合 RuleLintResult 契约,已回退至内置结果。"),I(z,q)}catch(U){return console.error("⚠️ [linter] 自定义校验器执行异常:",U),I(z,q)}}}var y$,fE1="official",x$,YD;var Ei=e(()=>{Ni();Ai();Bi();Di();y$=A6(xE1(),".config","seal-use","linters"),x$=A6(y$,fE1),YD=A6(process.cwd(),"linters")});async function ji($,I,z){let q=await I.linter($,z);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:q.score,passed:q.passed,issues:q.issues,description:$.description}}async function $P0($,I,z,q){let U=q?.minScore??0,Y=q?.level??"all",J=[],Q=0;for(let X of $){let w=await ji(X,I,z);Q+=w.score;let L=w.issues;if(Y==="error")L=w.issues.filter((F)=>F.level==="error");else if(Y==="warning")L=w.issues.filter((F)=>F.level==="warning"||F.level==="error");let O=L.every((F)=>F.level!=="error");if(q?.summary){if(L.length>0)J.push({...w,passed:O,issues:L})}else J.push({...w,passed:O,issues:L})}let K=$.length,H=K===0?100:Math.round(Q/K),G=J.filter((X)=>X.issues.length>0).length,Z=K-Line truncated
`,"utf8"),z}function UP0($){return $.map((I,z)=>{let q;if(typeof I.code==="number")q=`#${String(I.code).padStart(4,"0")}`;else if(typeof I.code==="string")q=I.code.startsWith("#")?I.code:`#${I.code}`;else q=`#${String(z+1).padStart(4,"0")}`;return{id:I.id,code:q,name:I.name,description:I.description,scope:I.scope,strictness:I.strictness}})}var YP0=()=>{};var JP0,W5;var gY=e(()=>{JP0=class JP0 extends Error{errors;warnings;constructor($,I=[]){super([`webhook 资源包校验失败:${$.length} 个错误`,...$.map((z)=>`- ${z}`)].join(`
`));this.errors=$;this.warnings=I;this.name="ResourcePackValidationError"}};W5=JP0});var GP0=M((d34,HP0)=>{HP0.exports=JD;function JD(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}JD.prototype.go=function($){if(this.pending<this.max)KP0(this,$);else this.waiting.push($)};JD.prototype.wait=function($){if(this.pending===0)$(this.error);else this.listeners.push($)};JD.prototype.hold=function(){return QP0(this)};function QP0($){$.pending+=1;var I=!1;return z;function z(U){if(I)throw Error("callback called twice");if(I=!0,$.error=$.error||U,$.pending-=1,$.waiting.length>0&&$.pending<$.max)KP0($,$.waiting.shift());else if($.pending===0){var Y=$.listeners;$.listeners=[],Y.forEach(q)}}function q(U){U($.error)}}function KP0($,I){I(QP0($))}});var XP0=M((rE1)=>{var Ri=d("fs"),vi=d("util"),ZP0=d("stream"),WP0=ZP0.Readable,lE1=ZP0.PassThrough,oE1=GP0(),QD=d("events").EventEmitter;rE1.BufferSlicer=yY;rE1.FdSlicer=SY;vi.inherits(SY,QD);function SY($){QD.call(this),this.fd=$,this.pend=new oE1,this.pend.max=1,this.refCount=0}SY.prototype.read=function($,I,z,q,U){var Y=this;Y.pend.go(function(J){Ri.read(Y.fd,$,I,z,q,function(Q,K,H){J(),U(Q,K,H)})})};SY.prototype.createReadStream=function($){return new ZZ(this,$)};SY.prototype.ref=function(){this.refCount+=1};SY.prototype.unref=function(){var $=this;if($.refCount-=1,$.refCount<0)throw Error("invalid unref");if($.refCount>0)return;Ri.close($.fd,I);function I(z){if(z)$.emit("error",z);else $.emit("close")}};vi.inherits(ZZ,WP0);function ZZ($,I){I=I||{},WP0.call(this,I),this.context=$,this.context.ref(),this.start=I.start||0,this.endOffset=I.end,this.pos=this.start}ZZ.prototype._read=function($){var I=this,z=Math.min(I._readableState.highWaterMark,$);if(I.endOffset!=null)z=Math.min(z,I.endOffset-I.pos);if(z<=0){I.push(null),this._cleanup();return}I.context.pend.go(function(q){var U=Buffer.allocUnsafe(z);Ri.read(I.context.fd,U,0,z,I.pos,function(Y,J){if(Y)I.destroy(Y);else if(J===0)I.push(null),I._cleanup();else I.pos+=J,I.push(U.slice(0,J));q()})})};ZZ.prototype._destroy=function($,I){this._cleanup(),I($)};ZZ.prototype._cleanup=function(){if(this.context!=null)this.context.unref(),this.context=null};vi.inherits(yY,QD);function yY($){QD.call(this),this.refCount=0,this.buffer=$}yY.prototype.read=function($,I,z,q,U){if(!(0<=I&&I<=$.length))throw RangeError("offset outside buffer: 0 <= "+I+" <= "+$.length);if(q<0)throw RangeError("position is negative: "+q);if(I+z>$.length)z=$.length-I;if(q+z>this.buffer.length)z=this.buffer.length-q;if(z<=0){setImmediate(function(){U(null,0)});return}this.buffer.copy($,I,q,q+z),setImmediate(function(){U(null,z)})};yY.prototype.createReadStream=function($){$=$||{};var I=new lE1($);I.start=$.start||0,I.endOffset=$.end,I.pos=I.endOffset||this.buffer.length;var z=this.buffer.slice(I.start,I.pos),q=65536,U=0;while(!0){var Y=U+q;if(Y>=z.length){if(U<z.length)I.write(z.slice(U,z.length));break}I.write(z.slice(U,Y)),U=Y}return I.end(),I};yY.prototype.ref=function(){this.refCount+=1};yY.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw Error("invalid unref")}});var wP0=M((l34,VP0)=>{var aE1=new Int32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090 Line truncated
`}});import{existsSync as KU,mkdirSync as cN1,readFileSync as nN1,readdirSync as ZB0,rmSync as pN1,unlinkSync as dN1,writeFileSync as mN1}from"node:fs";import{homedir as lN1}from"node:os";import{isAbsolute as oN1,join as f6,resolve as rN1}from"node:path";import{pathToFileURL as HB0}from"node:url";function qB0($=i$){let Y=[],z=[];try{if(!KU($))cN1($,{recursive:!0});let U=Object.keys(Kp);for(let[J,I]of Object.entries(Kp)){let K=f6($,J),G=!0;if(KU(K))try{if(nN1(K,"utf8")===I)G=!1}catch{G=!0}if(G)mN1(K,I,"utf8");Y.push(J)}let Q=ZB0($,{withFileTypes:!0});for(let J of Q)if(!U.includes(J.name)){let I=f6($,J.name);try{if(J.isDirectory())pN1(I,{recursive:!0,force:!0});else dN1(I);z.push(J.name)}catch{}}}catch{}return{synced:Y,pruned:z}}function VB0($={syncOfficial:!0}){if($.syncOfficial!==!1)qB0();let Y=[{name:"builtin",type:"builtin",path:f6(i$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:f6(i$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:f6(i$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],z=[b$,uP];for(let U of z)if(KU(U))try{let Q=ZB0(U,{withFileTypes:!0});for(let J of Q){if(J.isDirectory())continue;let I=J.name;if(I.endsWith(".ts")||I.endsWith(".js")||I.endsWith(".mjs")){let K=I.replace(/\.(ts|js|mjs)$/,"");if(!Y.some((G)=>G.name===K))Y.push({name:K,type:"custom",path:f6(U,I),description:`用户自定义规则校验器 (${I})`})}}}catch{}return Y}function aN1($){let Y=($||"").trim();if(!Y||Y==="builtin"||Y==="default"||Y==="official/builtin"||Y==="official/builtin.ts")return{path:f6(i$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(Y==="strict"||Y==="official/strict"||Y==="official/strict.ts")return{path:f6(i$,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(Y==="hlab"||Y==="hlab-sop"||Y==="hlab-rules"||Y==="hlab-standard"||Y==="official/hlab"||Y==="official/hlab.ts")return{path:f6(i$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(oN1(Y)||Y.startsWith("./")||Y.startsWith("../")){let U=rN1(Y);if(KU(U))return{path:U};for(let Q of[".ts",".js",".mjs"])if(KU(`${U}${Q}`))return{path:`${U}${Q}`}}let z=[f6(b$,`${Y}.ts`),f6(b$,`${Y}.js`),f6(b$,`${Y}.mjs`),f6(uP,`${Y}.ts`),f6(uP,`${Y}.js`),f6(uP,`${Y}.mjs`)];for(let U of z)if(KU(U))return{path:U};return{}}async function Wp($){qB0();let Y=aN1($??"builtin");if(Y.isOfficial){let U=Y.officialKind==="strict"?GB0:Y.officialKind==="hlab"?WB0:sI,Q=Y.officialKind==="builtin"?"builtin":"official",J=Y.path;if(J&&KU(J))try{let K=await import(HB0(J).href),G=K.default??K.lintRule??K.linter??K.lint;if(typeof G==="function")return{name:Y.officialKind??"builtin",type:Q,filePath:J,linter:XB0(G,U)}}catch{}return{name:Y.officialKind??"builtin",type:Q,filePath:J,linter:U}}let z=Y.path;if(!z)return console.error(`⚠️ [linter] 未找到自定义校验器 "${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:sI};try{let Q=await import(HB0(z).href),J=Q.default??Q.lintRule??Q.linter??Q.lint;if(typeof J!=="function")return console.error(`⚠️ [linter] 自定义校验器 "${z}" 未导出标准函数 (default / lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:sI};return{name:$??"custom",type:"custom",filePath:z,linter:XB0(J,sI)}}catch(U){return console.error(`⚠️ [linter] 加载自定义校验器脚本 "${z}" 失败(语法错误或依赖缺失: ${U?.message??U}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:sI}}}function XB0($,Y){return async(z,U)=>{try{let Q=await $(z,U);if(Q&&typeof Q==="object"&&typeof Q.score==="number"&&Array.isArray(Q.issues))return Q;return console.error("⚠️ [linter] 自定义校验器返回值格式不符合 RuleLintResult 契约,已回退至内置结果。"),Y(z,U)}catch(Q){return console.error("⚠️ [linter] 自定义校验器执行异常:",Q),Y(z,U)}}}var b$,sN1="official",i$,uP;var Hp=o(()=>{Qp();Ip();Gp();Jp();b$=f6(lN1(),".config","seal-use","linters"),i$=f6(b$,sN1),uP=f6(process.cwd(),"linters")});async function Xp($,Y,z){let U=await Y.linter($,z);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:U.score,passed:U.passed,issues:U.issues,description:$.description}}async function LB0($,Y,z,U){let Q=U?.minScore??0,J=U?.level??"all",I=[],K=0;for(let q of $){let V=await Xp(q,Y,z);K+=V.score;let F=V.issues;if(J==="error")F=V.issues.filter((w)=>w.level==="error");else if(J==="warning")F=V.issues.filter((w)=>w.level==="warning"||w.level==="error");let M=F.every((w)=>w.level!=="error");if(U?.summary){if(F.length>0)I.push({...V,passed:M,issues:F})}else I.push({...V,passed:M,issues:F})}let G=$.length,W=G===0?100:Math.round(K/G),H=I.filter((q)=>q.issues.length>0).length,X=G-Line truncated
`,"utf8"),z}function OB0($){return $.map((Y,z)=>{let U;if(typeof Y.code==="number")U=`#${String(Y.code).padStart(4,"0")}`;else if(typeof Y.code==="string")U=Y.code.startsWith("#")?Y.code:`#${Y.code}`;else U=`#${String(z+1).padStart(4,"0")}`;return{id:Y.id,code:U,name:Y.name,description:Y.description,scope:Y.scope,strictness:Y.strictness}})}var NB0=()=>{};var DB0,D5;var aI=o(()=>{DB0=class DB0 extends Error{errors;warnings;constructor($,Y=[]){super([`webhook 资源包校验失败:${$.length} 个错误`,...$.map((z)=>`- ${z}`)].join(`
`));this.errors=$;this.warnings=Y;this.name="ResourcePackValidationError"}};D5=DB0});var TB0=E((B04,AB0)=>{AB0.exports=bP;function bP(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}bP.prototype.go=function($){if(this.pending<this.max)PB0(this,$);else this.waiting.push($)};bP.prototype.wait=function($){if(this.pending===0)$(this.error);else this.listeners.push($)};bP.prototype.hold=function(){return BB0(this)};function BB0($){$.pending+=1;var Y=!1;return z;function z(Q){if(Y)throw Error("callback called twice");if(Y=!0,$.error=$.error||Q,$.pending-=1,$.waiting.length>0&&$.pending<$.max)PB0($,$.waiting.shift());else if($.pending===0){var J=$.listeners;$.listeners=[],J.forEach(U)}}function U(Q){Q($.error)}}function PB0($,Y){Y(BB0($))}});var CB0=E((ID1)=>{var Vp=I0("fs"),Lp=I0("util"),jB0=I0("stream"),EB0=jB0.Readable,QD1=jB0.PassThrough,JD1=TB0(),iP=I0("events").EventEmitter;ID1.BufferSlicer=eI;ID1.FdSlicer=tI;Lp.inherits(tI,iP);function tI($){iP.call(this),this.fd=$,this.pend=new JD1,this.pend.max=1,this.refCount=0}tI.prototype.read=function($,Y,z,U,Q){var J=this;J.pend.go(function(I){Vp.read(J.fd,$,Y,z,U,function(K,G,W){I(),Q(K,G,W)})})};tI.prototype.createReadStream=function($){return new _Z(this,$)};tI.prototype.ref=function(){this.refCount+=1};tI.prototype.unref=function(){var $=this;if($.refCount-=1,$.refCount<0)throw Error("invalid unref");if($.refCount>0)return;Vp.close($.fd,Y);function Y(z){if(z)$.emit("error",z);else $.emit("close")}};Lp.inherits(_Z,EB0);function _Z($,Y){Y=Y||{},EB0.call(this,Y),this.context=$,this.context.ref(),this.start=Y.start||0,this.endOffset=Y.end,this.pos=this.start}_Z.prototype._read=function($){var Y=this,z=Math.min(Y._readableState.highWaterMark,$);if(Y.endOffset!=null)z=Math.min(z,Y.endOffset-Y.pos);if(z<=0){Y.push(null),this._cleanup();return}Y.context.pend.go(function(U){var Q=Buffer.allocUnsafe(z);Vp.read(Y.context.fd,Q,0,z,Y.pos,function(J,I){if(J)Y.destroy(J);else if(I===0)Y.push(null),Y._cleanup();else Y.pos+=I,Y.push(Q.slice(0,I));U()})})};_Z.prototype._destroy=function($,Y){this._cleanup(),Y($)};_Z.prototype._cleanup=function(){if(this.context!=null)this.context.unref(),this.context=null};Lp.inherits(eI,iP);function eI($){iP.call(this),this.refCount=0,this.buffer=$}eI.prototype.read=function($,Y,z,U,Q){if(!(0<=Y&&Y<=$.length))throw RangeError("offset outside buffer: 0 <= "+Y+" <= "+$.length);if(U<0)throw RangeError("position is negative: "+U);if(Y+z>$.length)z=$.length-Y;if(U+z>this.buffer.length)z=this.buffer.length-U;if(z<=0){setImmediate(function(){Q(null,0)});return}this.buffer.copy($,Y,U,U+z),setImmediate(function(){Q(null,z)})};eI.prototype.createReadStream=function($){$=$||{};var Y=new QD1($);Y.start=$.start||0,Y.endOffset=$.end,Y.pos=Y.endOffset||this.buffer.length;var z=this.buffer.slice(Y.start,Y.pos),U=65536,Q=0;while(!0){var J=Q+U;if(J>=z.length){if(Q<z.length)Y.write(z.slice(Q,z.length));break}Y.write(z.slice(Q,J)),Q=J}return Y.end(),Y};eI.prototype.ref=function(){this.refCount+=1};eI.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw Error("invalid unref")}});var _B0=E((A04,RB0)=>{var WD1=new Int32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462, 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 lP0=M((sj1)=>{var Xn=I3().Buffer;sj1._dbcs=q3;var p6=-1,mP0=-2,f$=-10,N8=-1000,nY=Array(256),VZ=-1;for(XZ=0;XZ<256;XZ++)nY[XZ]=p6;var XZ;function q3($,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 z=$.table();this.decodeTables=[],this.decodeTables[0]=nY.slice(0),this.decodeTableSeq=[];for(var q=0;q<z.length;q++)this._addDecodeChunk(z[q]);if(typeof $.gb18030==="function"){this.gb18030=$.gb18030();var U=this.decodeTables.length;this.decodeTables.push(nY.slice(0));var Y=this.decodeTables.length;this.decodeTables.push(nY.slice(0));var J=this.decodeTables[0];for(var q=129;q<=254;q++){var Q=this.decodeTables[N8-J[q]];for(var K=48;K<=57;K++){if(Q[K]===p6)Q[K]=N8-U;else if(Q[K]>N8)throw Error("gb18030 decode tables conflict at byte 2");var H=this.decodeTables[N8-Q[K]];for(var G=129;G<=254;G++){if(H[G]===p6)H[G]=N8-Y;else if(H[G]===N8-Y)continue;else if(H[G]>N8)throw Error("gb18030 decode tables conflict at byte 3");var Z=this.decodeTables[N8-H[G]];for(var W=48;W<=57;W++)if(Z[W]===p6)Z[W]=mP0}}}}this.defaultCharUnicode=I.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var X={};if($.encodeSkipVals)for(var q=0;q<$.encodeSkipVals.length;q++){var w=$.encodeSkipVals[q];if(typeof w==="number")X[w]=!0;else for(var K=w.from;K<=w.to;K++)X[K]=!0}if(this._fillEncodeTable(0,0,X),$.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===p6)this.defCharSB=this.encodeTable[0]["?"];if(this.defCharSB===p6)this.defCharSB=63}q3.prototype.encoder=ND;q3.prototype.decoder=Vn;q3.prototype._getDecodeTrieNode=function($){var I=[];for(;$>0;$>>>=8)I.push($&255);if(I.length==0)I.push(0);var z=this.decodeTables[0];for(var q=I.length-1;q>0;q--){var U=z[I[q]];if(U==p6)z[I[q]]=N8-this.decodeTables.length,this.decodeTables.push(z=nY.slice(0));else if(U<=N8)z=this.decodeTables[N8-U];else throw Error("Overwrite byte in "+this.encodingName+", addr: "+$.toString(16))}return z};q3.prototype._addDecodeChunk=function($){var I=parseInt($[0],16),z=this._getDecodeTrieNode(I);I=I&255;for(var q=1;q<$.length;q++){var U=$[q];if(typeof U==="string")for(var Y=0;Y<U.length;){var J=U.charCodeAt(Y++);if(J>=55296&&J<56320){var Q=U.charCodeAt(Y++);if(Q>=56320&&Q<57344)z[I++]=65536+(J-55296)*1024+(Q-56320);else throw Error("Incorrect surrogate pair in "+this.encodingName+" at chunk "+$[0])}else if(J>4080&&J<=4095){var K=4095-J+2,H=[];for(var G=0;G<K;G++)H.push(U.charCodeAt(Y++));z[I++]=f$-this.decodeTableSeq.length,this.decodeTableSeq.push(H)}else z[I++]=J}else if(typeof U==="number"){var Z=z[I-1]+1;for(var Y=0;Y<U;Y++)z[I++]=Z++}else throw Error("Incorrect type '"+typeof U+"' given in "+this.encodingName+" at chunk "+$[0])}if(I>255)throw Error("Incorrect chunk in "+this.encoLine truncated
`;super(I);this.name="AggregateError",this.errors=$}}zT0.exports={AggregateError:IT0,ArrayIsArray($){return Array.isArray($)},ArrayPrototypeIncludes($,I){return $.includes(I)},ArrayPrototypeIndexOf($,I){return $.indexOf(I)},ArrayPrototypeJoin($,I){return $.join(I)},ArrayPrototypeMap($,I){return $.map(I)},ArrayPrototypePop($,I){return $.pop(I)},ArrayPrototypePush($,I){return $.push(I)},ArrayPrototypeSlice($,I,z){return $.slice(I,z)},Error,FunctionPrototypeCall($,I,...z){return $.call(I,...z)},FunctionPrototypeSymbolHasInstance($,I){return Function.prototype[Symbol.hasInstance].call($,I)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties($,I){return Object.defineProperties($,I)},ObjectDefineProperty($,I,z){return Object.defineProperty($,I,z)},ObjectGetOwnPropertyDescriptor($,I){return Object.getOwnPropertyDescriptor($,I)},ObjectKeys($){return Object.keys($)},ObjectSetPrototypeOf($,I){return Object.setPrototypeOf($,I)},Promise,PromisePrototypeCatch($,I){return $.catch(I)},PromisePrototypeThen($,I,z){return $.then(I,z)},PromiseReject($){return Promise.reject($)},PromiseResolve($){return Promise.resolve($)},ReflectApply:Reflect.apply,RegExpPrototypeTest($,I){return $.test(I)},SafeSet:Set,String,StringPrototypeSlice($,I,z){return $.slice(I,z)},StringPrototypeToLowerCase($){return $.toLowerCase()},StringPrototypeToUpperCase($){return $.toUpperCase()},StringPrototypeTrim($){return $.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet($,I,z){return $.set(I,z)},Boolean,Uint8Array}});var un=M((t74,qT0)=>{qT0.exports={format($,...I){return $.replace(/%([sdifj])/g,function(...[z,q]){let U=I.shift();if(q==="f")return U.toFixed(6);else if(q==="j")return JSON.stringify(U);else if(q==="s"&&typeof U==="object")return`${U.constructor!==Object?U.constructor.name:""} {}`.trim();else return U.toString()})},inspect($){switch(typeof $){case"string":if($.includes("'")){if(!$.includes('"'))return`"${$}"`;else if(!$.includes("`")&&!$.includes("${"))return`\`${$}\``}return`'${$}'`;case"number":if(isNaN($))return"NaN";else if(Object.is($,-0))return String($);return $;case"bigint":return`${String($)}n`;case"boolean":case"undefined":return String($);case"object":return"{}"}}}});var q8=M((a74,QT0)=>{var{format:c_1,inspect:ED}=un(),{AggregateError:p_1}=T4(),d_1=globalThis.AggregateError||p_1,m_1=Symbol("kIsNodeError"),l_1=["string","function","number","object","Function","Object","boolean","bigint","symbol"],o_1=/^([A-Z][a-z0-9]*)+$/,jD={};function tI($,I){if(!$)throw new jD.ERR_INTERNAL_ASSERTION(I)}function UT0($){let I="",z=$.length,q=$[0]==="-"?1:0;for(;z>=q+4;z-=3)I=`_${$.slice(z-3,z)}${I}`;return`${$.slice(0,z)}${I}`}function r_1($,I,z){if(typeof I==="function")return tI(I.length<=z.length,`Code: ${$}; The provided arguments length (${z.length}) does not match the required ones (${I.length}).`),I(...z);let q=(I.match(/%[dfijoOs]/g)||[]).length;if(tI(q===z.length,`Code: ${$}; The provided arguments length (${z.length}) does not match the required ones (${q}).`),z.length===0)return I;return c_1(I,...z)}function d6($,I,z){if(!z)z=Error;class q extends z{constructor(...U){super(r_1($,I,U))}toString(){return`${this.name} [${$}]: ${this.message}`}}Object.defineProperties(q.prototype,{name:{value:z.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${$}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),q.prototype.code=$,q.prototype[m_1]=!0,jD[$]=q}function YT0($){let I="__node_internal_"+$.name;return Object.defineProperty($,"name",{value:I}),$}function s_1($,I){if($&&I&&$!==I){if(Array.isArray(I.errors))return I.errors.push($),I;let z=new d_1([I,$],I.message);return z.code=I.code,z}return $||I}class JT0 extends Error{constructor($="The operation was aborted",I=void 0){if(I!==void 0&&typeof I!=="object")throw new jD.ERR_INVALID_ARG_TYPE("options","Object",I);super($,I);this.code="ABORT_ERR",this.name="AbortError"}}d6("ERR_ASSERTION","%s",Error);d6("ERR_INVALID_ARG_TYPE",($,I,z)=>{if(tI(typeof $==="string","'name' must be a string"),!Array.isArray(I))I=[I];let q="The ";if($.endsWith(" argument"))q+=`${$} `;else q+=`"${$}" ${$.includes(".")?"property":"argument"} `;q+="must be ";let U=[],Y=[],J=[];for(let K of I)if(tI(typeof K==="string","All expected entries have to be of type string"),l_1.includes(K))U.push(K.toLowerCase());else if(o_1.test(K))Y.push(K);else tI(K!=="object",'The value "object" should be written as "Object"'),J.push(K);if(Y.length>0){let K=U.indexOf("object");if(K!==-1)U.splice(U,K,1),Y.push("Object")}if(U.length>0){switch(U.length){case 1:q+=`of type ${U[Line truncated
`);if(I.linkname)z+=Vp(" linkpath="+I.linkname+`
`);let q=I.pax;if(q)for(let U in q)z+=Vp(" "+U+"="+q[U]+`
`);return T1.from(z)};lx1.decodePax=function(I){let z={};while(I.length){let q=0;while(q<I.length&&I[q]!==32)q++;let U=parseInt(T1.toString(I.subarray(0,q)),10);if(!U)return z;let Y=T1.toString(I.subarray(q+1,U-1)),J=Y.indexOf("=");if(J===-1)return z;z[Y.slice(0,J)]=Y.slice(J+1),I=I.subarray(U)}return z};lx1.encode=function(I){let z=T1.alloc(512),q=I.name,U="";if(I.typeflag===5&&q[q.length-1]!=="/")q+="/";if(T1.byteLength(q)!==q.length)return null;while(T1.byteLength(q)>100){let Y=q.indexOf("/");if(Y===-1)return null;U+=U?"/"+q.slice(0,Y):q.slice(0,Y),q=q.slice(Y+1)}if(T1.byteLength(q)>100||T1.byteLength(U)>155)return null;if(I.linkname&&T1.byteLength(I.linkname)>100)return null;if(T1.write(z,q),T1.write(z,I2(I.mode&4095,6),100),T1.write(z,I2(I.uid,6),108),T1.write(z,I2(I.gid,6),116),dx1(I.size,z,124),T1.write(z,I2(I.mtime.getTime()/1000|0,11),136),z[156]=48+cx1(I.type),I.linkname)T1.write(z,I.linkname,157);if(T1.copy(v_0,z,257),T1.copy(xx1,z,263),I.uname)T1.write(z,I.uname,265);if(I.gname)T1.write(z,I.gname,297);if(T1.write(z,I2(I.devmajor||0,6),329),T1.write(z,I2(I.devminor||0,6),337),U)T1.write(z,U,345);return T1.write(z,I2(g_0(z),6),148),z};lx1.decode=function(I,z,q){let U=I[156]===0?0:I[156]-48,Y=KJ(I,0,100,z),J=$2(I,100,8),Q=$2(I,108,8),K=$2(I,116,8),H=$2(I,124,12),G=$2(I,136,12),Z=nx1(U),W=I[157]===0?null:KJ(I,157,100,z),X=KJ(I,265,32),w=KJ(I,297,32),L=$2(I,329,8),O=$2(I,337,8),F=g_0(I);if(F===256)return null;if(F!==$2(I,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(fx1(I)){if(I[345])Y=KJ(I,345,155,z)+"/"+Y}else if(bx1(I));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:H,byteOffset:0,mtime:new Date(1000*G),type:Z,linkname:W,uname:X,gname:w,devmajor:L,devminor:O,pax:null}};function fx1($){return T1.equals(v_0,$.subarray(257,263))}function bx1($){return T1.equals(ux1,$.subarray(257,263))&&T1.equals(kx1,$.subarray(263,265))}function ix1($,I,z){if(typeof $!=="number")return z;if($=~~$,$>=I)return I;if($>=0)return $;if($+=I,$>=0)return $;return 0}function nx1($){switch($){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function cx1($){switch($){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function h_0($,I,z,q){for(;z<q;z++)if($[z]===I)return z;return q}function g_0($){let I=256;for(let z=0;z<148;z++)I+=$[z];for(let z=156;z<512;z++)I+=$[z];return I}function I2($,I){if($=$.toString(8),$.length>I)return"7777777777777777777".slice(0,I)+" ";return"0000000000000000000".slice(0,I-$.length)+$+" "}function px1($,I,z){I[z]=128;for(let q=11;q>0;q--)I[z+q]=$&255,$=Math.floor($/256)}function dx1($,I,z){if($.toString(8).length>11)px1($,I,z);else T1.write(I,I2($,11),z)}function mx1($){let I;if($[0]===128)I=!0;else if($[0]===255)I=!1;else return null;let z=[],q;for(q=$.length-1;q>0;q--){let J=$[q];if(I)z.push(J);else z.push(255-J)}let U=0,Y=z.length;for(q=0;q<Y;q++)U+=z[q]*Math.pow(256,q);return I?U:-1*U}function $2($,I,z){if($=$.subarray(I,I+z),I=0,$[I]&128)return mx1($);else{while(I<$.length&&$[I]===32)I++;let q=ix1(h_0($,32,I,$.length),$.length,$.length);while(I<q&&$[I]===0)I++;if(q===I)return 0;return parseInt(T1.toString($.subarray(I,q)),8)}}function KJ($,I,z,q){return T1.toString($.subarray(I,h_0($,0,I,I+z)),q)}function Vp($){let I=T1.byteLength($),z=Math.floor(Math.log(I)/Math.log(10))+1;if(I+z>=Math.pow(10,z))z++;return I+z+$}});var i_0=M((nI4,b_0)=>{var{Writable:ex1,Readable:$u1,getStreamError:S_0}=Xp(),Iu1=Yp(),y_0=QJ(),HJ=wp(),zu1=y_0.alloc(0);class x_0{constructor(){this.buffered=0,this.shifted=0,this.queue=new Iu1,this._offset=0}push($){this.buffered+=$.byteLength,this.queue.push($)}shiftFirst($){return this.buffered===0?null:this._next($)}shift($){if($>this.buffered)return null;if($===0)return zu1;let I=this._next($);if($===I.byteLength)return I;let z=[I];while(($-=I.byteLength)>0)I=this._next($),z.push(I);return y_0.concat(z)}_next($){let I=this.queue.peek(),z=I.byteLength-this._offset;if($>=z){let q=this._offset?I.subarray(this._offset,I.byteLength):I;return this.queue.shift(),this._offset=0,this.buffered-=z,this.shifted+=z,q}return this.buffered-=$,this.shifted+=$,I.subarray(this._offset,this._offset+=$)}}class u_0 extends $u1{constructor($,I,z){super();this.header=I,this.offset=z,this._parent=$}_read($){if(this.header.size===0)this.push(null);if(this._parent._stream===this)this._parent._update();$(null)}_predestroy(){this._parent.destroy(S_0(this))}_detach(){if(this._parent._stream= Line truncated
`),q=[await z4($,z.recordId)];else if(z.recordIds&&z.recordIds.length>0)process.stderr.write(`\uD83D\uDD0D 批量查询 ${z.recordIds.length} 条单据记录...
`),q=await Promise.all(z.recordIds.map((F)=>z4($,F)));else{let F=z.limit??10;process.stderr.write(`\uD83D\uDD0D 检索企业「${I.name}」(${I.id}) 的线上审核记录 (限制 ${F} 条)...
`);let P=(await a4($,{limit:F,status:z.status,startDate:z.startDate!==void 0?String(z.startDate):void 0,endDate:z.endDate!==void 0?String(z.endDate):void 0})).records??[];if(P.length===0)throw Error("未检索到符合条件的线上审核记录,无法导出 webhook 资源包。");process.stderr.write(`\uD83D\uDCE5 正在拉取 ${P.length} 条审核记录完整详情...
`),q=await Promise.all(P.map((A)=>z4($,A.id)))}let U=new Map,Y=0;for(let F of q){let D=F.document,P=F.sourceDocumentId??(typeof D?.id==="string"?D.id:void 0)??(typeof D?.sourceDocumentId==="string"?D.sourceDocumentId:void 0)??F.documentId??F.id,A=`${z.docIdPrefix??""}${P}${z.docIdSuffix??""}`,T=[];if(z.includeAttachments!==!1){let h=d7(F,{summary:!1}).attachments,f=new Set;for(let C of h){let b=C.ossSignedUrl??C.url;if(!b)continue;let i=C.fileName??C.fileId??"attachment",v=Yi(i),y=v,c=v.lastIndexOf("."),$0=c>0?v.slice(0,c):v,R=c>0?v.slice(c):"",u=1;while(f.has(y.toLowerCase()))y=`${$0}_${u}${R}`,u++;f.add(y.toLowerCase());try{process.stderr.write(`⬇ 下载单据「${A}」附件: ${i}...
`);let p=await fetch(b);if(p.ok){let s=await p.arrayBuffer(),U0=Buffer.from(s);T.push({fileName:y,zipPath:`${A}/${y}`,buffer:U0,sourceField:C.sourceField??"附件"}),Y++}}catch(p){process.stderr.write(`⚠️ [跳过附件] 下载失败 ${i}: ${p}
`)}}}U.set(A,T)}let J=new YR0.default.Workbook;J.creator="seal-use",J.created=new Date;let Q=new Set;for(let F of U.values())for(let D of F)Q.add(D.sourceField);if(Q.size===0)Q.add("附件");let K=new Set;for(let F of q){let D=F.document,P=Array.isArray(D?.fields)?D.fields:[];for(let A of P)if(A&&typeof A==="object"){let T=A,k=typeof T.label==="string"?T.label.trim():typeof T.key==="string"?T.key.trim():"",h=typeof T.type==="string"?T.type.toUpperCase():"";if(k&&h!=="ATTACHMENT"&&h!=="LIST")K.add(k)}}let H=["会议编号","会议名称","状态","总金额","报销事由","申请日期"],G=Array.from(K).filter((F)=>!H.includes(F)&&F!=="单据编号"&&F!=="单号"),Z=Array.from(Q).map((F)=>`[附件]${F}`),W=[...H,...G,...Z],X=J.addWorksheet("主表");X.addRow(W),X.getRow(1).font={bold:!0};for(let F of q){let D=F.document,P=F.sourceDocumentSN??(typeof D?.sn==="string"?D.sn:void 0)??(typeof D?.sourceDocumentSN==="string"?D.sourceDocumentSN:void 0)??F.id,A=F.sourceDocumentId??(typeof D?.id==="string"?D.id:void 0)??(typeof D?.sourceDocumentId==="string"?D.sourceDocumentId:void 0)??F.documentId??F.id,T=`${z.docIdPrefix??""}${A}${z.docIdSuffix??""}`,k=`${z.docIdPrefix??""}${P}${z.docIdSuffix??""}`,h=(typeof D?.title==="string"?D.title:void 0)??(typeof D?.name==="string"?D.name:void 0)??k,f="";if(typeof D?.sourceStartTime==="number")f=new Date(D.sourceStartTime*1000).toLocaleDateString("en-CA",{timeZone:"Asia/Shanghai"});else if(typeof F.createdAt==="number")f=new Date(F.createdAt).toLocaleDateString("en-CA",{timeZone:"Asia/Shanghai"});else if(typeof F.createdAt==="string")f=F.createdAt.slice(0,10);let C=new Map,b=Array.isArray(D?.fields)?D.fields:[];for(let $0 of b)if($0&&typeof $0==="object"){let R=$0,u=typeof R.label==="string"?R.label.trim():typeof R.key==="string"?R.key.trim():"";if(u)C.set(u,R.value)}let i,v=C.get("总金额")??C.get("报销金额")??C.get("total_amount");if(typeof v==="number")i=v;else if(v&&typeof v==="object"&&"amount"in v&&typeof v.amount==="number")i=v.amount;let y=[];y.push(T),y.push(h),y.push(F.status??"已审批"),y.push(i??""),y.push(C.get("报销事由")??C.get("事由")??h),y.push(f);for(let $0 of G){let R=C.get($0);if(R===void 0||R===null)y.push("");else if(typeof R==="object")if("amount"in R)y.push(R.amount);else y.push(JSON.stringify(R));else y.push(R)}let c=U.get(T)??[];for(let $0 of Q){let R=c.filter((u)=>u.sourceField===$0||Q.size===1);if(R.length>0)y.push(R.map((u)=>u.zipPath).join(`
`));else y.push("")}X.addRow(y)}let w=Du1(z,I);Lu1(Mu1(w),{recursive:!0});let L=await J.xlsx.writeBuffer();process.stderr.write(`\uD83D\uDCE6 正在压缩生成 Webhook 资源包: ${w}...
`),await new Promise((F,D)=>{let P=wu1(w),A=new Np({zlib:{level:9}});P.on("close",()=>F()),A.on("error",(T)=>D(T)),A.pipe(P),A.append(Buffer.from(L),{name:"信息表.xlsx"});for(let T of U.values())for(let k of T)A.append(k.buffer,{name:k.zipPath});A.finalize()});let O=Ou1(w);return{filePath:w,corpId:I.id,corpName:I.name,recordCount:q.length,attachmentCount:Y,fileSizeBytes:O.size,exportedAt:new Date().toISOString(),nextAction:`seal-use webhook resource-pack push ${w} --corp <targetCorpId>`}}var YR0;var Dp=e(()=>{qR0();e4();lN();YR0=j4(QZ(),1)});import{readFileSync as Au1}from"node:fs";function Pu1($){let I=new URL($),z=I.pathname.match(/\/webhook\/([^/]+)/);if(!z)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${I.protocol}//${I.host}`,webhookId:z[1]}}function Bu1($,I){return I.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!I.toLowerCase().endsWith(".xlsx")}function Tu1($,I){if(!$.length)return;let z=new Set($.map((Y)=>{let J=Y.fileName.split("/")[0],Q=J.indexOf("@");return Q>=0?J.slice(0,Q):J}).filter((Y)=>Y!=="信息表.xlsx")),q=[];for(let Y of I){let J=Y.document.documentId;if((Y.documentAttachments.length>0||Object.values(Y.expenseAttachments).some((K)=>K.length>0)||Object.values(Y.personAttachments).some((K)=>K.length>0))&&!z.has(J))q.push(`Excel 会议编号「${J}」声明了附件,但在 ZIP 中找不到对应的根目录「${J}/」或「${J}@.../」。`)}let U=new Set(I.map((Y)=>Y.document.documentId));for(let Y of z)if(!U.has(Y))q.push(`ZIP 根目录对应的编号「${Y}」在信息表中找不到对应的会议编号。`);if(q.length)throw new W5(q)}async function JR0($,I,z){let q=[],U=$;if(Bu1($,I)){q=await LB0($),FB0(q,z);let K=q.find((H)=>H.fileName==="信息表.xlsx");if(!K)throw Error("ZIP 根目录缺少信息表.xlsx");U=await Nn($,K)}let Y=await TB0(U);Tu1(q,Y);let J=EB0(q,Y),Q=Y.map((K)=>K.document);return{entries:q,parsed:Y,plans:J,documents:Q,fileBuffer:$}}async function wz($,I,z){let q=await JR0($,I,z),U=q.parsed.map((Y,J)=>En(Y.document,q.plans[J],new Map));return{warnings:[],documents:U,attachmentPlan:q.plans}}async function LA($,I,z){let q=await JR0($,I,z.materialPackFilePolicy),{baseUrl:U,webhookId:Y}=Pu1(z.webhookUrl),J=[];for(let Q=0;Q<q.parsed.length;Q+=1){let K=q.parsed[Q],H=q.plans[Q],G=new Map,Z=[...H.categoryFields,...Object.values(H.personAttachments).flat(),...Object.values(H.expenseAttachments).flat()];for(let w of Z)for(let L of w.paths){if(G.has(L))continue;let O=q.entries.find((k)=>k.fileName===L);if(!O)continue;process.stderr.write(`⬆ 上传附件: ${L}
`);let F=new FormData,D=await Nn(q.fileBuffer,O),P=L.split("/").pop()??L;F.append("files",new File([new Uint8Array(D)],P));let A=await fetch(`${U}/api/v1/integrations/webhook/${encodeURIComponent(Y)}/attachments`,{method:"POST",headers:{...z.customHeaders??{},...HZ({},z.secret)},body:F});if(!A.ok)throw Error(`附件上传失败 ${A.status}: ${await A.text()}`);let T=await A.json();G.set(L,T.attachments?.map((k)=>k.data)??(T.data===void 0?[]:[T.data])),process.stderr.write(`✓ 附件上传成功: ${L}
`)}process.stderr.write(`\uD83D\uDCE4 推送单据: ${K.document.documentId}
`);let W=En(K.document,H,G),X=await fetch(`${U}/api/v1/integrations/webhook/${encodeURIComponent(Y)}/document`,{method:"POST",headers:{...z.customHeaders??{},"Content-Type":"application/json",...HZ({webhookId:Y,...W},z.secret)},body:JSON.stringify(W)});if(!X.ok)throw Error(`Webhook 单据推送失败 ${X.status}: ${await X.text()}`);J.push({documentId:W.documentId,document:W,pushResult:await X.json()}),process.stderr.write(`✓ 单据推送成功: ${W.documentId}
`)}return{warnings:[],results:J}}function Lz($){return{fileBuffer:Au1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}var Ap=e(()=>{ID();jn();Tn();Dn();gY();Dp()});import{existsSync as Eu1}from"node:fs";async function OA($,I,z={}){let U=O4().stateful?"stateful":"stateless",Y="ok",J,Q,K;try{let A=await r6($);K={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){Y="error",J=A instanceof Error?A.message:String(A)}let H=[];if(Y==="ok")try{H=await e8($,I.seal.endpoints.approvalStylePreferences)}catch(A){Y="error",J=`读取 Webhook 配置失败: ${A instanceof Error?A.message:String(A)}`}let G=H.length===1,Z=H.map((A)=>({id:A.id,name:A.name,mode:A.mode,incomingDocumentWebhookUrl:A.incomingDocumentWebhook.url,outgoingResultWebhookUrl:A.outgoingResultWebhook,autoApprovalRate:A.autoApprovalRate,...G?{isDefault:!0}:{}})),W=G?{id:H[0].id,name:H[0].name,mode:H[0].mode}:null,X=z.webhook?b3(H,z.webhook):G?H[0]:void 0,w;if(z.filePath)if(!Eu1(z.filePath))w={valid:!1,filePath:z.filePath,fileName:z.filePath.split(/[\\/]/).pop()??z.filePath,documentCount:0,errors:[`文件不存在: ${z.filePath}`]};else try{let A=Lz(z.filePath),T=await wz(A.fileBuffer,A.fileName,X?.materialPackFilePolicy);w={valid:!0,filePath:z.filePath,fileName:A.fileName,documentCount:T.documents.length,warnings:T.warnings}}catch(A){w={valid:!1,filePath:z.filePath,fileName:z.filePath.split(/[\\/]/).pop()??z.filePath,documentCount:0,errors:[A instanceof Error?A.message:String(A)]}}let L=w?w.valid:!0,O=Y==="ok"&&Z.length>0&&L,F=U==="stateful"?"":` --corp ${I.id}`,D="",P="";if(Y!=="ok")P=`凭证鉴权异常: ${J}`,D=`seal-use auth diagnose${F}`;else if(Z.length===0)P="当前企业尚未配置任何 Webhook 集成通道",D=`seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${F}`;else if(w&&!w.valid)P=`资源包预检失败: ${w.errors?.join("; ")}`,D=`seal-use webhook resource-pack preview ${w.filePath}${F}`;else{P=G?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到 ${Z.length} 个 Webhook 通道,等待载入`;let A=w?.filePath??"<资源包.zip>",T=G?"":` --webhook ${W?W.id:"<webhookIdOrName>"}`;D=`seal-use webhook resource-pack push ${A}${T}${F}`}return{ready:O,corp:{id:I.id,name:I.name,sourceType:I.source.type,tenant:Q,user:K},stateMode:U,authStatus:Y,authError:J,activeWebhooks:Z,defaultWebhook:W,resourcePack:w,materialPack:w,statusMessage:P,nextAction:D}}var QR0=e(()=>{e9();e4();Ap()});var Pp=e(()=>{gY();Cq();ID();Dn();Tn();jn();Ap();QR0();Dp()});import{existsSync as KR0,mkdirSync as HR0,statSync as ju1}from"node:fs";import{homedir as Cu1}from"node:os";import{dirname as _u1,resolve as FA}from"node:path";function Ru1($){if($.outputFile){let J=FA($.outputFile),Q=_u1(J);if(!KR0(Q))HR0(Q,{recursive:!0});return J}let z=($.corpName||$.corpId||"企业").replace(/[/\\?%*:|"<>]/g,"_").trim()||"企业",q=$.dateTag||new Date().toISOString().slice(0,10),U=`${z}_智能洞察报告_${q}.xlsx`,Y;if($.toDownloads)Y=FA(Cu1(),"Downloads");else Y=FA(process.cwd(),"exports");if(!KR0(Y))HR0(Y,{recursive:!0});return FA(Y,U)}async function MA($,I,z={}){let q=I.name||I.id,U=zi({startDate:z.startDate,endDate:z.endDate,force:z.force}),Y=new Date().toISOString(),[J,Q]=await Promise.all([kw($,{startDate:U.startDateStr,endDate:U.endDateStr,limit:z.limit??100}),bw($,{startDate:U.startDateStr,endDate:U.endDateStr}).catch(()=>({metrics:{},sankeyData:{nodes:[],links:[]}}))]),K=J.tagStats||[],H=[],G=Math.min(K.length,z.limit??50);for(let C=0;C<G;C++){let b=K[C];if(!b?.tagId)continue;try{let i=await fw($,{tagId:b.tagId,startDate:U.startDateStr,endDate:U.endDateStr});for(let v of i.risks||[])H.push({tagId:b.tagId,tagName:b.tagName||b.tagId,documentSN:v.documentSN||"-",documentType:v.documentType||"-",riskLevel:v.riskLevel||"warning",confidence:v.confidence??0,riskDetails:v.riskDetails||"-",reasoning:v.reasoning||"-",sourceDocumentURL:v.sourceDocumentURL,createdAt:v.createdAt})}catch{}}let Z=new GR0.default.Workbook;Z.creator="seal-use",Z.lastModifiedBy="seal-use",Z.created=new Date,Z.modified=new Date;let W={type:"pattern",pattern:"solid",fgColor:{argb:"FF1E293B"}},X={name:"Microsoft YaHei",size:11,bold:!0,color:{argb:"FFFFFFFF"}},w={top:{style:"thin",color:{argb:"FFE2E8F0"}},bottom:{style:"thin",color:{argb:"FFE2E8F0"}},left:{style:"thin",color:{argb:"FFE2E8F0"}},right:{style:"thin",color:{argb:"FFE2E8F0"}}},L=Z.addWorksheet("审核效能与决策流向",{views:[{showGridLines:!0}]});L.columns=[{header:"分类",key:"category",width:20},{header:"指标名称",key:"name",width:28},{header:"数值",key:"val",width:22},{header:"环比/趋势",key:"trend",width:18},{header:"说明",key:"desc",width:36}],L.getRow(1).height=28,L.getRow(1).font=X,L.getRow(1).fill=W,L.getRow(1).alignment={vertical:"middle",horizontal:"center"};let O=Q.metrics||{},F=[{c Line truncated
`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:ZJ({id:I?.id,sn:I?.sn??I?.sourceDocumentSN??$.sourceDocumentSN,title:I?.title??I?.name,template:TA(I,["template.name","templateName","form.name","formName","formTitle"]),amount:DA(z,["金额","报销金额","付款金额","合计","价税合计"])??TA(I,["amount","totalAmount","expenseAmount"]),expenseType:DA(z,["费用类型","费用类别","报销类型"]),costCompany:DA(z,["费用承担公司","承担公司","成本中心","费用归属"]),payee:DA(z,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:z.slice(0,30)}),invoices:lu1($),attachments:d7($,{summary:!0}).attachments,aiResult:jA($),manualResult:Fz($)?.value,hints:ZJ({amountMentions:VR0(q,["金额","合计","税率"],8),partyMentions:VR0(q,["买方","卖方","甲方","乙方","收款"],8)})}}function cu1($){let I=[["result.citedRules",H3($,"result.citedRules")],["result.matchedRules",H3($,"result.matchedRules")],["result.ruleResults",H3($,"result.ruleResults")],["result.rules",H3($,"result.rules")],["pipelineData.citedRules",H3($,"pipelineData.citedRules")],["pipelineData.matchedRules",H3($,"pipelineData.matchedRules")]],z=[],q=new Set;for(let[U,Y]of I)(Array.isArray(Y)?Y:Y&&typeof Y==="object"?Object.values(Y):[]).forEach((Q,K)=>{let H=mZ(Q);if(!H)return;let G=N4(H.runtimeRuleId)??N4(H.runtimeId)??N4(H.id)??N4(H.ruleId),Z=N4(H.ruleCode)??N4(H.code)??(G?su1(G):void 0),W=ZJ({runtimeRuleId:G,ruleCode:Z,versionNumber:du1(H.versionNumber)??$.ruleSetVersionNumber,scope:N4(H.scope),strictness:N4(H.strictness),appliedAnalysis:H.appliedAnalysis??H.analysis??H.reasoning,checkResult:H.checkResult??H.result??H.decision,findings:H.findings??H.riskPoints??H.evidence,sourcePath:`${U}.${K}`}),X=JSON.stringify(W);if(!q.has(X))q.add(X),z.push(W)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:z.length,rules:z}}function TA($,I){if(!$)return;for(let z of I){let q=H3($,z);if(q!==void 0)return q}return}function XR0($,I){if(!$)return 0;for(let z of I){let q=H3($,z);if(Array.isArray(q))return q.length;if(q&&typeof q==="object")return Object.keys(q).length;if(typeof q==="number")return q}return 0}function H3($,I){return I.split(".").reduce((z,q)=>{if(z===void 0||z===null)return;if(Array.isArray(z)){let U=Number(q);return Number.isInteger(U)?z[U]:void 0}if(typeof z==="object")return z[q];return},$)}function pu1($,I,z){let q=I.split("."),U=$;for(let Y of q.slice(0,-1)){let J=U[Y];if(!J||typeof J!=="object"||Array.isArray(J))U[Y]={};U=U[Y]}U[q[q.length-1]??I]=z}function ZJ($){return Object.fromEntries(Object.entries($).filter(([,I])=>I!==void 0))}function mZ($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function du1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function mu1($){let I=[];return jp($,"document",I),I}function jp($,I,z){if(Array.isArray($)){$.forEach((J,Q)=>jp(J,`${I}.${Q}`,z));return}let q=mZ($);if(!q)return;let U=N4(q.label)??N4(q.name)??N4(q.title)??N4(q.fieldName),Y=q.value??q.displayValue??q.text??q.content;if(U&&Y!==void 0&&typeof Y!=="object")z.push(ZJ({path:I,label:U,value:Y,type:N4(q.type)??N4(q.fieldType)}));for(let[J,Q]of Object.entries(q)){if(J==="attachments")continue;jp(Q,`${I}.${J}`,z)}}function DA($,I){return $.find((q)=>{let U=N4(q.label)??"";return I.some((Y)=>U.includes(Y))})?.value}function lu1($){let I=[];return EA($.result,"result",I),EA($.document,"document",I),I.slice(0,20)}function EA($,I,z){if(Array.isArray($)){$.forEach((U,Y)=>EA(U,`${I}.${Y}`,z));return}let q=mZ($);if(!q)return;if(/invoice|发票/i.test(I))z.push(ZJ({path:I,fileName:N4(q.fileName)??N4(q.filename)??N4(q.name),buyer:q.buyer??q.buyerName??q.purchaserName,seller:q.seller??q.sellerName,amount:q.amount??q.totalAmount??q.total,taxRate:q.taxRate,category:q.category??q.type}));for(let[U,Y]of Object.entries(q))EA(Y,`${I}.${U}`,z)}function VR0($,I,z){return $.split(/\r?\n/).filter((q)=>I.some((U)=>q.includes(U))).slice(0,z)}function AA($){return $.map((I)=>{let z=Oz(I);return{recordId:z.id,tenantId:z.tenantId,agentId:z.agentId,sourceDocumentSN:z.sourceDocumentSN,sourceDocumentId:z.sourceDocumentId,simulationBatchId:z.simulationBatchId,langfuseTraceId:z.langfuseTraceId,langfuseSessionFallback:z.langfuseSessionFallback,ruleSetVersionNumber:z.ruleSetVersionNumber,ruleSetPublishedAt:z.ruleSetPublishedAt,ruleSetPublishedByName:z.ruleSetPublishedByName,resolution:z.langfuseTraceId?"trace":z.langfuseSessionFallback?"session-fallback":"unresolved"}})}function Tp($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function ou1($,I){if(I.recordId&&!I.versionId&&!I.versionNumber&&!I.latest){let z=await z4($,I.recordId);if(!z.ruleSetVersionNumber)throw Er Line truncated
`+`• 身份主体:${F}${D}
\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 GP0=E((KB1)=>{var ap=y7().Buffer;KB1._dbcs=x7;var z8=-1,KP0=-2,p$=-10,h8=-1000,IK=Array(256),SZ=-1;for(hZ=0;hZ<256;hZ++)IK[hZ]=z8;var hZ;function x7($,Y){if(this.encodingName=$.encodingName,!$)throw Error("DBCS codec is called without the data.");if(!$.table)throw Error("Encoding '"+this.encodingName+"' has no data.");var z=$.table();this.decodeTables=[],this.decodeTables[0]=IK.slice(0),this.decodeTableSeq=[];for(var U=0;U<z.length;U++)this._addDecodeChunk(z[U]);if(typeof $.gb18030==="function"){this.gb18030=$.gb18030();var Q=this.decodeTables.length;this.decodeTables.push(IK.slice(0));var J=this.decodeTables.length;this.decodeTables.push(IK.slice(0));var I=this.decodeTables[0];for(var U=129;U<=254;U++){var K=this.decodeTables[h8-I[U]];for(var G=48;G<=57;G++){if(K[G]===z8)K[G]=h8-Q;else if(K[G]>h8)throw Error("gb18030 decode tables conflict at byte 2");var W=this.decodeTables[h8-K[G]];for(var H=129;H<=254;H++){if(W[H]===z8)W[H]=h8-J;else if(W[H]===h8-J)continue;else if(W[H]>h8)throw Error("gb18030 decode tables conflict at byte 3");var X=this.decodeTables[h8-W[H]];for(var Z=48;Z<=57;Z++)if(X[Z]===z8)X[Z]=KP0}}}}this.defaultCharUnicode=Y.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var q={};if($.encodeSkipVals)for(var U=0;U<$.encodeSkipVals.length;U++){var V=$.encodeSkipVals[U];if(typeof V==="number")q[V]=!0;else for(var G=V.from;G<=V.to;G++)q[G]=!0}if(this._fillEncodeTable(0,0,q),$.encodeAdd){for(var F in $.encodeAdd)if(Object.prototype.hasOwnProperty.call($.encodeAdd,F))this._setEncodeChar(F.charCodeAt(0),$.encodeAdd[F])}if(this.defCharSB=this.encodeTable[0][Y.defaultCharSingleByte.charCodeAt(0)],this.defCharSB===z8)this.defCharSB=this.encodeTable[0]["?"];if(this.defCharSB===z8)this.defCharSB=63}x7.prototype.encoder=$A;x7.prototype.decoder=tp;x7.prototype._getDecodeTrieNode=function($){var Y=[];for(;$>0;$>>>=8)Y.push($&255);if(Y.length==0)Y.push(0);var z=this.decodeTables[0];for(var U=Y.length-1;U>0;U--){var Q=z[Y[U]];if(Q==z8)z[Y[U]]=h8-this.decodeTables.length,this.decodeTables.push(z=IK.slice(0));else if(Q<=h8)z=this.decodeTables[h8-Q];else throw Error("Overwrite byte in "+this.encodingName+", addr: "+$.toString(16))}return z};x7.prototype._addDecodeChunk=function($){var Y=parseInt($[0],16),z=this._getDecodeTrieNode(Y);Y=Y&255;for(var U=1;U<$.length;U++){var Q=$[U];if(typeof Q==="string")for(var J=0;J<Q.length;){var I=Q.charCodeAt(J++);if(I>=55296&&I<56320){var K=Q.charCodeAt(J++);if(K>=56320&&K<57344)z[Y++]=65536+(I-55296)*1024+(K-56320);else throw Error("Incorrect surrogate pair in "+this.encodingName+" at chunk "+$[0])}else if(I>4080&&I<=4095){var G=4095-I+2,W=[];for(var H=0;H<G;H++)W.push(Q.charCodeAt(J++));z[Y++]=p$-this.decodeTableSeq.length,this.decodeTableSeq.push(W)}else z[Y++]=I}else if(typeof Q==="number"){var X=z[Y-1]+1;for(var J=0;J<Q;J++)z[Y++]=X++}else throw Error("Incorrect type '"+typeof Q+"' given in "+this.encodingName+" at chunk "+$[0])}if(Y>255)throw Error("Incorrect chunk in "+this.encoLine truncated
`;super(Y);this.name="AggregateError",this.errors=$}}wA0.exports={AggregateError:FA0,ArrayIsArray($){return Array.isArray($)},ArrayPrototypeIncludes($,Y){return $.includes(Y)},ArrayPrototypeIndexOf($,Y){return $.indexOf(Y)},ArrayPrototypeJoin($,Y){return $.join(Y)},ArrayPrototypeMap($,Y){return $.map(Y)},ArrayPrototypePop($,Y){return $.pop(Y)},ArrayPrototypePush($,Y){return $.push(Y)},ArrayPrototypeSlice($,Y,z){return $.slice(Y,z)},Error,FunctionPrototypeCall($,Y,...z){return $.call(Y,...z)},FunctionPrototypeSymbolHasInstance($,Y){return Function.prototype[Symbol.hasInstance].call($,Y)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties($,Y){return Object.defineProperties($,Y)},ObjectDefineProperty($,Y,z){return Object.defineProperty($,Y,z)},ObjectGetOwnPropertyDescriptor($,Y){return Object.getOwnPropertyDescriptor($,Y)},ObjectKeys($){return Object.keys($)},ObjectSetPrototypeOf($,Y){return Object.setPrototypeOf($,Y)},Promise,PromisePrototypeCatch($,Y){return $.catch(Y)},PromisePrototypeThen($,Y,z){return $.then(Y,z)},PromiseReject($){return Promise.reject($)},PromiseResolve($){return Promise.resolve($)},ReflectApply:Reflect.apply,RegExpPrototypeTest($,Y){return $.test(Y)},SafeSet:Set,String,StringPrototypeSlice($,Y,z){return $.slice(Y,z)},StringPrototypeToLowerCase($){return $.toLowerCase()},StringPrototypeToUpperCase($){return $.toUpperCase()},StringPrototypeTrim($){return $.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet($,Y,z){return $.set(Y,z)},Boolean,Uint8Array}});var Dd=E((C14,MA0)=>{MA0.exports={format($,...Y){return $.replace(/%([sdifj])/g,function(...[z,U]){let Q=Y.shift();if(U==="f")return Q.toFixed(6);else if(U==="j")return JSON.stringify(Q);else if(U==="s"&&typeof Q==="object")return`${Q.constructor!==Object?Q.constructor.name:""} {}`.trim();else return Q.toString()})},inspect($){switch(typeof $){case"string":if($.includes("'")){if(!$.includes('"'))return`"${$}"`;else if(!$.includes("`")&&!$.includes("${"))return`\`${$}\``}return`'${$}'`;case"number":if(isNaN($))return"NaN";else if(Object.is($,-0))return String($);return $;case"bigint":return`${String($)}n`;case"boolean":case"undefined":return String($);case"object":return"{}"}}}});var M8=E((R14,BA0)=>{var{format:$A1,inspect:IA}=Dd(),{AggregateError:YA1}=x4(),zA1=globalThis.AggregateError||YA1,UA1=Symbol("kIsNodeError"),QA1=["string","function","number","object","Function","Object","boolean","bigint","symbol"],JA1=/^([A-Z][a-z0-9]*)+$/,KA={};function HU($,Y){if(!$)throw new KA.ERR_INTERNAL_ASSERTION(Y)}function OA0($){let Y="",z=$.length,U=$[0]==="-"?1:0;for(;z>=U+4;z-=3)Y=`_${$.slice(z-3,z)}${Y}`;return`${$.slice(0,z)}${Y}`}function IA1($,Y,z){if(typeof Y==="function")return HU(Y.length<=z.length,`Code: ${$}; The provided arguments length (${z.length}) does not match the required ones (${Y.length}).`),Y(...z);let U=(Y.match(/%[dfijoOs]/g)||[]).length;if(HU(U===z.length,`Code: ${$}; The provided arguments length (${z.length}) does not match the required ones (${U}).`),z.length===0)return Y;return $A1(Y,...z)}function U8($,Y,z){if(!z)z=Error;class U extends z{constructor(...Q){super(IA1($,Y,Q))}toString(){return`${this.name} [${$}]: ${this.message}`}}Object.defineProperties(U.prototype,{name:{value:z.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${$}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),U.prototype.code=$,U.prototype[UA1]=!0,KA[$]=U}function NA0($){let Y="__node_internal_"+$.name;return Object.defineProperty($,"name",{value:Y}),$}function KA1($,Y){if($&&Y&&$!==Y){if(Array.isArray(Y.errors))return Y.errors.push($),Y;let z=new zA1([Y,$],Y.message);return z.code=Y.code,z}return $||Y}class DA0 extends Error{constructor($="The operation was aborted",Y=void 0){if(Y!==void 0&&typeof Y!=="object")throw new KA.ERR_INVALID_ARG_TYPE("options","Object",Y);super($,Y);this.code="ABORT_ERR",this.name="AbortError"}}U8("ERR_ASSERTION","%s",Error);U8("ERR_INVALID_ARG_TYPE",($,Y,z)=>{if(HU(typeof $==="string","'name' must be a string"),!Array.isArray(Y))Y=[Y];let U="The ";if($.endsWith(" argument"))U+=`${$} `;else U+=`"${$}" ${$.includes(".")?"property":"argument"} `;U+="must be ";let Q=[],J=[],I=[];for(let G of Y)if(HU(typeof G==="string","All expected entries have to be of type string"),QA1.includes(G))Q.push(G.toLowerCase());else if(JA1.test(G))J.push(G);else HU(G!=="object",'The value "object" should be written as "Object"'),I.push(G);if(J.length>0){let G=Q.indexOf("object");if(G!==-1)Q.splice(Q,G,1),J.push("Object")}if(Q.length>0){switch(Q.length){case 1:U+=`of type ${Q[Line truncated
`);if(Y.linkname)z+=am(" linkpath="+Y.linkname+`
`);let U=Y.pax;if(U)for(let Q in U)z+=am(" "+Q+"="+U[Q]+`
`);return n1.from(z)};Qv1.decodePax=function(Y){let z={};while(Y.length){let U=0;while(U<Y.length&&Y[U]!==32)U++;let Q=parseInt(n1.toString(Y.subarray(0,U)),10);if(!Q)return z;let J=n1.toString(Y.subarray(U+1,Q-1)),I=J.indexOf("=");if(I===-1)return z;z[J.slice(0,I)]=J.slice(I+1),Y=Y.subarray(Q)}return z};Qv1.encode=function(Y){let z=n1.alloc(512),U=Y.name,Q="";if(Y.typeflag===5&&U[U.length-1]!=="/")U+="/";if(n1.byteLength(U)!==U.length)return null;while(n1.byteLength(U)>100){let J=U.indexOf("/");if(J===-1)return null;Q+=Q?"/"+U.slice(0,J):U.slice(0,J),U=U.slice(J+1)}if(n1.byteLength(U)>100||n1.byteLength(Q)>155)return null;if(Y.linkname&&n1.byteLength(Y.linkname)>100)return null;if(n1.write(z,U),n1.write(z,m2(Y.mode&4095,6),100),n1.write(z,m2(Y.uid,6),108),n1.write(z,m2(Y.gid,6),116),zv1(Y.size,z,124),n1.write(z,m2(Y.mtime.getTime()/1000|0,11),136),z[156]=48+$v1(Y.type),Y.linkname)n1.write(z,Y.linkname,157);if(n1.copy(mC0,z,257),n1.copy(l_1,z,263),Y.uname)n1.write(z,Y.uname,265);if(Y.gname)n1.write(z,Y.gname,297);if(n1.write(z,m2(Y.devmajor||0,6),329),n1.write(z,m2(Y.devminor||0,6),337),Q)n1.write(z,Q,345);return n1.write(z,m2(oC0(z),6),148),z};Qv1.decode=function(Y,z,U){let Q=Y[156]===0?0:Y[156]-48,J=jK(Y,0,100,z),I=d2(Y,100,8),K=d2(Y,108,8),G=d2(Y,116,8),W=d2(Y,124,12),H=d2(Y,136,12),X=e_1(Q),Z=Y[157]===0?null:jK(Y,157,100,z),q=jK(Y,265,32),V=jK(Y,297,32),F=d2(Y,329,8),M=d2(Y,337,8),w=oC0(Y);if(w===256)return null;if(w!==d2(Y,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(s_1(Y)){if(Y[345])J=jK(Y,345,155,z)+"/"+J}else if(a_1(Y));else if(!U)throw Error("Invalid tar header: unknown format.");if(Q===0&&J&&J[J.length-1]==="/")Q=5;return{name:J,mode:I,uid:K,gid:G,size:W,byteOffset:0,mtime:new Date(1000*H),type:X,linkname:Z,uname:q,gname:V,devmajor:F,devminor:M,pax:null}};function s_1($){return n1.equals(mC0,$.subarray(257,263))}function a_1($){return n1.equals(o_1,$.subarray(257,263))&&n1.equals(r_1,$.subarray(263,265))}function t_1($,Y,z){if(typeof $!=="number")return z;if($=~~$,$>=Y)return Y;if($>=0)return $;if($+=Y,$>=0)return $;return 0}function e_1($){switch($){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function $v1($){switch($){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function lC0($,Y,z,U){for(;z<U;z++)if($[z]===Y)return z;return U}function oC0($){let Y=256;for(let z=0;z<148;z++)Y+=$[z];for(let z=156;z<512;z++)Y+=$[z];return Y}function m2($,Y){if($=$.toString(8),$.length>Y)return"7777777777777777777".slice(0,Y)+" ";return"0000000000000000000".slice(0,Y-$.length)+$+" "}function Yv1($,Y,z){Y[z]=128;for(let U=11;U>0;U--)Y[z+U]=$&255,$=Math.floor($/256)}function zv1($,Y,z){if($.toString(8).length>11)Yv1($,Y,z);else n1.write(Y,m2($,11),z)}function Uv1($){let Y;if($[0]===128)Y=!0;else if($[0]===255)Y=!1;else return null;let z=[],U;for(U=$.length-1;U>0;U--){let I=$[U];if(Y)z.push(I);else z.push(255-I)}let Q=0,J=z.length;for(U=0;U<J;U++)Q+=z[U]*Math.pow(256,U);return Y?Q:-1*Q}function d2($,Y,z){if($=$.subarray(Y,Y+z),Y=0,$[Y]&128)return Uv1($);else{while(Y<$.length&&$[Y]===32)Y++;let U=t_1(lC0($,32,Y,$.length),$.length,$.length);while(Y<U&&$[Y]===0)Y++;if(U===Y)return 0;return parseInt(n1.toString($.subarray(Y,U)),8)}}function jK($,Y,z,U){return n1.toString($.subarray(Y,lC0($,0,Y,Y+z)),U)}function am($){let Y=n1.byteLength($),z=Math.floor(Math.log(Y)/Math.log(10))+1;if(Y+z>=Math.pow(10,z))z++;return Y+z+$}});var zR0=E((O64,YR0)=>{var{Writable:Hv1,Readable:Xv1,getStreamError:rC0}=sm(),Zv1=cm(),sC0=TK(),EK=tm(),qv1=sC0.alloc(0);class aC0{constructor(){this.buffered=0,this.shifted=0,this.queue=new Zv1,this._offset=0}push($){this.buffered+=$.byteLength,this.queue.push($)}shiftFirst($){return this.buffered===0?null:this._next($)}shift($){if($>this.buffered)return null;if($===0)return qv1;let Y=this._next($);if($===Y.byteLength)return Y;let z=[Y];while(($-=Y.byteLength)>0)Y=this._next($),z.push(Y);return sC0.concat(z)}_next($){let Y=this.queue.peek(),z=Y.byteLength-this._offset;if($>=z){let U=this._offset?Y.subarray(this._offset,Y.byteLength):Y;return this.queue.shift(),this._offset=0,this.buffered-=z,this.shifted+=z,U}return this.buffered-=$,this.shifted+=$,Y.subarray(this._offset,this._offset+=$)}}class tC0 extends Xv1{constructor($,Y,z){super();this.header=Y,this.offset=z,this._parent=$}_read($){if(this.header.size===0)this.push(null);if(this._parent._stream===this)this._parent._update();$(null)}_predestroy(){this._parent.destroy(rC0(this))}_detach(){if(this._parent._stream= Line truncated
`),U=[await G4($,z.recordId)];else if(z.recordIds&&z.recordIds.length>0)process.stderr.write(`\uD83D\uDD0D 批量查询 ${z.recordIds.length} 条单据记录...
`),U=await Promise.all(z.recordIds.map((w)=>G4($,w)));else{let w=z.limit??10;process.stderr.write(`\uD83D\uDD0D 检索企业「${Y.name}」(${Y.id}) 的线上审核记录 (限制 ${w} 条)...
`);let N=(await b4($,{limit:w,status:z.status,startDate:z.startDate!==void 0?String(z.startDate):void 0,endDate:z.endDate!==void 0?String(z.endDate):void 0})).records??[];if(N.length===0)throw Error("未检索到符合条件的线上审核记录,无法导出 webhook 资源包。");process.stderr.write(`\uD83D\uDCE5 正在拉取 ${N.length} 条审核记录完整详情...
`),U=await Promise.all(N.map((D)=>G4($,D.id)))}let Q=new Map,J=0;for(let w of U){let O=w.document,N=w.sourceDocumentId??(typeof O?.id==="string"?O.id:void 0)??(typeof O?.sourceDocumentId==="string"?O.sourceDocumentId:void 0)??w.documentId??w.id,D=`${z.docIdPrefix??""}${N}${z.docIdSuffix??""}`,T=[];if(z.includeAttachments!==!1){let B=k2(w,{summary:!1}).attachments,j=new Set;for(let C of B){let b=C.ossSignedUrl??C.url;if(!b)continue;let k=C.fileName??C.fileId??"attachment",h=dn(k),i=h,c=h.lastIndexOf("."),U0=c>0?h.slice(0,c):h,x=c>0?h.slice(c):"",d=1;while(j.has(i.toLowerCase()))i=`${U0}_${d}${x}`,d++;j.add(i.toLowerCase());try{process.stderr.write(`⬇ 下载单据「${D}」附件: ${k}...
`);let t=await fetch(b);if(t.ok){let $0=await t.arrayBuffer(),g=Buffer.from($0);T.push({fileName:i,zipPath:`${D}/${i}`,buffer:g,sourceField:C.sourceField??"附件"}),J++}}catch(t){process.stderr.write(`⚠️ [跳过附件] 下载失败 ${k}: ${t}
`)}}}Q.set(D,T)}let I=new NR0.default.Workbook;I.creator="seal-use",I.created=new Date;let K=new Set;for(let w of Q.values())for(let O of w)K.add(O.sourceField);if(K.size===0)K.add("附件");let G=new Set;for(let w of U){let O=w.document,N=Array.isArray(O?.fields)?O.fields:[];for(let D of N)if(D&&typeof D==="object"){let T=D,A=typeof T.label==="string"?T.label.trim():typeof T.key==="string"?T.key.trim():"",B=typeof T.type==="string"?T.type.toUpperCase():"";if(A&&B!=="ATTACHMENT"&&B!=="LIST")G.add(A)}}let W=["会议编号","会议名称","状态","总金额","报销事由","申请日期"],H=Array.from(G).filter((w)=>!W.includes(w)&&w!=="单据编号"&&w!=="单号"),X=Array.from(K).map((w)=>`[附件]${w}`),Z=[...W,...H,...X],q=I.addWorksheet("主表");q.addRow(Z),q.getRow(1).font={bold:!0};for(let w of U){let O=w.document,N=w.sourceDocumentSN??(typeof O?.sn==="string"?O.sn:void 0)??(typeof O?.sourceDocumentSN==="string"?O.sourceDocumentSN:void 0)??w.id,D=w.sourceDocumentId??(typeof O?.id==="string"?O.id:void 0)??(typeof O?.sourceDocumentId==="string"?O.sourceDocumentId:void 0)??w.documentId??w.id,T=`${z.docIdPrefix??""}${D}${z.docIdSuffix??""}`,A=`${z.docIdPrefix??""}${N}${z.docIdSuffix??""}`,B=(typeof O?.title==="string"?O.title:void 0)??(typeof O?.name==="string"?O.name:void 0)??A,j="";if(typeof O?.sourceStartTime==="number")j=new Date(O.sourceStartTime*1000).toLocaleDateString("en-CA",{timeZone:"Asia/Shanghai"});else if(typeof w.createdAt==="number")j=new Date(w.createdAt).toLocaleDateString("en-CA",{timeZone:"Asia/Shanghai"});else if(typeof w.createdAt==="string")j=w.createdAt.slice(0,10);let C=new Map,b=Array.isArray(O?.fields)?O.fields:[];for(let U0 of b)if(U0&&typeof U0==="object"){let x=U0,d=typeof x.label==="string"?x.label.trim():typeof x.key==="string"?x.key.trim():"";if(d)C.set(d,x.value)}let k,h=C.get("总金额")??C.get("报销金额")??C.get("total_amount");if(typeof h==="number")k=h;else if(h&&typeof h==="object"&&"amount"in h&&typeof h.amount==="number")k=h.amount;let i=[];i.push(T),i.push(B),i.push(w.status??"已审批"),i.push(k??""),i.push(C.get("报销事由")??C.get("事由")??B),i.push(j);for(let U0 of H){let x=C.get(U0);if(x===void 0||x===null)i.push("");else if(typeof x==="object")if("amount"in x)i.push(x.amount);else i.push(JSON.stringify(x));else i.push(x)}let c=Q.get(T)??[];for(let U0 of K){let x=c.filter((d)=>d.sourceField===U0||K.size===1);if(x.length>0)i.push(x.map((d)=>d.zipPath).join(`
`));else i.push("")}q.addRow(i)}let V=hv1(z,Y);Ev1(_v1(V),{recursive:!0});let F=await I.xlsx.writeBuffer();process.stderr.write(`\uD83D\uDCE6 正在压缩生成 Webhook 资源包: ${V}...
`),await new Promise((w,O)=>{let N=jv1(V),D=new Ul({zlib:{level:9}});N.on("close",()=>w()),D.on("error",(T)=>O(T)),D.pipe(N),D.append(Buffer.from(F),{name:"信息表.xlsx"});for(let T of Q.values())for(let A of T)D.append(A.buffer,{name:A.zipPath});D.finalize()});let M=Cv1(V);return{filePath:V,corpId:Y.id,corpName:Y.name,recordCount:U.length,attachmentCount:J,fileSizeBytes:M.size,exportedAt:new Date().toISOString(),nextAction:`seal-use webhook resource-pack push ${V} --corp <targetCorpId>`}}var NR0;var Ql=o(()=>{MR0();X6();EP();NR0=J6(PZ(),1)});import{readFileSync as Sv1}from"node:fs";function gv1($){let Y=new URL($),z=Y.pathname.match(/\/webhook\/([^/]+)/);if(!z)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${Y.protocol}//${Y.host}`,webhookId:z[1]}}function yv1($,Y){return Y.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!Y.toLowerCase().endsWith(".xlsx")}function kv1($,Y){if(!$.length)return;let z=new Set($.map((J)=>{let I=J.fileName.split("/")[0],K=I.indexOf("@");return K>=0?I.slice(0,K):I}).filter((J)=>J!=="信息表.xlsx")),U=[];for(let J of Y){let I=J.document.documentId;if((J.documentAttachments.length>0||Object.values(J.expenseAttachments).some((G)=>G.length>0)||Object.values(J.personAttachments).some((G)=>G.length>0))&&!z.has(I))U.push(`Excel 会议编号「${I}」声明了附件,但在 ZIP 中找不到对应的根目录「${I}/」或「${I}@.../」。`)}let Q=new Set(Y.map((J)=>J.document.documentId));for(let J of z)if(!Q.has(J))U.push(`ZIP 根目录对应的编号「${J}」在信息表中找不到对应的会议编号。`);if(U.length)throw new D5(U)}async function DR0($,Y,z){let U=[],Q=$;if(yv1($,Y)){U=await vP0($),SP0(U,z);let G=U.find((W)=>W.fileName==="信息表.xlsx");if(!G)throw Error("ZIP 根目录缺少信息表.xlsx");Q=await Qd($,G)}let J=await bP0(Q);kv1(U,J);let I=iP0(U,J),K=J.map((G)=>G.document);return{entries:U,parsed:J,plans:I,documents:K,fileBuffer:$}}async function CU($,Y,z){let U=await DR0($,Y,z),Q=U.parsed.map((J,I)=>Hd(J.document,U.plans[I],new Map));return{warnings:[],documents:Q,attachmentPlan:U.plans}}async function sA($,Y,z){let U=await DR0($,Y,z.materialPackFilePolicy),{baseUrl:Q,webhookId:J}=gv1(z.webhookUrl),I=[];for(let K=0;K<U.parsed.length;K+=1){let G=U.parsed[K],W=U.plans[K],H=new Map,X=[...W.categoryFields,...Object.values(W.personAttachments).flat(),...Object.values(W.expenseAttachments).flat()];for(let V of X)for(let F of V.paths){if(H.has(F))continue;let M=U.entries.find((A)=>A.fileName===F);if(!M)continue;process.stderr.write(`⬆ 上传附件: ${F}
`);let w=new FormData,O=await Qd(U.fileBuffer,M),N=F.split("/").pop()??F;w.append("files",new File([new Uint8Array(O)],N));let D=await fetch(`${Q}/api/v1/integrations/webhook/${encodeURIComponent(J)}/attachments`,{method:"POST",headers:{...z.customHeaders??{},...EZ({},z.secret)},body:w});if(!D.ok)throw Error(`附件上传失败 ${D.status}: ${await D.text()}`);let T=await D.json();H.set(F,T.attachments?.map((A)=>A.data)??(T.data===void 0?[]:[T.data])),process.stderr.write(`✓ 附件上传成功: ${F}
`)}process.stderr.write(`\uD83D\uDCE4 推送单据: ${G.document.documentId}
`);let Z=Hd(G.document,W,H),q=await fetch(`${Q}/api/v1/integrations/webhook/${encodeURIComponent(J)}/document`,{method:"POST",headers:{...z.customHeaders??{},"Content-Type":"application/json",...EZ({webhookId:J,...Z},z.secret)},body:JSON.stringify(Z)});if(!q.ok)throw Error(`Webhook 单据推送失败 ${q.status}: ${await q.text()}`);I.push({documentId:Z.documentId,document:Z,pushResult:await q.json()}),process.stderr.write(`✓ 单据推送成功: ${Z.documentId}
`)}return{warnings:[],results:I}}function RU($){return{fileBuffer:Sv1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}var Jl=o(()=>{kP();Xd();Wd();Jd();aI();Ql()});import{existsSync as xv1}from"node:fs";async function aA($,Y,z={}){let Q=_4().stateful?"stateful":"stateless",J="ok",I,K,G;try{let D=await H8($);G={id:D.user.id,name:D.user.name,isAdmin:D.user.isAdmin},K={id:D.tenant.id,name:D.tenant.name,tenantSlug:D.tenant.tenantSlug,corporationName:D.tenant.hoseCorpConfig?.corporationName}}catch(D){J="error",I=D instanceof Error?D.message:String(D)}let W=[];if(J==="ok")try{W=await J$($,Y.seal.endpoints.approvalStylePreferences)}catch(D){J="error",I=`读取 Webhook 配置失败: ${D instanceof Error?D.message:String(D)}`}let H=W.length===1,X=W.map((D)=>({id:D.id,name:D.name,mode:D.mode,incomingDocumentWebhookUrl:D.incomingDocumentWebhook.url,outgoingResultWebhookUrl:D.outgoingResultWebhook,autoApprovalRate:D.autoApprovalRate,...H?{isDefault:!0}:{}})),Z=H?{id:W[0].id,name:W[0].name,mode:W[0].mode}:null,q=z.webhook?v3(W,z.webhook):H?W[0]:void 0,V;if(z.filePath)if(!xv1(z.filePath))V={valid:!1,filePath:z.filePath,fileName:z.filePath.split(/[\\/]/).pop()??z.filePath,documentCount:0,errors:[`文件不存在: ${z.filePath}`]};else try{let D=RU(z.filePath),T=await CU(D.fileBuffer,D.fileName,q?.materialPackFilePolicy);V={valid:!0,filePath:z.filePath,fileName:D.fileName,documentCount:T.documents.length,warnings:T.warnings}}catch(D){V={valid:!1,filePath:z.filePath,fileName:z.filePath.split(/[\\/]/).pop()??z.filePath,documentCount:0,errors:[D instanceof Error?D.message:String(D)]}}let F=V?V.valid:!0,M=J==="ok"&&X.length>0&&F,w=Q==="stateful"?"":` --corp ${Y.id}`,O="",N="";if(J!=="ok")N=`凭证鉴权异常: ${I}`,O=`seal-use auth diagnose${w}`;else if(X.length===0)N="当前企业尚未配置任何 Webhook 集成通道",O=`seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${w}`;else if(V&&!V.valid)N=`资源包预检失败: ${V.errors?.join("; ")}`,O=`seal-use webhook resource-pack preview ${V.filePath}${w}`;else{N=H?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到 ${X.length} 个 Webhook 通道,等待载入`;let D=V?.filePath??"<资源包.zip>",T=H?"":` --webhook ${Z?Z.id:"<webhookIdOrName>"}`;O=`seal-use webhook resource-pack push ${D}${T}${w}`}return{ready:M,corp:{id:Y.id,name:Y.name,sourceType:Y.source.type,tenant:K,user:G},stateMode:Q,authStatus:J,authError:I,activeWebhooks:X,defaultWebhook:Z,resourcePack:V,materialPack:V,statusMessage:N,nextAction:O}}var BR0=o(()=>{S7();X6();Jl()});var Il=o(()=>{aI();nQ();kP();Jd();Wd();Xd();Jl();BR0();Ql()});import{existsSync as PR0,mkdirSync as AR0,statSync as fv1}from"node:fs";import{homedir as uv1}from"node:os";import{dirname as bv1,resolve as tA}from"node:path";function iv1($){if($.outputFile){let I=tA($.outputFile),K=bv1(I);if(!PR0(K))AR0(K,{recursive:!0});return I}let z=($.corpName||$.corpId||"企业").replace(/[/\\?%*:|"<>]/g,"_").trim()||"企业",U=$.dateTag||new Date().toISOString().slice(0,10),Q=`${z}_智能洞察报告_${U}.xlsx`,J;if($.toDownloads)J=tA(uv1(),"Downloads");else J=tA(process.cwd(),"exports");if(!PR0(J))AR0(J,{recursive:!0});return tA(J,Q)}async function eA($,Y,z={}){let U=Y.name||Y.id,Q=cn({startDate:z.startDate,endDate:z.endDate,force:z.force}),J=new Date().toISOString(),[I,K]=await Promise.all([VM($,{startDate:Q.startDateStr,endDate:Q.endDateStr,limit:z.limit??100}),FM($,{startDate:Q.startDateStr,endDate:Q.endDateStr}).catch(()=>({metrics:{},sankeyData:{nodes:[],links:[]}}))]),G=I.tagStats||[],W=[],H=Math.min(G.length,z.limit??50);for(let C=0;C<H;C++){let b=G[C];if(!b?.tagId)continue;try{let k=await LM($,{tagId:b.tagId,startDate:Q.startDateStr,endDate:Q.endDateStr});for(let h of k.risks||[])W.push({tagId:b.tagId,tagName:b.tagName||b.tagId,documentSN:h.documentSN||"-",documentType:h.documentType||"-",riskLevel:h.riskLevel||"warning",confidence:h.confidence??0,riskDetails:h.riskDetails||"-",reasoning:h.reasoning||"-",sourceDocumentURL:h.sourceDocumentURL,createdAt:h.createdAt})}catch{}}let X=new TR0.default.Workbook;X.creator="seal-use",X.lastModifiedBy="seal-use",X.created=new Date,X.modified=new Date;let Z={type:"pattern",pattern:"solid",fgColor:{argb:"FF1E293B"}},q={name:"Microsoft YaHei",size:11,bold:!0,color:{argb:"FFFFFFFF"}},V={top:{style:"thin",color:{argb:"FFE2E8F0"}},bottom:{style:"thin",color:{argb:"FFE2E8F0"}},left:{style:"thin",color:{argb:"FFE2E8F0"}},right:{style:"thin",color:{argb:"FFE2E8F0"}}},F=X.addWorksheet("审核效能与决策流向",{views:[{showGridLines:!0}]});F.columns=[{header:"分类",key:"category",width:20},{header:"指标名称",key:"name",width:28},{header:"数值",key:"val",width:22},{header:"环比/趋势",key:"trend",width:18},{header:"说明",key:"desc",width:36}],F.getRow(1).height=28,F.getRow(1).font=q,F.getRow(1).fill=Z,F.getRow(1).alignment={vertical:"middle",horizontal:"center"};let M=K.metrics||{},w=[{c Line truncated
`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:RK({id:Y?.id,sn:Y?.sn??Y?.sourceDocumentSN??$.sourceDocumentSN,title:Y?.title??Y?.name,template:JT(Y,["template.name","templateName","form.name","formName","formTitle"]),amount:YT(z,["金额","报销金额","付款金额","合计","价税合计"])??JT(Y,["amount","totalAmount","expenseAmount"]),expenseType:YT(z,["费用类型","费用类别","报销类型"]),costCompany:YT(z,["费用承担公司","承担公司","成本中心","费用归属"]),payee:YT(z,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:z.slice(0,30)}),invoices:Jh1($),attachments:k2($,{summary:!0}).attachments,aiResult:KT($),manualResult:vU($)?.value,hints:RK({amountMentions:RR0(U,["金额","合计","税率"],8),partyMentions:RR0(U,["买方","卖方","甲方","乙方","收款"],8)})}}function Yh1($){let Y=[["result.citedRules",n7($,"result.citedRules")],["result.matchedRules",n7($,"result.matchedRules")],["result.ruleResults",n7($,"result.ruleResults")],["result.rules",n7($,"result.rules")],["pipelineData.citedRules",n7($,"pipelineData.citedRules")],["pipelineData.matchedRules",n7($,"pipelineData.matchedRules")]],z=[],U=new Set;for(let[Q,J]of Y)(Array.isArray(J)?J:J&&typeof J==="object"?Object.values(J):[]).forEach((K,G)=>{let W=Xq(K);if(!W)return;let H=S4(W.runtimeRuleId)??S4(W.runtimeId)??S4(W.id)??S4(W.ruleId),X=S4(W.ruleCode)??S4(W.code)??(H?Gh1(H):void 0),Z=RK({runtimeRuleId:H,ruleCode:X,versionNumber:Uh1(W.versionNumber)??$.ruleSetVersionNumber,scope:S4(W.scope),strictness:S4(W.strictness),appliedAnalysis:W.appliedAnalysis??W.analysis??W.reasoning,checkResult:W.checkResult??W.result??W.decision,findings:W.findings??W.riskPoints??W.evidence,sourcePath:`${Q}.${G}`}),q=JSON.stringify(Z);if(!U.has(q))U.add(q),z.push(Z)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:z.length,rules:z}}function JT($,Y){if(!$)return;for(let z of Y){let U=n7($,z);if(U!==void 0)return U}return}function CR0($,Y){if(!$)return 0;for(let z of Y){let U=n7($,z);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 n7($,Y){return Y.split(".").reduce((z,U)=>{if(z===void 0||z===null)return;if(Array.isArray(z)){let Q=Number(U);return Number.isInteger(Q)?z[Q]:void 0}if(typeof z==="object")return z[U];return},$)}function zh1($,Y,z){let U=Y.split("."),Q=$;for(let J of U.slice(0,-1)){let I=Q[J];if(!I||typeof I!=="object"||Array.isArray(I))Q[J]={};Q=Q[J]}Q[U[U.length-1]??Y]=z}function RK($){return Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))}function Xq($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function Uh1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Qh1($){let Y=[];return Hl($,"document",Y),Y}function Hl($,Y,z){if(Array.isArray($)){$.forEach((I,K)=>Hl(I,`${Y}.${K}`,z));return}let U=Xq($);if(!U)return;let Q=S4(U.label)??S4(U.name)??S4(U.title)??S4(U.fieldName),J=U.value??U.displayValue??U.text??U.content;if(Q&&J!==void 0&&typeof J!=="object")z.push(RK({path:Y,label:Q,value:J,type:S4(U.type)??S4(U.fieldType)}));for(let[I,K]of Object.entries(U)){if(I==="attachments")continue;Hl(K,`${Y}.${I}`,z)}}function YT($,Y){return $.find((U)=>{let Q=S4(U.label)??"";return Y.some((J)=>Q.includes(J))})?.value}function Jh1($){let Y=[];return IT($.result,"result",Y),IT($.document,"document",Y),Y.slice(0,20)}function IT($,Y,z){if(Array.isArray($)){$.forEach((Q,J)=>IT(Q,`${Y}.${J}`,z));return}let U=Xq($);if(!U)return;if(/invoice|发票/i.test(Y))z.push(RK({path:Y,fileName:S4(U.fileName)??S4(U.filename)??S4(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[Q,J]of Object.entries(U))IT(J,`${Y}.${Q}`,z)}function RR0($,Y,z){return $.split(/\r?\n/).filter((U)=>Y.some((Q)=>U.includes(Q))).slice(0,z)}function zT($){return $.map((Y)=>{let z=_U(Y);return{recordId:z.id,tenantId:z.tenantId,agentId:z.agentId,sourceDocumentSN:z.sourceDocumentSN,sourceDocumentId:z.sourceDocumentId,simulationBatchId:z.simulationBatchId,langfuseTraceId:z.langfuseTraceId,langfuseSessionFallback:z.langfuseSessionFallback,ruleSetVersionNumber:z.ruleSetVersionNumber,ruleSetPublishedAt:z.ruleSetPublishedAt,ruleSetPublishedByName:z.ruleSetPublishedByName,resolution:z.langfuseTraceId?"trace":z.langfuseSessionFallback?"session-fallback":"unresolved"}})}function Gl($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function Ih1($,Y){if(Y.recordId&&!Y.versionId&&!Y.versionNumber&&!Y.latest){let z=await G4($,Y.recordId);if(!z.ruleSetVersionNumber)throw Er Line truncated
`+`• 身份主体:${w}${O}
`+`• 权限范围:持有该链接者在 Seal AI 中拥有该用户的完整操作权限(含系统设置与规则编辑)
`+`• 时效性:换票凭证有效时间 ${X} 秒(${Math.round(X/60)} 分钟),在浏览器打开后将保留 30 天会话
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:I.sso?G:H,sealResultUrl:H,ssoUrl:G,type:I.sso?"sso_link":"deep_link",expiresIn:I.sso?X:void 0,identity:Z,warning:W,enterpriseAssistUrl:J,enterpriseUrl:J,hoseDomain:Y.type==="hose"?$k1(Y.domain):void 0,documentUrl:Q,recordId:U?.id,sourceDocumentSN:U?.sourceDocumentSN,sourceDocumentId:U?.sourceDocumentId,sourceSystem:U?.sourceSystem,missing:{enterpriseAssistUrl:J?void 0:"Current enterprise source is not Hose, so no Hose enterprise assist URL is configured.",documentUrl:q&&!Q?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:V.object({query:V.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:V.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:V.string().optional().describe("模拟批次 ID"),latest:V.boolean().optional().describe("只返回最新一条匹配记录"),fields:V.union([V.string(),V.array(V.string())]).optional().describe("限制返回字段"),limit:V.number().int().positive().max(100).optional(),maxScan:V.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:V.boolean().optional()}),handler:async($,I)=>{let z=I.sn??I.query;if(!z)throw Error("query or sn is required");let q=await Ik1($,{query:z,sn:I.sn,batchId:I.batchId,latest:I.latest,limit:I.latest?1:I.limit??20,maxScan:I.maxScan??1000}),U=await Promise.all(q.records.map((Q)=>z4($,Q.id))),Y=WR0(I.fields),J=U.map((Q)=>tu1(Q,Y));return{query:z,sourceDocumentSN:I.sn,simulationBatchId:I.batchId,latest:I.latest??!1,total:q.total,scanned:q.scanned,matched:J.length,records:J,next:{getSummary:"seal-home approval-runs get <recordId> --summary",getRuleVersion:"seal-home rules version <ruleSetVersionNumber>",searchRuleVersion:`seal-home tool seal_approval_search --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","ruleVersionNumber":14}'`,getVersionContext:`seal-home tool seal_approval_context_get --json '{"ruleVersionNumber":14}'`},...I.includeBridge?{bridge:AA(U)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:V.object({batchId:V.string().describe("simulation batch ID"),query:V.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,I)=>{let z=gp(await Nv($,I.batchId),I.query);return{batchId:I.batchId,count:z.length,records:z.map(Oz),bridge:AA(z)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:V.object({mode:V.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:V.array(V.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:V.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:V.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:V.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:V.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:V.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:V.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:V.array(V.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:V.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:V.record(V.string(),V.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),noWait:V.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),rawParams:V.record(V.string(),V.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,I)=>{let z=I.mode??"hosecloud",q=I.signKey;if(z==="hosecloud"&&!q){if(q=(await Av($)).find((Q)=>Q.signKey)?.signKey,!q)throw Error("未找到合思集成 signKey, 请通过 signKey Line truncated
`)}function Zk1($){let I=[];if(I.push(`seal-use ${$.area} - ${$.title}`),$.description)I.push($.description);I.push(""),I.push("Usage:");for(let z of $.commands)for(let q of z.usage)I.push(` ${q}`);if($.commands.some((z)=>z.name))I.push(""),I.push(`Run 'seal-use ${$.area} <command> --help' for details on a specific command.`);return I.join(`
`)}function vR0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let I of hR0)for(let z of I.commands)for(let q of z.usage)$.push(` ${q}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var hR0;var bp=e(()=>{H$();hR0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",commands:[{name:"list",summary:"List configured enterprises sorted by 7-day usage frequency",usage:["seal-use corps list [query] [--all] [--limit <n>] [--env <production|test>] [--strict] [--corp <corpId>]"],options:[{flag:"--all",description:"Display all configured enterprises without the default 10-item limit"},{flag:"--limit <n>",description:"Maximum number of enterprises to display (defaults to 10)"},{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}]},{name:"search",aliases:["find"],summary:"Search configured enterprises with intelligent soft fuzzy matching",usage:["seal-use corps search <query> [--env <production|test>] [--strict]"],options:[{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}],description:"Searches enterprise ID, name, staff ID, domain, tenant slug, environment, or bindings. Uses soft search by default (case-insensitive, Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance)."},{name:"get",aliases:["show"],summary:"Get rich details and configuration of an enterprise",usage:["seal-use corps get <corpId>"],description:"Retrieves complete enterprise details (URLs, tenant slugs, custom headers/cookies, staff IDs, relations, config file path) with sensitive secrets safely redacted."},{name:"current",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",summary:"Mark enterprise environment as production or test",usage:["seal-use corps mark <corpId> --env <production|test> [--confirm]"],options:[{flag:"--env <production|test>",description:"Target environment: 'production' or 'test' (required)"},{flag:"--confirm",description:"Confirm the environment update (required)"}],description:"Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."},{name:"bind-test",summary:"Bind a production enterprise to a test enterprise (1-to-1 association)",usage:["seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]","seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"],options:[{flag:"--confirm",description:"Explicitly confirm binding and tag test environment (required)"},{flag:"--force",description:"Force re-binding if the production enterprise is already bound"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Establishes a strict 1-to-1 association between a production enterprise and a test enterprise. Automatically marks the test enterprise with environment 'test'."},{name:"unbind-test",summary:"Unbind a production and test enterprise association",usage:["seal-use corps unbind-test [<corpId>] [--confirm]"],options:[{flag:"--confirm",description:"Explicitly confirm unbinding both sides (required)"},{flag:"--corp <corpId>",description:"Specify enterprise ID or name"}],description:"Removes the 1-to-1 test association from both the production enterprise and the test enterprise."},{name:"sync-test",summary:"Synchronize rules and preferences from production to test enterprise",usage:["seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]"],options:[{flag:"--dry-run",description:"Preview sync diff without making network mutations (default)"},{flag:"--yes",description:"Execute synchronization and publish new rule version on test enterprise"},{flag:"--version-name <name>",description:"Custom version name for published test rule version"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Overwrites test enterprise decision preferences with production preferences, syncs production draft rules to test enterprise, and immediately publishes a new version on the test enterprise. Production rules remain safe in draft state."},{name:"replay-test",summary:"Replay approval records from production enterprise to bound test enterprise via Webhook",usage:["seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--webhook <idOrName>] [--dry-run]"],options:[{flag:"<prodCorpId>",description:"Production enterprise ID (default: active enterprise)"},{flag:"--record-id <id>",description:"Replay a specific approval run ID"},{flag:"--sn <sn>",description:"Replay a specific document SN"},{flag:"--limit <n>",description:"Batch replay latest N records from production (default: 1)"},{flag:"--status <status>",descripti Line truncated
`+`• 时效性:换票凭证有效时间 ${q} 秒(${Math.round(q/60)} 分钟),在浏览器打开后将保留 30 天会话
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:Y.sso?H:W,sealResultUrl:W,ssoUrl:H,type:Y.sso?"sso_link":"deep_link",expiresIn:Y.sso?q:void 0,identity:X,warning:Z,enterpriseAssistUrl:I,enterpriseUrl:I,hoseDomain:J.type==="hose"?Zh1(J.domain):void 0,documentUrl:K,recordId:Q?.id,sourceDocumentSN:Q?.sourceDocumentSN,sourceDocumentId:Q?.sourceDocumentId,sourceSystem:Q?.sourceSystem,missing:{enterpriseAssistUrl:I?void 0:"Current enterprise source is not Hose, so no Hose enterprise assist URL is configured.",documentUrl:U&&!K?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:L.object({query:L.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:L.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:L.string().optional().describe("模拟批次 ID"),latest:L.boolean().optional().describe("只返回最新一条匹配记录"),fields:L.union([L.string(),L.array(L.string())]).optional().describe("限制返回字段"),limit:L.number().int().positive().max(100).optional(),maxScan:L.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:L.boolean().optional()}),handler:async($,Y)=>{let z=Y.sn??Y.query;if(!z)throw Error("query or sn is required");let U=await qh1($,{query:z,sn:Y.sn,batchId:Y.batchId,latest:Y.latest,limit:Y.latest?1:Y.limit??20,maxScan:Y.maxScan??1000}),Q=await Promise.all(U.records.map((K)=>G4($,K.id))),J=ER0(Y.fields),I=Q.map((K)=>Wh1(K,J));return{query:z,sourceDocumentSN:Y.sn,simulationBatchId:Y.batchId,latest:Y.latest??!1,total:U.total,scanned:U.scanned,matched:I.length,records:I,next:{getSummary:"seal-home approval-runs get <recordId> --summary",getRuleVersion:"seal-home rules version <ruleSetVersionNumber>",searchRuleVersion:`seal-home tool seal_approval_search --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","ruleVersionNumber":14}'`,getVersionContext:`seal-home tool seal_approval_context_get --json '{"ruleVersionNumber":14}'`},...Y.includeBridge?{bridge:zT(Q)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:L.object({batchId:L.string().describe("simulation batch ID"),query:L.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,Y)=>{let z=Fl(await oS($,Y.batchId),Y.query);return{batchId:Y.batchId,count:z.length,records:z.map(_U),bridge:zT(z)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:L.object({mode:L.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:L.array(L.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:L.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:L.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:L.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:L.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:L.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:L.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:L.array(L.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:L.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:L.record(L.string(),L.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),noWait:L.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),rawParams:L.record(L.string(),L.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,Y)=>{let z=Y.mode??"hosecloud",U=Y.signKey;if(z==="hosecloud"&&!U){if(U=(await sS($)).find((K)=>K.signKey)?.signKey,!U)throw Error("未找到合思集成 signKey, 请通过 signKey Line truncated
`)}function Ph1($){let Y=[];if(Y.push(`seal-use ${$.area} - ${$.title}`),$.description)Y.push($.description);Y.push(""),Y.push("Usage:");for(let z of $.commands)for(let U of z.usage)Y.push(` ${U}`);if($.commands.some((z)=>z.name))Y.push(""),Y.push(`Run 'seal-use ${$.area} <command> --help' for details on a specific command.`);return Y.join(`
`)}function lR0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let Y of oR0)for(let z of Y.commands)for(let U of z.usage)$.push(` ${U}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var oR0;var Bl=o(()=>{L$();oR0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",commands:[{name:"list",summary:"List configured enterprises sorted by 7-day usage frequency",usage:["seal-use corps list [query] [--all] [--limit <n>] [--env <production|test>] [--strict] [--corp <corpId>]"],options:[{flag:"--all",description:"Display all configured enterprises without the default 10-item limit"},{flag:"--limit <n>",description:"Maximum number of enterprises to display (defaults to 10)"},{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}]},{name:"search",aliases:["find"],summary:"Search configured enterprises with intelligent soft fuzzy matching",usage:["seal-use corps search <query> [--env <production|test>] [--strict]"],options:[{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}],description:"Searches enterprise ID, name, staff ID, domain, tenant slug, environment, or bindings. Uses soft search by default (case-insensitive, Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance)."},{name:"get",aliases:["show"],summary:"Get rich details and configuration of an enterprise",usage:["seal-use corps get <corpId>"],description:"Retrieves complete enterprise details (URLs, tenant slugs, custom headers/cookies, staff IDs, relations, config file path) with sensitive secrets safely redacted."},{name:"current",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",summary:"Mark enterprise environment as production or test",usage:["seal-use corps mark <corpId> --env <production|test> [--confirm]"],options:[{flag:"--env <production|test>",description:"Target environment: 'production' or 'test' (required)"},{flag:"--confirm",description:"Confirm the environment update (required)"}],description:"Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."},{name:"bind-test",summary:"Bind a production enterprise to a test enterprise (1-to-1 association)",usage:["seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]","seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"],options:[{flag:"--confirm",description:"Explicitly confirm binding and tag test environment (required)"},{flag:"--force",description:"Force re-binding if the production enterprise is already bound"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Establishes a strict 1-to-1 association between a production enterprise and a test enterprise. Automatically marks the test enterprise with environment 'test'."},{name:"unbind-test",summary:"Unbind a production and test enterprise association",usage:["seal-use corps unbind-test [<corpId>] [--confirm]"],options:[{flag:"--confirm",description:"Explicitly confirm unbinding both sides (required)"},{flag:"--corp <corpId>",description:"Specify enterprise ID or name"}],description:"Removes the 1-to-1 test association from both the production enterprise and the test enterprise."},{name:"sync-test",summary:"Synchronize rules and preferences from production to test enterprise",usage:["seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]"],options:[{flag:"--dry-run",description:"Preview sync diff without making network mutations (default)"},{flag:"--yes",description:"Execute synchronization and publish new rule version on test enterprise"},{flag:"--version-name <name>",description:"Custom version name for published test rule version"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Overwrites test enterprise decision preferences with production preferences, syncs production draft rules to test enterprise, and immediately publishes a new version on the test enterprise. Production rules remain safe in draft state."},{name:"replay-test",summary:"Replay approval records from production enterprise to bound test enterprise via Webhook",usage:["seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--webhook <idOrName>] [--dry-run]"],options:[{flag:"<prodCorpId>",description:"Production enterprise ID (default: active enterprise)"},{flag:"--record-id <id>",description:"Replay a specific approval run ID"},{flag:"--sn <sn>",description:"Replay a specific document SN"},{flag:"--limit <n>",description:"Batch replay latest N records from production (default: 1)"},{flag:"--status <status>",descripti Line truncated
`)}
`}function oZ($){return $.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function P0($,I={}){Lk1($,I);let z=`${JSON.stringify($,null,2)}
`;if(I.outputFile){Wk1(I.outputFile,z),console.log(JSON.stringify({outputFile:I.outputFile,bytes:Buffer.byteLength(z,"utf-8")},null,2));return}console.log(z.trimEnd())}function Lk1($,I={}){if(I.allowFull||I.outputFile)return;let z=Buffer.byteLength(JSON.stringify($),"utf-8");if(z>wk1)throw new zD(`Output is large (${z} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function xR0($,I){if(I)return;let z=$&&typeof $==="object"?$:{},q=typeof z.count==="number"?z.count:void 0,U=Array.isArray(z.rules)?z.rules.length:void 0,Y=Buffer.byteLength(JSON.stringify($),"utf-8"),J=q??U??0;if(J>Xk1||Y>Vk1)throw new zD(`Rule list is large (${J} rules, ${Y} 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:X0($.full)===!0,outputFile:E($.outputFile)??E($["output-file"])}}function uR0($=[]){console.log(SR0($))}var Xk1=100,Vk1=120000,yR0,wk1=200000;var n1=e(()=>{D4();H$();bp();yR0=["id","code","status","strictness","scope","createdAt","updatedAt"]});var kR0={};o8(kR0,{selectCorp:()=>W1,runToolResult:()=>q2,runTool:()=>N0,globalConfigSummary:()=>z2});function W1($){let I=c8(),z=O4(),q=l7(I,{stateful:z.stateful,defaultCorpId:z.defaultCorpId,corpId:$},a9());return xA0(q.id),q}function z2($=O4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:mI()}}async function N0($,I,z,q,U={}){P0(await q2($,I,z,q),U)}async function q2($,I,z,q){let U=dZ.find((Q)=>Q.name===$);if(!U)throw Error(`Unknown Seal tool: ${$}`);let Y=Object.fromEntries(Object.entries(q).filter(([,Q])=>Q!==void 0)),J=U.handler;return J(I,Y,{corp:z})}var x4=e(()=>{e9();Li();CA();n1()});var yh0={};o8(yh0,{formatTenantDoctorDashboard:()=>Pf1,diagnoseTenantContract:()=>Af1});async function Af1($,I){let z=[],q=I.environment==="test"?"test":"production",U=q==="test"?I.prodCorpId:I.testCorpId,Y=q==="test"?"prodParent":"testTarget",J=null,Q=null;try{let O=await r6($);if(J=O.user,Q=O.tenant,Boolean(J?.isAdmin||J?.permissions?.includes("*")))z.push({id:"auth_identity",name:"身份与权限契约",status:"pass",summary:`已认证为管理员「${J.name??"未知"}」(${J.id??""}),具备完整操作权限`,details:{userId:J.id,userName:J.name,isAdmin:!0,tenantSlug:Q?.tenantSlug,permissions:J.permissions}});else z.push({id:"auth_identity",name:"身份与权限契约",status:"warn",summary:`已认证为普通用户「${J.name??"未知"}」,非超级管理员,部分配置操作可能受限`,details:{userId:J.id,userName:J.name,isAdmin:!1,permissions:J.permissions},recommendation:"建议使用具有管理权限的企业主账号执行规则修改与集成发布"})}catch(O){z.push({id:"auth_identity",name:"身份与权限契约",status:"fail",summary:`鉴权握手失败:${O instanceof Error?O.message:String(O)}`,details:{error:String(O)},recommendation:`请执行 seal-use auth login --corp ${I.id} 重新登录或更新 Token`})}let K={featureCode:"ai-approval",balance:0,deductionAmount:120,estimatedRuns:0,status:"exhausted"},H={used:0,remaining:0};try{let O=await C2($),F=Array.isArray(O.features)?O.features:[],D=F.find((A)=>A?.code==="ai-approval");if(D){let A=typeof D.balance==="number"?D.balance:0,T=typeof D.deductionAmount==="number"&&D.deductionAmount>0?D.deductionAmount:120,k=Math.floor(A/T);if(K.balance=A,K.deductionAmount=T,K.estimatedRuns=k,A<=0)K.status="exhausted",z.push({id:"billing_quota",name:"AI 审批额度余量",status:"fail",summary:"当前额度已耗尽 (余量 0 点),无法执行审批模拟或回归测试",details:{balance:A,deductionAmount:T,estimatedRuns:k},recommendation:"请联系管理员为企业充值 AI 审批额度"});else if(k<10)K.status="low",z.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`额度偏低:剩余 ${A} 点 (单笔扣除 ${T} 点),仅可支持约 ${k} 笔审核`,details:{balance:A,deductionAmount:T,estimatedRuns:k},recommendation:"建议在发起大规模自动化回归前充值补充额度"});else K.status="sufficient",z.push({id:"billing_quota",name:"AI 审批额度余量",status:"pass",summary:`额度充裕:剩余 ${A} 点,预估可支持 ${k} 笔审核单据`,details:{balance:A,deductionAmount:T,estimatedRuns:k}})}else z.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:"未检索到「ai-approval」功能包额度明细,按默认通道运行",details:{features:F.map((A)=>A?.code)}});let P=F.find((A)=>A?.code==="approval-rules");if(P)H.used=typeof P.used==="number"?P.used:0,H.remaining=typeof P.remaining==="number"?P.remaining:0}catch(O){z.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`读取计费状态失败:${O instanceof Error?O.message:String(O)}Line truncated
`)}var xh0=e(()=>{e4()});import{dirname as UW,resolve as Dg0}from"node:path";import{fileURLToPath as zb1}from"node:url";C8();function oz($){return!!$._zod}function T3($,I){if(oz($))return Rz($,I);return $.safeParse(I)}function EX($){if(!$)return;let I;if(oz($))I=$._zod?.def?.shape;else I=$.shape;if(!I)return;if(typeof I==="function")try{return I()}catch{return}return I}function ol($){if(oz($)){let Y=$._zod?.def;if(Y){if(Y.value!==void 0)return Y.value;if(Array.isArray(Y.values)&&Y.values.length>0)return Y.values[0]}}let z=$._def;if(z){if(z.value!==void 0)return z.value;if(Array.isArray(z.values)&&z.values.length>0)return z.values[0]}let q=$.value;if(q!==void 0)return q;return}var G_="2025-11-25";var Wr=[G_,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],j3="io.modelcontextprotocol/related-task",YV="2.0",Q6=qV(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),Xr=t1([K0(),E1().int()]),Vr=K0(),Wc1=E6({ttl:E1().optional(),pollInterval:E1().optional()}),dx0=j0({ttl:E1().optional()}),mx0=j0({taskId:K0()}),Z_=E6({progressToken:Xr.optional(),[j3]:mx0.optional()}),t8=j0({_meta:Z_.optional()}),LQ=t8.extend({task:dx0.optional()}),wr=($)=>LQ.safeParse($).success,C6=j0({method:K0(),params:t8.loose().optional()}),L$=j0({_meta:Z_.optional()}),O$=j0({method:K0(),params:L$.loose().optional()}),_6=E6({_meta:Z_.optional()}),JV=t1([K0(),E1().int()]),Lr=j0({jsonrpc:y0(YV),id:JV,...C6.shape}).strict(),W_=($)=>Lr.safeParse($).success,Or=j0({jsonrpc:y0(YV),...O$.shape}).strict(),Fr=($)=>Or.safeParse($).success,X_=j0({jsonrpc:y0(YV),id:JV,result:_6}).strict(),OQ=($)=>X_.safeParse($).success;var V1;(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(V1||(V1={}));var V_=j0({jsonrpc:y0(YV),id:JV.optional(),error:j0({code:E1().int(),message:K0(),data:s1().optional()})}).strict();var Mr=($)=>V_.safeParse($).success;var Nr=t1([Lr,Or,X_,V_]),Xc1=t1([X_,V_]),QV=_6.strict(),lx0=L$.extend({requestId:JV.optional(),reason:K0().optional()}),KV=O$.extend({method:y0("notifications/cancelled"),params:lx0}),ox0=j0({src:K0(),mimeType:K0().optional(),sizes:Q1(K0()).optional(),theme:j6(["light","dark"]).optional()}),FQ=j0({icons:Q1(ox0).optional()}),qq=j0({name:K0(),title:K0().optional()}),Dr=qq.extend({...qq.shape,...FQ.shape,version:K0(),websiteUrl:K0().optional(),description:K0().optional()}),rx0=zq(j0({applyDefaults:p4().optional()}),d1(K0(),s1())),sx0=wQ(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},zq(j0({form:rx0.optional(),url:Q6.optional()}),d1(K0(),s1()).optional())),tx0=E6({list:Q6.optional(),cancel:Q6.optional(),requests:E6({sampling:E6({createMessage:Q6.optional()}).optional(),elicitation:E6({create:Q6.optional()}).optional()}).optional()}),ax0=E6({list:Q6.optional(),cancel:Q6.optional(),requests:E6({tools:E6({call:Q6.optional()}).optional()}).optional()}),ex0=j0({experimental:d1(K0(),Q6).optional(),sampling:j0({context:Q6.optional(),tools:Q6.optional()}).optional(),elicitation:sx0.optional(),roots:j0({listChanged:p4().optional()}).optional(),tasks:tx0.optional(),extensions:d1(K0(),Q6).optional()}),$u0=t8.extend({protocolVersion:K0(),capabilities:ex0,clientInfo:Dr}),w_=C6.extend({method:y0("initialize"),params:$u0});var Iu0=j0({experimental:d1(K0(),Q6).optional(),logging:Q6.optional(),completions:Q6.optional(),prompts:j0({listChanged:p4().optional()}).optional(),resources:j0({subscribe:p4().optional(),listChanged:p4().optional()}).optional(),tools:j0({listChanged:p4().optional()}).optional(),tasks:ax0.optional(),extensions:d1(K0(),Q6).optional()}),zu0=_6.extend({protocolVersion:K0(),capabilities:Iu0,serverInfo:Dr,instructions:K0().optional()}),L_=O$.extend({method:y0("notifications/initialized"),params:L$.optional()});var HV=C6.extend({method:y0("ping"),params:t8.optional()}),qu0=j0({progress:E1(),total:$4(E1()),message:$4(K0())}),Uu0=j0({...L$.shape,...qu0.shape,progressToken:Xr}),GV=O$.extend({method:y0("notifications/progress"),params:Uu0}),Yu0=t8.extend({cursor:Vr.optional()}),MQ=C6.extend({params:Yu0.optional()}),NQ=_6.extend({nextCursor:Vr.optional()}),Ju0=j6(["working","input_required","completed","failed","cancelled"]),DQ=j0({taskId:K0(),status:Ju0,ttl:t1([E1(),QQ()]),createdAt:K0(),lastUpdatedAt:K0(),pollInterval:$4(E1()),statusMessage:$4(K0())}),Uq=_6.extend({task:DQ}),Qu0=L$.merge(DQ),AQ=O$.extend({method:y0("notifications/tasks/status"),params:Qu0}),ZV=C6.extend({method:y0("tasks/get"),params:t8.extend({taskId:K0()})}),WV=_6.merge(DQ),XV=C6.extend({method:y0("tasks/result"),params:t8.extend({taskId:K0()})}),Vc1=_6.loose(),VV=MQ.extend({method:y0("tasks/list")}),wV=NQ.extend({tasks:Q1(DQ)}),LV=C6.extend({method:y0("tasks/cancel"),para Line truncated
`);if($===-1)return null;let I=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),am0(I)}clear(){this._buffer=void 0}}function am0($){return Nr.parse(JSON.parse($))}function L00($){return JSON.stringify($)+`
`}class kR{constructor($=O00.stdin,I=O00.stdout){this._stdin=$,this._stdout=I,this._readBuffer=new uR,this._started=!1,this._ondata=(z)=>{this._readBuffer.append(z),this.processReadBuffer()},this._onerror=(z)=>{this.onerror?.(z)}}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 z=L00($);if(this._stdout.write(z))I();else this._stdout.once("drain",I)})}}S8();import{dirname as Nd,join as sf1}from"node:path";import{fileURLToPath as tf1}from"node:url";import{spawnSync as O10}from"node:child_process";var JK={name:"seal-use",version:"0.10.22",type:"module",module:"src/server.ts",bin:{"seal-use":"src/cli.ts","seal-home":"src/cli.ts"},scripts:{dev:"bun run --watch src/server.ts",start:"bun run src/server.ts",probe:"bun run src/probe.ts",cli:"bun run src/cli.ts",check:"tsc --noEmit","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"},dependencies:{"@modelcontextprotocol/sdk":"^1.29.0",archiver:"^8.0.0",exceljs:"^4.4.0","iconv-lite":"^0.7.3",ky:"^2.0.2","pinyin-pro":"^3.29.3",yauzl:"^3.4.0",zod:"^4.4.3"},devDependencies:{"@types/archiver":"^8.0.0","@types/bun":"^1.3.14","@types/yauzl":"^3.4.0","bun-types":"^1.3.14",typescript:"^5.9.3",yaml:"^2.9.0"}};function il0($,I=JK.version){let z=$.trim();if(!z)return null;let q=z.endsWith("-dirty"),U=q?z.slice(0,-6):z,Y=U.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/);if(Y&&Y[1]&&Y[2]&&Y[3])return{baseVersion:Y[1],commitsAhead:Number.parseInt(Y[2],10),commit:Y[3],dirty:q,describe:z};let J=U.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)$/);if(J&&J[1])return{baseVersion:J[1],commitsAhead:0,commit:"",dirty:q,describe:z};let Q=U.match(/^([0-9a-f]{7,40})$/);if(Q&&Q[1])return{baseVersion:I,commitsAhead:0,commit:Q[1],dirty:q,describe:z};return null}function nl0($,I,z,q){let Y=z?`+g${z}${q?".dirty":""}`:q?"+dirty":"";return`${$}-dev.${I}${Y}`}function cl0($){let I=$?.env,z=I?.SEAL_BUILD_VERSION??process.env.SEAL_BUILD_VERSION,q=I?.SEAL_BUILD_IS_RELEASE??process.env.SEAL_BUILD_IS_RELEASE,U=I?.SEAL_BUILD_CHANNEL??process.env.SEAL_BUILD_CHANNEL,Y=I?.SEAL_BUILD_GIT_BASE??process.env.SEAL_BUILD_GIT_BASE,J=I?.SEAL_BUILD_GIT_COMMITS_AHEAD??process.env.SEAL_BUILD_GIT_COMMITS_AHEAD,Q=I?.SEAL_BUILD_GIT_COMMIT??process.env.SEAL_BUILD_GIT_COMMIT,K=I?.SEAL_BUILD_GIT_DIRTY??process.env.SEAL_BUILD_GIT_DIRTY,H=I?.SEAL_BUILD_GIT_DESCRIBE??process.env.SEAL_BUILD_GIT_DESCRIBE,G=I?.SEAL_FORCE_RELEASE??process.env.SEAL_FORCE_RELEASE,Z=$?.cwd;if(z){let W=q==="true",w={name:"seal-use",version:z,channel:U||(W?"release":"dev"),isRelease:W};if(Y)w.git={baseVersion:Y,commitsAhead:Number.parseInt(J||"0",10),commit:Q||"",dirty:K==="true",describe:H||z};return w}if(q==="true"||G==="1")return{name:"seal-use",version:JK.version,channel:"release",isRelease:!0};try{let W=O10("git",["describe","--tags","--long","--dirty","--always"],{cwd:Z,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(W.status===0&&W.stdout){let X=il0(W.stdout.trim(),JK.version);if(X){if(!X.commit){let L=O10("git",["rev-parse","--short","HEAD"],{cwd:Z,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(L.status===0&&L.stdout)X.commit=L.stdout.trim()}return{name:"seal-use",version:nl0(X.baseVersion,X.commitsAhead,X.commit,X.dirty),channel:"dev",isRelease:!1,git:X}}}}catch{}return{name:"seal-use",version:`${JK.version}-dev.0+local`,channel:"dev",isRelease:!1}}var QK=cl0(),q1=QK.version,Jv=QK.isRelease,gs1=QK.channel;e4();dN();lN();x4();D4();n1();S8();x4();e4();e4();GZ();Pp();D4();n1();H$();import{existsSync as fR0}from"node:fs";async function bR0($,I){if(!fR0($))throw Error(`File not found: ${$}`);let z=Lz($);console.log(JSON.stringify(await wz(z.fileBuffer,z.fileName,I),null,2))}async function gA($,I,z,q,U){if($==="ready"||$==="status"){let Y=I??E(U.options.file)??E(U.options.input),J=await OA(z,q,{filePath:Y,webhook:E(U.options.webhook)??E(U.options.selector)});if(console.error(`[webhook-ready] 企业环境: ${J.corp.name} (${J.corp.id}) [${J.stateMode}]`),J.corp.tenant?.name)console.error(`[webhook-ready] 租户信息: ${J.corp.tenant.name} (${J.corp.tenant.id})`);console.error(`[webhook-ready] 凭证状态: ${J.authStatus==="ok"?"OK":`异常 (${J.authError})`}`),console.erro Line truncated
`}function Lq($){return $.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function c0($,Y={}){Ch1($,Y);let z=`${JSON.stringify($,null,2)}
`;if(Y.outputFile){Ah1(Y.outputFile,z),console.log(JSON.stringify({outputFile:Y.outputFile,bytes:Buffer.byteLength(z,"utf-8")},null,2));return}console.log(z.trimEnd())}function Ch1($,Y={}){if(Y.allowFull||Y.outputFile)return;let z=Buffer.byteLength(JSON.stringify($),"utf-8");if(z>Eh1)throw new xP(`Output is large (${z} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function tR0($,Y){if(Y)return;let z=$&&typeof $==="object"?$:{},U=typeof z.count==="number"?z.count:void 0,Q=Array.isArray(z.rules)?z.rules.length:void 0,J=Buffer.byteLength(JSON.stringify($),"utf-8"),I=U??Q??0;if(I>Th1||J>jh1)throw new xP(`Rule list is large (${I} rules, ${J} 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 C0($){return{allowFull:F0($.full)===!0,outputFile:S($.outputFile)??S($["output-file"])}}function eR0($=[]){console.log(sR0($))}var Th1=100,jh1=120000,aR0,Eh1=200000;var J4=o(()=>{D4();L$();Bl();aR0=["id","code","status","strictness","scope","createdAt","updatedAt"]});var $_0={};x8($_0,{selectCorp:()=>E1,runToolResult:()=>o2,runTool:()=>k0,globalConfigSummary:()=>l2});function E1($){let Y=s8(),z=_4(),U=f2(Y,{stateful:z.stateful,defaultCorpId:z.defaultCorpId,corpId:$},h7());return aD0(U.id),U}function l2($=_4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:JU()}}async function k0($,Y,z,U,Q={}){c0(await o2($,Y,z,U),Q)}async function o2($,Y,z,U){let Q=Hq.find((K)=>K.name===$);if(!Q)throw Error(`Unknown Seal tool: ${$}`);let J=Object.fromEntries(Object.entries(U).filter(([,K])=>K!==void 0)),I=Q.handler;return I(Y,J,{corp:z})}var o4=o(()=>{S7();gP();Zq();J4()});import{existsSync as Y_0}from"node:fs";async function z_0($,Y){if(!Y_0($))throw Error(`File not found: ${$}`);let z=RU($);console.log(JSON.stringify(await CU(z.fileBuffer,z.fileName,Y),null,2))}async function ZT($,Y,z,U,Q){if($==="ready"||$==="status"){let J=Y??S(Q.options.file)??S(Q.options.input),I=await aA(z,U,{filePath:J,webhook:S(Q.options.webhook)??S(Q.options.selector)});if(console.error(`[webhook-ready] 企业环境: ${I.corp.name} (${I.corp.id}) [${I.stateMode}]`),I.corp.tenant?.name)console.error(`[webhook-ready] 租户信息: ${I.corp.tenant.name} (${I.corp.tenant.id})`);console.error(`[webhook-ready] 凭证状态: ${I.authStatus==="ok"?"OK":`异常 (${I.authError})`}`),console.error(`[webhook-ready] Webhook 通道: ${I.activeWebhooks.length} 个可用`);for(let K of I.activeWebhooks){let G=K.isDefault?" [默认通道]":"";console.error(` - ${K.name} (${K.id}) mode=${K.mode}${G}`)}if(I.materialPack)console.error(`[webhook-ready] 材料包预检: ${I.materialPack.valid?`通过 (${I.materialPack.documentCount} 单)`:`失败 (${I.materialPack.errors?.join("; ")})`}`);if(I.ready)console.error(`\uD83D\uDFE2 ${I.statusMessage}`),console.error(`\uD83D\uDC49 Next action: ${I.nextAction}`);else console.error(`\uD83D\uDD34 准备阶段未通过: ${I.statusMessage}`),console.error(`\uD83D\uDC49 Next action: ${I.nextAction}`);console.log(JSON.stringify(I,null,2));return}if($==="replay"){let J=Y??S(Q.options.recordId)??S(Q.options["record-id"])??S(Q.options.id),I=S(Q.options.recordIds)??S(Q.options["record-ids"]),K=I?I.split(",").map((c)=>c.trim()).filter(Boolean):void 0,G=S(Q.options.sn)??S(Q.options.documentSn)??S(Q.options["document-sn"]),W=S(Q.options.sns)??S(Q.options["document-sns"]),H=W?W.split(",").map((c)=>c.trim()).filter(Boolean):void 0,X=s0(Q.options.limit),Z=S(Q.options.status),q=S(Q.options.startDate)??S(Q.options["start-date"]),V=S(Q.options.endDate)??S(Q.options["end-date"]);if(!J&&!K&&!G&&!H&&X===void 0)throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let F=S(Q.options.sourceCorp)??S(Q.options["source-corp"])??S(Q.options.prodCorp)??S(Q.options["prod-corp"]),M=S(Q.options.targetCorp)??S(Q.options["target-corp"])??S(Q.options.testCorp)??S(Q.options["test-corp"]),w=F0(Q.options.force)===!0,{sourceCorp:O,targetCorp:N}=fP({sourceCorpId:F,targetCorpId:M,activeCorp:U,force:w},E1),D=O.id===U.id?z:await j1(O),T=N.id===U.id?z:await j1(N),A=S(Q.options.webhook)??S(Q.options.selector),B=S(Q.options.snSuffix)??S(Q.options["sn-suffix"]),j=S(Q.options.snPrefix)??S(Q.options["sn-prefix"]),C=S(Q.options.docIdSuffix)??S(Q.options["doc-id-suffix"]),b=S(Q.options.docIdPrefix)??S(Q.options["doc-id-prefix"]),k=F0(Q.options.dryRun)??F0(Q.options["dry-run"]),i=await rI({query:{recordId:J,recordIds:K,sn:G,sns:H,limit:X,status:Z,startDate:q,endDate:V},sourceClient:D,targetClient:T,sourceCorp:O,targetCorp:N,webhookSelector:A,snPrefix:j,snSuffix:B,docIdPrefix:b,docIdSuffix:C Line truncated
`+`\uD83D\uDC49 查看全部请添加: seal-use corps list --all
`+"\uD83D\uDC49 检索指定企业请使用: seal-use corps search <keyword>")}P0(F.map((D)=>({id:D.id,name:D.name,environment:D.environment??"production",sourceType:D.source.type,provider:D.source.provider??D.source.type,staffId:D.source.staffId,testCorpId:D.testCorpId,prodCorpId:D.prodCorpId,current:D.id===H})));return}if($==="get"||$==="show"){let q=I??E(z.options.corp);if(!q)throw g4("Usage: seal-use corps get <corpId>");let U=W1(q),Y=Wi(U.id),J=ok1(U);P0({id:U.id,name:U.name,environment:U.environment??"production",configFile:Y,seal:{url:J,tenantSlug:U.seal.tenantSlug??U.source.tenantSlug,customHeaderNames:U.seal.headers?Object.keys(U.seal.headers):[],customCookieNames:U.seal.cookies?Object.keys(U.seal.cookies):[],endpoints:U.seal.endpoints},source:rk1(U.source),relations:{testCorpId:U.testCorpId,prodCorpId:U.prodCorpId},auth:{refreshTtl:U.auth.refreshTtl}});return}if($==="current"){let q=W1(E(z.options.corp));P0({id:q.id,name:q.name,environment:q.environment??"production",sourceType:q.source.type,provider:q.source.provider??q.source.type,staffId:q.source.staffId,testCorpId:q.testCorpId,prodCorpId:q.prodCorpId});return}if($==="mark"||$==="mark-test"||$==="mark-prod"){let q=I??E(z.options.corp);if(!q)throw g4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");let U=W1(q),Y=$==="mark-test"?"test":$==="mark-prod"?"production":E(z.options.env)??E(z.options.environment);if(Y!=="production"&&Y!=="test")throw g4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");if(!(X0(z.options.confirm)===!0||X0(z.options.yes)===!0))throw e5(`Refusing to change environment tag of enterprise '${U.name}' (${U.id}) to '${Y}' without --confirm. Marking alters synchronization safety guards.`,`seal-use corps mark ${U.id} --env ${Y} --confirm`);let Q=m7(U.id,{environment:Y});P0({id:Q.id,name:Q.name,environment:Q.environment,testCorpId:Q.testCorpId,prodCorpId:Q.prodCorpId});return}if($==="bind-test"){let q,U;if(I&&z.command[3])q=I,U=z.command[3];else if(I){let Z=E(z.options.corp),W=E(z.options["test-corp"])??E(z.options.testCorp);if(Z)q=Z,U=I;else if(W)q=I,U=W}if(!q||!U)throw g4(`Usage: seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
or: seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]`);let Y=W1(q),J=W1(U);if(Y.id===J.id)throw g4(`Cannot bind enterprise '${Y.id}' to itself.`);if(Y.prodCorpId&&Y.prodCorpId!==J.id)throw g4(`Cannot use '${Y.id}' as a production enterprise because it is already registered as a test enterprise for '${Y.prodCorpId}'. Multi-tier chaining is not permitted.`);if(J.testCorpId&&J.testCorpId!==Y.id)throw g4(`Cannot bind '${J.id}' as a test enterprise because it already has a bound test enterprise '${J.testCorpId}'. Multi-tier chaining is not permitted.`);let Q=X0(z.options.force)===!0;if(Y.testCorpId&&Y.testCorpId!==J.id||J.prodCorpId&&J.prodCorpId!==Y.id){if(!Q)throw e5(`Enterprise binding conflict: production enterprise '${Y.id}' is bound to '${Y.testCorpId??"none"}', and test enterprise '${J.id}' is bound to '${J.prodCorpId??"none"}'. Overwriting an existing binding requires --force and --confirm.`,`seal-use corps bind-test ${Y.id} ${J.id} --confirm --force`)}if(!(X0(z.options.confirm)===!0||X0(z.options.yes)===!0)){let Z=Q?" --force":"";throw e5(`Refusing to bind test enterprise '${J.name}' (${J.id}) to production enterprise '${Y.name}' (${Y.id}) without --confirm. Enterprise binding establishes 1-to-1 sync pairing and marks '${J.id}' as a test environment.`,`seal-use corps bind-test ${Y.id} ${J.id} --confirm${Z}`)}if(Y.testCorpId&&Y.testCorpId!==J.id)try{m7(Y.testCorpId,{prodCorpId:void 0})}catch{}if(J.prodCorpId&&J.prodCorpId!==Y.id)try{m7(J.prodCorpId,{testCorpId:void 0})}catch{}let H=m7(Y.id,{environment:"production",testCorpId:J.id}),G=m7(J.id,{environment:"test",prodCorpId:Y.id});P0({success:!0,productionEnterprise:{id:H.id,name:H.name,environment:H.environment,testCorpId:H.testCorpId},testEnterprise:{id:G.id,name:G.name,environment:G.environment,prodCorpId:G.prodCorpId}});return}if($==="unbind-test"){let q=I??E(z.options.corp),U=W1(q);if(!U.testCorpId&&!U.prodCorpId){P0({unbound:!1,message:`Enterprise '${U.name}' (${U.id}) does not have an active test enterprise binding.`});return}let Y=U.testCorpId?U.id:U.prodCorpId,J=U.testCorpId?U.testCorpId:U.id;if(!(X0(z.options.confirm)===!0||X0(z.options.yes)===!0))throw e5(`Refusing to unbind production enterprise '${Y}' and test enterprise '${J}' without --confirm.`,`seal-use corps unbind-test ${U.id} --confirm`);m7(Y,{testCorpId:void 0});try{m7(J,{prodCorpId:void 0})}catch{}P0({success:!0,unboundProduction:Y,unboundTest:J});return}if($==="sync-test"){let q=I??E(z.options.corp),U=W1(q);if(!U.testCorpId)throw g4(`Production enterprise '${U.name}' (${U.id}) has no bound test enterprise.
Run 'seal-use corps bind-test ${U.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`);let Y=W1(U.testCorpId);if(Y.environment!=="test")throw Error(`Target enterprise '${Y.name}' (${Y.id}) is marked as '${Y.environment}', NOT 'test'. Aborting sync to protect non-test environments.`);let J=await K1(U),Q=await K1(Y),[K,H,G,Z,W,X,w,L]=await Promise.all([v1(J,U.seal.endpoints.approvalStylePreferences).catch(()=>({})),v1(Q,Y.seal.endpoints.approvalStylePreferences).catch(()=>({})),h6(J),h6(Q),N$(J).catch(()=>[]),N$(Q).catch(()=>[]),f3(J,{limit:100}).catch(()=>({articles:[]})),f3(Q,{limit:100}).catch(()=>({articles:[]}))]),O=(w.articles||[]).filter((o)=>!o.isDeleted),F=(L.articles||[]).filter((o)=>!o.isDeleted),D=new Map(F.map((o)=>[o.title.trim(),o])),P=[],A=[],T=new Set(O.map((o)=>o.title.trim()));for(let o of O){let E0=o.title.trim(),k0=D.get(E0);if(!k0)P.push(o);else{let L1=k0.content!==o.content,k4=(k0.purpose??"")!==(o.purpose??""),t4=k0.enabled!==o.enabled,Z$=k0.contentType!==o.contentType,T8=(k0.status??"")!==(o.status??""),J8=JSON.stringify([...k0.scenarios??[]].sort())!==JSON.stringify([...o.scenarios??[]].sort()),W$=JSON.stringify([...k0.tags??[]].sort())!==JSON.stringify([...o.tags??[]].sort());if(L1||k4||t4||Z$||T8||J8||W$)A.push({testId:k0.id,prodDoc:o,reasons:[...L1?["content"]:[],...k4?["purpose"]:[],...t4?["enabled"]:[],...Z$?["contentType"]:[],...T8?["status"]:[],...J8?["scenarios"]:[],...W$?["tags"]:[]]})}}let k=F.filter((o)=>!T.has(o.title.trim())),f=[...W].sort((o,E0)=>E0.versionNumber-o.versionNumber)[0],C=f?.versionNumber,i=([...X].sort((o,E0)=>E0.versionNumber-o.versionNumber)[0]?.versionNumber??0)+1,v=zh0(U.name,C,X),c=E(z.options["version-name"])??E(z.options.versionName)??qh0(U.name,C,v,i),$0={...H,tone:K.tone,language:K.language,detailLevel:K.detailLevel,outputFormat:K.outputFormat,examples:K.examples??[],prohibitedPhrases:K.prohibitedPhrases??[],customInstructions:K.customInstructions,decisionPreferences:K.decisionPreferences,thinkingDepthPreference:K.thinkingDepthPreference};if(X0(z.options["dry-run"])===!0||X0(z.options.dryRun)===!0){P0({dryRun:!0,source:{id:U.id,name:U.name,environment:U.environment,latestPublishedVersion:f?{versionNumber:f.versionNumber,versionName:f.versionName}:null,documentsCount:O.length},target:{id:Y.id,name:Y.name,environment:Y.environment},versionMappingPlan:{sourceProdVersionNumber:C??null,sourceProdVersionName:f?.versionName??null,targetTestExpectedVersionNumber:i,targetTestPublishVersionName:c,iteration:v},preferencesDiff:{decisionPreferences:{before:H.decisionPreferences,after:K.decisionPreferences},thinkingDepthPreference:{before:H.thinkingDepthPreference,after:K.thinkingDepthPreference}},rulesPlan:{sourceDraftRuleCount:G.rules.length,targetExistingDraftRuleCount:Z.rules.length,toDeleteCount:Z.rules.length,toCreateCount:G.rules.length,rulesToSync:G.rules.map((o,E0)=>({index:E0+1,sourceRuleId:o.id,sourceRuleCode:o.code??E0+1,expectedTargetCode:`rule-${E0+1}`,description:o.description,scope:o.scope,strictness:o.strictness}))},documentsPlan:{sourceDocumentCount:O.length,targetExistingDocumentCount:F.length,toCreateCount:P.length,toCreate:P.map((o)=>({title:o.title,purpose:o.purpose,contentType:o.contentType,scenarios:o.scenarios})),toUpdateCount:A.length,toUpdate:A.map((o)=>({targetDocumentId:o.testId,title:o.prodDoc.title,reasons:o.reasons})),toDeleteCount:k.length,toDelete:k.map((o)=>({targetDocumentId:o.id,title:o.title}))},publishingPlan:{targetCorpId:Y.id,publishVersionName:c,publishTarget:"test"},hosecloudSyncPlan:(()=>{if(U.source.type!=="hose")return{sourceType:U.source.type,skipped:!0,reason:"prod source is not hose; no hosecloud credentials available"};let o=(K.integrations??[]).filter((L1)=>L1.type==="hosecloud"),E0=new Set,k0=o.filter((L1)=>{let k4=L1.corporationId??U.id;if(E0.has(k4))return!1;return E0.add(k4),!0});return{sourceType:"hose",outboundName:Hh0(U.name),targetMode:"assisted",integrationsCount:k0.length,integrations:k0.map((L1)=>({corporationId:L1.corporationId,apiOrigin:L1.apiOrigin,customApiUrl:L1.customApiUrl}))}})(),productionGuarantees:{prodRulesStayDraft:!0,prodVersionPublished:!1}});return}if(!(X0(z.options.yes)===!0||X0(z.options.confirm)===!0))throw e5(`Refusing to overwrite test enterprise '${Y.name}' (${Y.id}) with preferences, ${G.rules.length} draft rules, and ${O.length} knowledge documents from production enterprise '${U.name}' (${U.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 ${U.id} --yes`);await T5(Q,$0,Y.seal.endpoints.approvalStylePreferences);let p=[];for(let o of k)await hw(Q,o.id),p.push({id:o.id,title:o.title});let s=[];for(let o of A)await vw(Q,o.testId,{title:o.prodDoc.title,purpose:o.prodDoc.purpose,content:o.prodDoc.content,contentType:o.prodDoc.contentType,status:o.prodDoc.status,enabled:o.prodDoc.enabled,scenarios:o.prodDoc.scenarios&&o.prodDoc.scenarios.le Line truncated
Run 'seal-use corps bind-test ${U.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association,
or add '--force' (or use 'seal-use webhook replay <recordId> --force') if you explicitly intend to replay directly within production.`);J=U}else if(J=W1(U.testCorpId),J.environment!=="test"&&!Y)throw Error(`Target enterprise '${J.name}' (${J.id}) is marked as '${J.environment}', NOT 'test'. Aborting replay to protect non-test environments (use --force to override).`);let Q=E(z.options.recordId)??E(z.options["record-id"])??E(z.options.id),K=E(z.options.recordIds)??E(z.options["record-ids"]),H=K?K.split(",").map((i)=>i.trim()).filter(Boolean):void 0,G=E(z.options.sn)??E(z.options.documentSn)??E(z.options["document-sn"]),Z=E(z.options.sns)??E(z.options["document-sns"]),W=Z?Z.split(",").map((i)=>i.trim()).filter(Boolean):void 0,X=R0(z.options.limit)??(!Q&&!H&&!G&&!W?1:void 0),w=E(z.options.status),L=E(z.options.startDate)??E(z.options["start-date"]),O=E(z.options.endDate)??E(z.options["end-date"]),F=await K1(U),D=U.id===J.id?F:await K1(J),P=E(z.options.webhook)??E(z.options.selector),A=E(z.options.snSuffix)??E(z.options["sn-suffix"]),T=E(z.options.snPrefix)??E(z.options["sn-prefix"]),k=E(z.options.docIdSuffix)??E(z.options["doc-id-suffix"]),h=E(z.options.docIdPrefix)??E(z.options["doc-id-prefix"]),f=X0(z.options.dryRun)??X0(z.options["dry-run"]),C={recordId:Q,recordIds:H,sn:G,sns:W,limit:X,status:w,startDate:L,endDate:O};console.error(`[corps-replay-test] 正式企业「${U.name}」(${U.id}) -> 测试企业「${J.name}」(${J.id})`);let b=await vY({query:C,sourceClient:F,targetClient:D,sourceCorp:U,targetCorp:J,webhookSelector:P,snPrefix:T,snSuffix:A,docIdPrefix:h,docIdSuffix:k,dryRun:f});if(f){console.error(`[corps-replay-test] 预览模式:已成功从 ${U.name} 提取单据并转换为 Webhook Payload(未实际推送)。`),console.log(JSON.stringify(b,null,2));return}if(b.success)if(b.totalCount===1&&b.replayedDocument)console.error(`\uD83D\uDFE2 成功重放单据「${b.replayedDocument.documentSN}」至 ${J.name} (${b.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDFE2 成功重放 ${b.successCount} 条单据(来自「${U.name}」)至「${J.name}」(${b.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDD34 单据重放部分或全部失败(成功 ${b.successCount} 条,失败 ${b.failureCount} 条)至「${J.name}」`);if(console.error(`\uD83D\uDC49 Next action: seal-use approval-runs list --corp ${J.id} --limit ${b.totalCount}`),console.log(JSON.stringify(b,null,2)),!b.success)process.exitCode=1;return}if($==="switch"){let q=I;if(!q)throw Error("Usage: seal-use corps switch <corpId>");let U=O4();if(!U.stateful)throw Error("Cannot switch the default enterprise while stateless mode is enabled. Use `seal-use config mode stateful` first.");let Y=W1(q);lI({...U,stateful:!0,defaultCorpId:Y.id}),P0({current:!0,id:Y.id,name:Y.name});return}if($==="probe-hose"){await tk1(P8(z.json));return}if($==="hose-staffs"){await ak1(P8(z.json));return}if($==="add-hose"){await ek1(P8(z.json));return}if($==="add-seal"){await $f1(P8(z.json));return}if($==="add-link"){let q=I??E(z.options.link)??E(z.options.url);if(!q)throw Error("Usage: seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]");await If1(q,E(z.options.name),X0(z.options.overwrite)===!0);return}throw Error(`Unknown corps command: ${$??""}. Run 'seal-use help' for available commands.`)}function Hh0($){return[...$].slice(0,6).join("")+"(Seal测)"}async function sk1($,I,z,q){if($.source.type!=="hose")return{skipped:!0,reason:"prod source is not hose; no hosecloud credentials available"};let U=($.source.appKey??$.source.key)?.trim(),Y=($.source.appSecurity??$.source.password)?.trim();if(!U||!Y)return{skipped:!0,reason:"prod hose source missing appKey/appSecurity (or key/password)"};let[J,Q]=await Promise.all([v1(z,$.seal.endpoints.approvalStylePreferences).catch(()=>({})),v1(q,I.seal.endpoints.approvalStylePreferences).catch(()=>({}))]),K=(J.integrations??[]).filter((D)=>D.type==="hosecloud");if(K.length===0)return{skipped:!0,reason:"prod Seal enterprise has no hosecloud integrations configured"};let H=new Set,G=[];for(let D of K){let P=D.corporationId??$.id;if(!H.has(P))H.add(P),G.push(D)}let Z=Q.integrations??[],W=new Map(Z.filter((D)=>D.type==="hosecloud").map((D)=>[D.corporationId,D])),X=Hh0($.name),w=[],L=G.map((D)=>{let P=W.get(D.corporationId),A=P?.signKey??lk1(6).toString("hex");return w.push({signKey:A,outboundName:X,corporationId:D.corporationId,action:P?"updated":"created"}),{type:"hosecloud",signKey:A,outboundName:X,mode:"assisted",apiKey:U,apiSecret:Y,apiOrigin:D.apiOrigin,...D.customApiUrl?{customApiUrl:D.customApiUrl}:{},corporationId:D.corporationId}}),O=Z.filter((D)=>D.type!=="hosecloud"),F={...Q,integrations:[...O,...L]};return await T5(q,F,I.seal.endpoints.approvalStylePreferences),{skipped:!1,synced:w}}async function tk1($){let I=G3($,"appKey"),z=G3($,"appSecurity"),q=l1($,"domain"),U=await Eq(I,z,q),Y=await Mw(U.domain,U.openapiToken).catch(()=>[]) Line truncated
`+"\uD83D\uDC49 检索指定企业请使用: seal-use corps search <keyword>")}c0(w.map((O)=>({id:O.id,name:O.name,environment:O.environment??"production",sourceType:O.source.type,provider:O.source.provider??O.source.type,staffId:O.source.staffId,testCorpId:O.testCorpId,prodCorpId:O.prodCorpId,current:O.id===W})));return}if($==="get"||$==="show"){let U=Y??S(z.options.corp);if(!U)throw d4("Usage: seal-use corps get <corpId>");let Q=E1(U),J=tn(Q.id),I=zS1(Q);c0({id:Q.id,name:Q.name,environment:Q.environment??"production",configFile:J,seal:{url:I,tenantSlug:Q.seal.tenantSlug??Q.source.tenantSlug,customHeaderNames:Q.seal.headers?Object.keys(Q.seal.headers):[],customCookieNames:Q.seal.cookies?Object.keys(Q.seal.cookies):[],endpoints:Q.seal.endpoints},source:US1(Q.source),relations:{testCorpId:Q.testCorpId,prodCorpId:Q.prodCorpId},auth:{refreshTtl:Q.auth.refreshTtl}});return}if($==="current"){let U=E1(S(z.options.corp));c0({id:U.id,name:U.name,environment:U.environment??"production",sourceType:U.source.type,provider:U.source.provider??U.source.type,staffId:U.source.staffId,testCorpId:U.testCorpId,prodCorpId:U.prodCorpId});return}if($==="mark"||$==="mark-test"||$==="mark-prod"){let U=Y??S(z.options.corp);if(!U)throw d4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");let Q=E1(U),J=$==="mark-test"?"test":$==="mark-prod"?"production":S(z.options.env)??S(z.options.environment);if(J!=="production"&&J!=="test")throw d4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");if(!(F0(z.options.confirm)===!0||F0(z.options.yes)===!0))throw D9(`Refusing to change environment tag of enterprise '${Q.name}' (${Q.id}) to '${J}' without --confirm. Marking alters synchronization safety guards.`,`seal-use corps mark ${Q.id} --env ${J} --confirm`);let K=x2(Q.id,{environment:J});c0({id:K.id,name:K.name,environment:K.environment,testCorpId:K.testCorpId,prodCorpId:K.prodCorpId});return}if($==="bind-test"){let U,Q;if(Y&&z.command[3])U=Y,Q=z.command[3];else if(Y){let X=S(z.options.corp),Z=S(z.options["test-corp"])??S(z.options.testCorp);if(X)U=X,Q=Y;else if(Z)U=Y,Q=Z}if(!U||!Q)throw d4(`Usage: seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
or: seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]`);let J=E1(U),I=E1(Q);if(J.id===I.id)throw d4(`Cannot bind enterprise '${J.id}' to itself.`);if(J.prodCorpId&&J.prodCorpId!==I.id)throw d4(`Cannot use '${J.id}' as a production enterprise because it is already registered as a test enterprise for '${J.prodCorpId}'. Multi-tier chaining is not permitted.`);if(I.testCorpId&&I.testCorpId!==J.id)throw d4(`Cannot bind '${I.id}' as a test enterprise because it already has a bound test enterprise '${I.testCorpId}'. Multi-tier chaining is not permitted.`);let K=F0(z.options.force)===!0;if(J.testCorpId&&J.testCorpId!==I.id||I.prodCorpId&&I.prodCorpId!==J.id){if(!K)throw D9(`Enterprise binding conflict: production enterprise '${J.id}' is bound to '${J.testCorpId??"none"}', and test enterprise '${I.id}' is bound to '${I.prodCorpId??"none"}'. Overwriting an existing binding requires --force and --confirm.`,`seal-use corps bind-test ${J.id} ${I.id} --confirm --force`)}if(!(F0(z.options.confirm)===!0||F0(z.options.yes)===!0)){let X=K?" --force":"";throw D9(`Refusing to bind test enterprise '${I.name}' (${I.id}) to production enterprise '${J.name}' (${J.id}) without --confirm. Enterprise binding establishes 1-to-1 sync pairing and marks '${I.id}' as a test environment.`,`seal-use corps bind-test ${J.id} ${I.id} --confirm${X}`)}if(J.testCorpId&&J.testCorpId!==I.id)try{x2(J.testCorpId,{prodCorpId:void 0})}catch{}if(I.prodCorpId&&I.prodCorpId!==J.id)try{x2(I.prodCorpId,{testCorpId:void 0})}catch{}let W=x2(J.id,{environment:"production",testCorpId:I.id}),H=x2(I.id,{environment:"test",prodCorpId:J.id});c0({success:!0,productionEnterprise:{id:W.id,name:W.name,environment:W.environment,testCorpId:W.testCorpId},testEnterprise:{id:H.id,name:H.name,environment:H.environment,prodCorpId:H.prodCorpId}});return}if($==="unbind-test"){let U=Y??S(z.options.corp),Q=E1(U);if(!Q.testCorpId&&!Q.prodCorpId){c0({unbound:!1,message:`Enterprise '${Q.name}' (${Q.id}) does not have an active test enterprise binding.`});return}let J=Q.testCorpId?Q.id:Q.prodCorpId,I=Q.testCorpId?Q.testCorpId:Q.id;if(!(F0(z.options.confirm)===!0||F0(z.options.yes)===!0))throw D9(`Refusing to unbind production enterprise '${J}' and test enterprise '${I}' without --confirm.`,`seal-use corps unbind-test ${Q.id} --confirm`);x2(J,{testCorpId:void 0});try{x2(I,{prodCorpId:void 0})}catch{}c0({success:!0,unboundProduction:J,unboundTest:I});return}if($==="sync-test"){let U=Y??S(z.options.corp),Q=E1(U);if(!Q.testCorpId)throw d4(`Production enterprise '${Q.name}' (${Q.id}) has no bound test enterprise.
Run 'seal-use corps bind-test ${Q.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`);let J=E1(Q.testCorpId);if(J.environment!=="test")throw Error(`Target enterprise '${J.name}' (${J.id}) is marked as '${J.environment}', NOT 'test'. Aborting sync to protect non-test environments.`);let I=await j1(Q),K=await j1(J),[G,W,H,X,Z,q,V,F]=await Promise.all([o1(I,Q.seal.endpoints.approvalStylePreferences).catch(()=>({})),o1(K,J.seal.endpoints.approvalStylePreferences).catch(()=>({})),p6(I),p6(K),A$(I).catch(()=>[]),A$(K).catch(()=>[]),_3(I,{limit:100}).catch(()=>({articles:[]})),_3(K,{limit:100}).catch(()=>({articles:[]}))]),M=(V.articles||[]).filter((G0)=>!G0.isDeleted),w=(F.articles||[]).filter((G0)=>!G0.isDeleted),O=new Map(w.map((G0)=>[G0.title.trim(),G0])),N=[],D=[],T=new Set(M.map((G0)=>G0.title.trim()));for(let G0 of M){let T0=G0.title.trim(),b0=O.get(T0);if(!b0)N.push(G0);else{let Y1=b0.content!==G0.content,a=(b0.purpose??"")!==(G0.purpose??""),H0=b0.enabled!==G0.enabled,L0=b0.contentType!==G0.contentType,f0=(b0.status??"")!==(G0.status??""),u0=JSON.stringify([...b0.scenarios??[]].sort())!==JSON.stringify([...G0.scenarios??[]].sort()),i0=JSON.stringify([...b0.tags??[]].sort())!==JSON.stringify([...G0.tags??[]].sort());if(Y1||a||H0||L0||f0||u0||i0)D.push({testId:b0.id,prodDoc:G0,reasons:[...Y1?["content"]:[],...a?["purpose"]:[],...H0?["enabled"]:[],...L0?["contentType"]:[],...f0?["status"]:[],...u0?["scenarios"]:[],...i0?["tags"]:[]]})}}let A=w.filter((G0)=>!T.has(G0.title.trim())),j=[...Z].sort((G0,T0)=>T0.versionNumber-G0.versionNumber)[0],C=j?.versionNumber,k=([...q].sort((G0,T0)=>T0.versionNumber-G0.versionNumber)[0]?.versionNumber??0)+1,h=Cv0(Q.name,C,q),c=S(z.options["version-name"])??S(z.options.versionName)??Rv0(Q.name,C,h,k),U0={...W,tone:G.tone,language:G.language,detailLevel:G.detailLevel,outputFormat:G.outputFormat,examples:G.examples??[],prohibitedPhrases:G.prohibitedPhrases??[],customInstructions:G.customInstructions,decisionPreferences:G.decisionPreferences,thinkingDepthPreference:G.thinkingDepthPreference};if(F0(z.options["dry-run"])===!0||F0(z.options.dryRun)===!0){c0({dryRun:!0,source:{id:Q.id,name:Q.name,environment:Q.environment,latestPublishedVersion:j?{versionNumber:j.versionNumber,versionName:j.versionName}:null,documentsCount:M.length},target:{id:J.id,name:J.name,environment:J.environment},versionMappingPlan:{sourceProdVersionNumber:C??null,sourceProdVersionName:j?.versionName??null,targetTestExpectedVersionNumber:k,targetTestPublishVersionName:c,iteration:h},preferencesDiff:{decisionPreferences:{before:W.decisionPreferences,after:G.decisionPreferences},thinkingDepthPreference:{before:W.thinkingDepthPreference,after:G.thinkingDepthPreference}},rulesPlan:{sourceDraftRuleCount:H.rules.length,targetExistingDraftRuleCount:X.rules.length,toDeleteCount:X.rules.length,toCreateCount:H.rules.length,rulesToSync:H.rules.map((G0,T0)=>({index:T0+1,sourceRuleId:G0.id,sourceRuleCode:G0.code??T0+1,expectedTargetCode:`rule-${T0+1}`,description:G0.description,scope:G0.scope,strictness:G0.strictness}))},documentsPlan:{sourceDocumentCount:M.length,targetExistingDocumentCount:w.length,toCreateCount:N.length,toCreate:N.map((G0)=>({title:G0.title,purpose:G0.purpose,contentType:G0.contentType,scenarios:G0.scenarios})),toUpdateCount:D.length,toUpdate:D.map((G0)=>({targetDocumentId:G0.testId,title:G0.prodDoc.title,reasons:G0.reasons})),toDeleteCount:A.length,toDelete:A.map((G0)=>({targetDocumentId:G0.id,title:G0.title}))},publishingPlan:{targetCorpId:J.id,publishVersionName:c,publishTarget:"test"},hosecloudSyncPlan:(()=>{if(Q.source.type!=="hose")return{sourceType:Q.source.type,skipped:!0,reason:"prod source is not hose; no hosecloud credentials available"};let G0=(G.integrations??[]).filter((Y1)=>Y1.type==="hosecloud"),T0=new Set,b0=G0.filter((Y1)=>{let a=Y1.corporationId??Q.id;if(T0.has(a))return!1;return T0.add(a),!0});return{sourceType:"hose",outboundName:yv0(Q.name),targetMode:"assisted",integrationsCount:b0.length,integrations:b0.map((Y1)=>({corporationId:Y1.corporationId,apiOrigin:Y1.apiOrigin,customApiUrl:Y1.customApiUrl}))}})(),productionGuarantees:{prodRulesStayDraft:!0,prodVersionPublished:!1}});return}if(!(F0(z.options.yes)===!0||F0(z.options.confirm)===!0))throw D9(`Refusing to overwrite test enterprise '${J.name}' (${J.id}) with preferences, ${H.rules.length} draft rules, and ${M.length} knowledge documents from production enterprise '${Q.name}' (${Q.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 ${Q.id} --yes`);await m5(K,U0,J.seal.endpoints.approvalStylePreferences);let t=[];for(let G0 of A)await GM(K,G0.id),t.push({id:G0.id,title:G0.title});let $0=[];for(let G0 of D)await KM(K,G0.testId,{title:G0.prodDoc.title,purpose:G0.prodDoc.purpose,content:G0.prodDoc.content,contentType:G0.prodDoc.contentType,status:G0.prodDoc.status,enabled:G0.prodDoc.enabled, Line truncated
Run 'seal-use corps bind-test ${Q.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association,
or add '--force' (or use 'seal-use webhook replay <recordId> --force') if you explicitly intend to replay directly within production.`);I=Q}else if(I=E1(Q.testCorpId),I.environment!=="test"&&!J)throw Error(`Target enterprise '${I.name}' (${I.id}) is marked as '${I.environment}', NOT 'test'. Aborting replay to protect non-test environments (use --force to override).`);let K=S(z.options.recordId)??S(z.options["record-id"])??S(z.options.id),G=S(z.options.recordIds)??S(z.options["record-ids"]),W=G?G.split(",").map((k)=>k.trim()).filter(Boolean):void 0,H=S(z.options.sn)??S(z.options.documentSn)??S(z.options["document-sn"]),X=S(z.options.sns)??S(z.options["document-sns"]),Z=X?X.split(",").map((k)=>k.trim()).filter(Boolean):void 0,q=s0(z.options.limit)??(!K&&!W&&!H&&!Z?1:void 0),V=S(z.options.status),F=S(z.options.startDate)??S(z.options["start-date"]),M=S(z.options.endDate)??S(z.options["end-date"]),w=await j1(Q),O=Q.id===I.id?w:await j1(I),N=S(z.options.webhook)??S(z.options.selector),D=S(z.options.snSuffix)??S(z.options["sn-suffix"]),T=S(z.options.snPrefix)??S(z.options["sn-prefix"]),A=S(z.options.docIdSuffix)??S(z.options["doc-id-suffix"]),B=S(z.options.docIdPrefix)??S(z.options["doc-id-prefix"]),j=F0(z.options.dryRun)??F0(z.options["dry-run"]),C={recordId:K,recordIds:W,sn:H,sns:Z,limit:q,status:V,startDate:F,endDate:M};console.error(`[corps-replay-test] 正式企业「${Q.name}」(${Q.id}) -> 测试企业「${I.name}」(${I.id})`);let b=await rI({query:C,sourceClient:w,targetClient:O,sourceCorp:Q,targetCorp:I,webhookSelector:N,snPrefix:T,snSuffix:D,docIdPrefix:B,docIdSuffix:A,dryRun:j});if(j){console.error(`[corps-replay-test] 预览模式:已成功从 ${Q.name} 提取单据并转换为 Webhook Payload(未实际推送)。`),console.log(JSON.stringify(b,null,2));return}if(b.success)if(b.totalCount===1&&b.replayedDocument)console.error(`\uD83D\uDFE2 成功重放单据「${b.replayedDocument.documentSN}」至 ${I.name} (${b.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDFE2 成功重放 ${b.successCount} 条单据(来自「${Q.name}」)至「${I.name}」(${b.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDD34 单据重放部分或全部失败(成功 ${b.successCount} 条,失败 ${b.failureCount} 条)至「${I.name}」`);if(console.error(`\uD83D\uDC49 Next action: seal-use approval-runs list --corp ${I.id} --limit ${b.totalCount}`),console.log(JSON.stringify(b,null,2)),!b.success)process.exitCode=1;return}if($==="switch"){let U=Y;if(!U)throw Error("Usage: seal-use corps switch <corpId>");let Q=_4();if(!Q.stateful)throw Error("Cannot switch the default enterprise while stateless mode is enabled. Use `seal-use config mode stateful` first.");let J=E1(U);IU({...Q,stateful:!0,defaultCorpId:J.id}),c0({current:!0,id:J.id,name:J.name});return}if($==="probe-hose"){await JS1(y8(z.json));return}if($==="hose-staffs"){await IS1(y8(z.json));return}if($==="add-hose"){await fl(y8(z.json));return}if($==="add-seal"){await KS1(y8(z.json));return}if($==="add-link"){let U=Y??S(z.options.link)??S(z.options.url);if(!U)throw Error("Usage: seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--as-hose] [--overwrite]");if(F0(z.options["as-hose"])===!0||F0(z.options.hose)===!0){await WS1(U,S(z.options.name),F0(z.options.overwrite)===!0,F0(z.options.force)===!0,{appKey:S(z.options["app-key"])??S(z.options.appKey),keyId:S(z.options["key-id"])??S(z.options.keyId)});return}await GS1(U,S(z.options.name),F0(z.options.overwrite)===!0);return}if($==="extract-keys"||$==="extract-key"){let U=Y??S(z.options.link)??S(z.options.url);if(!U)throw Error("Usage: seal-use corps extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]");let Q=F0(z.options.reveal)===!0||F0(z.options.r)===!0||F0(z.options.plain)===!0,J=F0(z.options.save)===!0||F0(z.options.add)===!0;await BT(U,{reveal:Q,save:J,name:S(z.options.name),overwrite:F0(z.options.overwrite)===!0,force:F0(z.options.force)===!0,appKey:S(z.options["app-key"])??S(z.options.appKey),keyId:S(z.options["key-id"])??S(z.options.keyId)});return}if($==="keys"){let U=Y??S(z.options.link)??S(z.options.url)??S(z.options.corp),Q=F0(z.options.reveal)===!0||F0(z.options.r)===!0||F0(z.options.plain)===!0;if(U&&(U.startsWith("http://")||U.startsWith("https://"))){let J=F0(z.options.save)===!0||F0(z.options.add)===!0;await BT(U,{reveal:Q,save:J,name:S(z.options.name),overwrite:F0(z.options.overwrite)===!0,force:F0(z.options.force)===!0,appKey:S(z.options["app-key"])??S(z.options.appKey),keyId:S(z.options["key-id"])??S(z.options.keyId)});return}await ul(U,{reveal:Q});return}throw Error(`Unknown corps command: ${$??""}. Run 'seal-use help' for available commands.`)}function yv0($){return[...$].slice(0,6).join("")+"(Seal测)"}async function QS1($,Y,z,U){if($.source.type!=="hose")return{skipped:!0,reason:"prod source is not hose; no hosecloud creden Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${C.length} candidate administrators:
- ${b}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!L)if(!G&&Y)L=Y;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-use corps hose-staffs' to discover available administrators.");let O=l1($,"id")??W,F=X??W,D=l1($,"sealUrl")??`https://${W.toLowerCase()}.sealai.cc`,P={id:O,name:F,environment:"production",seal:{url:D,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:Z,appKey:z,appSecurity:q,corpId:W,staffId:L},auth:{refreshTtl:300}};if(G)Xw(O),await LJ(P);let A=Zi();Yh0(A,{recursive:!0,mode:448});let T=Qh0(A,`${_A(O)}.json`);if(Uh0(T)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${T}. Pass "overwrite": true to replace it.`);Jh0(T,`${JSON.stringify(P,null,2)}
`,{mode:384}),P0({id:O,name:F,corpId:W,domain:Z,staffId:L,verified:G,path:T})}async function $f1($){let I=G3($,"token"),z=(l1($,"sealUrl")??l1($,"url")??"").replace(/\/+$/,"");if(!z)throw Error("Missing required JSON field: sealUrl");let q=yp($,"expiresIn")??2592000,U=$.force===!0||$.verify===!1?!1:!0,Y=Gh0($),J=U?await zf1(z,I,K6(Y)):void 0;Zh0($,{token:I,sealUrl:z,expiresIn:q,verify:U,remote:J,custom:Y})}function Gh0($){return{headers:Ji.parse($.headers),cookies:Qi.parse($.cookies)}}async function If1($,I,z){let q=await Vw($),U=X8(q.sealUrl,q.token),Y=await r6(U),J={user:Y.user,tenant:Y.tenant};ww(q.corpId,J.tenant),Zh0({id:q.corpId,corpId:q.corpId,name:I,provider:"hosecloud",overwrite:z},{token:q.token,sealUrl:q.sealUrl,expiresIn:q.expiresIn,verify:!0,remote:J})}function Zh0($,I){let{token:z,sealUrl:q,expiresIn:U,verify:Y,remote:J}=I,Q=I.custom??Gh0($),K=J?.user,H=J?.tenant,G=l1($,"tenantSlug")??Y2(H?.tenantSlug),Z=l1($,"tenantId")??Y2(H?.id),W=l1($,"tenantName")??Y2(H?.name),X=l1($,"id")??G??Z;if(!X)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let w=l1($,"staffId")??Y2(K?.providerUserId)??Y2(K?.id)??"seal",L=l1($,"provider")??Y2(K?.provider)??Y2(H?.providerConfig?.provider),O=l1($,"corpId")??G??Z??X,F={id:X,name:l1($,"name")??W??X,environment:"production",seal:{url:q,tenantSlug:G,headers:Q.headers,cookies:Q.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:z,sealUrl:q,expiresIn:U,staffId:w,corpId:O,tenantId:Z,tenantSlug:G,tenantName:W,providerUserId:Y2(K?.providerUserId),provider:L},auth:{refreshTtl:300}},D=Zi();Yh0(D,{recursive:!0,mode:448});let P=Qh0(D,`${_A(X)}.json`);if(Uh0(P)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${P}. Pass "overwrite": true to replace it.`);Jh0(P,`${JSON.stringify(F,null,2)}
`,{mode:384}),P0({id:X,name:F.name,tenantId:Z,tenantSlug:G,verified:Y,path:P})}async function zf1($,I,z={}){let q=X8($,I,z),U=await r6(q);return{user:U.user??{},tenant:U.tenant??{}}}function Y2($){return typeof $==="string"&&$?$:void 0}j2();S8();e4();x4();D4();n1();async function Wh0($,I){let z=await Vw($),q=X8(z.sealUrl,z.token),U=await r6(q);ww(z.corpId,U.tenant);let Y=await _q(q,{note:I});P0({tenant:{id:U.tenant.id,name:U.tenant.name,tenantSlug:U.tenant.tenantSlug,corpId:z.corpId},user:{id:U.user.id,name:U.user.name,providerUserId:U.user.providerUserId,isAdmin:U.user.isAdmin},delegation:Y,expiresIn:z.expiresIn})}async function Xh0($,I,z,q,U){if($==="list"){await N0("seal_delegation_list",z,q,{},V0(U.options));return}if($==="create"){let Y=E(U.options.note)??(I?[I,...U.command.slice(2)].join(" "):void 0);await N0("seal_delegation_create",z,q,{note:Y},V0(U.options));return}if($==="revoke"){let Y=I??E(U.options.tokenId);if(!Y)throw Error("Usage: seal-use delegation revoke <tokenId>");await N0("seal_delegation_revoke",z,q,{tokenId:Y},V0(U.options));return}throw Error(`Unknown delegation command: ${$??""}. Run 'seal-use help' for available commands.`)}x4();D4();n1();e4();H$();import{readFileSync as qf1}from"node:fs";async function Vh0($,I,z,q,U,Y){if(!$||$==="help")throw Error(`Usage: seal-use deploy <system> <action> [options]
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!F)if(!H&&J)F=J;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-use corps hose-staffs' to discover available administrators.");let M=H4($,"id")??Z,w=q??Z,O=H4($,"sealUrl")??`https://${Z.toLowerCase()}.sealai.cc`,N={id:M,name:w,environment:"production",seal:{url:O,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:X,appKey:z,appSecurity:U,corpId:Z,staffId:F},auth:{refreshTtl:300}};if(H)pw(M),await gK(N);let D=an();vv0(D,{recursive:!0,mode:448});let T=Sv0(D,`${GT(M)}.json`);if(_v0(T)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${T}. Pass "overwrite": true to replace it.`);hv0(T,`${JSON.stringify(N,null,2)}
`,{mode:384}),c0({id:M,name:w,corpId:Z,domain:X,staffId:F,verified:H,path:T})}async function KS1($){let Y=p7($,"token"),z=(H4($,"sealUrl")??H4($,"url")??"").replace(/\/+$/,"");if(!z)throw Error("Missing required JSON field: sealUrl");let U=wl($,"expiresIn")??2592000,Q=$.force===!0||$.verify===!1?!1:!0,J=kv0($),I=Q?await HS1(z,Y,B6(J)):void 0;fv0($,{token:Y,sealUrl:z,expiresIn:U,verify:Q,remote:I,custom:J})}function kv0($){return{headers:mn.parse($.headers),cookies:ln.parse($.cookies)}}async function GS1($,Y,z){let U=await dw($),Q=T8(U.sealUrl,U.token),J=await H8(Q),I={user:J.user,tenant:J.tenant};mw(U.corpId,I.tenant),fv0({id:U.corpId,corpId:U.corpId,name:Y,provider:"hosecloud",overwrite:z},{token:U.token,sealUrl:U.sealUrl,expiresIn:U.expiresIn,verify:!0,remote:I})}function xv0($,Y,z,U){if($.length===0)throw Error(`[合思子域提权] 未能从协助链接中提取到合思企业 [${Y}] 的 OpenAPI 密钥凭据。
`+"\uD83D\uDCA1 说明:此能力专属于合思 (Hose) 子域,用于将临时会话提权为标准 OpenAPI 开发者接入。需要企业管理员已在合思开放平台创建应用并生成 appKey/appSecurity。");if(z.keyId||z.appKey){let Q=$.find((J)=>z.keyId&&J.id===z.keyId||z.appKey&&J.appKey===z.appKey);if(!Q){console.error(`
❌ 未找到指定的合思 OpenAPI 密钥 (${z.appKey??z.keyId})。`),console.error(`ℹ️ 该合思企业当前存在以下 ${$.length} 套候选密钥:`);for(let J of $){let I=J.active?"\uD83D\uDFE2 启用":"⚪ 停用";console.error(` • "${J.name||"未命名应用"}" (appKey: ${J.appKey}, keyId: ${J.id}, 状态: ${I})`)}throw new w4("指定的合思密钥不存在,请从上述候选列表中选择正确的 appKey 或 keyId。",2,`${U} --app-key ${$[0].appKey}`)}return Q}if($.length===1)return $[0];console.error(`
ℹ️ [合思子域提权] 合思企业 [${Y}] 存在多套 (${$.length} 套) OpenAPI 应用密钥凭据:`);for(let Q=0;Q<$.length;Q++){let J=$[Q],I=J.active?"\uD83D\uDFE2 启用":"⚪ 停用",K=J.name||"未命名应用";console.error(` [${Q+1}] "${K}" (appKey: ${J.appKey}, keyId: ${J.id}, 状态: ${I})`)}throw console.error(`
\uD83D\uDC49 为确保权限提权绑定正确的业务应用,请显式指定要使用的密钥套件:`),console.error(` 在命令后追加 --app-key <key> 或 --key-id <id> 参数。
`),new w4(`合思企业 [${Y}] 存在多套 OpenAPI 密钥,必须指定 --app-key 或 --key-id 明确选择要绑定的密钥。`,2,`${U} --app-key ${$[0].appKey}`)}async function WS1($,Y,z,U=!1,Q){console.error("ℹ️ [合思子域提权] 正在通过合思协助链接提取 OpenAPI 开发者密钥并提升企业权限等级...");let J=await vS($),I=xv0(J.keys,J.corpId,Q??{},'seal-use corps add-link "<url>" --as-hose');console.error(`ℹ️ [合思子域提权] 已选定合思 OpenAPI 凭据 (appKey: ${I.appKey}, 应用: "${I.name||"未命名应用"}"),正在初始化为长期合思标准配置...`),await fl({domain:J.baseUrl,appKey:I.appKey,appSecurity:I.appSecurity,corpId:J.corpId,name:Y??J.corpName??J.corpId,staffId:J.staffId,overwrite:z,force:U})}async function BT($,Y){let z=await vS($),U=Y.reveal===!0;if(Y.save){let Q=xv0(z.keys,z.corpId,{appKey:Y.appKey,keyId:Y.keyId},'seal-use corps extract-keys "<url>" --save');console.error(`ℹ️ [合思子域提权] 正在将选定的合思 OpenAPI 密钥 (appKey: ${Q.appKey}, 应用: "${Q.name||"未命名应用"}") 保存为标准合思企业配置...`),await fl({domain:z.baseUrl,appKey:Q.appKey,appSecurity:Q.appSecurity,corpId:z.corpId,name:Y.name??z.corpName??z.corpId,staffId:z.staffId,overwrite:Y.overwrite,force:Y.force});return}if(!U)console.error(`ℹ️ [合思子域提权] 成功提取合思 (Hose) OpenAPI 密钥。接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文;附加 --save 可将临时会话提权并持久化为标准合思企业。
`);else console.error(`⚠️ [合思子域提权] 正在以明文展示合思 (Hose) appSecurity 接入密码,请妥善保管敏感凭据。
`);c0({provider:"hose",capability:"privilege-elevation",corpId:z.corpId,corpName:z.corpName??z.corpId,baseUrl:z.baseUrl,staffId:z.staffId,keyCount:z.keys.length,keys:z.keys.map((Q)=>({id:Q.id,name:Q.name||"-",appKey:Q.appKey,appSecurity:U?Q.appSecurity:_S(Q.appSecurity),active:Q.active,createTime:Q.createTime,updateTime:Q.updateTime}))})}async function ul($,Y){let z=E1($),U=Y.reveal===!0;if(z.source.type!=="hose")throw new w4(`【合思子域专享能力】当前企业「${z.name}」(id: ${z.id}) 为原生 Seal (${z.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。
`+"OpenAPI 密钥查询与提权能力专属于合思生态租户(用于从合思协助链接或合思凭据中提取开发者密钥提升权限等级),非合思渠道企业不支持此能力。",2);let Q=z.source.appKey??z.source.key,J=z.source.appSecurity??z.source.password;if(!U)console.error(`\uD83D\uDCA1 [合思子域] 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文。
`);else console.error(`⚠️ [合思子域] 正在以明文展示合思 appSecurity 接入密码,请妥善保管敏感凭据。
`);c0({provider:"hose",capability:"privilege-elevation",corpId:z.id,corpName:z.name,domain:z.source.domain,staffId:z.source.staffId,appKey:Q??"-",appSecurity:J?U?J:_S(J):"-",active:!0})}function fv0($,Y){let{token:z,sealUrl:U,expiresIn:Q,verify:J,remote:I}=Y,K=Y.custom??kv0($),G=I?.user,W=I?.tenant,H=H4($,"tenantSlug")??s2(W?.tenantSlug),X=H4($,"tenantId")??s2(W?.id),Z=H4($,"tenantName")??s2(W?.name),q=H4($,"id")??H??X;if(!q)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let V=H4($,"staffId")??s2(G?.providerUserId)??s2(G?.id)??"seal",F=H4($,"provider")??s2(G?.provider)??s2(W?.providerConfig?.provider),M=H4($,"corpId")??H??X??q,w={id:q,name:H4($,"name")??Z??q,environment:"production",seal:{url:U,tenantSlug:H,headers:K.headers,cookies:K.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:z,sealUrl:U,expiresIn:Q,staffId:V,corpId:M,tenantId:X,tenantSlug:H,tenantName:Z,providerUserId:s2(G?.providerUserId),provider:F},auth:{refreshTtl:300}},O=an();vv0(O,{recursive:!0,mode:448});let N=Sv0(O,`${GT(q)}.json`);if(_v0(N)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${N}. Pass "overwrite": true to replace it.`);hv0(N,`${JSON.stringify(w,null,2)}
`,{mode:384}),c0({id:q,name:w.name,tenantId:X,tenantSlug:H,verified:J,path:N})}async function HS1($,Y,z={}){let U=T8($,Y,z),Q=await H8(U);return{user:Q.user??{},tenant:Q.tenant??{}}}function s2($){return typeof $==="string"&&$?$:void 0}var bl=o(()=>{a9();DW();i8();S7();Bv0();gP();rn();X6();X6();kl();RZ();DT();o4();L$();D4();J4()});async function bv0($,Y){let z=$??S(Y.options.link)??S(Y.options.url);if(!z)throw Error("Usage: seal-use auth extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]");let U=F0(Y.options.reveal)===!0||F0(Y.options.r)===!0||F0(Y.options.plain)===!0,Q=F0(Y.options.save)===!0||F0(Y.options.add)===!0;await BT(z,{reveal:U,save:Q,name:S(Y.options.name),overwrite:F0(Y.options.overwrite)===!0,force:F0(Y.options.force)===!0,appKey:S(Y.options["app-key"])??S(Y.options.appKey),keyId:S(Y.options["key-id"])??S(Y.options.keyId)})}async function iv0($,Y,z){if($==="diagnose"){c0(await XS1(Y));return}if($==="hose-link"){let U=s0(z.options.expire)??7200;c0(await ow(Y,U));return}if($==="keys"){let U=F0(z.options.reveal)===!0||F0(z.options.r)===!0||F0(z.options.plain)===!0;await ul(Y.id,{reveal:U});return}throw Error(`Unknown auth command: ${$??""}. Run 'seal-use help' for available commands.`)}async function XS1($){if($.source.type!=="hose"){let F=await j1($),M=await H8(F);return{corp:{id:$.id,name:$.name,sourceType:$.source.type},ok:!0,stages:[{name:"seal.whoami",ok:!0,user:M.user,tenant:M.tenant}]}}pw($.id);let Y=$.source,z=Y.appKey??Y.key,U=Y.appSecurity??Y.password,Q=($.seal.url??Y.sealUrl??`https://${Y.corpId.toLowerCase()}.sealai.cc`).replace(/\/+$/,""),J=Y.staffId.includes(":")?Y.staffId:`${Y.corpId}:${Y.staffId}`,I=[];if(!z||!U)return{corp:{id:$.id,name:$.name,sourceType:$.source.type},ok:!1,stages:[{name:"hose.openapi",ok:!1,error:"Hose source requires appKey/key and appSecurity/password"}]};let K=await PT("hose.openapi",async()=>{let F=await uv0(`${Y.domain.replace(/\/+$/,"")}/api/openapi/v1/auth/getAccessToken`,{appKey:z,appSecurity:U}),M=d7(F.value),w=b6(M.accessToken)??b6(F.accessToken)??b6(F.token);if(!w)throw Error("Hose login did not return an access token");return{token:w,public:{corporationId:b6(M.corporationId)??b6(d7(M.corporation).id),expireTime:Nq(M.expireTime)}}});I.push(K.public);let G=K.private?.token,W=G?await PT("hose.provisional",async()=>{let F=await uv0(`${Y.domain.replace(/\/+$/,"")}/api/openapi/v1.1/provisional/getProvisionalAuth?accessToken=${encodeURIComponent(G)}`,{uid:J,pageType:"home",expireDate:7200}),M=b6(d7(F.value).message);if(!M)throw Error("Hose CloseAPI did not return a provisional auth URL");let w=new URL(M).searchParams.get("accessToken");if(!w)throw Error("Hose provisional auth URL did not include accessToken");return{token:w,public:{uid:J,enterpriseUrl:Lq(M)}}}):il("hose.provisional");I.push(W.public);let H=B6($.seal),X=W.private?.token,Z=X?await PT("seal.sso",async()=>{let M=await T8(Q,void 0,H).get(`api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(X)}&returnToken=1`).json(),w=d7(M.data),O=b6(M.token)??b6(M.accessToken)??b6(w.token)??b6(w.accessToken);if(!O)throw Error("Seal SSO did not return a bearer token");return{token:O,public:{sealUrl:Q,expiresIn:Nq(M.expiresIn)??Nq(M.expires_in)??Nq(w.expiresIn)??Nq(w.expires_in)}}}):il("seal.sso");I.push(Z.public);let q=Z.private?.token,V=q?await PT("seal.whoami",async()=>{let M=await T8(Q,q,H).get("api/v1/auth/me").json(),w=d7(M.data),O=d7(w.user??M.user),N=d7(w.tenant??M.tenant);return{public:{user:{id:b6(O.id),name:b6(O.name),isAdmin:qS1(O.isAdmin),providerUserId:b6(O.providerUserId)},tenant:{id:b6(N.id),name:b6(N.name),tenantSlug:b6(N.tenantSlug),hoseCorpConfig:VS1(N.hoseCorpConfig)}}}}):il("seal.whoami");return I.push(V.public),{corp:{id:$.id,name:$.name,sourceType:$.source.type},ok:I.every((F)=>F.ok===!0),stages:I}}async function PT($,Y){try{let z=await Y();return{public:{name:$,ok:!0,...cv0(z.public)},private:z.token?{token:z.token}:void 0}}catch(z){return{public:{name:$,ok:!1,error:Lq(z instanceof Error?z.message:String(z))}}}}function il($){return{public:{name:$,ok:!1,skipped:!0}}}async function uv0($,Y){let z=await fetch($,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Y)});return ZS1(z)}async function ZS1($){let Y=await $.text();if(!$.ok)throw Error(`${$.status} ${Y}`);let z=JSON.parse(Y);return d7(z)}function d7($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function b6($){return typeof $==="string"&&$?$:void 0}function Nq($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function qS1($){return typeof $==="boolean"?$:void 0}function VS1($){let Y=d7($);return cv0({corporationId:b6(Y.corporationId),corporationName:b6(Y.corporationName)})}function cv0($){return Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))}var nv0=o(()=>{a9();DW();i8();X6();D4();J4();bl()});async function pv0($,Y,z,U){if($==="status"||$==="get"){await k0("seal_billing_status_get",Y,z,{},C0(U.options) Line truncated
`+`支持的审批系统与发布目标:
`+` • hosecloud (合思费控): seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>
@@ -922,24 +939,33 @@ 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 H=$==="maycur"?"每刻报销":"汇联易";throw Error(`${H}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${H}' --result-url <url> --corp <corpId>`)}let J=$==="hosecloud",Q=$==="hosecloud"?I:$,K=$==="hosecloud"?z:I;if(!J)throw Error(`未知的发布目标系统: ${$}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);if(Q==="requirements"){await N0("seal_deploy_hosecloud_requirements",q,U,{},V0(Y.options));return}if(Q==="list"){await N0("seal_deploy_hosecloud_list",q,U,{},V0(Y.options));return}if(Q==="get"){let H=K??E(Y.options.signKey)??E(Y.options["sign-key"]);if(!H){let Z=((await v1(q)).integrations??[]).filter((W)=>W.type==="hosecloud");if(Z.length===0)throw Error(`当前企业 (${U.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${U.id}`);console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${U.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let W of Z){let X=W.outboundName??"SealAI 审批",w=W.signKey,L=W.apiOrigin??"production";console.error(` • "${X}" (signKey: ${w}, 环境: ${L})`),console.error(` \uD83D\uDC49 查看命令: seal-use deploy hosecloud get ${w} --corp ${U.id}
`)}throw new h4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。",2,Z.length===1?`seal-use deploy hosecloud get ${Z[0].signKey} --corp ${U.id}`:void 0)}await N0("seal_deploy_hosecloud_get",q,U,{signKey:H},V0(Y.options));return}if(Q==="status"){await N0("seal_deploy_hosecloud_status",q,U,{},V0(Y.options));return}if(Q==="configure"){let H=E(Y.options.input),G=H?JSON.parse(qf1(H,"utf8")):P8(Y.json);if(!G||Object.keys(G).length===0)throw Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");await N0("seal_deploy_hosecloud_configure",q,U,{...G,dryRun:X0(Y.options.dryRun)??X0(Y.options["dry-run"])},V0(Y.options));return}if(Q==="sync"){let H=K??E(Y.options.signKey)??E(Y.options["sign-key"]),G=X0(Y.options.auto)??X0(Y.options.yes);if(!H){let W=((await v1(q)).integrations??[]).filter((w)=>w.type==="hosecloud");if(W.length===0)throw Error(`当前企业 (${U.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${U.id}`);let X=W[0];if(X&&W.length===1&&G){let w=X.signKey;console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${w})`),await N0("seal_deploy_hosecloud_sync",q,U,{signKey:w},V0(Y.options));return}console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${U.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let w of W){let L=w.outboundName??"SealAI 审批",O=w.signKey,F=w.apiOrigin??"production";console.error(` • "${L}" (signKey: ${O}, 环境: ${F})`),console.error(` \uD83D\uDC49 同步命令: seal-use deploy hosecloud sync ${O} --corp ${U.id}
`)}if(W.length===1)console.error(`\uD83D\uDCA1 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${U.id}
`);throw new h4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,W.length===1?`seal-use deploy hosecloud sync ${W[0].signKey} --corp ${U.id}`:void 0)}await N0("seal_deploy_hosecloud_sync",q,U,{signKey:H},V0(Y.options));return}throw Error(`Unknown deploy hosecloud action: ${Q??""}. Available: requirements, list, get, status, configure, sync.`)}Ei();import{accessSync as Ff1,constants as Mf1,existsSync as Y8,readdirSync as Nf1}from"node:fs";import{homedir as Df1}from"node:os";import{join as W3}from"node:path";e9();import{existsSync as ap,mkdirSync as Eh0,rmSync as wf1,writeFileSync as Lf1}from"node:fs";import{homedir as jh0}from"node:os";import{dirname as Of1,join as ep}from"node:path";var wh0=`---
`+" • 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 W=$==="maycur"?"每刻报销":"汇联易";throw Error(`${W}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${W}' --result-url <url> --corp <corpId>`)}let I=$==="hosecloud",K=$==="hosecloud"?Y:$,G=$==="hosecloud"?z:Y;if(!I)throw Error(`未知的发布目标系统: ${$}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);if(K==="requirements"){await k0("seal_deploy_hosecloud_requirements",U,Q,{},C0(J.options));return}if(K==="list"){await k0("seal_deploy_hosecloud_list",U,Q,{},C0(J.options));return}if(K==="get"){let W=G??S(J.options.signKey)??S(J.options["sign-key"]);if(!W){let X=((await o1(U)).integrations??[]).filter((Z)=>Z.type==="hosecloud");if(X.length===0)throw Error(`当前企业 (${Q.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${Q.id}`);console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${Q.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let Z of X){let q=Z.outboundName??"SealAI 审批",V=Z.signKey,F=Z.apiOrigin??"production";console.error(` • "${q}" (signKey: ${V}, 环境: ${F})`),console.error(` \uD83D\uDC49 查看命令: seal-use deploy hosecloud get ${V} --corp ${Q.id}
`)}throw new w4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。",2,X.length===1?`seal-use deploy hosecloud get ${X[0].signKey} --corp ${Q.id}`:void 0)}await k0("seal_deploy_hosecloud_get",U,Q,{signKey:W},C0(J.options));return}if(K==="status"){await k0("seal_deploy_hosecloud_status",U,Q,{},C0(J.options));return}if(K==="configure"){let W=S(J.options.input),H=W?JSON.parse(LS1(W,"utf8")):y8(J.json);if(!H||Object.keys(H).length===0)throw Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");await k0("seal_deploy_hosecloud_configure",U,Q,{...H,dryRun:F0(J.options.dryRun)??F0(J.options["dry-run"])},C0(J.options));return}if(K==="sync"){let W=G??S(J.options.signKey)??S(J.options["sign-key"]),H=F0(J.options.auto)??F0(J.options.yes);if(!W){let Z=((await o1(U)).integrations??[]).filter((V)=>V.type==="hosecloud");if(Z.length===0)throw Error(`当前企业 (${Q.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${Q.id}`);let q=Z[0];if(q&&Z.length===1&&H){let V=q.signKey;console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${V})`),await k0("seal_deploy_hosecloud_sync",U,Q,{signKey:V},C0(J.options));return}console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${Q.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let F=V.outboundName??"SealAI 审批",M=V.signKey,w=V.apiOrigin??"production";console.error(` • "${F}" (signKey: ${M}, 环境: ${w})`),console.error(` \uD83D\uDC49 同步命令: seal-use deploy hosecloud sync ${M} --corp ${Q.id}
`)}if(Z.length===1)console.error(`\uD83D\uDCA1 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${Q.id}
`);throw new w4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,Z.length===1?`seal-use deploy hosecloud sync ${Z[0].signKey} --corp ${Q.id}`:void 0)}await k0("seal_deploy_hosecloud_sync",U,Q,{signKey:W},C0(J.options));return}throw Error(`Unknown deploy hosecloud action: ${K??""}. Available: requirements, list, get, status, configure, sync.`)}var Qh0=o(()=>{o4();D4();J4();X6();L$()});var Ih0=`---
name: seal-use
description: "v0.10.22: 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.26: 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.22
short-description: Seal tenant and Hose approval automation (v0.10.22)
version: 0.10.26
short-description: Seal tenant and Hose approval automation (v0.10.26)
---
# Seal Use (v0.10.22)
# Seal Use (v0.10.26)
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.
**The CLI is the primary path; the MCP server is an optional extra that is off by default.** Prefer the global \`seal-use\` CLI, and only use MCP when it is actually available in the current session. If no \`seal_cli*\` tool is present, that is the normal default — do not try to enable it or treat it as a fault; just use the CLI. Enabling it is the user's choice in the plugin settings (插件配置中的「启用 MCP 服务」,默认关闭,打开后需重连该插件的 MCP 服务).
When MCP *is* available, two tools are exposed:
- \`seal_cli\` — **read-only only.** Reads tenant state without changing it. It is annotated \`readOnlyHint: true\`, so clients may auto-approve it.
- \`seal_cli_write\` — everything that mutates tenant state, publishes configuration, mints credentials, self-updates or starts a server. Annotated \`destructiveHint: true\`; **confirm the exact command with the user before calling it.**
The boundary is enforced, not merely advertised: \`seal_cli\` refuses any command that is not on its read-only allow-list, and unclassified commands fail closed. A refusal names \`seal_cli_write\` as the follow-up. \`seal-use tool <name>\` is allowed through \`seal_cli\` only for tools the registry classifies as read-only (\`SEAL_READ_ONLY_TOOLS\`); the rest need \`seal_cli_write\`.
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.
## Bootstrap & Installation (环境安装与自愈)
@@ -974,8 +1000,9 @@ seal-use corps list
- Treat CLI/MCP as the Agent's execution channel, not the user's interface. Translate natural-language intent into commands yourself; never ask the user to compose CLI syntax, JSON payloads, placeholder values, or internal IDs.
- Before asking for enterprise parameters, resolve the target enterprise: when an enterprise is named, hinted, or keyword-identifiable, ALWAYS run \`seal-use corps search <keyword>\` (or \`seal-use corps get <corpId>\` if an exact ID is known) — DO NOT dump the entire enterprise catalog with \`seal-use corps list\` when the target is already known. Only run \`seal-use corps list\` (or \`corps list --env <test|production>\`) for initial discovery when zero enterprise context is known. Resolve its human name to the returned \`id\` and pass that value as \`--corp\`; do not ask the user to know \`corpId\`. Use \`seal-use corps get <corpId>\` to inspect rich enterprise attributes (URLs, tenant slugs, staff IDs, environment relations, and config file locations) with sensitive secrets safely redacted.
- If no enterprise is configured, the user is installing for the first time, or the user provides credentials, an assistance link, or a browser-copied cURL, read \`references/enterprise-onboarding.md\` before asking questions or running setup commands.
- When the user provides a Hose/合思 \`thirdparty.html\` assistance link, use \`seal-use corps add-link <url> [--name ...]\`; the command verifies the tenant and records the temporary Seal session without echoing the link token.
- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native.
- When the user provides a Hose/合思 \`thirdparty.html\` assistance link, use \`seal-use corps add-link <url> [--name ...]\` for temporary session access, or elevate privileges to permanent developer credentials using \`seal-use corps extract-keys <url> --save\` (or \`seal-use corps add-link <url> --as-hose\`). This Hose-exclusive capability extracts \`appKey\`/\`appSecurity\`. If the enterprise has multiple keys, specify \`--app-key <key>\` or \`--key-id <id>\`.
- **同等凭据原则(Equal Credential Scope Principle)**: A Hose assistance link and a cURL copied from an authenticated **Hose admin** page are both Hose web frontend sessions — structurally different in format only, carrying the same \`accesstoken\`/\`corpid\` web session credentials. **When a Hose administrator provides a browser cURL, do NOT silently downgrade it to a plain short-lived session import.** Attempt privilege elevation first by extracting \`accesstoken\`+\`corpid\`+\`baseUrl\` from the cURL and invoking the Hose key interface (\`/api/innerapi/v1/key\`) to retrieve permanent \`appKey\`/\`appSecurity\`. Only fall back to temporary session import if the user is not a Hose administrator or the key interface returns no keys.
- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native. Calling key extraction or \`keys\` on native Seal enterprises is strictly blocked.
- Never ask a normal user for \`corpId\`, \`staffId\`, \`proxyStaffBizId\`, \`tenantId\`, or another discoverable internal ID. Discover it first. If discovery fails, explain what the field means, why it could not be discovered, and exactly where the user can find it.
- Prefer compact commands first: \`pick\`, \`--summary\`, \`--fields\`, \`attachments --summary\`, \`rules count\`, and \`rules list --summary\`.
- Parse JSON stdout. Do not scrape human text.
@@ -1019,7 +1046,7 @@ seal-use corps list
- 规则本地工作流: \`seal-use rules pull\` 导出草稿规则,\`rules lint\` 做质量检查,\`rules push --dry-run\` 预览增量更新,确认后用 \`--yes\` 写入;\`rules map\` 查询 \`corps sync-test\` 生成的跨企业规则映射。规则版本与草稿/发布 code 空间的区别详见 \`references/rule-lightweight.md\` 和 \`references/cli.md\`。
- 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|sourceDocumentId|id] --corp <corpId>\`, \`approval-runs count\`, \`analytics insight|risks|performance|analyze\`, 以及 \`approval-runs export\`(Excel 报表);需要追踪单据时再使用 \`url\` 或 \`bridge\`。
- 审核大盘统计与去重分析: \`seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] --corp <corpId>\`, \`approval-runs count\`, \`analytics insight|risks|performance|analyze\`, 以及 \`approval-runs export\`(Excel 报表,文件名强制追加精确到分钟的 \`_YYYYMMDD_HHmm\` 时间戳后缀防止覆盖;支持 \`--sn <SN1,SN2>\` 定向筛选极速导出并跳过全量分页;追加 \`--with-flow\` 可额外输出 **E人工行为** / **E人工意见** 两列——基于合思原生审批流对齐,含样式 2-B 三行展开式驳回目标与重审规则、中途修改置顶事实且保留时序、动作 Emoji,200 条以上单据约增加 30 秒);需要追踪单据时再使用 \`url\` 或 \`bridge\`。
- User-facing 合思 authorization link (合思/易快报授权): \`seal-use auth hose-link --corp <corpId> --expire 7200\`; read \`references/hose-enterprise-auth.md\`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (\` \`\`\`text ... \`\`\` \`) AND a hyperlink.
- Delegation links management: \`seal-use delegation list --corp <corpId>\`, \`create [--note ...] --corp <corpId>\`, \`create --from-link <url> [--note ...]\`, \`revoke <tokenId> --corp <corpId>\`.
- User & Contacts Management (用户搜索、激活与一键代生成授权): \`seal-use users search [keyword] --corp <corpId>\`, \`users delegation <userIdOrPhone> --corp <corpId>\` (仅适用于 Seal 本地创建的账号 \`provider: local\`;对合思同步账号系统拒绝重置密码,需改用 \`auth hose-link\`), \`users activate <userId> --corp <corpId>\`, \`users create --name ... --phone ... --corp <corpId>\`, \`users reset-password <userId> --corp <corpId>\`, \`users get <userId> --corp <corpId>\`, \`users delete <userId> --corp <corpId>\`.
@@ -1044,8 +1071,8 @@ seal-use corps list
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。
3. 用户或业务负责人明确确认放宽策略后,读取目标 Webhook 当前配置:\`seal-use webhook get\`/\`webhook list\`,或等价的 \`seal-use tool seal_webhook_get\`/\`seal_webhook_list\`(MCP 下经 \`seal_cli\` 执行)。
4. 修改最小值、最大值或完整后缀白名单:\`seal-use webhook update\`,或等价的 \`seal-use tool seal_webhook_update\`(MCP 下经 \`seal_cli_write\` 执行,需用户确认)。写入后重新读取核对,再重试原来的材料包 push。
push 会重新读取最新 Webhook 配置;校验通过后才会开始上传附件。CLI 以非零退出码和 \`stderr\` 返回可恢复的业务错误,MCP 以工具错误返回。没有用户授权或没有修改权限时,不能擅自放宽策略,也不能绕过校验。
@@ -1090,6 +1117,10 @@ seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation status <batchId> --corp <corpId>
seal-use simulation approval-definitions --corp <corpId>
seal-use approval-runs export --corp <corpId> --downloads --completed-only
# Add --with-flow to also populate E人工行为 / E人工意见 columns (Hose Open API, adds ~30s):
seal-use approval-runs export --corp <corpId> --downloads --with-flow
# Target specific document SNs for instant export without full pagination:
seal-use approval-runs export --corp <corpId> --sn B26002307,B26002144 --with-flow --downloads
seal-use analytics insight --corp <corpId>
seal-use contacts departments --corp <corpId>
seal-use data invoices --corp <corpId> --limit 20
@@ -1125,11 +1156,11 @@ 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 Lh0=`interface:
`;var Jh0=()=>{};var Gh0=`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 Oh0=`# Rule Lightweight Queries
`;var Kh0=()=>{};var Hh0=`# 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.
@@ -1240,7 +1271,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 Fh0=`# Approval Bad Case Catalog
`;var Wh0=()=>{};var Zh0=`# 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.
@@ -1290,7 +1321,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 Mh0="# 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 the user-level `~/.config/seal-use/enterprises` directory is loaded. A configured\n `testEnterprisesDir` is loaded first for test-tenant workflows. The current working directory's\n `./enterprises` directory is not loaded implicitly.\n- Set `SEAL_USE_ENTERPRISES_DIR` to use one explicit directory instead. Legacy\n `~/.config/seal-home/enterprises` files are migrated to the primary directory when possible.\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 count [--corp <corpId>]\nseal-use rules list [--summary] [--count] [--limit 20] [--offset 0] [--corp <corpId>]\nseal-use rules clear [--corp <corpId>] [--dry-run|--yes]\nseal-use rules versions [--corp <corpId>]\nseal-use rules version <versionId|versionNumber|latest> [--corp <corpId>]\nseal-use rules get --corp <corpId> --version <number|latest> --code '#0038'\nseal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205\nseal-use rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20] [--corp <corpId>]\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 linters [--corp <corpId>]\nseal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]\nseal-use rules map [--corp <corpId>] [--version <id|num|latest>] [--code <code>]\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 [--check] [--force] [--version <v>]\nseal-use update check\nseal-use update changelog [--limit <n>]\nseal-use changelog [--limit <n>]\nseal-use mcp\nseal-use mcp config\nseal-use mcp-config\nseal-use skill dump\nseal-use skill install [--dir <path>|--local]\nseal-use skill status\nseal-use doctor [--quiet]\nseal-use doctor tenant [--corp <corpId>] [--quiet]\nseal-use doctor guide\nseal-use doctor paths\nseal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]\nseal-use probe [<corpId>]\nseal-use tools list\nseal-use corps list [query] [--env <production|test>] [--limit <n>] [--all] [--sort <usage|name|id>] [--strict] [--corp <corpId>]\nseal-use corps search <query> [--env <production|test>] [--strict]\nseal-use corps get <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 replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--force]\nseal-use corps regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]\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]Line truncated
`;var Xh0=()=>{};var Vh0="# 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 the user-level `~/.config/seal-use/enterprises` directory is loaded. A configured\n `testEnterprisesDir` is loaded first for test-tenant workflows. The current working directory's\n `./enterprises` directory is not loaded implicitly.\n- Set `SEAL_USE_ENTERPRISES_DIR` to use one explicit directory instead. Legacy\n `~/.config/seal-home/enterprises` files are migrated to the primary directory when possible.\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 count [--corp <corpId>]\nseal-use rules list [--summary] [--count] [--limit 20] [--offset 0] [--corp <corpId>]\nseal-use rules clear [--corp <corpId>] [--dry-run|--yes]\nseal-use rules versions [--corp <corpId>]\nseal-use rules version <versionId|versionNumber|latest> [--corp <corpId>]\nseal-use rules get --corp <corpId> --version <number|latest> --code '#0038'\nseal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205\nseal-use rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20] [--corp <corpId>]\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 linters [--corp <corpId>]\nseal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]\nseal-use rules map [--corp <corpId>] [--version <id|num|latest>] [--code <code>]\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 [--check] [--force] [--version <v>]\nseal-use update check\nseal-use update changelog [--limit <n>]\nseal-use changelog [--limit <n>]\nseal-use mcp\nseal-use mcp config\nseal-use mcp-config\nseal-use skill dump\nseal-use skill install [--dir <path>|--local]\nseal-use skill status\nseal-use doctor [--quiet]\nseal-use doctor tenant [--corp <corpId>] [--quiet]\nseal-use doctor guide\nseal-use doctor paths\nseal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]\nseal-use probe [<corpId>]\nseal-use tools list\nseal-use corps list [query] [--env <production|test>] [--limit <n>] [--all] [--sort <usage|name|id>] [--strict] [--corp <corpId>]\nseal-use corps search <query> [--env <production|test>] [--strict]\nseal-use corps get <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 replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--force]\nseal-use corps regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]\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>] [--as-hose] [--app-key <key>] [--key-id <id>] [--overwrite]\nseal-use corps extract-keys <https://.Line 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.
@@ -1511,7 +1542,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 Ah0=`# Customer Feedback Rule Remediation
`;var wh0=()=>{};var Nh0=`# 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.
@@ -1681,7 +1712,7 @@ Return a compact report containing:
- New version number and version name, if published
- Verification result
- Whether a regression rerun was performed
`;var Ph0=`# Enterprise Onboarding
`;var Oh0=()=>{};var Bh0=`# Enterprise Onboarding
Read 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.
@@ -1717,13 +1748,16 @@ All command examples in this reference are for the Agent to run. Do not hand the
Classify both the enterprise identity origin and how the current credential was acquired:
| Enterprise identity origin | Credential material the user may have | Meaning |
| --- | --- | --- |
| Hose/合思-sourced Seal tenant | Hose \`appKey\` + \`appSecurity\` | Stable, refreshable standard integration |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |
| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |
| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |
| Enterprise identity origin | Credential material the user may have | 权限等级与时效 | Meaning |
| --- | --- | --- | --- |
| Hose/合思-sourced Seal tenant | Hose \`appKey\` + \`appSecurity\` | 【最高·永久】自动签名/续期 | Stable, refreshable standard integration; unlocks full OpenAPI and \`corps sync-hosecloud\`. |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link (\`thirdparty.html\`) | 【两极分化】普通导入→短效;提权→永久 | Temporary session that can be **elevated** to permanent \`appKey\`/\`appSecurity\` with \`extract-keys --save\` or \`add-link --as-hose\`. |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated **Hose admin** page | 【两极分化】普通导入→短效;提权→永久 | **Same session scope as an assistance link.** If the user is a Hose administrator, this carries the same web session credentials (\`accesstoken\`, \`corpid\`, cookies) and can equally invoke \`/api/innerapi/v1/key\` to extract permanent \`appKey\`/\`appSecurity\`. |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Seal page | 【短效会话快照】 | Snapshot with Seal Bearer token; can set up temporary Seal session access. |
| Seal-native tenant | Seal assistance/delegation link | 【临时·可撤销】 | Temporary delegated access to a Seal tenant. |
| Seal-native tenant | cURL copied from an authenticated Seal page | 【短效会话快照】 | Snapshot containing the Seal host and session authentication. |
**同等凭据原则(Equal Credential Scope Principle)**: A Hose assistance link and a browser cURL from an authenticated Hose admin session are both Hose web frontend sessions — they carry the same underlying \`accessToken\`/\`accesstoken\` and \`corpid\`. The **only** structural difference is delivery format. When a Hose administrator sends you a cURL, treat it with the same privilege elevation potential as an assistance link. Do not downgrade it to a plain Seal session import without first attempting key extraction.
Credential 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.
@@ -1756,21 +1790,42 @@ seal-use auth diagnose --corp <discovered-id>
Do 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.
## Route 2: Incoming Assistance Link
## Route 2: Incoming Assistance Link & Hose Subdomain Privilege Elevation
First distinguish the link by its host and purpose:
First distinguish the link by its host, purpose, and identity origin:
- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.
- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.
- \`seal-use auth hose-link\` and \`seal-use delegation create\` generate links for an enterprise that is already configured. \`seal-use corps add-link <url>\` imports a received Hose/合思 \`thirdparty.html\` assistance link and verifies the resulting Seal tenant.
- A **Hose/合思 authorization/assistance link** (\`https://<domain>/web/thirdparty.html?...\`) opens an upstream Hose session and may continue through Seal SSO. It is not a Seal delegation link.
- A **Seal-native assistance/delegation link** grants temporary delegated access on a Seal tenant. It is not a Hose credential and cannot be elevated to Hose OpenAPI credentials.
- **Hose Subdomain Boundary (合思子域专属提权)**: \`seal-use\` primarily manages Seal tenants. Tenants sourced from the Hose ecosystem have an upstream Hose enterprise backing them. A received Hose assistance link contains only a temporary session \`accessToken\`. If you run standard \`corps add-link\`, it exchanges that temporary token for a short-lived Seal Bearer token—sufficient for basic Seal inspection, but it will expire and cannot call any Hose OpenAPI.
- **Privilege Elevation (权限等级提升)**: To elevate from a short-lived session token to permanent, durable Hose OpenAPI developer credentials, use \`corps extract-keys <url> --save\` or \`corps add-link <url> --as-hose\`. This leverages Hose's internal key interface (\`GET /api/innerapi/v1/key\`) using the session token to retrieve the enterprise's OpenAPI \`appKey\` and \`appSecurity\`. Once saved, the enterprise is upgraded to a standard Hose configuration with full OpenAPI support (e.g. \`corps sync-hosecloud\`).
- **Multi-Key Disambiguation (多套密钥明确抉择)**: If the enterprise owns multiple application keys, the CLI **will not** guess or silently pick the first key. Instead, it terminates with an informative candidate list and requires the user to specify \`--app-key <key>\` or \`--key-id <id>\`. If only one key exists, it is selected automatically.
- **Non-Hose Tenants Blocked**: Calling \`keys\` on native Seal enterprises (\`corp.source.type !== "hose"\`) is strictly rejected with exit code 2, explaining that this capability belongs exclusively to the Hose ecosystem.
Use the direct import route when the incoming link is an HTTPS \`thirdparty.html\` URL from a supported \`ekuaibao.com\` or \`hosecloud.com\` domain:
### Command Usage
\`\`\`bash
seal-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=<temporary-token>&ekbCorpId=<corpId>&pageType=home" [--name "企业名称"]
# 1. 提取密钥并脱敏查看(合思子域能力):
seal-use corps extract-keys "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..."
# 2. 显式完整查看密钥明文(--reveal / -r):
seal-use corps extract-keys "<url>" --reveal
# 3. 提权保存为标准持久化合思企业配置:
seal-use corps extract-keys "<url>" --save [--name "企业名称"] [--overwrite]
# 或简写为:
seal-use corps add-link "<url>" --as-hose [--name "企业名称"]
# 4. 多套密钥存在时,显式指定具体应用密钥:
seal-use corps extract-keys "<url>" --save --app-key "ekb_app_..."
# 或按 key ID 选取:
seal-use corps extract-keys "<url>" --save --key-id "key_id_..."
# 5. 查看已配置合思企业当前使用的应用密钥:
seal-use corps keys <corpId> [--reveal]
seal-use auth keys --corp <corpId> [--reveal]
\`\`\`
The command parses \`accessToken\` and \`ekbCorpId\`, exchanges the temporary Hose token at the target Seal tenant, verifies \`/api/v1/auth/me\`, and stores only the normalized short-lived Seal session. It never prints or persists the original URL. Use \`--overwrite\` only when intentionally replacing an existing enterprise config. To create a Seal delegation link without persisting the session, use \`seal-use delegation create --from-link <url> [--note ...]\`.
When using standard \`add-link\` (without \`--as-hose\`), it exchanges the temporary Hose token at the target Seal tenant, verifies \`/api/v1/auth/me\`, and stores only the normalized short-lived Seal session. When \`--as-hose\` or \`extract-keys --save\` is used, the CLI executes Hose subdomain privilege elevation to register a durable standard Hose configuration.
Assistance links are credentials. Do not follow a link merely to inspect it when the user's request was only explanatory, and never publish, log, or commit it.
@@ -1786,21 +1841,51 @@ When the user needs capture instructions, give these concrete steps:
6. Right-click it and choose **Copy → Copy as cURL**.
7. Send that complete cURL only to the local trusted Agent handling setup.
When receiving cURL:
When receiving cURL, immediately classify its origin before deciding on an action path:
### 3a. cURL from an authenticated Hose page (合思/易快报 后台)
This is functionally equivalent to a Hose assistance link. Both carry the same underlying web session credentials (\`accesstoken\`, \`corpid\`/\`ekbCorpId\`, and cookies). The structural difference is only in delivery format.
**Always attempt privilege elevation first when the session user is or may be a Hose administrator:**
1. Treat the entire cURL as a secret. Do not echo it, execute it blindly, paste it into another service, or store it in repository files.
2. Parse it as data. Extract the request host, path, \`Authorization\` header, cookies, and provider/tenant hints. Ignore the request body unless it is required to identify the tenant.
3. Classify whether the captured request is to Hose or Seal. A Seal request with \`Authorization: Bearer ...\` can supply \`sealUrl\` and a session token even when the user's identity origin is Hose.
4. Verify with the narrowest read-only identity endpoint available. For a Seal Bearer session, verify \`/api/v1/auth/me\` through \`seal-use corps add-seal\`; use returned provider metadata to retain the actual origin.
5. Persist only the normalized minimum configuration needed by seal-use. Do not preserve the raw cURL, unrelated headers, request body, cookies, or signed URL.
2. Extract: the request hostname (determines \`baseUrl\`), \`accesstoken\` header (session token), \`corpid\` header or cookie, and any other Hose session headers.
3. **Privilege elevation path (preferred)**: Use extracted \`accesstoken\`, \`corpid\`, and \`baseUrl\` to call \`/api/innerapi/v1/key\`, exactly as \`corps extract-keys\` does for assistance links. This retrieves permanent \`appKey\`/\`appSecurity\` to register a durable Hose enterprise configuration — do not skip this step just because the input is a cURL instead of a URL.
4. **Fallback short-term path**: If the session user is not an administrator and the key interface returns no keys, fall back to the Seal SSO bridge to register a temporary Seal session.
5. If key extraction succeeds, inform the user that credentials have been permanently elevated; if it fails, explain the limitation and suggest the administrator copy a dedicated cURL or provide an assistance link or \`appKey\`/\`appSecurity\`.
For a verified Seal Bearer captured from cURL, the existing CLI route is:
\`\`\`
⚠️ 【同等凭据原则】
合思协助链接与合思管理员登录态 cURL 均属于合思前端会话 (Web Session),本质完全等价。
区别仅在于交付形式:URL vs cURL。
收到合思管理员 cURL 时,优先走提权提取路径,将临时会话升级为永久 OpenAPI 配置,
而非仅作为短期会话导入。
\`\`\`
### 3b. cURL from an authenticated Seal page (Seal 后台)
1. Treat the entire cURL as a secret.
2. Parse it as data. Extract the request host, path, \`Authorization: Bearer ...\` header, and provider/tenant hints.
3. Verify with \`/api/v1/auth/me\` through \`seal-use corps add-seal\`; use returned provider metadata to retain the actual origin.
4. Persist only the normalized minimum configuration needed by seal-use.
\`\`\`bash
seal-use corps add-seal --json '{"sealUrl":"https://target-tenant.example","token":"<bearer>"}'
\`\`\`
The current CLI has no raw-cURL import command and \`add-seal\` requires a Bearer token. If the captured request contains only cookies or an authentication shape the CLI cannot verify, do not improvise a token. Ask the user to copy another successful Seal Fetch/XHR request that contains the Bearer header, or explain the current limitation.
If the captured request contains only cookies or an authentication shape the CLI cannot verify, do not improvise a token. Ask the user to copy another successful Seal Fetch/XHR request that contains the Bearer header, or explain the current limitation.
### 3c. Advantages and Limitations of F12 cURL
| 维度 | F12 cURL 会话 | 合思 OpenAPI 开发者密钥(提权后)|
|---|---|---|
| 获取难度 | 极低,无需管理员权限,前台业务人员即可操作 | 需要管理员在合思开放平台注册应用,或从管理员 cURL 中提权提取 |
| 权限等级 | 受当前登录用户权限约束 | 拥有开放平台全量 OpenAPI 能力 |
| 时效 | 浏览器 Cookie / Token 过期即失效(通常数小时至数天) | 永久有效,支持自动轮转与续期 |
| HoseCloud 同步 | ❌ 不支持 | ✅ 支持 \`corps sync-hosecloud\` |
## Verify and Hand Off
@@ -1815,7 +1900,7 @@ seal-use auth diagnose --corp <discovered-id> # Hose source
Report the human enterprise name, identity provider, credential method, and whether verification succeeded. Do not expose internal IDs unless they help with troubleshooting. Do not perform approval, rule, document, simulation, publishing, or other business mutations just because onboarding succeeded; continue only with the user's requested task and its normal confirmation rules.
If a temporary assistance-link or browser session expires, explain that it must be renewed or recaptured. Recommend standard Hose app credentials when the user needs durable unattended access.
`;var Bh0=`# Hose Enterprise Auth
`;var Dh0=()=>{};var Ah0=`# Hose Enterprise Auth
Use this reference for Hose/合思 enterprise configuration and user-facing Hose authorization links.
@@ -1880,7 +1965,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 Th0=`# Hose Enterprise Initialization & Automated Discovery
`;var Ph0=()=>{};var jh0=`# 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.
@@ -1986,7 +2071,7 @@ seal-use corps hose-staffs --json '{
}'
\`\`\`
* 直接使用指定 ID 完成接入并进行连通性验证。
`;var Ch0={"SKILL.md":wh0,"agents/openai.yaml":Lh0,"references/rule-lightweight.md":Oh0,"references/approval-bad-cases.md":Fh0,"references/cli.md":Mh0,"references/approval-run-lightweight.md":Nh0,"references/approval-attachment-trace.md":Dh0,"references/customer-feedback-rule-remediation.md":Ah0,"references/enterprise-onboarding.md":Ph0,"references/hose-enterprise-auth.md":Bh0,"references/hose-enterprise-init.md":Th0};function _h0(){return Ch0["SKILL.md"]||""}function Mz(){return ep(jh0(),".agents","skills","seal-use")}function Rh0(){return ep(jh0(),".agents","skills","seal-home")}function vh0(){let $=Rh0();if(ap($))try{return wf1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function $d($=Mz()){vh0(),Eh0($,{recursive:!0});let I=[];for(let[z,q]of Object.entries(Ch0)){let U=ep($,z);Eh0(Of1(U),{recursive:!0}),Lf1(U,q,"utf8"),I.push(z)}return{targetDir:$,files:I}}function Id(){let $=Rh0(),I=Mz(),z=ap($),q=ap(I);if(z||q)return vh0(),$d(I),{synced:!0,targetDir:I};return{synced:!1}}var zd=[{name:"配置与状态根目录",category:"config",standardPath:"~/.config/seal-use",purpose:"用户本地持久化配置根目录,存放企业连接元数据、会话缓存与全局状态。",accessMode:"read-write",retention:"persistent"},{name:"企业配置文件目录",category:"config",standardPath:"~/.config/seal-use/enterprises",purpose:"存放各已添加企业的配置 JSON 文件(如 xiezihao.json),存储企业域名、脱敏 Token、员工绑定关系等。",accessMode:"read-write",retention:"persistent"},{name:"全局配置文件",category:"config",standardPath:"~/.config/seal-use/config.json",purpose:"维护全局工作模式(stateful/stateless)、默认激活企业 defaultCorpId 以及 Lint 偏好。",accessMode:"read-write",retention:"persistent"},{name:"会话凭据安全缓存",category:"config",standardPath:"~/.config/seal-use/seal_tokens.json",purpose:"缓存已认证租户的 Bearer Token 与过期时间戳,避免高频调用上游 OAuth 换票接口。",accessMode:"read-write",retention:"cache"},{name:"规则版本映射快照",category:"config",standardPath:"~/.config/seal-use/mappings",purpose:"存储 corps sync-test 生成的生产与测试规则版本/编号对照映射快照,供 rules map 离线毫秒级速查。",accessMode:"read-write",retention:"persistent"},{name:"后台守护服务日志",category:"config",standardPath:"~/.config/seal-use/service.log",purpose:"常驻后台 HTTP 服务守护进程运行输出日志。",accessMode:"read-write",retention:"persistent"},{name:"全局命令行程序",category:"binary",standardPath:"/opt/homebrew/bin/seal-use",purpose:"macOS / Linux 全局独立单文件二进制程序;附带软链接 seal-home -> seal-use 兼容旧指令。",accessMode:"executable",retention:"persistent"},{name:"AI Agent 技能主目录",category:"skill",standardPath:"~/.agents/skills/seal-use",purpose:"面向 Antigravity、Codex 等 AI 智能体的标准技能目录,包含 SKILL.md、参考文档与操作规程。",accessMode:"read-write",retention:"persistent"},{name:"报表默认导出目录",category:"export",standardPath:"~/Downloads",purpose:"执行 approval-runs export 等大盘报表命令且未指定 --out 时,默认写入的 Excel 文件路径。",accessMode:"read-write",retention:"persistent"},{name:"系统隔离临时目录",category:"temp",standardPath:"/tmp 或 /var/folders/.../T",purpose:"自动化测试(bun test)生成的隔离工作副本,执行完毕后通过 afterEach 钩子彻底删除,零残留。",accessMode:"transient",retention:"ephemeral"}],qd=[{topic:"敏感凭据脱敏保护",guarantee:"appSecurity、password 等高危密钥永不回显在 stdout,Session Token 采用掩码处理(如 5oUL...Y%3D)。",enforcement:"CLI 所有展示接口(corps get、corps list、probe 等)均经 formatSafeSourceDetail 脱敏过滤。"},{topic:"正式环境与测试环境严格隔离",guarantee:"正式企业与测试企业必须严格 1 对 1 下挂,禁止多层级级联绑定;环境标记需显式 --confirm 确认。",enforcement:"corps bind-test 与 mark 强制要求 --confirm,缺少时阻断并返回退出码 10(confirmationRequired)。"},{topic:"跨环境规则同步安全基线",guarantee:"corps sync-test 仅将正式企业偏好与规则覆盖同步至测试企业并自动发布,正式企业规则严格维持草稿态永不发布。",enforcement:"规则同步流水线由 sync-test 独占受控,正式环境端仅执行拉取草稿读取操作,零发版变更。"},{topic:"只读诊断无副作用原则",guarantee:"doctor、search、get、list、context、probe 等命令为严格只读操作,不修改用户本地文件系统,零写入污染。",enforcement:"核心领域函数严格分离 Mutation 操作与 Query 操作,Query 路径杜绝写文件与环境篡改。"}],Ud=[{domain:"corps (企业管理)",summary:"多租户接入、智能软搜索、富属性查看、环境标记、测试绑定与配置规则同 Line truncated
`;var Th0=()=>{};import{existsSync as ES1,mkdirSync as Eh0,readFileSync as CS1,rmSync as RS1,writeFileSync as _S1}from"node:fs";import{homedir as Ch0}from"node:os";import{dirname as vS1,join as AT}from"node:path";function cl(){return Rh0["SKILL.md"]||""}function _h0($){return $.match(/^\s*version:\s*(\S+)\s*$/m)?.[1]}function vh0($=AT(hU(),"SKILL.md")){try{return _h0(CS1($,"utf8"))}catch{return}}function hU(){return AT(Ch0(),".agents","skills","seal-use")}function hS1(){return AT(Ch0(),".agents","skills","seal-home")}function SS1(){let $=hS1();if(ES1($))try{return RS1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function hh0($=hU()){SS1(),Eh0($,{recursive:!0});let Y=[];for(let[z,U]of Object.entries(Rh0)){let Q=AT($,z);Eh0(vS1(Q),{recursive:!0}),_S1(Q,U,"utf8"),Y.push(z)}return{targetDir:$,files:Y}}var Rh0,r74;var Dq=o(()=>{Jh0();Kh0();Wh0();Xh0();qh0();Lh0();wh0();Oh0();Dh0();Ph0();Th0();Rh0={"SKILL.md":Ih0,"agents/openai.yaml":Gh0,"references/rule-lightweight.md":Hh0,"references/approval-bad-cases.md":Zh0,"references/cli.md":Vh0,"references/approval-run-lightweight.md":Fh0,"references/approval-attachment-trace.md":Mh0,"references/customer-feedback-rule-remediation.md":Nh0,"references/enterprise-onboarding.md":Bh0,"references/hose-enterprise-auth.md":Ah0,"references/hose-enterprise-init.md":jh0};r74=_h0(cl())});function Sh0(){return`# Seal Use 系统架构与运行规范白皮书
> 本文档由 \`seal-use\` 单文件二进制程序内嵌提供,纯内存只读,未向用户电脑写入任何临时文件。
@@ -2009,14 +2094,14 @@ seal-use corps hose-staffs --json '{
| 目录名称 | 类别 | 规范路径 | 作用与生命周期 |
| :--- | :--- | :--- | :--- |
${zd.map(($)=>`| **${$.name}** | \`${$.category}\` | \`${$.standardPath}\` | ${$.purpose} (${$.retention}) |`).join(`
${nl.map(($)=>`| **${$.name}** | \`${$.category}\` | \`${$.standardPath}\` | ${$.purpose} (${$.retention}) |`).join(`
`)}
---
## 3. 安全与数据隐私保证
${qd.map(($,I)=>`### 3.${I+1} ${$.topic}
${pl.map(($,Y)=>`### 3.${Y+1} ${$.topic}
- **安全承诺**:${$.guarantee}
- **实现约束**:${$.enforcement}
`).join(`
@@ -2026,9 +2111,9 @@ ${qd.map(($,I)=>`### 3.${I+1} ${$.topic}
## 4. 业务域能力图谱
${Ud.map(($)=>`### \`seal-use ${$.domain}\`
${dl.map(($)=>`### \`seal-use ${$.domain}\`
* **能力定位**:${$.summary}
* **核心命令**:${$.primaryCommands.map((I)=>`\`seal-use ${I}\``).join("、")}
* **核心命令**:${$.primaryCommands.map((Y)=>`\`seal-use ${Y}\``).join("、")}
`).join(`
`)}
@@ -2039,20 +2124,19 @@ ${Ud.map(($)=>`### \`seal-use ${$.domain}\`
- **环境自检**:运行 \`seal-use doctor\`,一键检查当前运行时版本、本地目录健康度、企业资产接入数量以及守护服务状态。
- **查看企业配置源文件**:运行 \`seal-use corps get <corpId>\`,可直接查看指定企业的本地 JSON 存储绝对路径。
- **查阅完整操作手册**:运行 \`seal-use doctor guide\` 随时在离线状态下查看本文档。
`}function gh0($){if(!Y8($))return 0;try{return Nf1($).filter((I)=>I.endsWith(".json")).length}catch{return 0}}function iA($){try{return Ff1($,Mf1.W_OK),!0}catch{return!1}}function Yd(){let $=Df1(),I=W3($,".config","seal-use"),z=W3(I,"enterprises"),q=W3(I,"config.json"),U=W3(I,"seal_tokens.json"),Y=W3(I,"mappings"),J=Mz(),Q=W3($,"Downloads"),H=["/opt/homebrew/bin/seal-use","/usr/local/bin/seal-use",W3($,".local","bin","seal-use"),W3($,"bin","seal-use")].find((A)=>Y8(A))??process.execPath,G={configDir:{name:"配置根目录",path:I,exists:Y8(I),writable:Y8(I)?iA(I):!1,description:"用户持久化配置与企业状态根目录"},enterprisesDir:{name:"企业配置目录",path:z,exists:Y8(z),writable:Y8(z)?iA(z):!1,fileCount:gh0(z),description:"企业连接配置(JSON)保存路径"},globalConfigFile:{name:"全局配置文件",path:q,exists:Y8(q),description:"全局工作模式与默认企业配置"},tokenStore:{name:"凭据缓存",path:U,exists:Y8(U),description:"会话凭据与令牌缓存"},mappingsDir:{name:"规则版本映射快照",path:Y,exists:Y8(Y),fileCount:gh0(Y),description:"生产与测试规则版本映射对照表"},agentSkillDir:{name:"AI Agent 技能目录",path:J,exists:Y8(W3(J,"SKILL.md")),description:"本地 Agent 技能主目录"},exportDefaultDir:{name:"报表默认导出目录",path:Q,exists:Y8(Q),writable:Y8(Q)?iA(Q):!1,description:"审核大盘报表默认写入目录"},lintersDir:{name:"规则校验器目录 (用户自定义)",path:y$,exists:Y8(y$),writable:Y8(y$)?iA(y$):!1,description:"用户私有规则校验脚本存放目录"},officialLintersDir:{name:"官方内置规则校验器目录",path:x$,exists:Y8(x$),description:"官方标准与严格风控校验脚本目录 (系统自动保护与重写)"},globalBinary:{name:"全局命令行二进制",path:H,exists:Y8(H),description:"系统全局命令执行入口"}},Z=[];try{Z=c8()}catch{Z=[]}let X=O4().defaultCorpId??Z[0]?.id,w=Z.find((A)=>A.id===X),L=Z.filter((A)=>(A.environment??"production").toLowerCase()==="test").length,O=Z.length-L,F=[];if(F.push({id:"executable",title:"命令行二进制",status:"ok",message:`当前执行路径: ${process.execPath}`}),G.configDir?.exists&&G.configDir.writable)F.push({id:"config_dir",title:"配置目录访问",status:"ok",message:`${I} (正常读写)`});else if(G.configDir?.exists)F.push({id:"config_dir",title:"配置目录访问",status:"warn",message:`${I} (存在但可能不可写)`});else F.push({id:"config_dir",title:"配置目录访问",status:"warn",message:`未检测到配置目录 ${I},首次运行配置命令时将自动创建`});if(Z.length>0)F.push({id:"enterprises",title:"企业接入状态",status:"ok",message:`已接入 ${Z.length} 家企业 (正式: ${O}, 测试: ${L})`});else F.push({id:"enterprises",title:"企业接入状态",status:"warn",message:"当前未检测到企业配置,请使用 seal-use corps add-hose 或 add-seal 接入企业"});if(G.agentSkillDir?.exists)F.push({id:"agent_skill",title:"AI Agent 技能",status:"ok",message:`已就绪于 ${J}`});else F.push({id:"agent_skill",title:"AI Agent 技能",status:"warn",message:`未在 ${J} 检测到技能,可运行 'seal-use skill sync' 安装`});let D=F.some((A)=>A.status==="warn"||A.status==="error"),P=typeof globalThis.Bun<"u"?`Bun ${globalThis.Bun.version}`:`Node ${process.version}`;return{doctor:D?"warning":"ok",timestamp:new Date().toISOString(),runtime:{version:q1,executablePath:process.execPath,platform:`${process.platform} (${process.arch})`,engine:P},directories:G,enterprises:{total:Z.length,productionCount:O,testCount:L,activeCorpId:w?.id,activeCorpName:w?.name},checks:F,knowledge:{summary:"内嵌系统架构与目录规范白皮书(纯内存只读,零写入依赖)",directorySpecsCount:zd.length,securityPoliciesCount:qd.length,domainCapabilitiesCount:Ud.length,guideCommand:"seal-use doctor guide"}}}function Sh0($){let I=[],z=$.doctor==="ok"?"✨":"⚠️";I.push(`\uD83E\uDE7A [Seal Use Doctor] 系统健康诊断看板 ${z}`),I.push("─────────────────────────────────────────────────────────────"),I.push("【运行环境】"),I.push(` 版本号: ${$.runtime.version}`),I.push(` 程序路径: ${$.runtime.executablePath}`),I.push(` 操作系统: ${$.runtime.platform}`),I.push(` 执行引擎: ${$.runtime.engine}`),I.push(""),I.push("【核心路径状态】");for(let[,q]of Object.entries($.directories)){let U=q.exists?"✓":"○",Y=q.exists?q.fileCount!==void 0?`(${q.fileCount} 个文件)`:q.writable?"(就绪/可写)":"(存在)":"(未创建)";I.push(` ${U} ${q.name.padEnd(16," ")}: ${q.path} ${Y}`)}if(I.push(""),I.push("【企业资产概览】"),I.push(` 接入企业总计: ${$.enterprises.total} 家 (生产: ${$.enterprises.productionCount}, 测试: ${$.enterprises.testCount})`),$.enterprises.activeCorpId)I.push(` 当前激活企业: ${$.enterprises.activeCLine truncated
`)}D4();n1();async function uh0($,I,z){let q=($??I??"").toLowerCase();if(q==="guide"||q==="doc"||q==="knowledge"||q==="book"){console.error(`\uD83D\uDCD6 [Seal Use Doctor] 正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(hh0());return}if(q==="paths"||q==="dirs"||q==="directories"){let J=Yd();P0(J.directories);return}if(q==="tenant"||q==="corp"||q==="enterprise"){let{selectCorp:J}=await Promise.resolve().then(() => (x4(),kR0)),{createSealClient:Q}=await Promise.resolve().then(() => (S8(),L10)),{stringOption:K}=await Promise.resolve().then(() => (D4(),RR0)),{diagnoseTenantContract:H,formatTenantDoctorDashboard:G}=await Promise.resolve().then(() => (xh0(),yh0)),Z=K(z.options.corp)??(I&&I!==q?I:void 0)??(z.command[2]&&z.command[2]!==q?z.command[2]:void 0),W=J(Z),X=await Q(W),w=await H(X,W);if(!(X0(z.options.quiet)||X0(z.options.silent)))console.error(G(w));P0(w);return}let U=Yd();if(!(X0(z.options.quiet)||X0(z.options.silent)))console.error(Sh0(U));P0(U)}D4();import{createServer as Cf1}from"node:http";x4();import{URL as Tf1}from"node:url";var kh0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.22",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
`}var nl,pl,dl;var ml=o(()=>{nl=[{name:"配置与状态根目录",category:"config",standardPath:"~/.config/seal-use",purpose:"用户本地持久化配置根目录,存放企业连接元数据、会话缓存与全局状态。",accessMode:"read-write",retention:"persistent"},{name:"企业配置文件目录",category:"config",standardPath:"~/.config/seal-use/enterprises",purpose:"存放各已添加企业的配置 JSON 文件(如 xiezihao.json),存储企业域名、脱敏 Token、员工绑定关系等。",accessMode:"read-write",retention:"persistent"},{name:"全局配置文件",category:"config",standardPath:"~/.config/seal-use/config.json",purpose:"维护全局工作模式(stateful/stateless)、默认激活企业 defaultCorpId 以及 Lint 偏好。",accessMode:"read-write",retention:"persistent"},{name:"会话凭据安全缓存",category:"config",standardPath:"~/.config/seal-use/seal_tokens.json",purpose:"缓存已认证租户的 Bearer Token 与过期时间戳,避免高频调用上游 OAuth 换票接口。",accessMode:"read-write",retention:"cache"},{name:"规则版本映射快照",category:"config",standardPath:"~/.config/seal-use/mappings",purpose:"存储 corps sync-test 生成的生产与测试规则版本/编号对照映射快照,供 rules map 离线毫秒级速查。",accessMode:"read-write",retention:"persistent"},{name:"后台守护服务日志",category:"config",standardPath:"~/.config/seal-use/service.log",purpose:"常驻后台 HTTP 服务守护进程运行输出日志。",accessMode:"read-write",retention:"persistent"},{name:"全局命令行程序",category:"binary",standardPath:"/opt/homebrew/bin/seal-use",purpose:"macOS / Linux 全局独立单文件二进制程序;附带软链接 seal-home -> seal-use 兼容旧指令。",accessMode:"executable",retention:"persistent"},{name:"AI Agent 技能主目录",category:"skill",standardPath:"~/.agents/skills/seal-use",purpose:"面向 Antigravity、Codex 等 AI 智能体的标准技能目录,包含 SKILL.md、参考文档与操作规程。",accessMode:"read-write",retention:"persistent"},{name:"报表默认导出目录",category:"export",standardPath:"~/Downloads",purpose:"执行 approval-runs export 等大盘报表命令且未指定 --out 时,默认写入的 Excel 文件路径。",accessMode:"read-write",retention:"persistent"},{name:"系统隔离临时目录",category:"temp",standardPath:"/tmp 或 /var/folders/.../T",purpose:"自动化测试(bun test)生成的隔离工作副本,执行完毕后通过 afterEach 钩子彻底删除,零残留。",accessMode:"transient",retention:"ephemeral"}],pl=[{topic:"敏感凭据脱敏保护",guarantee:"appSecurity、password 等高危密钥永不回显在 stdout,Session Token 采用掩码处理(如 5oUL...Y%3D)。",enforcement:"CLI 所有展示接口(corps get、corps list、probe 等)均经 formatSafeSourceDetail 脱敏过滤。"},{topic:"正式环境与测试环境严格隔离",guarantee:"正式企业与测试企业必须严格 1 对 1 下挂,禁止多层级级联绑定;环境标记需显式 --confirm 确认。",enforcement:"corps bind-test 与 mark 强制要求 --confirm,缺少时阻断并返回退出码 10(confirmationRequired)。"},{topic:"跨环境规则同步安全基线",guarantee:"corps sync-test 仅将正式企业偏好与规则覆盖同步至测试企业并自动发布,正式企业规则严格维持草稿态永不发布。",enforcement:"规则同步流水线由 sync-test 独占受控,正式环境端仅执行拉取草稿读取操作,零发版变更。"},{topic:"只读诊断无副作用原则",guarantee:"doctor、search、get、list、context、probe 等命令为严格只读操作,不修改用户本地文件系统,零写入污染。",enforcement:"核心领域函数严格分离 Mutation 操作与 Query 操作,Query 路径杜绝写文件与环境篡改。"}],dl=[{domain:"corps (企业管理)",summary:"多租户接入、智能软搜索、富属性查看、环境标记、测试绑定与配置规则同步",primaryCommands:["corps list","corps search <query>","corps get <corpId>","corps mark","corps bind-test","corps sync-test"]},{domain:"approval-runs (审核大盘)",summary:"AI 审核单据检索、统计分析、引证规则查看、附件全链路追踪、Excel 报表导出、免登 SSO 深度链接",primaryCommands:["approval-runs list","approval-runs stats","approval-runs get","approval-runs export","approval-runs url"]},{domain:"rules (规则治理)",summary:"审核规则拉取、本地 Lint 质量检查、增量差量推送、离线版本与编号对照映射速查",primaryCommands:["rules pull","rules lint","rules push","rules map","rules count"]},{domain:"preference (决策偏好)",summary:"AI 审核偏好读取与更新、全局与分品类思考深度策略(medium/high)配置",primaryCommands:["preference get","preference decision update","preference thinking-depth set"]},{domain:"simulation (模拟演练)",summary:"合思单据指定、材 Line truncated
`)}var fh0=o(()=>{Hp();t9();S7();Dq();gP();ml()});var uh0={};x8(uh0,{formatTenantDoctorDashboard:()=>bS1,diagnoseTenantContract:()=>uS1});async function uS1($,Y){let z=[],U=Y.environment==="test"?"test":"production",Q=U==="test"?Y.prodCorpId:Y.testCorpId,J=U==="test"?"prodParent":"testTarget",I=null,K=null;try{let M=await H8($);if(I=M.user,K=M.tenant,Boolean(I?.isAdmin||I?.permissions?.includes("*")))z.push({id:"auth_identity",name:"身份与权限契约",status:"pass",summary:`已认证为管理员「${I.name??"未知"}」(${I.id??""}),具备完整操作权限`,details:{userId:I.id,userName:I.name,isAdmin:!0,tenantSlug:K?.tenantSlug,permissions:I.permissions}});else z.push({id:"auth_identity",name:"身份与权限契约",status:"warn",summary:`已认证为普通用户「${I.name??"未知"}」,非超级管理员,部分配置操作可能受限`,details:{userId:I.id,userName:I.name,isAdmin:!1,permissions:I.permissions},recommendation:"建议使用具有管理权限的企业主账号执行规则修改与集成发布"})}catch(M){z.push({id:"auth_identity",name:"身份与权限契约",status:"fail",summary:`鉴权握手失败:${M instanceof Error?M.message:String(M)}`,details:{error:String(M)},recommendation:`请执行 seal-use auth login --corp ${Y.id} 重新登录或更新 Token`})}let G={featureCode:"ai-approval",balance:0,deductionAmount:120,estimatedRuns:0,status:"exhausted"},W={used:0,remaining:0};try{let M=await bY($),w=Array.isArray(M.features)?M.features:[],O=w.find((D)=>D?.code==="ai-approval");if(O){let D=typeof O.balance==="number"?O.balance:0,T=typeof O.deductionAmount==="number"&&O.deductionAmount>0?O.deductionAmount:120,A=Math.floor(D/T);if(G.balance=D,G.deductionAmount=T,G.estimatedRuns=A,D<=0)G.status="exhausted",z.push({id:"billing_quota",name:"AI 审批额度余量",status:"fail",summary:"当前额度已耗尽 (余量 0 点),无法执行审批模拟或回归测试",details:{balance:D,deductionAmount:T,estimatedRuns:A},recommendation:"请联系管理员为企业充值 AI 审批额度"});else if(A<10)G.status="low",z.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`额度偏低:剩余 ${D} 点 (单笔扣除 ${T} 点),仅可支持约 ${A} 笔审核`,details:{balance:D,deductionAmount:T,estimatedRuns:A},recommendation:"建议在发起大规模自动化回归前充值补充额度"});else G.status="sufficient",z.push({id:"billing_quota",name:"AI 审批额度余量",status:"pass",summary:`额度充裕:剩余 ${D} 点,预估可支持 ${A} 笔审核单据`,details:{balance:D,deductionAmount:T,estimatedRuns:A}})}else z.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:"未检索到「ai-approval」功能包额度明细,按默认通道运行",details:{features:w.map((D)=>D?.code)}});let N=w.find((D)=>D?.code==="approval-rules");if(N)W.used=typeof N.used==="number"?N.used:0,W.remaining=typeof N.remaining==="number"?N.remaining:0}catch(M){z.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`读取计费状态失败:${M instanceof Error?M.message:String(M)}`,details:{error:String(M)}})}let H={totalCount:0,activeCount:0,quotaUsed:W.used,quotaRemaining:W.remaining};try{let M=await p6($),w=Array.isArray(M.rules)?M.rules:[];if(H.totalCount=w.length,H.activeCount=w.filter((O)=>O.status==="ACTIVE").length,w.length===0)z.push({id:"rules_status",name:"审核规则状态",status:"warn",summary:"当前租户未配置任何审核规则 (规则数为 0)",details:{totalCount:0,activeCount:0},recommendation:U==="test"&&Q?`可运行 seal-use corps sync-test --corp ${Q} 从生产企业同步规则`:"可运行 seal-use rules add 创建基础规则"});else z.push({id:"rules_status",name:"审核规则状态",status:"pass",summary:`审核规则健康:共 ${H.totalCount} 条规则,其中生效活跃 ${H.activeCount} 条`,details:{totalCount:H.totalCount,activeCount:H.activeCount,quotaUsed:W.used,quotaRemaining:W.remaining}})}catch(M){z.push({id:"rules_status",name:"审核规则状态",status:"fail",summary:`拉取规则列表失败:${M instanceof Error?M.message:String(M)}`,details:{error:String(M)}})}let X={integrationCount:0,hasReplayChannel:!1,activeWebhookId:void 0};try{let M=await J$($);X.integrationCount=M.length;let w=M.find((O)=>O.name.includes("回放")||O.name.toLowerCase().includes("replay"));if(X.hasReplayChannel=Boolean(w),X.activeWebhookId=w?.id??M[0]?.id,M.length===0)z.push({id:"webhook_integrations",name:"单据推送 Webhook 通道",status:"warn",summary:"未配置任何 Webhook 集成通道,执行重放测试时将自动创建临时回放通道",details:{integrationCount:0},recommendation:"可运行 seal-use webhook add --name (回放通道) 手动注册专属通道"});else z.push({id:"webhook_integrations",name:"单据推送 Webhook 通道",status:"pass",summary:`Webhook 集成通道就绪:共 ${M.length} 个通道${w?` (含专属回放通道「${w.name}」)`:""}`,details:{integrationCount:M.length Line truncated
`)}var bh0=o(()=>{X6()});async function ih0($,Y,z){let U=($??Y??"").toLowerCase();if(U==="guide"||U==="doc"||U==="knowledge"||U==="book"){console.error(`\uD83D\uDCD6 [Seal Use Doctor] 正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(Sh0());return}if(U==="paths"||U==="dirs"||U==="directories"){let I=ll();c0(I.directories);return}if(U==="tenant"||U==="corp"||U==="enterprise"){let{selectCorp:I}=await Promise.resolve().then(() => (o4(),$_0)),{createSealClient:K}=await Promise.resolve().then(() => (i8(),q00)),{stringOption:G}=await Promise.resolve().then(() => (D4(),mR0)),{diagnoseTenantContract:W,formatTenantDoctorDashboard:H}=await Promise.resolve().then(() => (bh0(),uh0)),X=G(z.options.corp)??(Y&&Y!==U?Y:void 0)??(z.command[2]&&z.command[2]!==U?z.command[2]:void 0),Z=I(X),q=await K(Z),V=await W(q,Z);if(!(F0(z.options.quiet)||F0(z.options.silent)))console.error(H(V));c0(V);return}let Q=ll();if(!(F0(z.options.quiet)||F0(z.options.silent)))console.error(xh0(Q));c0(Q)}var ch0=o(()=>{fh0();ml();D4();J4()});var ph0;var nh0=o(()=>{ph0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.26",description:"HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n"},servers:[{url:"http://localhost:8787",description:"Local HTTP adapter (`seal-use http`, or the `seal-use service start` daemon). Loopback-only by default."}],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","x-implementation-status":"implemented",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","x-implementation-status":"planned",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","x-implementation-status":"planned",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","x-implementation-status":"planned",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 Line truncated
the credentials already stored on this machine for the selected enterprise. Keep it bound
to loopback (\`--host 127.0.0.1\`) and do not expose the port to a network or an origin you
do not control.
`}},parameters:{CorpId:{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."},Offset:{name:"offset",in:"query",schema:{type:"integer",minimum:0,default:0},description:"Zero-based pagination offset."},Limit:{name:"limit",in:"query",schema:{type:"integer",minimum:1,maximum:100,default:50},description:"Maximum number of records to return."},RuleId:{name:"ruleId",in:"path",required:!0,schema:{type:"string"},description:"Approval rule ID."},VersionId:{name:"versionId",in:"path",required:!0,schema:{type:"string"},description:"Published rule version ID."},DocumentId:{name:"documentId",in:"path",required:!0,schema:{type:"string"},description:"Approval knowledge document ID."},RecordId:{name:"recordId",in:"path",required:!0,schema:{type:"string"},description:"seal-use approval run record ID."},BatchId:{name:"batchId",in:"path",required:!0,schema:{type:"string"},description:"Simulation batch ID."}},responses:{BadRequest:{description:"Invalid request.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}},Unauthorized:{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:{}}}}}},NotFound:{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}},schemas:{ErrorResponse:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}},CorpSummary:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}},SwitchCorpRequest:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}},SwitchCorpResponse:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}},SourceConfig:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."},AuthStage:{type:"object",additionalProperties:!0,required:["name","ok"],properties:{name:{type:"string",examples:["hose.openapi","hose.provisional","seal.sso","seal.whoami"]},ok:{type:"boolean"},error:{type:"string"}}},AuthDiagnosis:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}},SealUser:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},tenantId:{type:"string"},name:{type:"string"},isAdmin:{type:"boolean"},permissions:{type:"array",items:{type:"string"}}}},SealTenant:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},name:{type:"string"},tenantSlug:{type:"string"}}},WhoamiResponse:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}},SessionResponse:{type:"object",additionalProperties:!0,required:["user","session"],properties:{user:{$ref:"#/components/schemas/SealUser"},session:{type:"object",additionalProperties:!0}}},ApprovalRule:{type:"object",additionalProperties:!0,required:["id","description","scope","strictness"],properties:{id:{type:"string"},description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]},status:{type:"string"}}},ApprovalRuleInput:{type:"object",required:["description","scope","strictness"],properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulePatch:{type:"object",additionalProperties:!1,properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulesResponse:{type:"object",required:["rules"],properties:{rules:{type:"array",items:{$ref:"#/components/schemas/ApprovalRule"}},hasPendingDeletes:{type:"boolean"}}},RuleSetVersion:{type:"object",additionalProperties:!0,required:["id","versionNumber","versionName","rules"],properties:{id:{type:"string"},versionNumber:{type:"integer"},versionName:{type:"string"},publishedByName:{type:"string"},rules:{type:"array",items:{type:"object",additionalProperties:!0}}}},PublishRuleVersionRequest:{type:"object",required:["versionName"],properties:{versionName:{type:"string"}}},ApprovalDocument:{type:"object",additionalProperties:!0,required:["id","title","content"],properties:{id:{type:"string"},t 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${q1})</title>
<title>Seal Home API Docs (v${P1})</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 {
@@ -2071,24 +2155,22 @@ 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 L6($,I,z,q){let U=$.handler;return U(I,z,{corp:q})}async function bh0($,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 z=$.headers.host||"localhost",q=$.headers["x-forwarded-proto"]||"http",U=new Tf1($.url||"/",`${q}://${z}`),Y=U.pathname.replace(/\/+$/,"")||"/",J=($.method||"GET").toUpperCase();try{if(J==="GET"&&Y==="/"){Q4(I,200,{name:"seal-use",version:q1,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(J==="GET"&&Y==="/docs"){jf1(I,200,fh0());return}if(J==="GET"&&Y==="/openapi.json"){Q4(I,200,nA());return}if(J==="GET"&&Y==="/health"){Q4(I,200,{status:"ok",version:q1,name:"seal-use",timestamp:new Date().toISOString()});return}if(J==="POST"&&(Y==="/shutdown"||Y==="/api/shutdown")){Q4(I,200,{success:!0,message:"Shutting down seal-use background daemon",pid:process.pid}),setTimeout(()=>{process.kill(process.pid,"SIGTERM")},50);return}if(J==="POST"&&Y==="/api/cli"){let Q=await pA($),K=(typeof Q?.command==="string"?Q.command:"").trim();if(!K){cA(I,400,"Missing 'command' property in request body");return}let H=Jd(K),G=H[0]==="seal-use"||H[0]==="seal-home"||H[0]?.endsWith("/seal-use")||H[0]?.endsWith("/seal-home")?H.slice(1):H,Z=await $W(G),W=void 0;try{if(Z.stdout.trim().startsWith("{")||Z.stdout.trim().startsWith("["))W=JSON.parse(Z.stdout)}catch{}Q4(I,Z.isError?400:200,{success:!Z.isError,stdout:Z.stdout,stderr:Z.stderr,exitCode:Z.exitCode,data:W});return}if(J==="POST"&&Y.startsWith("/api/tool/")){let Q=Y.slice(10).trim(),K=J6(Q);if(!K){cA(I,404,`Tool not found: '${Q}'`);return}let H=await pA($)||{},G=B8($,U,H),Z=W1(G),W=await K1(Z),X={...H};delete X.corp;let w=await L6(K,W,X,Z);Q4(I,200,w);return}if(Y.startsWith("/v1/")){if(await Ef1($,I,J,Y,U))return}cA(I,404,`Cannot ${J} ${Y}. Visit /docs for available endpoints.`)}catch(Q){let K=Q instanceof Error?Q.message:String(Q);cA(I,500,K)}}async function Ef1($,I,z,q,U){let Y=Object.fromEntries(U.searchParams.entries());if(z==="GET"&&q==="/v1/corps"){let J=c8(),Q=O4();return Q4(I,200,{count:J.length,mode:Q.stateful?"stateful":"stateless",defaultCorpId:Q.defaultCorpId,corps:J.map((K)=>({id:K.id,name:K.name,sourceType:K.source.type,sealUrl:K.seal?.url}))}),!0}if(z==="GET"&&q==="/v1/whoami"){let J=B8($,U,Y),Q=W1(J),K=await K1(Q),H=J6("seal_whoami"),G=await L6(H,K,{},Q);return Q4(I,200,G),!0}if(z==="GET"&&q==="/v1/session"){let J=B8($,U,Y),Q=W1(J),K=await K1(Q),H=J6("seal_session_get"),G=await L6(H,K,{},Q);return Q4(I,200,G),!0}if(z==="GET"&&q==="/v1/approval-runs/summary"){let J=B8($,U,Y),Q=W1(J),K=await K1(Q),H=J6("seal_approval_runs_summary"),G=await L6(H,K,Y,Q);return Q4(I,200,G),!0}if(z==="GET"&&q==="/v1/approval-runs/stats"){let J=B8($,U,Y),Q=W1(J),K=await K1(Q),H=J6("seal_approval_runs_stats"),G=await L6(H,K,Y,Q);return Q4(I,200,G),!0}if(z==="GET"&&q==="/v1/approval-runs/pick"){let J=B8($,U,Y),Q=W1(J),K=await K1(Q),H=J6("seal_approval_run_pick"),G=await L6(H,K,Y,Q);return Q4(I,200,G),!0}if(z==="GET"&&q==="/v1/approval-runs/url"){let J=B8($,U,Y),Q=W1(J),K=await K1(Q),H=J6("seal_approval_run_url_get"),G=await L6(H,K,Y,Q);return Q4(I,200,G),!0}if(q.startsWith("/v1/approval-runs/")){let J=q.slice(18).split("/"),Q=J[0],K=J[1];if(Q&&!["summary","pick","stats","url","bridge"].includes(Q)){let H=B8($,U,Y),G=W1(H),Z=await K1(G);if(!K){let W=J6("seal_approval_run_get"),X=await L6(W,Z,{recordId:Q,...Y},G);return Q4(I,200,X),!0}if(K==="attachments"){let W=J6("seal_approval_run_attachments_get"),X=await L6(W,Z,{recordId:Q,...Y},G);return Q4(I,200,X),!0}if(K==="cited-rules"){let W=J6("seal_approval_run_cited_rules_get"),X=await L6(W,Z,{recordId:Q,...Y},G);return Q4(I,200,X),!0}if(K==="document-summary"){let W=J6("seal_approval_run_document_summary_get"),X=await L6(W,Z,{recordId:Q,...Y},G);return Q4(I,200,X),!0}if(K==="result"){let W=J6("seal_approval_run_result_get"),X=await L6(W,Z,{recordId:Q,...Y},G);return Q4(I,200,X),!0}}}if(z==="GET"&&q==="/v1/approval-runs"){let J=B8($,U,Y),Q=W1(J),K=await K1(Q),H=J6("seal_approval_runs_search"),G=await L6(H,K,{...Y,limit:Y.limit?Number(Y.limit):void 0,offset:Y.offset?Number(Y.offset):void 0,includeBridge:Y.includeBridge==="true"},Q);return Q4(I,200,G),!0}if(z==="GET"&&q==="/v1/approval/rules"){let J=B8($,U,Y),Q=W1(J),K=await K1(Q),H=J6("seal_approval_rules_list"),G=await L6(H,K,Y,Q);return Q4(I,200,G),!0}if(z==="GET"&&q==="/v1/simulation/batches"){let J=B8($,U,Y),Q=W1(J),K=await K1(Q),H=J6("seal_simulation_batches_list"),G=await L6(H,K,Y,Q);return Q4(I,200,G),!0}if(z==="POST"&&q==="/v1/simulation/create-batch"){let J=await pA($)||{},Q=B8($,U,J),K=W1(Q),H=await K1Line truncated
\uD83D\uDE80 seal-use HTTP Server (v${q1}) started`),console.error(` URL: http://${z}:${I}`),console.error(` Docs: http://${z}:${I}/docs`),console.error(` OpenAPI: http://${z}:${I}/openapi.json`),console.error(` CLI Exec: POST http://${z}:${I}/api/cli`),console.error(` REST API: http://${z}:${I}/v1/...
`);U(q)})})}async function ih0($){let I=R0($.options.port)??R0($.options.p),z=E($.options.host)??E($.options.h),q=await lA({port:I,host:z}),U=()=>{q.close(()=>{process.exit(0)})};process.on("SIGINT",U),process.on("SIGTERM",U),await new Promise(()=>{})}x4();n1();async function nh0($,I,z,q){if($==="config"||$==="get"){await N0("seal_llm_config_get",I,z,{},V0(q.options));return}if($==="providers"||$==="list"){await N0("seal_llm_providers_list",I,z,{},V0(q.options));return}throw Error(`Unknown llm command: ${$??""}. Run 'seal-use help' for available commands.`)}n1();async function ch0($,I){if($==="config"||$==="json"){Qd();return}await Kd()}function Qd(){P0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}n1();function ph0($){let I=nA();P0(I,{...V0($.options),allowFull:!0})}x4();n1();async function dh0($,I,z,q){if($==="available"){await N0("seal_permissions_available_list",I,z,{},V0(q.options));return}if($==="configs"||$==="list"){await N0("seal_permissions_configs_list",I,z,{},V0(q.options));return}throw Error(`Unknown permissions command: ${$??""}. Run 'seal-use help' for available commands.`)}x4();D4();n1();import{readFileSync as mh0}from"node:fs";async function lh0($,I,z,q,U,Y,J){if(!$||$==="get"){await N0("seal_preference_get",U,Y,{},V0(J.options));return}if($==="decision"){if(I==="update"||!I){let Q=E(J.options.input),K=Q?JSON.parse(mh0(Q,"utf8")):P8(J.json);if(!K||Object.keys(K).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await N0("seal_preference_decision_update",U,Y,{...K,dryRun:X0(J.options.dryRun)??X0(J.options["dry-run"])},V0(J.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(I==="set"){let Q=E(J.options.default)??E(J.options.level)??q;if(Q!=="medium"&&Q!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await N0("seal_preference_thinking_depth_set",U,Y,{defaultLevel:Q,dryRun:X0(J.options.dryRun)??X0(J.options["dry-run"])},V0(J.options));return}if(I==="policies"){if(z==="list"||!z){await N0("seal_preference_thinking_depth_policies_list",U,Y,{},V0(J.options));return}if(z==="upsert"){let Q=E(J.options.input),K=Q?JSON.parse(mh0(Q,"utf8")):P8(J.json);if(!K||!K.id||!K.name)throw Error(`Usage: seal-use preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await N0("seal_preference_thinking_depth_policies_upsert",U,Y,{...K,dryRun:X0(J.options.dryRun)??X0(J.options["dry-run"])},V0(J.options));return}if(z==="remove"||z==="delete"){let Q=q??E(J.options.id)??E(J.options.policyId);if(!Q)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await N0("seal_preference_thinking_depth_policies_remove",U,Y,{policyId:Q,dryRun:X0(J.options.dryRun)??X0(J.options["dry-run"])},V0(J.options));return}}}throw Error(`Unknown preference action: ${$??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}e9();S8();e4();async function oh0($={}){let I=c8(),z=O4(),q=l7(I,{stateful:z.stateful,defaultCorpId:z.defaultCorpId,corpId:$.corpId},a9());console.log(`[probe] corp=${q.id} source=${q.source.type}`);let U=await LJ(q);console.log("[probe] seal enterprise"),console.log(JSON.stringify(U,null,2));let Y=await K1(q),J=await xw(Y,{documentLimit:20,stylePreferencesEndpoint:q.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:J.rules.rules.length,hasPendingRuleDeletes:J.rules.hasPendingDeletes,documents:J.documents.articles.length,documentsTotal:J.documents.total,stylePreferences:J.stylePreferences.ok?"ok":`error: ${J.stylePreferences.error}`},null,2))}D4();async function rh0($,I,z){let q=I??E(z.options.corp)??($&&$!=="--corp"?$:void 0);await oh0({corpId:q})}Ci();x4();H$();D4();n1();async function Hd($,I,z,q,U){if($==="count"){await N0("seal_approval_rules_list",z,q,{countOnly:!0},V0(U.options));return}if($==="list"){if(X0(U.options.count)){await N0("seal_approval_rules_list",z,q,{countOnly:!0},V0(U.options));return}let Y=R0(U.options.limit),J=R0(U.options.offset);if(X0(U.options.summary)){await N0("seal_approval_rules_list",z,q,{fields:yR0,limit:Y,offset:J},V0(U.options));return}let Q=await q2("seal_approval_rules_list",z,q,{limit:Y,offset:J});xR0(Q,X0(U.options.full)===!0),P0(Q);return}if($==="clear"){let Y=X0(U.options.yes)===!0,J=X0(U.options.dryRun)??X0(U.options["dry-run"])??!Y;if(!Y&&!J)throw e5("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-use rules clear --corp ${q.id} --dry-run`);let Q=await q2("seal_approval_rules_clear",z,q,{dryRun:J,recode:X0(U.options.recode)});if(!Y&&J&&Q&&typeof Q==="object"){P0({...Q,nextCommand:`seal-use rules clear --corp ${q.id} --yes`},V0(U.options));return}P0(Q,V0(U.options));return}if($==="versions"){await N0("seal_approval_rule_versions_list",z,q,{},V0(U.options));return}if($==="version"){let Y=I??E(U.op Line truncated
`).filter(Boolean),Y=U.slice(-I);return{logFile:z,lines:Y,totalLines:U.length}}async function gf1($){let I=tA($),z=Wd($),q=IW($);eh0($.stateDir);let U=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):dA),Y=$.host??(process.env.HOST?process.env.HOST:mA);rA(I,`${process.pid}
`,{mode:384}),rA(z,JSON.stringify({pid:process.pid,port:U,host:Y,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),OJ(q,`service starting on http://${Y}:${U} pid=${process.pid}`);let J=null;try{J=await lA({port:U,host:Y,silent:!0}),OJ(q,`service listening pid=${process.pid}`)}catch(K){if(OJ(q,`service failed to bind port ${U}: ${K instanceof Error?K.message:String(K)}`),sA(I)===process.pid)K9(I,{force:!0}),K9(z,{force:!0});throw K}let Q=()=>{if(J)J.close(),J=null;if(sA(I)===process.pid)K9(I,{force:!0}),K9(z,{force:!0});OJ(q,`stopped pid=${process.pid}`)};await new Promise((K)=>{let H=!1,G=()=>{if(H)return;H=!0,Q(),process.off("SIGTERM",G),process.off("SIGINT",G),K()};process.once("SIGTERM",G),process.once("SIGINT",G)})}function sh0($){eh0($.stateDir);let I=FJ($);if(I.running)return I;let z=$.launcher??{command:process.execPath,args:[$.entryFile]},q=[...z.args??[],"service","run"];if($.port)q.push("--port",String($.port));if($.host)q.push("--host",String($.host));let U=_f1(z.command,q,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});U.unref();let Y=tA($);return rA(Y,`${U.pid}
`,{mode:384}),OJ(IW($),`started pid=${U.pid}`),{started:!0,...FJ($)}}function th0($,I={}){let z=tA($),q=Wd($),U=sA(z);if(!U||!ah0(U,$.appRoot))return K9(z,{force:!0}),K9(q,{force:!0}),I.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(U,"SIGTERM"),K9(z,{force:!0}),K9(q,{force:!0}),OJ(IW($),`stop requested pid=${U}`),I.quiet?void 0:{stopped:!0,pid:U}}function ah0($,I){if(!Sf1($))return!1;try{let z=Rf1("ps",["-p",String($),"-o","command="],{encoding:"utf8"});return(z.includes(I)||z.includes("seal-use")||z.includes("src/cli.ts"))&&z.includes("service")&&z.includes("run")}catch{return!1}}function Sf1($){try{return process.kill($,0),!0}catch{return!1}}function tA($){return Zd($.stateDir,"service.pid")}function Wd($){return Zd($.stateDir,"service.json")}function IW($){return Zd($.stateDir,"service.log")}function sA($){if(!oA($))return;let I=Number(Gd($,"utf8").trim());return Number.isInteger(I)&&I>0?I:void 0}function eh0($){vf1($,{recursive:!0,mode:448})}function OJ($,I){rA($,`${new Date().toISOString()} ${I}
`,{flag:"a",mode:384})}n1();D4();var Xd=xf1(yf1(),".config","seal-use");async function Vd($,I,z){let q=z?R0(z.options.port)??R0(z.options.p):void 0,U=z?E(z.options.host)??E(z.options.h):void 0,Y=z?R0(z.options.lines)??R0(z.options.n):void 0,J=await Nz($,{appRoot:I.appRoot,entryFile:I.entryFile,stateDir:Xd,version:q1,launcher:I.launcher,port:q,host:U},{maxLines:Y});if(J!==void 0)P0(J)}x4();D4();n1();import{existsSync as uf1,readFileSync as $g0}from"node:fs";async function Ig0($,I,z,q,U){if($==="batch-records"||$==="records"){let Y=I??E(U.options.batchId)??E(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation batch-records <batchId>");await N0("seal_simulation_batch_records_get",z,q,{batchId:Y,query:E(U.options.query)},V0(U.options));return}if($==="create"||$==="run"){let Y=E(U.options.mode)??E(U.options.sourceSystem)??E(U.options["source-system"])??"hosecloud",J=Y==="material-pack"?"material_pack":Y,Q=E(U.options.schemaConfig)??E(U.options["schema-config"]),K=Q?JSON.parse($g0(Q,"utf8")):void 0,H=E(U.options.input),G=H?JSON.parse($g0(H,"utf8")):P8(U.json),Z=E(U.options.packageId)??E(U.options["package-id"]),W=P6(U.options.packageIds)??P6(U.options["package-ids"])??(Z?[Z]:void 0),X=P6(U.options.flowIds)??P6(U.options["flow-ids"])??P6(U.options.documentSn)??P6(U.options["document-sn"]),w=E(U.options.signKey)??E(U.options["sign-key"])??E(U.options.integration),L=X0(U.options.noWait)??X0(U.options["no-wait"]);await N0("seal_simulation_batch_create",z,q,{mode:J,sourceSystem:J,flowIds:X,documentSn:X,rejectNodeName:E(U.options.rejectNode)??E(U.options["reject-node"])??null,thinkingDepthOverride:E(U.options.thinkingDepth)??E(U.options["thinking-depth"]),skipInvoiceGeneration:X0(U.options.skipInvoiceGeneration)??X0(U.options["skip-invoice-generation"]),skipExpenseExtraction:X0(U.options.skipExpenseExtraction)??X0(U.options["skip-expense-extraction"]),disableAttachmentCache:X0(U.options.disableAttachmentCache)??X0(U.options["disable-attachment-cache"]),signKey:w,packageIds:W,packageId:Z,templateId:E(U.options.templateId)??E(U.options["template-id"]),schemaConfig:K,requestIds:P6(U.options.requestIds)??P6(U.options["request-ids"]),workflowTypeId:E(U.options.workflowTypeId)??E(U.options["workflow-type-id"]),flowStatusList:P6(U.options.flowStatusList)?.map(Number)??P6(U.options["flow-status-list"])?.map(Number),businessCodes:P6(U.options.businessCodes)??P6(U.options["business-codes"]),documentType:E(U.options.documentType)??E(U.options["document-type"]),startTime:R0(U.options.startTime)??R0(U.options["start-time"]),endTime:R0(U.options.endTime)??R0(U.options["end-time"]),status:P6(U.options.status),limit:R0(U.options.limit),noWait:L,rawParams:G},V0(U.options));return}if($==="wait"){let Y=I??E(U.options.batchId)??E(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await N0("seal_simulation_batch_wait",z,q,{batchId:Y,timeout:E(U.options.timeout),pollInterval:E(U.options.pollInterval)??E(U.options["poll-interval"])},V0(U.options));return}if($==="status"){let Y=I??E(U.options.batchId)??E(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation status <batchId>");await N0("seal_simulation_batch_status",z,q,{batchId:Y},V0(U.options));return}if($==="clean"||$==="delete"){let Y=I??E(U.options.batchId)??E(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation clean <batchId>");await N0("seal_simulation_batch_clean",z,q,{batchId:Y},V0(U.options));return}if($==="specifications"){let Y=I??E(U.options.integration)??E(U.options.signKey)??E(U.options["sign-key"]);await N0("seal_simulation_specifications_list",z,q,{signKey:Y},V0(U.options));return}if($==="approval-definitions"||$==="definitions"){await N0("seal_simulation_feishu_approval_definitions_list",z,q,{},V0(U.options));return}if($==="list"){await N0("seal_simulation_batches_list",z,q,{limit:R0(U.options.limit)},V0(U.options));return}if($==="get"){let Y=I??E(U.options.batchId)??E(U.options["batch-id"]);if(!Y)throw Error("Usage: seal-use simulation get <batchId>");await N0("seal_simulation_batch_get",z,q,{batchId:Y},V0(U.options));return}if($==="templates"){await N0("seal_simulation_templates_get",z,q,{},V0(U.options));return}if($==="integrations"){await N0("seal_simulation_integrations_get",z,q,{},V0(U.options));return}if($==="package-upload"){let Y=I??E(U.options.file);if(!Y)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!uf1(Y))throw Error(`File not found: ${Y}`);await N0("seal_simulation_material_package_upload",z,q,{filePath:Y},V0(U.options));return}throw Error(`Unknown simulation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as zg0}from"node:fs";import{join as aA}from"node:path";D4();n1();function qg0($,I,z){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${_h0()}
`);return}if($==="install"||$==="init"||$==="sync"){let q=X0(z.options.local)||X0(z.options.workspace),U=E(z.options.dir)??E(z.options.target)??I,Y=U?U:q?aA(process.cwd(),".agents","skills","seal-use"):Mz(),J=$d(Y);P0({installed:!0,targetDir:J.targetDir,fileCount:J.files.length,files:J.files});return}if($==="status"||$==="get"||!$){let q=Mz(),U=aA(process.cwd(),".agents","skills","seal-use");P0({global:{dir:q,installed:zg0(aA(q,"SKILL.md"))},local:{dir:U,installed:zg0(aA(U,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${$}. Run 'seal-use help' for available commands.`)}n1();async function Ug0($,I){if($==="config"){P0(await LJ(I));return}throw Error(`Unknown source command: ${$??""}. Run 'seal-use help' for available commands.`)}H$();x4();D4();n1();S8();H$();e4();GZ();function wd($){if(typeof $!=="string"||!$.trim())return"UNKNOWN";let I=$.toUpperCase().trim();if(I==="APPROVE"||I==="PASS")return"APPROVE";if(I==="REJECT"||I==="DENIED")return"REJECT";if(I==="MANUAL"||I==="ASSISTED")return"MANUAL";if(I==="ERROR"||I==="FAILED")return"ERROR";return I}async function Yg0($){let{sourceCorp:I,targetCorp:z,sourceClient:q,targetClient:U,samples:Y=10,dryRun:J=!1,pollIntervalMs:Q=2000,timeoutMs:K=45000,snPrefix:H="REG_",fetchFn:G=fetch}=$;if(z.environment!=="test")throw new h4(`重放目标企业「${z.name}」(${z.id}) 的环境为「${z.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${I.id} <testCorpId>`);let Z=await C2(U),X=(Array.isArray(Z.features)?Z.features:[]).find((u)=>u?.code==="ai-approval"),w=typeof X?.balance==="number"?X.balance:0,L=typeof X?.deductionAmount==="number"&&X.deductionAmount>0?X.deductionAmount:120,O=Y*L;if(w<O)throw new h4(`测试企业「${z.name}」AI 审批额度不足:当前剩余 ${w} 点,本次回归抽样 ${Y} 笔需要约 ${O} 点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${z.id}」充值 AI 审批额度,或降低抽样笔数 (--samples ${Math.max(1,Math.floor(w/L))})`);let F=await a4(q,{limit:Y,status:"completed"}),D=Array.isArray(F.records)?F.records:[];if(D.length===0){let u=await a4(q,{limit:Y});D=Array.isArray(u.records)?u.records:[]}if(D.length===0)throw new h4(`在母企业「${I.name}」(${I.id}) 中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(D=D.slice(0,Y),J){let u=D.map((p)=>{let s=p.sourceDocumentSN??p.id,U0=p?.result?.decision??p.aiDecision??p?.decision,H0=wd(U0),D0=p?.result?.summary??p.aiSummary;return{sn:s,sourceRecordId:p.id,prodDecision:H0,prodSummary:D0,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:new Date().toISOString(),sourceCorp:{id:I.id,name:I.name,environment:I.environment??"production"},targetCorp:{id:z.id,name:z.name,environment:z.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:w,deductionAmount:L,estimatedRequired:O},metrics:{sampleCount:u.length,successCount:u.length,failureCount:0,matchCount:u.length,flipCount:0,concordanceRate:1},flips:[],records:u}}let P=await Mi(U,z),A=[];for(let u of D){let p=Date.now(),s=u.sourceDocumentSN??u.id,U0=wd(u?.result?.decision??u.aiDecision??u?.decision),H0=u?.result?.summary??u.aiSummary;try{let D0=await z4(q,u.id),_0=`${H}${s}`,Y1=Oi(D0,{snPrefix:H,docIdPrefix:H});await Fi(P.incomingDocumentWebhook.url,P.secret,Y1,G,K6(z.seal));let u0=null,r0=Date.now();while(Date.now()-r0<K){await new Promise((t4)=>setTimeout(t4,Q));let k4=await a4(U,{sourceDocumentSN:_0,limit:1});if(k4.records&&k4.records.length>0){let t4=k4.records[0];if(t4.status==="completed"||t4.status==="failed"){u0=t4;break}}}if(!u0){A.push({sn:s,sourceRecordId:u.id,prodDecision:U0,prodSummary:H0,status:"FAILED",error:`测试租户单据审核超时 (${Math.round(K/1000)}s 未完成)`,durationMs:Date.now()-p});continue}let I1=wd(u0?.result?.decision??u0.aiDecision??u0?.decision??(u0.status==="completed"?"APPROVE":"ERROR")),o=u0?.result?.summary??u0.aiSummary,E0=U0===I1,k0=E0?"MATCHED":"FLIPPED",L1={sn:s,sourceRecordId:u.id,prodDecision:U0,prodSummary:H0,testRecordId:u0.id,testDecision:I1,testSummary:o,status:k0,durationMs:Date.now()-p};if(!E0)L1.diff={from:U0,to:I1,reasonDiff:o&&H0&&o!==H0?`生产: ${H0.slice(0,60)}... -> 测试: ${o.slice(0,60)}...`:void 0};A.push(L1)}catch(D0){A.push({sn:s,sourceRecordId:u.id,prodDecision:U0,prodSummary:H0,status:"FAILED",error:D0 instanceof Error?D0.message:String(D0),durationMs:Date.now()-p})}}let T=A.filter((u)=>u.status==="MATCHED"||u.status==="FLIPPED"),k=A.filter((u)=>u.status==="MATCHED"),h=A.filter((u)=>u.status==="FLIPPED"),f=A.filter((u)=>u.status==="FAILED").length,C=k.length,b=h.length,i=C+b,v=i>0?C/i:0,y=b>0,c=y?"REGRESSIONS_DETECTED":"CLEAN",$0=!y&&f===0,R;try{let u=await C2(U),s=(Array.isArray(u.features)?u.features:[]).find((U0)=>U0?.code==="ai-approval");if(typeof s?.balance==="number")R=s.balance}catch{}return{ok:!y&&f===0,verdict:c,safeToPublish:$0,timestamp:new Date().toISOString(),sourceCorp:{id:I.id,name:I.name,environment:I.environment??"production"},targetCorp:{id:z.id,name:z.name,environment:z.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:w,deductionAmount:L,estimatedRequired:O,balanceAfter:R},metrics:{sampleCount:A.length,successCount:T.length,failureCount:f,matchCount:C,flipCount:b,concordanceRate:Number(v.toFixed(4))},flips:h,records:A}}function Jg0($){let{sourceCorp:I,targetCorp:z,verdict:q,safeToPublish:U,metrics:Y,quota:J,flips:Q,records:K}=$,H=q==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":q==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",G=["",`\uD83E\uDDEA [Seal Use Test] 规则回归测试矩阵: 生产「${I.name}」-> 测试靶场「${z.name}」`,` 判定: ${H} · 准许发布: ${U?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),` 样本总数: ${Y.sampleCount} | 一致通过: ${Y.matchCount} | 决策翻转: ${Y.flipCount} | 异常失败: ${Y.failureCount}`,` 一致率: ${(Y.concordanceRate*100).toFixed(1)}% | 消耗预估: ${J.estimatedRequired} 点 (余量: ${J.balanceBefore}${J.balanceAfter!==void 0?` -> ${J.balanceAfter}`:""})`," "+"─".repeat(65)];if(Q.length>0){G.push(` ⚠️ 决策翻转清单 (${Q.length} 笔单据在新规则下结果改变):`);for(let Z of Q)if(G.push(` • 单据 [${Z.sn}]: 原生产判定「${Z.prodDecision}」 ➔ 测试新判定「${Z.testDecision}」`),Z.diff?.reasonDiff)G.push(` 理由差异: ${Z.diff.reasonDiff}`);G.push(" "+"─".repeat(65)),G.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(q==="CLEAN")G.push(" ✓ 全部样本在新规则下的审核决策与生产历史 1 Line truncated
`)}async function Ld($,I,z){let q=($??I??"regression").toLowerCase();if(q==="regression"||q==="regress"||q==="matrix"){let U=E(z.options.corp)??(I&&I!==q?I:void 0),Y=W1(U),J=Y,Q=Y;if(Y.environment==="test"){Q=Y;let D=E(z.options["prod-corp"])??E(z.options.prod)??Y.prodCorpId;if(!D)throw new h4(`测试企业「${Y.name}」(${Y.id}) 未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-use corps bind-test <prodCorpId> ${Y.id}`);J=W1(D)}else{J=Y;let D=E(z.options["test-corp"])??E(z.options.test)??Y.testCorpId;if(!D)throw new h4(`生产企业「${Y.name}」(${Y.id}) 未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${Y.id} <testCorpId>`);Q=W1(D)}let K=await K1(J),H=await K1(Q),G=R0(z.options.samples)??R0(z.options.limit)??R0(z.options.n)??10,Z=X0(z.options["dry-run"]),W=X0(z.options["fail-on-flips"]),X=R0(z.options["poll-interval"])??2000,w=R0(z.options.timeout)??45000,L=E(z.options["sn-prefix"])??"REG_",O=await Yg0({sourceCorp:J,targetCorp:Q,sourceClient:K,targetClient:H,samples:G,dryRun:Z,pollIntervalMs:X,timeoutMs:w,snPrefix:L,failOnFlips:W});if(!(X0(z.options.quiet)||X0(z.options.silent)))console.error(Jg0(O));if(P0(O),W&&!O.ok)throw new h4(`回归测试发现 ${O.metrics.flipCount} 笔单据决策翻转,已按 --fail-on-flips 策略非零终止。`,1);return}throw new h4(`未知的 test 子命令: "${q}"。
可用子命令: seal-use test regression [--corp <id>] [--samples <N>] [--dry-run]`,2,"seal-use test regression --help")}x4();D4();n1();async function Qg0($,I,z,q){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await N0($,I,z,P8(q.json),V0(q.options))}CA();n1();function Kg0(){P0(dZ.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as kf1,mkdirSync as ff1,renameSync as Od,rmSync as bf1,unlinkSync as Xg0,writeFileSync as Hg0}from"node:fs";import{dirname as if1,join as Gg0}from"node:path";import{spawnSync as Dz}from"node:child_process";function eA($=process.execPath,I=import.meta.url){if(I.includes("/$bunfs/")||I.includes("\\$bunfs\\"))return!0;let z=$.toLowerCase().replace(/\\/g,"/");return!z.endsWith("/bun")&&!z.endsWith("/bun.exe")&&!z.endsWith("/node")&&!z.endsWith("/node.exe")}n1();var Vg0="yunyingk/seal-use",qW="yunyingk/seal-home";var nf1="SEAL_USE_GITHUB_REPO",cf1="SEAL_HOME_GITHUB_REPO";async function wg0($,I={}){let z={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:Xd,version:q1,launcher:$.launcher},q=I.repo||process.env[nf1]?.trim()||process.env[cf1]?.trim()||Vg0,U=I.targetVersion?.trim(),Y=U&&U.toLowerCase()!=="latest"?U:void 0;if(Y){let A=Y.replace(/^v/,""),T=Lg0(A,q1);if(T<0)if(!Jv&&I.force);else{P0({updated:!1,currentVersion:q1,targetVersion:A,mode:eA()?"binary":"source",message:!Jv?`Cannot downgrade seal-use from dev build v${q1} to release v${A}. Use --force to overwrite.`:`Cannot downgrade seal-use from v${q1} to older version v${A}. Updates must be forward-only.`});return}if(T===0&&!I.force){P0({updated:!1,currentVersion:q1,targetVersion:A,mode:eA()?"binary":"source",message:`seal-use is already at version v${q1}. Use --force to reinstall.`});return}}if(I.changelogOnly){let A=await Fd(q,I.limit??10);P0({currentVersion:q1,totalQueried:A.length,releases:A.map((T)=>({version:T.version,tagName:T.tagName,publishedAt:T.publishedAt,author:T.author,releaseNotes:T.notes,releaseUrl:T.htmlUrl,isCurrent:T.version===q1,isNewer:zW(T.version,q1)}))});return}if(!eA()){if(I.checkOnly){let T=await Fd(q,30),k=T[0],h=k?.version??q1,f=T.find((i)=>i.version===q1),C=zW(h,q1),b=T.filter((i)=>zW(i.version,q1));P0({updated:!1,updateAvailable:C,currentVersion:q1,currentVersionPublishedAt:f?.publishedAt,latestVersion:h,latestVersionPublishedAt:k?.publishedAt,behindCount:b.length,pendingReleases:b.map((i)=>({version:i.version,tagName:i.tagName,publishedAt:i.publishedAt,author:i.author,releaseNotes:i.notes,releaseUrl:i.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=FJ(z).running;if(A)await Nz("stop",z);try{Wg0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(T){console.error(`git pull skipped: ${T instanceof Error?T.message:String(T)}`)}if(Wg0("bun",["install"],{cwd:$.appRoot}),A)await Nz("start",z);P0({updated:!0,serviceRestarted:A,version:q1,mode:"source"});return}let J=pf1(),Q=df1(),K=await Fd(q,30),H=Y?K.find((A)=>A.version===Y||A.tagName===Y||A.tagName===`v${Y}`)??await Zg0(q,Y):K[0]??await Zg0(q);if(!H){P0({updated:!1,currentVersion:q1,mode:"binary",message:`Failed to query releases from repository '${q}'`});return}let G=H.version,Z=K.find((A)=>A.version===q1),W=zW(G,q1),X=W||Boolean(I.force),w=K.filter((A)=>zW(A.version,q1));if(I.checkOnly){P0({updated:!1,updateAvailable:W,currentVersion:q1,currentVersionPublishedAt:Z?.publishedAt,latestVersion:G,latestVersionPublishedAt:H.publishedAt,behindCount:w.length,pendingReleases:w.map((A)=>({version:A.version,tagName:A.tagName,publishedAt:A.publishedAt,author:A.author,releaseNotes:A.notes,releaseUrl:A.htmlUrl})),releaseNotes:H.notes,releaseUrl:H.htmlUrl,mode:"binary"});return}if(!X){P0({updated:!1,currentVersion:q1,currentVersionPublishedAt:Z?.publishedAt,latestVersion:G,latestVersionPublishedAt:H.publishedAt,mode:"binary",message:`seal-use is already up to date (v${q1})`});return}let L=mf1(H.assets,J,Q);if(!L)throw Error(`No compatible binary found for ${J}-${Q} in release v${G}. Available assets: ${H.assets.map((A)=>A.name).join(", ")}`);let O=FJ(z).running;if(O)await Nz("stop",z);let F=process.execPath,D=if1(F),P=Gg0(D,`.tmp-update-${Date.now()}`);ff1(P,{recursive:!0});try{let A=Gg0(P,L.name);await lf1(L.downloadUrl,A,H.tagName,L.name);let T=A;if(L.name.endsWith(".tar.gz")||L.name.endsWith(".tgz"))T=of1(A,P,J);else if(L.name.endsWith(".zip"))T=rf1(A,P,J);if(kf1(T,493),process.platform==="darwin")try{Dz("/usr/bin/codesign",["--remove-signature",T],{stdio:"ignore"}),Dz("/usr/bin/codesign",["--force","--sign","-",T],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let h=`${F}.old.${Date.now()}`;try{Od(F,h)}catch{}Od(T,F)}else Od(T,F);if(O)await Nz("start",z);let k=Id();P0({updated:!0,fromVersion:q1,toVersion:G,serviceRestarted:O,skillSynced:k.synced?k.targetDir:!1,mode:"binary"})}finally{try{bf1(P,{recursive:!0,force:!0})}catch{}}}function pf1(){if(process.platform==="darwin")retur Line truncated
`)}catch{}}async function lf1($,I,z,q){let U=Md(),Y=[],J=z?z.startsWith("v")?z:`v${z}`:void 0,Q=q||$.split("/").pop()||"";if(U!=="github"){if(J&&Q)Y.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${J}/${Q}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${J}/${Q}`);if($.startsWith("https://git.ying-qing.cn"))Y.push($)}if(U!=="gitea")if(J&&Q){let L=`https://github.com/${Vg0}/releases/download/${J}/${Q}`;if(!process.env.CI)Y.push(`https://ghfast.top/${L}`,`https://gh.ddlc.top/${L}`);Y.push(L)}else if($.includes("github.com")){if(!process.env.CI)Y.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);Y.push($)}else Y.push($);let K=Array.from(new Set(Y)),H,G=6000,Z=6000,W=307200,X=1e4,w=180000;for(let L=0;L<K.length;L++){let O=K[L],F=new AbortController,D="",P=(h)=>{D=h;try{F.abort()}catch{}},A=setTimeout(()=>{P("Connection timed out (no response headers within 6s)")},G),T,k;try{$P(`==> [${L+1}/${K.length}] Downloading via: ${O}`);let h=await fetch(O,{signal:F.signal});if(A)clearTimeout(A),A=void 0;if(!h.ok)throw Error(`HTTP ${h.status} ${h.statusText}`);T=setTimeout(()=>{P("Overall download time exceeded 3 minutes")},w);let f=Number(h.headers.get("content-length"))||0,C=h.body?.getReader();if(!C){let c=Buffer.from(await h.arrayBuffer());if(c.length<1000)throw Error(`Downloaded content is suspiciously small (${c.length} bytes)`);Hg0(I,c),$P(`✓ Download succeeded (${(c.length/1024/1024).toFixed(1)} MB)`);return}let b=[],i=0,v=0;k=setTimeout(()=>{if(i<W){let c=(i/1024).toFixed(1);P(`Initial transfer too slow (${c} KB < 300 KB in 6s), switching mirror...`)}},Z);while(!0){let c=C.read(),$0,R=new Promise((U0,H0)=>{$0=setTimeout(()=>{H0(Error("Data transfer stalled (no chunk received for 10s)"))},X)}),u;try{u=await Promise.race([c,R])}finally{if($0)clearTimeout($0)}let{done:p,value:s}=u;if(p)break;if(s){if(b.push(s),i+=s.length,k&&i>=W)clearTimeout(k),k=void 0;let U0=Date.now();if(U0-v>200){v=U0;let H0=f?Math.round(i/f*100):0,D0=(i/1048576).toFixed(1),_0=f?(f/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${H0}% (${D0} / ${_0} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let y=Buffer.concat(b);if(y.length<1000)throw Error(`Downloaded content is suspiciously small (${y.length} bytes)`);Hg0(I,y),$P(`✓ Download completed successfully (${(y.length/1024/1024).toFixed(1)} MB)`);return}catch(h){if(A)clearTimeout(A);if(k)clearTimeout(k);if(T)clearTimeout(T);let f=D||(h instanceof Error?h.message:String(h));H=Error(f),$P(`
↳ Mirror failed: ${H.message}`)}finally{if(A)clearTimeout(A);if(k)clearTimeout(k);if(T)clearTimeout(T)}}throw Error(`Failed to download asset from all mirrors: ${H?.message}`)}function of1($,I,z){let q=Dz("tar",["-xzf",$,"-C",I],{stdio:"pipe"});if(q.status!==0)throw Error(`Failed to extract tar archive: ${q.stderr.toString()}`);Xg0($);let U=z==="windows"?"seal-use.exe":"seal-use",Y=Dz("find",[I,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),J=Y.find((Q)=>Q.endsWith(`/${U}`)||Q.endsWith(U));if(J)return J;return Y[0]||$}function rf1($,I,z){let q=Dz("unzip",["-q","-o",$,"-d",I],{stdio:"pipe"});if(q.status!==0)throw Error(`Failed to extract zip archive: ${q.stderr.toString()}`);Xg0($);let U=z==="windows"?"seal-use.exe":"seal-use",Y=Dz("find",[I,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),J=Y.find((Q)=>Q.endsWith(`/${U}`)||Q.endsWith(U));if(J)return J;return Y[0]||$}function Lg0($,I){let z=$.replace(/^v/,"").split(".").map((U)=>Number.parseInt(U,10)||0),q=I.replace(/^v/,"").split(".").map((U)=>Number.parseInt(U,10)||0);for(let U=0;U<Math.max(z.length,q.length);U++){let Y=z[U]??0,J=q[U]??0;if(Y>J)return 1;if(Y<J)return-1}return 0}function zW($,I){return Lg0($,I)>0}function Wg0($,I,z={}){let q=Dz($,I,{cwd:z.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(q.stdout)console.error(q.stdout.trimEnd());if(q.stderr)console.error(q.stderr.trimEnd());if(q.status!==0)throw Error(`${$} ${I.join(" ")} failed with status ${q.status}`)}x4();D4();n1();async function Og0($,I,z,q,U){if($==="create"){let Y=E(U.options.name)??I,J=E(U.options.phone);if(!Y||!J)throw Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");let Q=E(U.options.dept)??E(U.options.departmentId);await N0("seal_user_create",z,q,{name:Y,phone:J,departmentIds:Q?[Q]:void 0},V0(U.options));return}if($==="reset-password"){let Y=I??E(U.options.userId);if(!Y)throw Error("Usage: seal-use users reset-password <userId>");await N0("seal_user_reset_password",z,q,{userId:Y},V0(U.options));return}if($==="search"||$==="list"){let Y=I??E(U.options.keyword)??E(U.options.query)??"";await N0("seal_user_search",z,q,{keyword:Y},V0(U.options));return}if($==="get"){let Y=I??E(U.options.userId);if(!Y)throw Error("Usage: seal-use users get <userId>");await N0("seal_user_get",z,q,{userId:Y},V0(U.options));return}if($==="delete"){let Y=I??E(U.options.userId);if(!Y)throw Error("Usage: seal-use users delete <userId>");await N0("seal_user_delete",z,q,{userId:Y},V0(U.options));return}if($==="activate"){let Y=I??E(U.options.userId);if(!Y)throw Error("Usage: seal-use users activate <userId>");await N0("seal_user_activate",z,q,{userId:Y},V0(U.options));return}if($==="delegation"||$==="impersonate"){let Y=I??E(U.options.userId)??E(U.options.phone);if(!Y)throw Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");let J=E(U.options.note);await N0("seal_user_delegation_create",z,q,{userIdOrPhone:Y,note:J},V0(U.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}H$();x4();D4();bp();n1();var Fg0=Nd(Nd(Nd(tf1(import.meta.url)))),af1=new Set(["config","service","stop","http","serve","update","tools","corps","corp","tool","source","auth","delegation","users","contacts","data","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","analytics","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","doctor","changelog","test"]),ef1=new Set(["http","server","web","mcp"]);function $b1($){if(!$.length)return!1;let I=$[0]?.toLowerCase(),z=$[1]?.toLowerCase();if(I&&ef1.has(I))return!0;if((I==="service"||I==="daemon")&&z==="run")return!0;return!1}var Mg0=Promise.resolve();function $W($,I={}){if($b1($))return Ng0($,I);let z=Mg0.then(()=>Ng0($,I));return Mg0=z.then(()=>{return},()=>{return}),z}async function Ng0($,I){let z=[],q=[],U=console.log,Y=console.error,J={appRoot:I.appRoot??Fg0,entryFile:I.entryFile??sf1(I.appRoot??Fg0,"src","cli.ts"),launcher:I.launcher};console.log=(...Q)=>{z.push(ip(Q))},console.error=(...Q)=>{q.push(ip(Q))};try{return await Ib1($,J),{stdout:lZ(z),stderr:lZ(q),isError:!1,exitCode:0}}catch(Q){let K=oZ(Q instanceof Error?Q.message:String(Q)),H=qD(Q);if(q.push(K),H.nextAction&&!K.includes("Next action:"))q.push(`\uD83D\uDC49 Next action: ${H.nextAction}`);return{stdout:lZ(z),stderr:lZ(q),isError:!0,exitCode:H.exitCode}}finally{console.log=U,console.error=Y}}async function Ib1($,I){let z=Sp($),[q,U,Y]=z.command;if(q==="version"||q==="v"||Boolean(z.options.version)||Boolean(z.options.v)||Boolean(z.options.V)){P0(QK);return}let J=gR0(z);if(J.isHelp){uR0(J.target);return}if(!q||!af1.has(q))throw Error(`Unknown command: ${z.command.join(" ")}. Run 'seal-use help' for available commands.`);if(q==="webhook"&&(U==="resource-pack"||U==="pack"||U==="material-pack")&&Y==="preview"){let H=z.command[3]??E(z.options.file)??E(z.options.input);if(!H)throw Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");await bR0(H,XJ(z.options));return}if(q==="openapi"){ph0(z);return}if(q==="mcp-config"){Qd();return}if(q==="skill"){qg0(U,Y,z);return}if(q==="mcp"||q==="server"){await ch0(U,z);return}if(q==="probe"){await rh0(U,Y,z);return}if(q==="doctor"){await uh0(U,Y,z);return}if(q==="test"){await Ld(U,Y,z);return}if(q==="config"){lR0(U,Y,z);return}if(q==="service"){await Vd(U,I,z);return}if(q==="stop"){await Vd("stop",I,z);return}if(q==="http"||q==="serve"){await ih0(z);return}if(q==="update"||q==="changelog"){let H=q==="changelog"||U==="changelog"||U==="log"||U==="history"||X0(z.options.changelog)===!0,G=U==="check"||X0(z.options.check)===!0||X0(z.options["check-only"])===!0,Z=E(z.options.version)??E(z.options.tag)??(!H&&!G&&U&&!U.startsWith("-")?U:void 0);await wg0 Line truncated
</html>`}var lh0=o(()=>{t9()});import{URL as cS1}from"node:url";async function _6($,Y,z,U){let Q=$.handler;return Q(Y,z,{corp:U})}async function oh0($,Y){if(Y.setHeader("Access-Control-Allow-Origin","*"),Y.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),Y.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),$.method==="OPTIONS"){Y.writeHead(204),Y.end();return}let z=$.headers.host||"localhost",U=$.headers["x-forwarded-proto"]||"http",Q=new cS1($.url||"/",`${U}://${z}`),J=Q.pathname.replace(/\/+$/,"")||"/",I=($.method||"GET").toUpperCase();try{if(I==="GET"&&J==="/"){B4(Y,200,{name:"seal-use",version:P1,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(I==="GET"&&J==="/docs"){pS1(Y,200,mh0());return}if(I==="GET"&&J==="/openapi.json"){B4(Y,200,jT());return}if(I==="GET"&&J==="/health"){B4(Y,200,{status:"ok",version:P1,name:"seal-use",timestamp:new Date().toISOString()});return}if(I==="POST"&&(J==="/shutdown"||J==="/api/shutdown")){B4(Y,200,{success:!0,message:"Shutting down seal-use background daemon",pid:process.pid}),setTimeout(()=>{process.kill(process.pid,"SIGTERM")},50);return}if(I==="POST"&&J==="/api/cli"){let K=await CT($),G=(typeof K?.command==="string"?K.command:"").trim();if(!G){ET(Y,400,"Missing 'command' property in request body");return}let W=Bq(G),H=W[0]==="seal-use"||W[0]==="seal-home"||W[0]?.endsWith("/seal-use")||W[0]?.endsWith("/seal-home")?W.slice(1):W,X=await Pq(H),Z=void 0;try{if(X.stdout.trim().startsWith("{")||X.stdout.trim().startsWith("["))Z=JSON.parse(X.stdout)}catch{}B4(Y,X.isError?400:200,{success:!X.isError,stdout:X.stdout,stderr:X.stderr,exitCode:X.exitCode,data:Z});return}if(I==="POST"&&J.startsWith("/api/tool/")){let K=J.slice(10).trim(),G=M6(K);if(!G){ET(Y,404,`Tool not found: '${K}'`);return}let W=await CT($)||{},H=k8($,Q,W),X=E1(H),Z=await j1(X),q={...W};delete q.corp;let V=await _6(G,Z,q,X);B4(Y,200,V);return}if(J.startsWith("/v1/")){if(await nS1($,Y,I,J,Q))return}ET(Y,404,`Cannot ${I} ${J}. Visit /docs for available endpoints.`)}catch(K){let G=K instanceof Error?K.message:String(K);ET(Y,500,G)}}async function nS1($,Y,z,U,Q){let J=Object.fromEntries(Q.searchParams.entries());if(z==="GET"&&U==="/v1/corps"){let I=s8(),K=_4();return B4(Y,200,{count:I.length,mode:K.stateful?"stateful":"stateless",defaultCorpId:K.defaultCorpId,corps:I.map((G)=>({id:G.id,name:G.name,sourceType:G.source.type,sealUrl:G.seal?.url}))}),!0}if(z==="GET"&&U==="/v1/whoami"){let I=k8($,Q,J),K=E1(I),G=await j1(K),W=M6("seal_whoami"),H=await _6(W,G,{},K);return B4(Y,200,H),!0}if(z==="GET"&&U==="/v1/session"){let I=k8($,Q,J),K=E1(I),G=await j1(K),W=M6("seal_session_get"),H=await _6(W,G,{},K);return B4(Y,200,H),!0}if(z==="GET"&&U==="/v1/approval-runs/summary"){let I=k8($,Q,J),K=E1(I),G=await j1(K),W=M6("seal_approval_runs_summary"),H=await _6(W,G,J,K);return B4(Y,200,H),!0}if(z==="GET"&&U==="/v1/approval-runs/stats"){let I=k8($,Q,J),K=E1(I),G=await j1(K),W=M6("seal_approval_runs_stats"),H=await _6(W,G,J,K);return B4(Y,200,H),!0}if(z==="GET"&&U==="/v1/approval-runs/pick"){let I=k8($,Q,J),K=E1(I),G=await j1(K),W=M6("seal_approval_run_pick"),H=await _6(W,G,J,K);return B4(Y,200,H),!0}if(z==="GET"&&U==="/v1/approval-runs/url"){let I=k8($,Q,J),K=E1(I),G=await j1(K),W=M6("seal_approval_run_url_get"),H=await _6(W,G,J,K);return B4(Y,200,H),!0}if(U.startsWith("/v1/approval-runs/")){let I=U.slice(18).split("/"),K=I[0],G=I[1];if(K&&!["summary","pick","stats","url","bridge"].includes(K)){let W=k8($,Q,J),H=E1(W),X=await j1(H);if(!G){let Z=M6("seal_approval_run_get"),q=await _6(Z,X,{recordId:K,...J},H);return B4(Y,200,q),!0}if(G==="attachments"){let Z=M6("seal_approval_run_attachments_get"),q=await _6(Z,X,{recordId:K,...J},H);return B4(Y,200,q),!0}if(G==="cited-rules"){let Z=M6("seal_approval_run_cited_rules_get"),q=await _6(Z,X,{recordId:K,...J},H);return B4(Y,200,q),!0}if(G==="document-summary"){let Z=M6("seal_approval_run_document_summary_get"),q=await _6(Z,X,{recordId:K,...J},H);return B4(Y,200,q),!0}if(G==="result"){let Z=M6("seal_approval_run_result_get"),q=await _6(Z,X,{recordId:K,...J},H);return B4(Y,200,q),!0}}}if(z==="GET"&&U==="/v1/approval-runs"){let I=k8($,Q,J),K=E1(I),G=await j1(K),W=M6("seal_approval_runs_search"),H=await _6(W,G,{...J,limit:J.limit?Number(J.limit):void 0,offset:J.offset?Number(J.offset):void 0,includeBridge:J.includeBridge==="true"},K);return B4(Y,200,H),!0}if(z==="GET"&&U==="/v1/approval/rules"){let I=k8($,Q,J),K=E1(I),G=await j1(K),W=M6("seal_approval_rules_list"),H=await _6(W,G,J,K);return B4(Y,200,H),!0}if(z==="GET"&&U==="/v1/simulation/batches"){let I=k8($,Q,J),K=E1(I),G=await j1(K),W=M6("seal_simulation_batches_list"),H=await _6(W,G,J,K);return B4(Y,200,H),!0}if(z==="POST"&&U==="/v1/simulation/create-batchLine truncated
\uD83D\uDE80 seal-use HTTP Server (v${P1}) started`),console.error(` URL: http://${z}:${Y}`),console.error(` Docs: http://${z}:${Y}/docs`),console.error(` OpenAPI: http://${z}:${Y}/openapi.json`),console.error(` CLI Exec: POST http://${z}:${Y}/api/cli`),console.error(` REST API: http://${z}:${Y}/v1/...
`);Q(U)})})}var RT=8787,_T="127.0.0.1";var sl=o(()=>{rh0();t9()});async function sh0($){let Y=s0($.options.port)??s0($.options.p),z=S($.options.host)??S($.options.h),U=await vT({port:Y,host:z}),Q=()=>{U.close(()=>{process.exit(0)})};process.on("SIGINT",Q),process.on("SIGTERM",Q),await new Promise(()=>{})}var ah0=o(()=>{D4();sl()});async function th0($,Y,z,U){if($==="config"||$==="get"){await k0("seal_llm_config_get",Y,z,{},C0(U.options));return}if($==="providers"||$==="list"){await k0("seal_llm_providers_list",Y,z,{},C0(U.options));return}throw Error(`Unknown llm command: ${$??""}. Run 'seal-use help' for available commands.`)}var eh0=o(()=>{o4();J4()});async function $S0($,Y){if($==="config"||$==="json"){al();return}let{startServer:z}=await US0().then(() => zS0);z()}function al(){c0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}var YS0=o(()=>{J4()});function QS0($){let Y=jT();c0(Y,{...C0($.options),allowFull:!0})}var JS0=o(()=>{ol();J4()});async function IS0($,Y,z,U){if($==="available"){await k0("seal_permissions_available_list",Y,z,{},C0(U.options));return}if($==="configs"||$==="list"){await k0("seal_permissions_configs_list",Y,z,{},C0(U.options));return}throw Error(`Unknown permissions command: ${$??""}. Run 'seal-use help' for available commands.`)}var KS0=o(()=>{o4();J4()});import{readFileSync as GS0}from"node:fs";async function WS0($,Y,z,U,Q,J,I){if(!$||$==="get"){await k0("seal_preference_get",Q,J,{},C0(I.options));return}if($==="decision"){if(Y==="update"||!Y){let K=S(I.options.input),G=K?JSON.parse(GS0(K,"utf8")):y8(I.json);if(!G||Object.keys(G).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await k0("seal_preference_decision_update",Q,J,{...G,dryRun:F0(I.options.dryRun)??F0(I.options["dry-run"])},C0(I.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(Y==="set"){let K=S(I.options.default)??S(I.options.level)??U;if(K!=="medium"&&K!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await k0("seal_preference_thinking_depth_set",Q,J,{defaultLevel:K,dryRun:F0(I.options.dryRun)??F0(I.options["dry-run"])},C0(I.options));return}if(Y==="policies"){if(z==="list"||!z){await k0("seal_preference_thinking_depth_policies_list",Q,J,{},C0(I.options));return}if(z==="upsert"){let K=S(I.options.input),G=K?JSON.parse(GS0(K,"utf8")):y8(I.json);if(!G||!G.id||!G.name)throw Error(`Usage: seal-use preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await k0("seal_preference_thinking_depth_policies_upsert",Q,J,{...G,dryRun:F0(I.options.dryRun)??F0(I.options["dry-run"])},C0(I.options));return}if(z==="remove"||z==="delete"){let K=U??S(I.options.id)??S(I.options.policyId);if(!K)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await k0("seal_preference_thinking_depth_policies_remove",Q,J,{policyId:K,dryRun:F0(I.options.dryRun)??F0(I.options["dry-run"])},C0(I.options));return}}}throw Error(`Unknown preference action: ${$??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}var HS0=o(()=>{o4();D4();J4()});async function XS0($={}){let Y=s8(),z=_4(),U=f2(Y,{stateful:z.stateful,defaultCorpId:z.defaultCorpId,corpId:$.corpId},h7());console.log(`[probe] corp=${U.id} source=${U.source.type}`);let Q=await gK(U);console.log("[probe] seal enterprise"),console.log(JSON.stringify(Q,null,2));let J=await j1(U),I=await ZM(J,{documentLimit:20,stylePreferencesEndpoint:U.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:I.rules.rules.length,hasPendingRuleDeletes:I.rules.hasPendingDeletes,documents:I.documents.articles.length,documentsTotal:I.documents.total,stylePreferences:I.stylePreferences.ok?"ok":`error: ${I.stylePreferences.error}`},null,2))}var ZS0=o(()=>{S7();i8();DT();X6()});async function qS0($,Y,z){let U=Y??S(z.options.corp)??($&&$!=="--corp"?$:void 0);await XS0({corpId:U})}var VS0=o(()=>{ZS0();D4()});async function tl($,Y,z,U,Q){if($==="count"){await k0("seal_approval_rules_list",z,U,{countOnly:!0},C0(Q.options));return}if($==="list"){if(F0(Q.options.count)){await k0("seal_approval_rules_list",z,U,{countOnly:!0},C0(Q.options));return}let J=s0(Q.options.limit),I=s0(Q.options.offset);if(F0(Q.options.summary)){await k0("seal_approval_rules_list",z,U,{fields:aR0,limit:J,offset:I},C0(Q.options));return}let K=await o2("seal_approval_rules_list",z,U,{limit:J,offset:I});tR0(K,F0(Q.options.full)===!0),c0(K);return}if($==="clear"){let J=F0(Q.options.yes)===!0,I=F0(Q.options.dryRun)??F0(Q.options["dry-run"])??!J;if(!J&&!I)throw D9("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-use rules clear --corp ${U.id} --dry-run`);let K=await o2("seal_approval_rules_clear",z,U,{dryRun:I,recode:F0(Q.options.recode)});if(!J&&I&&K&&typeof K==="object"){c0({...K, Line truncated
`).filter(Boolean),J=Q.slice(-Y);return{logFile:z,lines:J,totalLines:Q.length}}async function sS1($){let Y=yT($),z=Yo($),U=Aq($);OS0($.stateDir);let Q=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):RT),J=$.host??(process.env.HOST?process.env.HOST:_T);ST(Y,`${process.pid}
`,{mode:384}),ST(z,JSON.stringify({pid:process.pid,port:Q,host:J,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),yK(U,`service starting on http://${J}:${Q} pid=${process.pid}`);let I=null;try{I=await vT({port:Q,host:J,silent:!0}),yK(U,`service listening pid=${process.pid}`)}catch(G){if(yK(U,`service failed to bind port ${Q}: ${G instanceof Error?G.message:String(G)}`),gT(Y)===process.pid)v9(Y,{force:!0}),v9(z,{force:!0});throw G}let K=()=>{if(I)I.close(),I=null;if(gT(Y)===process.pid)v9(Y,{force:!0}),v9(z,{force:!0});yK(U,`stopped pid=${process.pid}`)};await new Promise((G)=>{let W=!1,H=()=>{if(W)return;W=!0,K(),process.off("SIGTERM",H),process.off("SIGINT",H),G()};process.once("SIGTERM",H),process.once("SIGINT",H)})}function FS0($){OS0($.stateDir);let Y=kK($);if(Y.running)return Y;let z=$.launcher??{command:process.execPath,args:[$.entryFile]},U=[...z.args??[],"service","run"];if($.port)U.push("--port",String($.port));if($.host)U.push("--host",String($.host));let Q=mS1(z.command,U,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});Q.unref();let J=yT($);return ST(J,`${Q.pid}
`,{mode:384}),yK(Aq($),`started pid=${Q.pid}`),{started:!0,...kK($)}}function wS0($,Y={}){let z=yT($),U=Yo($),Q=gT(z);if(!Q||!MS0(Q,$.appRoot))return v9(z,{force:!0}),v9(U,{force:!0}),Y.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(Q,"SIGTERM"),v9(z,{force:!0}),v9(U,{force:!0}),yK(Aq($),`stop requested pid=${Q}`),Y.quiet?void 0:{stopped:!0,pid:Q}}function MS0($,Y){if(!aS1($))return!1;try{let z=lS1("ps",["-p",String($),"-o","command="],{encoding:"utf8"}),U=z.trim().split(/\s+/).filter(Boolean),Q=U.indexOf("service"),J=Q!==-1&&U[Q+1]==="run",I=z.includes(Y)||U.some((K)=>/(^|[\\/])(seal-use|seal-home)(\.exe)?$/.test(K));return J&&I}catch{return!1}}function aS1($){try{return process.kill($,0),!0}catch{return!1}}function yT($){return $o($.stateDir,"service.pid")}function Yo($){return $o($.stateDir,"service.json")}function Aq($){return $o($.stateDir,"service.log")}function gT($){if(!hT($))return;let Y=Number(el($,"utf8").trim());return Number.isInteger(Y)&&Y>0?Y:void 0}function OS0($){oS1($,{recursive:!0,mode:448})}function yK($,Y){ST($,`${new Date().toISOString()} ${Y}
`,{flag:"a",mode:384})}var zo=o(()=>{sl()});import{homedir as tS1}from"node:os";import{join as eS1}from"node:path";async function Qo($,Y,z){let U=z?s0(z.options.port)??s0(z.options.p):void 0,Q=z?S(z.options.host)??S(z.options.h):void 0,J=z?s0(z.options.lines)??s0(z.options.n):void 0,I=await SU($,{appRoot:Y.appRoot,entryFile:Y.entryFile,stateDir:Uo,version:P1,launcher:Y.launcher,port:U,host:Q},{maxLines:J});if(I!==void 0)c0(I)}var Uo;var Jo=o(()=>{t9();zo();J4();D4();Uo=eS1(tS1(),".config","seal-use")});import{existsSync as $g1,readFileSync as NS0}from"node:fs";async function DS0($,Y,z,U,Q){if($==="batch-records"||$==="records"){let J=Y??S(Q.options.batchId)??S(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation batch-records <batchId>");await k0("seal_simulation_batch_records_get",z,U,{batchId:J,query:S(Q.options.query)},C0(Q.options));return}if($==="create"||$==="run"){let J=S(Q.options.mode)??S(Q.options.sourceSystem)??S(Q.options["source-system"])??"hosecloud",I=J==="material-pack"?"material_pack":J,K=S(Q.options.schemaConfig)??S(Q.options["schema-config"]),G=K?JSON.parse(NS0(K,"utf8")):void 0,W=S(Q.options.input),H=W?JSON.parse(NS0(W,"utf8")):y8(Q.json),X=S(Q.options.packageId)??S(Q.options["package-id"]),Z=u6(Q.options.packageIds)??u6(Q.options["package-ids"])??(X?[X]:void 0),q=u6(Q.options.flowIds)??u6(Q.options["flow-ids"])??u6(Q.options.documentSn)??u6(Q.options["document-sn"]),V=S(Q.options.signKey)??S(Q.options["sign-key"])??S(Q.options.integration),F=F0(Q.options.noWait)??F0(Q.options["no-wait"]);await k0("seal_simulation_batch_create",z,U,{mode:I,sourceSystem:I,flowIds:q,documentSn:q,rejectNodeName:S(Q.options.rejectNode)??S(Q.options["reject-node"])??null,thinkingDepthOverride:S(Q.options.thinkingDepth)??S(Q.options["thinking-depth"]),skipInvoiceGeneration:F0(Q.options.skipInvoiceGeneration)??F0(Q.options["skip-invoice-generation"]),skipExpenseExtraction:F0(Q.options.skipExpenseExtraction)??F0(Q.options["skip-expense-extraction"]),disableAttachmentCache:F0(Q.options.disableAttachmentCache)??F0(Q.options["disable-attachment-cache"]),signKey:V,packageIds:Z,packageId:X,templateId:S(Q.options.templateId)??S(Q.options["template-id"]),schemaConfig:G,requestIds:u6(Q.options.requestIds)??u6(Q.options["request-ids"]),workflowTypeId:S(Q.options.workflowTypeId)??S(Q.options["workflow-type-id"]),flowStatusList:u6(Q.options.flowStatusList)?.map(Number)??u6(Q.options["flow-status-list"])?.map(Number),businessCodes:u6(Q.options.businessCodes)??u6(Q.options["business-codes"]),documentType:S(Q.options.documentType)??S(Q.options["document-type"]),startTime:s0(Q.options.startTime)??s0(Q.options["start-time"]),endTime:s0(Q.options.endTime)??s0(Q.options["end-time"]),status:u6(Q.options.status),limit:s0(Q.options.limit),noWait:F,rawParams:H},C0(Q.options));return}if($==="wait"){let J=Y??S(Q.options.batchId)??S(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await k0("seal_simulation_batch_wait",z,U,{batchId:J,timeout:S(Q.options.timeout),pollInterval:S(Q.options.pollInterval)??S(Q.options["poll-interval"])},C0(Q.options));return}if($==="status"){let J=Y??S(Q.options.batchId)??S(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation status <batchId>");await k0("seal_simulation_batch_status",z,U,{batchId:J},C0(Q.options));return}if($==="clean"||$==="delete"){let J=Y??S(Q.options.batchId)??S(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation clean <batchId>");await k0("seal_simulation_batch_clean",z,U,{batchId:J},C0(Q.options));return}if($==="specifications"){let J=Y??S(Q.options.integration)??S(Q.options.signKey)??S(Q.options["sign-key"]);await k0("seal_simulation_specifications_list",z,U,{signKey:J},C0(Q.options));return}if($==="approval-definitions"||$==="definitions"){await k0("seal_simulation_feishu_approval_definitions_list",z,U,{},C0(Q.options));return}if($==="list"){await k0("seal_simulation_batches_list",z,U,{limit:s0(Q.options.limit)},C0(Q.options));return}if($==="get"){let J=Y??S(Q.options.batchId)??S(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation get <batchId>");await k0("seal_simulation_batch_get",z,U,{batchId:J},C0(Q.options));return}if($==="templates"){await k0("seal_simulation_templates_get",z,U,{},C0(Q.options));return}if($==="integrations"){await k0("seal_simulation_integrations_get",z,U,{},C0(Q.options));return}if($==="package-upload"){let J=Y??S(Q.options.file);if(!J)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!$g1(J))throw Error(`File not found: ${J}`);await k0("seal_simulation_material_package_upload",z,U,{filePath:J},C0(Q.options));return}throw Error(`Unknown simulation command: ${$??""}. Run 'seal-use help' for available commands.`)}var BS0=o(()=>{o4();D4();J4()});import{existsSync as PS0}from"node:fs";import{join as kT}from"node:path";function AS0($,Y,z){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${clLine truncated
`);return}if($==="install"||$==="init"||$==="sync"){let U=F0(z.options.local)||F0(z.options.workspace),Q=S(z.options.dir)??S(z.options.target)??Y,J=Q?Q:U?kT(process.cwd(),".agents","skills","seal-use"):hU(),I=hh0(J);c0({installed:!0,targetDir:I.targetDir,fileCount:I.files.length,files:I.files});return}if($==="status"||$==="get"||!$){let U=hU(),Q=kT(process.cwd(),".agents","skills","seal-use");c0({global:{dir:U,installed:PS0(kT(U,"SKILL.md"))},local:{dir:Q,installed:PS0(kT(Q,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${$}. Run 'seal-use help' for available commands.`)}var TS0=o(()=>{Dq();D4();J4()});async function jS0($,Y){if($==="config"){c0(await gK(Y));return}throw Error(`Unknown source command: ${$??""}. Run 'seal-use help' for available commands.`)}var ES0=o(()=>{DT();J4()});function Io($){if(typeof $!=="string"||!$.trim())return"UNKNOWN";let Y=$.toUpperCase().trim();if(Y==="APPROVE"||Y==="PASS")return"APPROVE";if(Y==="REJECT"||Y==="DENIED")return"REJECT";if(Y==="MANUAL"||Y==="ASSISTED")return"MANUAL";if(Y==="ERROR"||Y==="FAILED")return"ERROR";return Y}async function CS0($){let{sourceCorp:Y,targetCorp:z,sourceClient:U,targetClient:Q,samples:J=10,dryRun:I=!1,pollIntervalMs:K=2000,timeoutMs:G=45000,snPrefix:W="REG_",fetchFn:H=fetch}=$;if(z.environment!=="test")throw new w4(`重放目标企业「${z.name}」(${z.id}) 的环境为「${z.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${Y.id} <testCorpId>`);let X=await bY(Q),q=(Array.isArray(X.features)?X.features:[]).find((d)=>d?.code==="ai-approval"),V=typeof q?.balance==="number"?q.balance:0,F=typeof q?.deductionAmount==="number"&&q.deductionAmount>0?q.deductionAmount:120,M=J*F;if(V<M)throw new w4(`测试企业「${z.name}」AI 审批额度不足:当前剩余 ${V} 点,本次回归抽样 ${J} 笔需要约 ${M} 点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${z.id}」充值 AI 审批额度,或降低抽样笔数 (--samples ${Math.max(1,Math.floor(V/F))})`);let w=await b4(U,{limit:J,status:"completed"}),O=Array.isArray(w.records)?w.records:[];if(O.length===0){let d=await b4(U,{limit:J});O=Array.isArray(d.records)?d.records:[]}if(O.length===0)throw new w4(`在母企业「${Y.name}」(${Y.id}) 中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(O=O.slice(0,J),I){let d=O.map((t)=>{let $0=t.sourceDocumentSN??t.id,g=t?.result?.decision??t.aiDecision??t?.decision,p=Io(g),e=t?.result?.summary??t.aiSummary;return{sn:$0,sourceRecordId:t.id,prodDecision:p,prodSummary:e,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:z.id,name:z.name,environment:z.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:F,estimatedRequired:M},metrics:{sampleCount:d.length,successCount:d.length,failureCount:0,matchCount:d.length,flipCount:0,concordanceRate:1},flips:[],records:d}}let N=await Up(Q,z),D=[];for(let d of O){let t=Date.now(),$0=d.sourceDocumentSN??d.id,g=Io(d?.result?.decision??d.aiDecision??d?.decision),p=d?.result?.summary??d.aiSummary;try{let e=await G4(U,d.id),y=`${W}${$0}`,s=Yp(e,{snPrefix:W,docIdPrefix:W});await zp(N.incomingDocumentWebhook.url,N.secret,s,H,B6(z.seal));let Y0=null,M0=Date.now();while(Date.now()-M0<G){await new Promise((H0)=>setTimeout(H0,K));let a=await b4(Q,{sourceDocumentSN:y,limit:1});if(a.records&&a.records.length>0){let H0=a.records[0];if(H0.status==="completed"||H0.status==="failed"){Y0=H0;break}}}if(!Y0){D.push({sn:$0,sourceRecordId:d.id,prodDecision:g,prodSummary:p,status:"FAILED",error:`测试租户单据审核超时 (${Math.round(G/1000)}s 未完成)`,durationMs:Date.now()-t});continue}let E0=Io(Y0?.result?.decision??Y0.aiDecision??Y0?.decision??(Y0.status==="completed"?"APPROVE":"ERROR")),G0=Y0?.result?.summary??Y0.aiSummary,T0=g===E0,b0=T0?"MATCHED":"FLIPPED",Y1={sn:$0,sourceRecordId:d.id,prodDecision:g,prodSummary:p,testRecordId:Y0.id,testDecision:E0,testSummary:G0,status:b0,durationMs:Date.now()-t};if(!T0)Y1.diff={from:g,to:E0,reasonDiff:G0&&p&&G0!==p?`生产: ${p.slice(0,60)}... -> 测试: ${G0.slice(0,60)}...`:void 0};D.push(Y1)}catch(e){D.push({sn:$0,sourceRecordId:d.id,prodDecision:g,prodSummary:p,status:"FAILED",error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}let T=D.filter((d)=>d.status==="MATCHED"||d.status==="FLIPPED"),A=D.filter((d)=>d.status==="MATCHED"),B=D.filter((d)=>d.status==="FLIPPED"),j=D.filter((d)=>d.status==="FAILED").length,C=A.length,b=B.length,k=C+b,h=k>0?C/k:0,i=b>0,c=i?"REGRESSIONS_DETECTED":"CLEAN",U0=!i&&j===0,x;try{let d=await bY(Q),$0=(Array.isArray(d.features)?d.features:[]).find((g)=>g?.code==="ai-approval");if(typeof $0?.balance==="number")x=$0.balance}catch{}return{ok:!i&&j===0,verdict:c,safeToPublish:U0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:z.id,name:z.name,environment:z.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:F,estimatedRequired:M,balanceAfter:x},metrics:{sampleCount:D.length,successCount:T.length,failureCount:j,matchCount:C,flipCount:b,concordanceRate:Number(h.toFixed(4))},flips:B,records:D}}function RS0($){let{sourceCorp:Y,targetCorp:z,verdict:U,safeToPublish:Q,metrics:J,quota:I,flips:K,records:G}=$,W=U==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":U==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",H=["",`\uD83E\uDDEA [Seal Use Test] 规则回归测试矩阵: 生产「${Y.name}」-> 测试靶场「${z.name}」`,` 判定: ${W} · 准许发布: ${Q?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),` 样本总数: ${J.sampleCount} | 一致通过: ${J.matchCount} | 决策翻转: ${J.flipCount} | 异常失败: ${J.failureCount}`,` 一致率: ${(J.concordanceRate*100).toFixed(1)}% | 消耗预估: ${I.estimatedRequired} 点 (余量: ${I.balanceBefore}${I.balanceAfter!==void 0?` -> ${I.balanceAfter}`:""})`," "+"─".repeat(65)];if(K.length>0){H.push(` ⚠️ 决策翻转清单 (${K.length} 笔单据在新规则下结果改变):`);for(let X of K)if(H.push(` • 单据 [${X.sn}]: 原生产判定「${X.prodDecision}」 ➔ 测试新判定「${X.testDecision}」`),X.diff?.reasonDiff)H.push(` 理由差异: ${X.diff.reasonDiff}`);H.push(" "+"─".repeat(65)),H.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(U==="CLEAN")H.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100% 吻合,无任 Line truncated
`)}var _S0=o(()=>{L$();X6();RZ()});async function Ko($,Y,z){let U=($??Y??"regression").toLowerCase();if(U==="regression"||U==="regress"||U==="matrix"){let Q=S(z.options.corp)??(Y&&Y!==U?Y:void 0),J=E1(Q),I=J,K=J;if(J.environment==="test"){K=J;let O=S(z.options["prod-corp"])??S(z.options.prod)??J.prodCorpId;if(!O)throw new w4(`测试企业「${J.name}」(${J.id}) 未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-use corps bind-test <prodCorpId> ${J.id}`);I=E1(O)}else{I=J;let O=S(z.options["test-corp"])??S(z.options.test)??J.testCorpId;if(!O)throw new w4(`生产企业「${J.name}」(${J.id}) 未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${J.id} <testCorpId>`);K=E1(O)}let G=await j1(I),W=await j1(K),H=s0(z.options.samples)??s0(z.options.limit)??s0(z.options.n)??10,X=F0(z.options["dry-run"]),Z=F0(z.options["fail-on-flips"]),q=s0(z.options["poll-interval"])??2000,V=s0(z.options.timeout)??45000,F=S(z.options["sn-prefix"])??"REG_",M=await CS0({sourceCorp:I,targetCorp:K,sourceClient:G,targetClient:W,samples:H,dryRun:X,pollIntervalMs:q,timeoutMs:V,snPrefix:F,failOnFlips:Z});if(!(F0(z.options.quiet)||F0(z.options.silent)))console.error(RS0(M));if(c0(M),Z&&!M.ok)throw new w4(`回归测试发现 ${M.metrics.flipCount} 笔单据决策翻转,已按 --fail-on-flips 策略非零终止。`,1);return}throw new w4(`未知的 test 子命令: "${U}"。
可用子命令: seal-use test regression [--corp <id>] [--samples <N>] [--dry-run]`,2,"seal-use test regression --help")}var vS0=o(()=>{L$();o4();D4();J4();i8();_S0()});async function hS0($,Y,z,U){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await k0($,Y,z,y8(U.json),C0(U.options))}var SS0=o(()=>{o4();D4();J4()});function gS0(){c0(Hq.map(($)=>({name:$.name,description:$.description})))}var yS0=o(()=>{Zq();J4()});function xT($=process.execPath,Y=import.meta.url){if(Y.includes("/$bunfs/")||Y.includes("\\$bunfs\\"))return!0;let z=$.toLowerCase().replace(/\\/g,"/");return!z.endsWith("/bun")&&!z.endsWith("/bun.exe")&&!z.endsWith("/node")&&!z.endsWith("/node.exe")}var kS0=o(()=>{Dq()});import{chmodSync as Yg1,mkdirSync as zg1,readdirSync as Ug1,renameSync as Go,rmSync as Qg1,unlinkSync as bS0,writeFileSync as xS0}from"node:fs";import{basename as Jg1,dirname as Ig1,join as uT}from"node:path";import{spawnSync as xK}from"node:child_process";async function cS0($,Y={}){let z={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:Uo,version:P1,launcher:$.launcher},U=Y.repo||process.env[Kg1]?.trim()||process.env[Gg1]?.trim()||iS0,Q=Y.targetVersion?.trim(),J=Q&&Q.toLowerCase()!=="latest"?Q:void 0;if(J){let D=J.replace(/^v/,""),T=mS0(D,P1);if(T<0)if(!gS&&Y.force);else{c0({updated:!1,currentVersion:P1,targetVersion:D,mode:xT()?"binary":"source",message:!gS?`Cannot downgrade seal-use from dev build v${P1} to release v${D}. Use --force to overwrite.`:`Cannot downgrade seal-use from v${P1} to older version v${D}. Updates must be forward-only.`});return}if(T===0&&!Y.force){c0({updated:!1,currentVersion:P1,targetVersion:D,mode:xT()?"binary":"source",message:`seal-use is already at version v${P1}. Use --force to reinstall.`});return}}if(Y.changelogOnly){let D=await Wo(U,Y.limit??10);c0({currentVersion:P1,totalQueried:D.length,releases:D.map((T)=>({version:T.version,tagName:T.tagName,publishedAt:T.publishedAt,author:T.author,releaseNotes:T.notes,releaseUrl:T.htmlUrl,isCurrent:T.version===P1,isNewer:Tq(T.version,P1)}))});return}if(!xT()){if(Y.checkOnly){let T=await Wo(U,30),A=T[0],B=A?.version??P1,j=T.find((k)=>k.version===P1),C=Tq(B,P1),b=T.filter((k)=>Tq(k.version,P1));c0({updated:!1,updateAvailable:C,currentVersion:P1,currentVersionPublishedAt:j?.publishedAt,latestVersion:B,latestVersionPublishedAt:A?.publishedAt,behindCount:b.length,pendingReleases:b.map((k)=>({version:k.version,tagName:k.tagName,publishedAt:k.publishedAt,author:k.author,releaseNotes:k.notes,releaseUrl:k.htmlUrl})),releaseNotes:A?.notes??"",releaseUrl:A?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let D=kK(z).running;if(D)await SU("stop",z);try{uS0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(T){console.error(`git pull skipped: ${T instanceof Error?T.message:String(T)}`)}if(uS0("bun",["install"],{cwd:$.appRoot}),D)await SU("start",z);c0({updated:!0,serviceRestarted:D,version:P1,mode:"source"});return}let I=Hg1(),K=Xg1(),G=await Wo(U,30),W=J?G.find((D)=>D.version===J||D.tagName===J||D.tagName===`v${J}`)??await fS0(U,J):G[0]??await fS0(U);if(!W){c0({updated:!1,currentVersion:P1,mode:"binary",message:`Failed to query releases from repository '${U}'`});return}let H=W.version,X=G.find((D)=>D.version===P1),Z=Tq(H,P1),q=Z||Boolean(Y.force),V=G.filter((D)=>Tq(D.version,P1));if(Y.checkOnly){c0({updated:!1,updateAvailable:Z,currentVersion:P1,currentVersionPublishedAt:X?.publishedAt,latestVersion:H,latestVersionPublishedAt:W.publishedAt,behindCount:V.length,pendingReleases:V.map((D)=>({version:D.version,tagName:D.tagName,publishedAt:D.publishedAt,author:D.author,releaseNotes:D.notes,releaseUrl:D.htmlUrl})),releaseNotes:W.notes,releaseUrl:W.htmlUrl,mode:"binary"});return}if(!q){c0({updated:!1,currentVersion:P1,currentVersionPublishedAt:X?.publishedAt,latestVersion:H,latestVersionPublishedAt:W.publishedAt,mode:"binary",message:`seal-use is already up to date (v${P1})`});return}let F=qg1(W.assets,I,K);if(!F)throw Error(`No compatible binary found for ${I}-${K} in release v${H}. Available assets: ${W.assets.map((D)=>D.name).join(", ")}`);let M=kK(z).running;if(M)await SU("stop",z);let w=process.execPath,O=Ig1(w),N=uT(O,`.tmp-update-${Date.now()}`);zg1(N,{recursive:!0});try{let D=uT(N,F.name);await Vg1(F.downloadUrl,D,W.tagName,F.name);let T=D;if(F.name.endsWith(".tar.gz")||F.name.endsWith(".tgz"))T=Lg1(D,N,I);else if(F.name.endsWith(".zip"))T=Fg1(D,N,I);if(Yg1(T,493),process.platform==="darwin")try{xK("/usr/bin/codesign",["--remove-signature",T],{stdio:"ignore"}),xK("/usr/bin/codesign",["--force","--sign","-",T],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let B=`${w}.old.${Date.now()}`;try{Go(w,B)}catch{}Go(T,w)}else Go(T,w);if(M)await SU("start",z);let A=Wg1(w,H);c0({updated:!0,fromVersion:P1,toVersion:H,serviceRestarted:M,skillSynced:A.targetDir??!1,skillVersion:A.version??!1,mode:"binary"})}finally{try{Qg1(N,{recursive:!0,force:!0})}catch{}}}function Line truncated
`)}catch{}}async function Vg1($,Y,z,U){let Q=Ho(),J=[],I=z?z.startsWith("v")?z:`v${z}`:void 0,K=U||$.split("/").pop()||"";if(Q!=="github"){if(I&&K)J.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${I}/${K}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${I}/${K}`);if($.startsWith("https://git.ying-qing.cn"))J.push($)}if(Q!=="gitea")if(I&&K){let F=`https://github.com/${iS0}/releases/download/${I}/${K}`;if(!process.env.CI)J.push(`https://ghfast.top/${F}`,`https://gh.ddlc.top/${F}`);J.push(F)}else if($.includes("github.com")){if(!process.env.CI)J.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);J.push($)}else J.push($);let G=Array.from(new Set(J)),W,H=6000,X=6000,Z=307200,q=1e4,V=180000;for(let F=0;F<G.length;F++){let M=G[F],w=new AbortController,O="",N=(B)=>{O=B;try{w.abort()}catch{}},D=setTimeout(()=>{N("Connection timed out (no response headers within 6s)")},H),T,A;try{fT(`==> [${F+1}/${G.length}] Downloading via: ${M}`);let B=await fetch(M,{signal:w.signal});if(D)clearTimeout(D),D=void 0;if(!B.ok)throw Error(`HTTP ${B.status} ${B.statusText}`);T=setTimeout(()=>{N("Overall download time exceeded 3 minutes")},V);let j=Number(B.headers.get("content-length"))||0,C=B.body?.getReader();if(!C){let c=Buffer.from(await B.arrayBuffer());if(c.length<1000)throw Error(`Downloaded content is suspiciously small (${c.length} bytes)`);xS0(Y,c),fT(`✓ Download succeeded (${(c.length/1024/1024).toFixed(1)} MB)`);return}let b=[],k=0,h=0;A=setTimeout(()=>{if(k<Z){let c=(k/1024).toFixed(1);N(`Initial transfer too slow (${c} KB < 300 KB in 6s), switching mirror...`)}},X);while(!0){let c=C.read(),U0,x=new Promise((g,p)=>{U0=setTimeout(()=>{p(Error("Data transfer stalled (no chunk received for 10s)"))},q)}),d;try{d=await Promise.race([c,x])}finally{if(U0)clearTimeout(U0)}let{done:t,value:$0}=d;if(t)break;if($0){if(b.push($0),k+=$0.length,A&&k>=Z)clearTimeout(A),A=void 0;let g=Date.now();if(g-h>200){h=g;let p=j?Math.round(k/j*100):0,e=(k/1048576).toFixed(1),y=j?(j/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${p}% (${e} / ${y} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let i=Buffer.concat(b);if(i.length<1000)throw Error(`Downloaded content is suspiciously small (${i.length} bytes)`);xS0(Y,i),fT(`✓ Download completed successfully (${(i.length/1024/1024).toFixed(1)} MB)`);return}catch(B){if(D)clearTimeout(D);if(A)clearTimeout(A);if(T)clearTimeout(T);let j=O||(B instanceof Error?B.message:String(B));W=Error(j),fT(`
↳ Mirror failed: ${W.message}`)}finally{if(D)clearTimeout(D);if(A)clearTimeout(A);if(T)clearTimeout(T)}}throw Error(`Failed to download asset from all mirrors: ${W?.message}`)}function pS0($){let Y;try{Y=Ug1($,{withFileTypes:!0})}catch{return[]}let z=[];for(let U of Y){let Q=uT($,U.name);if(U.isDirectory())z.push(...pS0(Q));else if(U.isFile())z.push(Q)}return z}function dS0($,Y,z){let U=Y==="windows"?"seal-use.exe":"seal-use",Q=pS0($);return Q.find((J)=>Jg1(J)===U)??Q[0]??z}function Lg1($,Y,z){let U=xK("tar",["-xzf",$,"-C",Y],{stdio:"pipe"});if(U.status!==0)throw Error(`Failed to extract tar archive: ${U.stderr.toString()}`);return bS0($),dS0(Y,z,$)}function Fg1($,Y,z){let U=xK("unzip",["-q","-o",$,"-d",Y],{stdio:"pipe"});if(U.status!==0)throw Error(`Failed to extract zip archive: ${U.stderr.toString()}`);return bS0($),dS0(Y,z,$)}function mS0($,Y){let z=$.replace(/^v/,"").split(".").map((Q)=>Number.parseInt(Q,10)||0),U=Y.replace(/^v/,"").split(".").map((Q)=>Number.parseInt(Q,10)||0);for(let Q=0;Q<Math.max(z.length,U.length);Q++){let J=z[Q]??0,I=U[Q]??0;if(J>I)return 1;if(J<I)return-1}return 0}function Tq($,Y){return mS0($,Y)>0}function uS0($,Y,z={}){let U=xK($,Y,{cwd:z.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(`${$} ${Y.join(" ")} failed with status ${U.status}`)}var iS0="yunyingk/seal-use",jq="yunyingk/seal-home",Kg1="SEAL_USE_GITHUB_REPO",Gg1="SEAL_HOME_GITHUB_REPO";var lS0=o(()=>{kS0();Dq();t9();zo();J4();Jo()});async function oS0($,Y,z,U,Q){if($==="create"){let J=S(Q.options.name)??Y,I=S(Q.options.phone);if(!J||!I)throw Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");let K=S(Q.options.dept)??S(Q.options.departmentId);await k0("seal_user_create",z,U,{name:J,phone:I,departmentIds:K?[K]:void 0},C0(Q.options));return}if($==="reset-password"){let J=Y??S(Q.options.userId);if(!J)throw Error("Usage: seal-use users reset-password <userId>");await k0("seal_user_reset_password",z,U,{userId:J},C0(Q.options));return}if($==="search"||$==="list"){let J=Y??S(Q.options.keyword)??S(Q.options.query)??"";await k0("seal_user_search",z,U,{keyword:J},C0(Q.options));return}if($==="get"){let J=Y??S(Q.options.userId);if(!J)throw Error("Usage: seal-use users get <userId>");await k0("seal_user_get",z,U,{userId:J},C0(Q.options));return}if($==="delete"){let J=Y??S(Q.options.userId);if(!J)throw Error("Usage: seal-use users delete <userId>");await k0("seal_user_delete",z,U,{userId:J},C0(Q.options));return}if($==="activate"){let J=Y??S(Q.options.userId);if(!J)throw Error("Usage: seal-use users activate <userId>");await k0("seal_user_activate",z,U,{userId:J},C0(Q.options));return}if($==="delegation"||$==="impersonate"){let J=Y??S(Q.options.userId)??S(Q.options.phone);if(!J)throw Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");let I=S(Q.options.note);await k0("seal_user_delegation_create",z,U,{userIdOrPhone:J,note:I},C0(Q.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}var rS0=o(()=>{o4();D4();J4()});import{dirname as Xo,join as wg1}from"node:path";import{fileURLToPath as Mg1}from"node:url";function Dg1($){if(!$.length)return!1;let Y=$[0]?.toLowerCase(),z=$[1]?.toLowerCase();if(Y&&Ng1.has(Y))return!0;if((Y==="service"||Y==="daemon")&&z==="run")return!0;return!1}function Pq($,Y={}){if(Dg1($))return tS0($,Y);let z=aS0.then(()=>tS0($,Y));return aS0=z.then(()=>{return},()=>{return}),z}async function tS0($,Y){let z=[],U=[],Q=console.log,J=console.error,I={appRoot:Y.appRoot??sS0,entryFile:Y.entryFile??wg1(Y.appRoot??sS0,"src","cli.ts"),launcher:Y.launcher};console.log=(...K)=>{z.push(Pl(K))},console.error=(...K)=>{U.push(Pl(K))};try{return await Bg1($,I),{stdout:Vq(z),stderr:Vq(U),isError:!1,exitCode:0}}catch(K){let G=Lq(K instanceof Error?K.message:String(K)),W=CZ(K);if(U.push(G),W.nextAction&&!G.includes("Next action:"))U.push(`\uD83D\uDC49 Next action: ${W.nextAction}`);return{stdout:Vq(z),stderr:Vq(U),isError:!0,exitCode:W.exitCode}}finally{console.log=Q,console.error=J}}async function Bg1($,Y){let z=qq($),[U,Q,J]=z.command;if(U==="version"||U==="v"||Boolean(z.options.version)||Boolean(z.options.v)||Boolean(z.options.V)){c0(PW);return}let I=rR0(z);if(I.isHelp){eR0(I.target);return}if(!U||!Og1.has(U))throw Error(`Unknown command: ${z.command.join(" ")}. Run 'seal-use help' for available commands.`);if(U==="webhook"&&(Q==="resource-pack"||Q==="pack"||Q==="material-pack")&&J==="preview"){let W=z.command[3]??S(z.options.file)??S(z.options.input);if(!W)throw Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");await z_0(W,vK(z.options));return}if(U==="openapi"){QS0(z);return}if(U==="mcp-config"){al();return}if(U==="skill"){AS0(Q,J,z);return}if(U==="mcp"||U==="server"){await $S0(Q,z);return}if(U==="probe"){await qS0(Q,J,z);return}if(U==="doctor"){await ih0(Q,J,z);return Line truncated
`)?"":`
`}`);process.exitCode=$.exitCode}var Gb1=Boolean(d.main==d.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&Dg0(process.argv[1])===Dg0(X3));if(Gb1)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await Hb1();else Kd().catch(($)=>{console.error($),process.exitCode=1});export{Jd as tokenizeCommand,Kd as startServer,Jb1 as resolveMcpEnabled,Qb1 as createServer,Ub1 as SEAL_MCP_ENABLED_ENV,qb1 as SEAL_CLI_TOOL_NAME,Yb1 as LEGACY_SEAL_MCP_ENABLED_ENV};
`}`);process.exitCode=$.exitCode}var m7,Ug0,bT="seal_cli",Rq="seal_cli_write",Qg0="SEAL_USE_MCP_ENABLED",Jg0="SEAL_HOME_MCP_ENABLED",Rg1;var US0=o(async()=>{He();qe();B$();rl();$g0();L$();t9();m7=Eg1(import.meta.url),Ug0=m7.includes("/dist/mcp/")||m7.includes("\\dist\\mcp\\")?Eq(Eq(Eq(m7))):Eq(Eq(m7));Rg1=Boolean(I0.main==I0.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&Yg0(process.argv[1])===Yg0(m7));if(Rg1)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await Cg1();else try{Gg0()}catch($){console.error($),process.exitCode=1}});await US0();export{Bq as tokenizeCommand,Gg0 as startServer,Ig0 as resolveMcpEnabled,Kg0 as createServer,Qg0 as SEAL_MCP_ENABLED_ENV,Rq as SEAL_CLI_WRITE_TOOL_NAME,bT as SEAL_CLI_TOOL_NAME,Jg0 as LEGACY_SEAL_MCP_ENABLED_ENV};
+274 -4
View File
@@ -2,13 +2,13 @@
"openapi": "3.1.0",
"info": {
"title": "seal-use Wrapped API",
"version": "0.10.22",
"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"
"version": "0.10.26",
"description": "HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n"
},
"servers": [
{
"url": "http://localhost:8787",
"description": "Reserved for a future local HTTP adapter; the current service uses MCP stdio."
"description": "Local HTTP adapter (`seal-use http`, or the `seal-use service start` daemon). Loopback-only by default."
}
],
"security": [
@@ -49,6 +49,7 @@
"Corps"
],
"operationId": "listCorps",
"x-implementation-status": "implemented",
"summary": "List configured enterprises",
"responses": {
"200": {
@@ -98,6 +99,7 @@
"Corps"
],
"operationId": "getCurrentCorp",
"x-implementation-status": "planned",
"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": {
@@ -145,6 +147,7 @@
"Corps"
],
"operationId": "switchCurrentCorp",
"x-implementation-status": "planned",
"summary": "Switch current enterprise",
"requestBody": {
"required": true,
@@ -223,6 +226,7 @@
"Source"
],
"operationId": "getSourceConfig",
"x-implementation-status": "planned",
"summary": "Resolve source-derived Seal enterprise config",
"parameters": [
{
@@ -279,6 +283,7 @@
"Auth"
],
"operationId": "diagnoseAuth",
"x-implementation-status": "planned",
"summary": "Diagnose wrapped source-to-Seal authentication",
"parameters": [
{
@@ -321,6 +326,7 @@
"Auth"
],
"operationId": "whoami",
"x-implementation-status": "implemented",
"summary": "Get current wrapped Seal identity",
"parameters": [
{
@@ -387,6 +393,7 @@
"Auth"
],
"operationId": "getSession",
"x-implementation-status": "implemented",
"summary": "Get current wrapped Seal session metadata",
"parameters": [
{
@@ -455,6 +462,7 @@
"Approval Knowledge"
],
"operationId": "getApprovalContext",
"x-implementation-status": "planned",
"summary": "Get rules, documents, and style preferences together",
"parameters": [
{
@@ -518,6 +526,7 @@
"Approval Knowledge"
],
"operationId": "searchApprovalKnowledge",
"x-implementation-status": "planned",
"summary": "Search approval rules, documents, and preferences",
"requestBody": {
"required": true,
@@ -583,6 +592,7 @@
"Approval Knowledge"
],
"operationId": "listApprovalRules",
"x-implementation-status": "implemented",
"summary": "List current draft approval rules",
"responses": {
"200": {
@@ -616,6 +626,7 @@
"Approval Knowledge"
],
"operationId": "createApprovalRule",
"x-implementation-status": "planned",
"summary": "Create draft approval rule",
"requestBody": {
"required": true,
@@ -708,6 +719,7 @@
"Approval Knowledge"
],
"operationId": "updateApprovalRule",
"x-implementation-status": "planned",
"summary": "Update draft approval rule",
"requestBody": {
"required": true,
@@ -783,6 +795,7 @@
"Approval Knowledge"
],
"operationId": "deleteApprovalRule",
"x-implementation-status": "planned",
"summary": "Delete draft approval rule",
"responses": {
"200": {
@@ -797,6 +810,7 @@
"Approval Knowledge"
],
"operationId": "listApprovalRuleVersions",
"x-implementation-status": "planned",
"summary": "List published approval rule versions",
"responses": {
"200": {
@@ -860,6 +874,7 @@
"Approval Knowledge"
],
"operationId": "getApprovalRuleVersion",
"x-implementation-status": "planned",
"summary": "Get published approval rule version",
"responses": {
"200": {
@@ -909,6 +924,7 @@
"Approval Knowledge"
],
"operationId": "getApprovalRuleByVersion",
"x-implementation-status": "planned",
"summary": "Get one wrapped rule from a published version",
"parameters": [
{
@@ -986,6 +1002,7 @@
"Approval Knowledge"
],
"operationId": "publishApprovalRuleVersion",
"x-implementation-status": "planned",
"summary": "Publish current draft rules",
"requestBody": {
"required": true,
@@ -1026,6 +1043,7 @@
"Approval Knowledge"
],
"operationId": "listApprovalDocuments",
"x-implementation-status": "planned",
"summary": "List approval knowledge documents",
"parameters": [
{
@@ -1092,6 +1110,7 @@
"Approval Knowledge"
],
"operationId": "createApprovalDocument",
"x-implementation-status": "planned",
"summary": "Create approval knowledge document",
"requestBody": {
"required": true,
@@ -1210,6 +1229,7 @@
"Approval Knowledge"
],
"operationId": "getApprovalDocument",
"x-implementation-status": "planned",
"summary": "Get approval knowledge document",
"responses": {
"200": {
@@ -1271,6 +1291,7 @@
"Approval Knowledge"
],
"operationId": "updateApprovalDocument",
"x-implementation-status": "planned",
"summary": "Update approval knowledge document",
"requestBody": {
"required": true,
@@ -1375,6 +1396,7 @@
"Approval Knowledge"
],
"operationId": "deleteApprovalDocument",
"x-implementation-status": "planned",
"summary": "Delete approval knowledge document",
"responses": {
"200": {
@@ -1389,6 +1411,7 @@
"Approval Knowledge"
],
"operationId": "getApprovalStylePreferences",
"x-implementation-status": "planned",
"summary": "Get approval style preferences",
"responses": {
"200": {
@@ -1438,6 +1461,7 @@
"Approval Knowledge"
],
"operationId": "updateApprovalStylePreferences",
"x-implementation-status": "planned",
"summary": "Update approval style preferences",
"requestBody": {
"required": true,
@@ -1523,12 +1547,165 @@
}
}
},
"/v1/preferences": {
"get": {
"tags": [
"Approval Knowledge"
],
"operationId": "getPreferences",
"x-implementation-status": "implemented",
"summary": "Get current decision, thinking-depth and rule-version preferences",
"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": "Decision preferences, thinking depth preference and the bound rule set version.",
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": true,
"properties": {
"tone": {
"type": "string"
},
"language": {
"type": "string"
},
"detailLevel": {
"type": "string"
},
"outputFormat": {
"type": "string"
},
"examples": {
"type": "array",
"items": {
"type": "string"
}
},
"prohibitedPhrases": {
"type": "array",
"items": {
"type": "string"
}
},
"customInstructions": {
"type": "string"
}
}
}
}
}
}
}
}
},
"/v1/preferences/decision": {
"post": {
"tags": [
"Approval Knowledge"
],
"operationId": "updatePreferenceDecision",
"x-implementation-status": "implemented",
"summary": "Update decision preferences (takes effect immediately for the running approval agent)",
"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."
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"explicitApprove": {
"type": "string"
},
"explicitReject": {
"type": "string"
},
"exemptApprove": {
"type": "string"
},
"review": {
"type": "string"
},
"dryRun": {
"type": "boolean",
"description": "Return the before/after diff without writing."
}
}
}
}
}
},
"responses": {
"200": {
"description": "Updated preferences, or the previewed diff when dryRun is set.",
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": true,
"properties": {
"tone": {
"type": "string"
},
"language": {
"type": "string"
},
"detailLevel": {
"type": "string"
},
"outputFormat": {
"type": "string"
},
"examples": {
"type": "array",
"items": {
"type": "string"
}
},
"prohibitedPhrases": {
"type": "array",
"items": {
"type": "string"
}
},
"customInstructions": {
"type": "string"
}
}
}
}
}
}
}
}
},
"/v1/approval-runs": {
"get": {
"tags": [
"Approval Runs"
],
"operationId": "searchApprovalRuns",
"x-implementation-status": "implemented",
"summary": "Search wrapped approval run history",
"parameters": [
{
@@ -1690,6 +1867,7 @@
"Approval Runs"
],
"operationId": "summarizeApprovalRuns",
"x-implementation-status": "implemented",
"summary": "Summarize approval runs by local date",
"parameters": [
{
@@ -1780,12 +1958,88 @@
}
}
},
"/v1/approval-runs/stats": {
"get": {
"tags": [
"Approval Runs"
],
"operationId": "statApprovalRuns",
"x-implementation-status": "implemented",
"summary": "Aggregate approval run counts by status and source system",
"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."
},
{
"name": "since",
"in": "query",
"schema": {
"type": "string"
},
"description": "Time window such as 3months, 7days or 24hours."
},
{
"name": "dedupeBy",
"in": "query",
"schema": {
"type": "string",
"enum": [
"sourceDocumentSN",
"sourceDocumentId",
"id"
],
"default": "sourceDocumentSN"
},
"description": "Field used to count distinct business documents."
},
{
"name": "status",
"in": "query",
"schema": {
"type": "string"
}
},
{
"name": "sourceSystem",
"in": "query",
"schema": {
"type": "string"
}
},
{
"name": "taskMode",
"in": "query",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Counts grouped by status and source system, plus the deduplicated total.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/v1/approval-runs/pick": {
"get": {
"tags": [
"Approval Runs"
],
"operationId": "pickApprovalRuns",
"x-implementation-status": "implemented",
"summary": "Pick likely approval runs by document number or trace key",
"parameters": [
{
@@ -1872,6 +2126,7 @@
"Approval Runs"
],
"operationId": "getApprovalRunLangfuseBridge",
"x-implementation-status": "planned",
"summary": "Resolve approval runs to Langfuse trace or session hints",
"parameters": [
{
@@ -1950,6 +2205,7 @@
"Approval Runs"
],
"operationId": "getApprovalRunUrl",
"x-implementation-status": "implemented",
"summary": "Get enterprise assist URL and optional source document URL",
"parameters": [
{
@@ -2031,6 +2287,7 @@
"Approval Runs"
],
"operationId": "getApprovalRun",
"x-implementation-status": "implemented",
"summary": "Get wrapped approval run detail",
"parameters": [
{
@@ -2081,6 +2338,7 @@
"Approval Runs"
],
"operationId": "getApprovalRunCitedRules",
"x-implementation-status": "implemented",
"summary": "Extract rules cited or matched by the AI result",
"responses": {
"200": {
@@ -2114,6 +2372,7 @@
"Approval Runs"
],
"operationId": "getApprovalRunDocumentSummary",
"x-implementation-status": "implemented",
"summary": "Get key document fields and compact AI/manual result",
"responses": {
"200": {
@@ -2147,6 +2406,7 @@
"Approval Runs"
],
"operationId": "getApprovalRunAttachments",
"x-implementation-status": "implemented",
"summary": "List compact attachment metadata",
"parameters": [
{
@@ -2189,6 +2449,7 @@
"Approval Runs"
],
"operationId": "getApprovalRunResult",
"x-implementation-status": "implemented",
"summary": "Get AI result, optionally as a compact summary",
"parameters": [
{
@@ -2220,6 +2481,7 @@
"Simulation"
],
"operationId": "createSimulationBatch",
"x-implementation-status": "implemented",
"summary": "Create a simulation batch",
"requestBody": {
"required": true,
@@ -2253,6 +2515,7 @@
"Simulation"
],
"operationId": "createMaterialPackBatch",
"x-implementation-status": "planned",
"summary": "Create a material pack simulation batch",
"requestBody": {
"required": true,
@@ -2286,6 +2549,7 @@
"Simulation"
],
"operationId": "listSimulationBatches",
"x-implementation-status": "implemented",
"summary": "List simulation batches",
"parameters": [
{
@@ -2332,6 +2596,7 @@
"Simulation"
],
"operationId": "getSimulationBatch",
"x-implementation-status": "implemented",
"summary": "Get a simulation batch detail including echoed create params",
"responses": {
"200": {
@@ -2365,6 +2630,7 @@
"Simulation"
],
"operationId": "getSimulationBatchRecords",
"x-implementation-status": "planned",
"summary": "Get wrapped simulation batch records",
"parameters": [
{
@@ -2397,6 +2663,7 @@
"Simulation"
],
"operationId": "listSimulationTemplates",
"x-implementation-status": "planned",
"summary": "List simulation test templates",
"responses": {
"200": {
@@ -2422,6 +2689,7 @@
"Simulation"
],
"operationId": "getSimulationIntegrationStatus",
"x-implementation-status": "planned",
"summary": "Get available source integration status for simulation",
"responses": {
"200": {
@@ -2444,6 +2712,7 @@
"Simulation"
],
"operationId": "listSimulationHosecloudIntegrations",
"x-implementation-status": "planned",
"summary": "List hosecloud source integrations available for simulation",
"responses": {
"200": {
@@ -2469,6 +2738,7 @@
"Simulation"
],
"operationId": "uploadMaterialPackage",
"x-implementation-status": "planned",
"summary": "Upload a material package ZIP for simulation",
"requestBody": {
"required": true,
@@ -2508,7 +2778,7 @@
"type": "apiKey",
"in": "header",
"name": "X-Seal-Home-Session",
"description": "Optional local service session header for future HTTP deployments."
"description": "Reserved header. The local adapter does not currently authenticate requests: it acts with\nthe credentials already stored on this machine for the selected enterprise. Keep it bound\nto loopback (`--host 127.0.0.1`) and do not expose the port to a network or an origin you\ndo not control.\n"
}
},
"parameters": {
@@ -152,6 +152,6 @@ seal-home/ # 仓库根即插件根
## 7. 风险与注意
- **cli.ts 抽离是最大改动面**:1441 行的 bin 入口重构需保证零行为变化,以 `cli.test.ts` + 手工冒烟为准。
- **node target bundle 可行性未验证**:`@modelcontextprotocol/sdk` 为纯 JS、ky/zod 通用,预期可行;失败则退 bun target,不影响整体设计。
- **插件根变量名**:`${CLAUDE_PLUGIN_ROOT}` 是 Claude 生态约定,ZCode 是否沿用需以本机实测为准。
- **[已结案] node target bundle 可行性**:`bun build src/server.ts --target=node` 曾产出**无法启动**的 bundle(`TypeError: ... is not a constructor`)。根因是 zod 的类初始化顺序被 `server.ts ↔ cli/runner ↔ cli/commands/mcp` 与 `http/routes` 两条循环依赖打乱;已通过 `tokenizeCommand` 下沉到 `src/cli/tokenize.ts`、`mcp` 命令改为惰性导入 server 修复,并新增 `packaged MCP bundle` 测试守护。注意:改用 bun target 并不能绕过(实测同样失败),`--compile` 亦同。
- **[已结案] 插件根变量名**:实测 ZCode 解析器把 `${CLAUDE_PLUGIN_ROOT}` 与 `${ZCODE_PLUGIN_ROOT}` 视为同一别名(均取 `loaded.rootPath`),`${user_config.*}` 亦受支持且缺失时回退 manifest 的 `default`。`.mcp.json` 已改用 ZCode 原生名。
- **workspace skill 来源变更**:迁移后开发期 workspace 的 seal-home skill 来自符号链接,若 ZCode 不支持链接目录,改用副本并接受双份维护(以 §4 T4 的验证结果为准)。
+40
View File
@@ -0,0 +1,40 @@
# `linters/` — local custom rule linters (intentionally untracked)
`seal-use rules lint` resolves custom linters from two directories, in this order
(`src/domains/seal/linter/loader.ts`):
1. `<cwd>/linters/` — **this directory**, relative to the working directory the CLI runs in
2. `~/.config/seal-use/linters/`
`<cwd>/linters/` is gitignored (all of it except this file), so a fresh clone has no custom
linters and `rules lint` silently falls back to the official ones. Only this README is tracked,
to record the convention.
## Conventions
- One linter per file, named `<name>.ts`, `<name>.js` or `<name>.mjs`. The basename is the
linter name used by `seal-use rules lint --linter <name>`.
- The official linters occupy `~/.config/seal-use/linters/official/`, which is **excluded** from
custom-linter discovery and rewritten on every load. Never put custom code there; put it
directly in `linters/` or in `~/.config/seal-use/linters/`.
- Prefer `~/.config/seal-use/linters/` for linters you want available from every directory: this
directory only applies when the CLI happens to be started from the repository root.
## Module shape
```ts
import type { RuleLintTarget, RuleLintResult } from "…";
export default function myLinter(rule: RuleLintTarget): RuleLintResult {
// …
}
```
`default`, `lintRule`, `linter` and `lint` are all accepted exports, and each is wrapped so a
throwing linter degrades to a reported error rather than aborting the run.
## Trust boundary
A custom linter is **imported and executed in the CLI process**, with the CLI's filesystem access
and the enterprise credentials it holds. Treat these files as code you trust: never drop an
unreviewed linter here, and never point the CLI's working directory at an untrusted checkout.
+22 -8
View File
@@ -1,17 +1,27 @@
openapi: 3.1.0
info:
title: seal-use Wrapped API
version: 0.10.22
version: 0.10.26
description: |
Planned HTTP contract for the seal-use wrapped backend API.
HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter
(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).
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.
These endpoints describe the stable wrapped API for frontend developers and agents. They are
not the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,
source authentication, response compaction, and diagnostics-friendly fields.
Every operation declares `x-implementation-status`, so a caller can tell what the running
adapter actually serves:
- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`
fails when an `implemented` operation has no matching route.
- `planned` — contract-only, designed but not routed yet. Calling it returns 404.
The same capabilities are reachable through the CLI, and through the optional MCP server when
it is enabled.
servers:
- url: http://localhost:8787
description: Reserved for a future local HTTP adapter; the current service uses MCP stdio.
description: Local HTTP adapter (`seal-use http`, or the `seal-use service start` daemon). Loopback-only by default.
security:
- localSession: []
tags:
@@ -35,7 +45,11 @@ components:
type: apiKey
in: header
name: X-Seal-Home-Session
description: Optional local service session header for future HTTP deployments.
description: |
Reserved header. The local adapter does not currently authenticate requests: it acts with
the credentials already stored on this machine for the selected enterprise. Keep it bound
to loopback (`--host 127.0.0.1`) and do not expose the port to a network or an origin you
do not control.
parameters:
$ref: ./components/parameters.yaml
responses:
+65
View File
@@ -3,6 +3,7 @@ paths:
get:
tags: [Approval Knowledge]
operationId: getApprovalContext
x-implementation-status: planned
summary: Get rules, documents, and style preferences together
parameters:
- $ref: ../components/parameters.yaml#/CorpId
@@ -30,6 +31,7 @@ paths:
post:
tags: [Approval Knowledge]
operationId: searchApprovalKnowledge
x-implementation-status: planned
summary: Search approval rules, documents, and preferences
requestBody:
required: true
@@ -48,6 +50,7 @@ paths:
get:
tags: [Approval Knowledge]
operationId: listApprovalRules
x-implementation-status: implemented
summary: List current draft approval rules
responses:
"200":
@@ -59,6 +62,7 @@ paths:
post:
tags: [Approval Knowledge]
operationId: createApprovalRule
x-implementation-status: planned
summary: Create draft approval rule
requestBody:
required: true
@@ -79,6 +83,7 @@ paths:
patch:
tags: [Approval Knowledge]
operationId: updateApprovalRule
x-implementation-status: planned
summary: Update draft approval rule
requestBody:
required: true
@@ -96,6 +101,7 @@ paths:
delete:
tags: [Approval Knowledge]
operationId: deleteApprovalRule
x-implementation-status: planned
summary: Delete draft approval rule
responses:
"200":
@@ -104,6 +110,7 @@ paths:
get:
tags: [Approval Knowledge]
operationId: listApprovalRuleVersions
x-implementation-status: planned
summary: List published approval rule versions
responses:
"200":
@@ -120,6 +127,7 @@ paths:
get:
tags: [Approval Knowledge]
operationId: getApprovalRuleVersion
x-implementation-status: planned
summary: Get published approval rule version
responses:
"200":
@@ -132,6 +140,7 @@ paths:
get:
tags: [Approval Knowledge]
operationId: getApprovalRuleByVersion
x-implementation-status: planned
summary: Get one wrapped rule from a published version
parameters:
- $ref: ../components/parameters.yaml#/CorpId
@@ -174,6 +183,7 @@ paths:
post:
tags: [Approval Knowledge]
operationId: publishApprovalRuleVersion
x-implementation-status: planned
summary: Publish current draft rules
requestBody:
required: true
@@ -193,6 +203,7 @@ paths:
get:
tags: [Approval Knowledge]
operationId: listApprovalDocuments
x-implementation-status: planned
summary: List approval knowledge documents
parameters:
- $ref: ../components/parameters.yaml#/Offset
@@ -220,6 +231,7 @@ paths:
post:
tags: [Approval Knowledge]
operationId: createApprovalDocument
x-implementation-status: planned
summary: Create approval knowledge document
requestBody:
required: true
@@ -240,6 +252,7 @@ paths:
get:
tags: [Approval Knowledge]
operationId: getApprovalDocument
x-implementation-status: planned
summary: Get approval knowledge document
responses:
"200":
@@ -251,6 +264,7 @@ paths:
patch:
tags: [Approval Knowledge]
operationId: updateApprovalDocument
x-implementation-status: planned
summary: Update approval knowledge document
requestBody:
required: true
@@ -268,6 +282,7 @@ paths:
delete:
tags: [Approval Knowledge]
operationId: deleteApprovalDocument
x-implementation-status: planned
summary: Delete approval knowledge document
responses:
"200":
@@ -276,6 +291,7 @@ paths:
get:
tags: [Approval Knowledge]
operationId: getApprovalStylePreferences
x-implementation-status: planned
summary: Get approval style preferences
responses:
"200":
@@ -287,6 +303,7 @@ paths:
patch:
tags: [Approval Knowledge]
operationId: updateApprovalStylePreferences
x-implementation-status: planned
summary: Update approval style preferences
requestBody:
required: true
@@ -301,3 +318,51 @@ paths:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalStylePreferences
/v1/preferences:
get:
tags: [Approval Knowledge]
operationId: getPreferences
x-implementation-status: implemented
summary: Get current decision, thinking-depth and rule-version preferences
parameters:
- $ref: ../components/parameters.yaml#/CorpId
responses:
"200":
description: Decision preferences, thinking depth preference and the bound rule set version.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalStylePreferences
/v1/preferences/decision:
post:
tags: [Approval Knowledge]
operationId: updatePreferenceDecision
x-implementation-status: implemented
summary: Update decision preferences (takes effect immediately for the running approval agent)
parameters:
- $ref: ../components/parameters.yaml#/CorpId
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
explicitApprove:
type: string
explicitReject:
type: string
exemptApprove:
type: string
review:
type: string
dryRun:
type: boolean
description: Return the before/after diff without writing.
responses:
"200":
description: Updated preferences, or the previewed diff when dryRun is set.
content:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalStylePreferences
+49
View File
@@ -3,6 +3,7 @@ paths:
get:
tags: [Approval Runs]
operationId: searchApprovalRuns
x-implementation-status: implemented
summary: Search wrapped approval run history
parameters:
- $ref: ../components/parameters.yaml#/CorpId
@@ -70,6 +71,7 @@ paths:
get:
tags: [Approval Runs]
operationId: summarizeApprovalRuns
x-implementation-status: implemented
summary: Summarize approval runs by local date
parameters:
- $ref: ../components/parameters.yaml#/CorpId
@@ -99,10 +101,50 @@ paths:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalRunsSummary
/v1/approval-runs/stats:
get:
tags: [Approval Runs]
operationId: statApprovalRuns
x-implementation-status: implemented
summary: Aggregate approval run counts by status and source system
parameters:
- $ref: ../components/parameters.yaml#/CorpId
- name: since
in: query
schema:
type: string
description: Time window such as 3months, 7days or 24hours.
- name: dedupeBy
in: query
schema:
type: string
enum: [sourceDocumentSN, sourceDocumentId, id]
default: sourceDocumentSN
description: Field used to count distinct business documents.
- name: status
in: query
schema:
type: string
- name: sourceSystem
in: query
schema:
type: string
- name: taskMode
in: query
schema:
type: string
responses:
"200":
description: Counts grouped by status and source system, plus the deduplicated total.
content:
application/json:
schema:
type: object
/v1/approval-runs/pick:
get:
tags: [Approval Runs]
operationId: pickApprovalRuns
x-implementation-status: implemented
summary: Pick likely approval runs by document number or trace key
parameters:
- $ref: ../components/parameters.yaml#/CorpId
@@ -151,6 +193,7 @@ paths:
get:
tags: [Approval Runs]
operationId: getApprovalRunLangfuseBridge
x-implementation-status: planned
summary: Resolve approval runs to Langfuse trace or session hints
parameters:
- $ref: ../components/parameters.yaml#/CorpId
@@ -181,6 +224,7 @@ paths:
get:
tags: [Approval Runs]
operationId: getApprovalRunUrl
x-implementation-status: implemented
summary: Get enterprise assist URL and optional source document URL
parameters:
- $ref: ../components/parameters.yaml#/CorpId
@@ -209,6 +253,7 @@ paths:
get:
tags: [Approval Runs]
operationId: getApprovalRun
x-implementation-status: implemented
summary: Get wrapped approval run detail
parameters:
- name: summary
@@ -234,6 +279,7 @@ paths:
get:
tags: [Approval Runs]
operationId: getApprovalRunCitedRules
x-implementation-status: implemented
summary: Extract rules cited or matched by the AI result
responses:
"200":
@@ -249,6 +295,7 @@ paths:
get:
tags: [Approval Runs]
operationId: getApprovalRunDocumentSummary
x-implementation-status: implemented
summary: Get key document fields and compact AI/manual result
responses:
"200":
@@ -264,6 +311,7 @@ paths:
get:
tags: [Approval Runs]
operationId: getApprovalRunAttachments
x-implementation-status: implemented
summary: List compact attachment metadata
parameters:
- name: summary
@@ -284,6 +332,7 @@ paths:
get:
tags: [Approval Runs]
operationId: getApprovalRunResult
x-implementation-status: implemented
summary: Get AI result, optionally as a compact summary
parameters:
- name: summary
+3
View File
@@ -3,6 +3,7 @@ paths:
get:
tags: [Auth]
operationId: diagnoseAuth
x-implementation-status: planned
summary: Diagnose wrapped source-to-Seal authentication
parameters:
- $ref: ../components/parameters.yaml#/CorpId
@@ -17,6 +18,7 @@ paths:
get:
tags: [Auth]
operationId: whoami
x-implementation-status: implemented
summary: Get current wrapped Seal identity
parameters:
- $ref: ../components/parameters.yaml#/CorpId
@@ -33,6 +35,7 @@ paths:
get:
tags: [Auth]
operationId: getSession
x-implementation-status: implemented
summary: Get current wrapped Seal session metadata
parameters:
- $ref: ../components/parameters.yaml#/CorpId
+3
View File
@@ -3,6 +3,7 @@ paths:
get:
tags: [Corps]
operationId: listCorps
x-implementation-status: implemented
summary: List configured enterprises
responses:
"200":
@@ -17,6 +18,7 @@ paths:
get:
tags: [Corps]
operationId: getCurrentCorp
x-implementation-status: planned
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:
@@ -30,6 +32,7 @@ paths:
post:
tags: [Corps]
operationId: switchCurrentCorp
x-implementation-status: planned
summary: Switch current enterprise
requestBody:
required: true
+6
View File
@@ -34,10 +34,16 @@
$ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1documents~1{documentId}
/v1/approval/style-preferences:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1approval~1style-preferences
/v1/preferences:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1preferences
/v1/preferences/decision:
$ref: ./approval-knowledge.yaml#/paths/~1v1~1preferences~1decision
/v1/approval-runs:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs
/v1/approval-runs/summary:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1summary
/v1/approval-runs/stats:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1stats
/v1/approval-runs/pick:
$ref: ./approval-runs.yaml#/paths/~1v1~1approval-runs~1pick
/v1/approval-runs/bridge:
+9
View File
@@ -3,6 +3,7 @@ paths:
post:
tags: [Simulation]
operationId: createSimulationBatch
x-implementation-status: implemented
summary: Create a simulation batch
requestBody:
required: true
@@ -23,6 +24,7 @@ paths:
post:
tags: [Simulation]
operationId: createMaterialPackBatch
x-implementation-status: planned
summary: Create a material pack simulation batch
requestBody:
required: true
@@ -43,6 +45,7 @@ paths:
get:
tags: [Simulation]
operationId: listSimulationBatches
x-implementation-status: implemented
summary: List simulation batches
parameters:
- name: limit
@@ -66,6 +69,7 @@ paths:
get:
tags: [Simulation]
operationId: getSimulationBatch
x-implementation-status: implemented
summary: Get a simulation batch detail including echoed create params
responses:
"200":
@@ -81,6 +85,7 @@ paths:
get:
tags: [Simulation]
operationId: getSimulationBatchRecords
x-implementation-status: planned
summary: Get wrapped simulation batch records
parameters:
- name: query
@@ -100,6 +105,7 @@ paths:
get:
tags: [Simulation]
operationId: listSimulationTemplates
x-implementation-status: planned
summary: List simulation test templates
responses:
"200":
@@ -115,6 +121,7 @@ paths:
get:
tags: [Simulation]
operationId: getSimulationIntegrationStatus
x-implementation-status: planned
summary: Get available source integration status for simulation
responses:
"200":
@@ -128,6 +135,7 @@ paths:
get:
tags: [Simulation]
operationId: listSimulationHosecloudIntegrations
x-implementation-status: planned
summary: List hosecloud source integrations available for simulation
responses:
"200":
@@ -143,6 +151,7 @@ paths:
post:
tags: [Simulation]
operationId: uploadMaterialPackage
x-implementation-status: planned
summary: Upload a material package ZIP for simulation
requestBody:
required: true
+1
View File
@@ -3,6 +3,7 @@ paths:
get:
tags: [Source]
operationId: getSourceConfig
x-implementation-status: planned
summary: Resolve source-derived Seal enterprise config
parameters:
- $ref: ../components/parameters.yaml#/CorpId
+17 -2
View File
@@ -1,12 +1,26 @@
{
"name": "seal-use",
"version": "0.10.22",
"version": "0.10.26",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
"author": {
"name": "yingqing"
},
"repository": {
"type": "git",
"url": "git+https://github.com/yunyingk/seal-use.git"
},
"type": "module",
"module": "src/server.ts",
"bin": {
"seal-use": "src/cli.ts",
"seal-home": "src/cli.ts"
},
"packageManager": "bun@1.3.14",
"engines": {
"bun": ">=1.3.14"
},
"scripts": {
"dev": "bun run --watch src/server.ts",
"start": "bun run src/server.ts",
@@ -23,7 +37,7 @@
"test": "bun test"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"@modelcontextprotocol/server": "^2.0.0",
"archiver": "^8.0.0",
"exceljs": "^4.4.0",
"iconv-lite": "^0.7.3",
@@ -33,6 +47,7 @@
"zod": "^4.4.3"
},
"devDependencies": {
"@modelcontextprotocol/client": "^2.0.0",
"@types/archiver": "^8.0.0",
"@types/bun": "^1.3.14",
"@types/yauzl": "^3.4.0",
+39 -3
View File
@@ -15,6 +15,38 @@ if (!input) {
process.exit(1);
}
const force = process.argv.includes("--force") || process.argv.includes("-f");
// Pre-flight check: ensure working tree is clean
try {
const gitStatus = execSync("git status --porcelain", { cwd: ROOT, encoding: "utf-8" }).trim();
if (gitStatus && !force) {
console.error("❌ 工作区存在未提交的修改,禁止执行版本升级:\n");
console.error(gitStatus);
console.error("\n💡 请先提交或暂存当前修改,或通过独立 worktree 进行隔离发版:");
console.error(" git worktree add /tmp/seal-use-release main");
console.error("(若确认强制执行,可追加 --force 参数)\n");
process.exit(1);
}
} catch {
// Not a git repo or git not available, ignore
}
// Branch check: ensure on main or a release branch
try {
const currentBranch = execSync("git branch --show-current", { cwd: ROOT, encoding: "utf-8" }).trim();
const allowedBranches = ["main", "master"];
const isReleaseBranch = currentBranch.startsWith("codex/release-") || currentBranch.startsWith("release/");
if (currentBranch && !allowedBranches.includes(currentBranch) && !isReleaseBranch && !force) {
console.error(`❌ 当前处于分支 '${currentBranch}',非主干或专用发布分支。`);
console.error("💡 发版应在 'main' 或 'codex/release-*' 分支上执行。");
console.error("(若确认强制执行,可追加 --force 参数)\n");
process.exit(1);
}
} catch {
// Ignore
}
let nextVersion = input.replace(/^v/, "");
if (input === "patch" || input === "minor" || input === "major") {
const [major, minor, patch] = currentVersion.split(".").map(Number);
@@ -79,8 +111,12 @@ execSync("bun run build:plugin", { cwd: ROOT, stdio: "inherit" });
execSync("bun run build:binary", { cwd: ROOT, stdio: "inherit" });
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
console.log("\nNext steps to publish:");
console.log("\nNext steps to publish (Protected-Branch Release):");
console.log(` 1. Update CHANGELOG.md`);
console.log(` 2. git commit -am "Release v${nextVersion}: <Summary>"`);
console.log(` 3. git tag -a v${nextVersion} -m "🚀 <Release notes>"`);
console.log(` 4. git push origin master --tags && git push home master --tags\n`);
console.log(` 3. git push origin HEAD:refs/heads/codex/release-v${nextVersion}`);
console.log(` 4. gh pr create --base main --head codex/release-v${nextVersion} --title "Release v${nextVersion}: ..."`);
console.log(` 5. gh pr checks <pr-number> --watch && gh pr merge <pr-number> --merge`);
console.log(` 6. git switch main && git pull --ff-only origin main && git push home main`);
console.log(` 7. git tag -a v${nextVersion} -m "🚀 <Release notes>"`);
console.log(` 8. git push home refs/tags/v${nextVersion} && git push origin refs/tags/v${nextVersion}\n`);
+90 -42
View File
@@ -37,14 +37,20 @@ case "$ARCH" in
;;
esac
# Resolve best writable bin directory without requiring sudo
TARGET_DIR=""
for candidate in "/opt/homebrew/bin" "/usr/local/bin" "$HOME/.local/bin" "$HOME/bin"; do
if [ -d "$candidate" ] && [ -w "$candidate" ]; then
TARGET_DIR="$candidate"
break
fi
done
# Resolve best writable bin directory without requiring sudo.
# SEAL_USE_INSTALL_DIR overrides the search, which also lets the installer be exercised against a
# scratch directory instead of a real global bin.
TARGET_DIR="${SEAL_USE_INSTALL_DIR:-${SEAL_HOME_INSTALL_DIR:-}}"
if [ -n "$TARGET_DIR" ]; then
mkdir -p "$TARGET_DIR"
else
for candidate in "/opt/homebrew/bin" "/usr/local/bin" "$HOME/.local/bin" "$HOME/bin"; do
if [ -d "$candidate" ] && [ -w "$candidate" ]; then
TARGET_DIR="$candidate"
break
fi
done
fi
if [ -z "$TARGET_DIR" ]; then
mkdir -p "$HOME/.local/bin"
@@ -52,6 +58,7 @@ if [ -z "$TARGET_DIR" ]; then
fi
ASSET_NAME="seal-use-${PLATFORM}-${ARCH_NAME}"
ARCHIVE_NAME="${ASSET_NAME}.tar.gz"
TARGET_PATH="${TARGET_DIR}/seal-use"
LEGACY_LINK="${TARGET_DIR}/seal-home"
@@ -127,7 +134,9 @@ verify_checksum() {
if curl -fsSL --connect-timeout 4 "$checksum_url" -o "$tmp_sum" 2>/dev/null; then
local expected_hash
expected_hash="$(grep "${asset}" "$tmp_sum" | awk '{print $1}' | head -n 1)"
# Exact filename match, not a regex: `grep seal-use-darwin-arm64` also matches the
# `seal-use-darwin-arm64.tar.gz` line and `head -n1` then picks the wrong hash.
expected_hash="$(awk -v name="$asset" '$2 == name { print $1; exit }' "$tmp_sum")"
if [ -n "$expected_hash" ]; then
local actual_hash=""
if command -v sha256sum >/dev/null 2>&1; then
@@ -152,57 +161,96 @@ echo "==> Target install location: ${TARGET_PATH}"
echo "==> Requested version: ${REQ_VERSION}"
TMP_FILE="$(mktemp)"
DOWNLOAD_SUCCESS=false
IS_ARCHIVE=false
USED_ASSET=""
# Candidate mirrors
# Candidate mirrors. The compressed archive is preferred over the raw binary: it is about a third
# of the size (25-39 MB against 67-102 MB), and it is the asset the Gitea mirror publishes first
# (Tier 1 for darwin-arm64, Tier 2 for the rest). The raw binary stays as a fallback for releases
# or mirrors that only carry it.
if [ "$REQ_VERSION" = "latest" ]; then
GITEA_URL="https://git.ying-qing.cn/gitea/seal-use/releases/download/latest/${ASSET_NAME}"
GITEA_LEGACY_URL="https://git.ying-qing.cn/gitea/seal-home/releases/download/latest/${ASSET_NAME}"
GITHUB_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
GHPROXY_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
CHECKSUM_URL="https://github.com/${REPO}/releases/latest/download/checksums.txt"
GITEA_TAG="latest"
GH_RELEASE_PATH="latest/download"
else
GITEA_URL="https://git.ying-qing.cn/gitea/seal-use/releases/download/${REQ_VERSION}/${ASSET_NAME}"
GITEA_LEGACY_URL="https://git.ying-qing.cn/gitea/seal-home/releases/download/${REQ_VERSION}/${ASSET_NAME}"
GITHUB_URL="https://github.com/${REPO}/releases/download/${REQ_VERSION}/${ASSET_NAME}"
GHPROXY_URL="https://ghfast.top/https://github.com/${REPO}/releases/download/${REQ_VERSION}/${ASSET_NAME}"
CHECKSUM_URL="https://github.com/${REPO}/releases/download/${REQ_VERSION}/checksums.txt"
GITEA_TAG="$REQ_VERSION"
GH_RELEASE_PATH="$REQ_VERSION"
fi
GITEA_BASE="https://git.ying-qing.cn/gitea/seal-use/releases/download/${GITEA_TAG}"
GITEA_LEGACY_BASE="https://git.ying-qing.cn/gitea/seal-home/releases/download/${GITEA_TAG}"
GITHUB_BASE="https://github.com/${REPO}/releases/${GH_RELEASE_PATH}"
GHPROXY_BASE="https://ghfast.top/${GITHUB_BASE}"
CHECKSUM_URL="https://github.com/${REPO}/releases/${GH_RELEASE_PATH}/checksums.txt"
MIRROR_MODE="${SEAL_USE_MIRROR:-${SEAL_HOME_MIRROR:-auto}}"
# 1. Try Gitea mirror
if [ "$MIRROR_MODE" = "gitea" ] || [ "$MIRROR_MODE" = "auto" ]; then
if download_candidate "$GITEA_URL" "$TMP_FILE" "Gitea High-Speed Mirror"; then
DOWNLOAD_SUCCESS=true
elif download_candidate "$GITEA_LEGACY_URL" "$TMP_FILE" "Gitea High-Speed Mirror (Legacy Path)"; then
DOWNLOAD_SUCCESS=true
candidate_urls() {
local name="$1"
if [ "$MIRROR_MODE" != "github" ]; then
echo "${GITEA_BASE}/${name}"
echo "${GITEA_LEGACY_BASE}/${name}"
fi
fi
if [ "$MIRROR_MODE" != "gitea" ]; then
echo "${GITHUB_BASE}/${name}"
echo "${GHPROXY_BASE}/${name}"
fi
}
# 2. Try direct GitHub Releases
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
if download_candidate "$GITHUB_URL" "$TMP_FILE" "GitHub Releases (Direct)"; then
DOWNLOAD_SUCCESS=true
fi
fi
try_asset() {
local name="$1"
local url
while IFS= read -r url; do
[ -n "$url" ] || continue
if download_candidate "$url" "$TMP_FILE" "$(extract_host "$url")"; then
return 0
fi
done < <(candidate_urls "$name")
return 1
}
# 3. Try GitHub CDN Proxy Fallback
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
if download_candidate "$GHPROXY_URL" "$TMP_FILE" "Fast CDN Mirror (Fallback)"; then
DOWNLOAD_SUCCESS=true
fi
if try_asset "$ARCHIVE_NAME"; then
DOWNLOAD_SUCCESS=true
IS_ARCHIVE=true
USED_ASSET="$ARCHIVE_NAME"
elif try_asset "$ASSET_NAME"; then
DOWNLOAD_SUCCESS=true
USED_ASSET="$ASSET_NAME"
fi
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
echo "Error: Failed to download ${ASSET_NAME} (${REQ_VERSION}) from all candidate mirrors." >&2
echo "Error: Failed to download ${ARCHIVE_NAME} or ${ASSET_NAME} (${REQ_VERSION}) from all candidate mirrors." >&2
rm -f "$TMP_FILE"
exit 1
fi
verify_checksum "$TMP_FILE" "$ASSET_NAME" "$CHECKSUM_URL"
verify_checksum "$TMP_FILE" "$USED_ASSET" "$CHECKSUM_URL"
chmod +x "$TMP_FILE"
mv "$TMP_FILE" "$TARGET_PATH"
if [ "$IS_ARCHIVE" = "true" ]; then
EXTRACT_DIR="$(mktemp -d)"
echo "==> Extracting ${USED_ASSET}..."
if ! tar -xzf "$TMP_FILE" -C "$EXTRACT_DIR"; then
echo "Error: failed to extract ${USED_ASSET}." >&2
rm -rf "$EXTRACT_DIR" "$TMP_FILE"
exit 1
fi
EXTRACTED="$(find "$EXTRACT_DIR" -type f -name "$(basename "$ASSET_NAME")" -print -quit 2>/dev/null || true)"
if [ -z "$EXTRACTED" ]; then
EXTRACTED="$(find "$EXTRACT_DIR" -type f -print -quit 2>/dev/null || true)"
fi
if [ -z "$EXTRACTED" ]; then
echo "Error: ${USED_ASSET} did not contain a seal-use binary." >&2
rm -rf "$EXTRACT_DIR" "$TMP_FILE"
exit 1
fi
chmod +x "$EXTRACTED"
mv "$EXTRACTED" "$TARGET_PATH"
rm -rf "$EXTRACT_DIR" "$TMP_FILE"
else
chmod +x "$TMP_FILE"
mv "$TMP_FILE" "$TARGET_PATH"
fi
# Create backward-compatible symlink seal-home -> seal-use
if [ "$TARGET_PATH" != "$LEGACY_LINK" ]; then
+24 -10
View File
@@ -1,14 +1,23 @@
---
name: seal-use
description: "v0.10.22: 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.26: 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.22
short-description: Seal tenant and Hose approval automation (v0.10.22)
version: 0.10.26
short-description: Seal tenant and Hose approval automation (v0.10.26)
---
# Seal Use (v0.10.22)
# Seal Use (v0.10.26)
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.
**The CLI is the primary path; the MCP server is an optional extra that is off by default.** Prefer the global `seal-use` CLI, and only use MCP when it is actually available in the current session. If no `seal_cli*` tool is present, that is the normal default — do not try to enable it or treat it as a fault; just use the CLI. Enabling it is the user's choice in the plugin settings (插件配置中的「启用 MCP 服务」,默认关闭,打开后需重连该插件的 MCP 服务).
When MCP *is* available, two tools are exposed:
- `seal_cli` — **read-only only.** Reads tenant state without changing it. It is annotated `readOnlyHint: true`, so clients may auto-approve it.
- `seal_cli_write` — everything that mutates tenant state, publishes configuration, mints credentials, self-updates or starts a server. Annotated `destructiveHint: true`; **confirm the exact command with the user before calling it.**
The boundary is enforced, not merely advertised: `seal_cli` refuses any command that is not on its read-only allow-list, and unclassified commands fail closed. A refusal names `seal_cli_write` as the follow-up. `seal-use tool <name>` is allowed through `seal_cli` only for tools the registry classifies as read-only (`SEAL_READ_ONLY_TOOLS`); the rest need `seal_cli_write`.
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.
## Bootstrap & Installation (环境安装与自愈)
@@ -43,8 +52,9 @@ seal-use corps list
- Treat CLI/MCP as the Agent's execution channel, not the user's interface. Translate natural-language intent into commands yourself; never ask the user to compose CLI syntax, JSON payloads, placeholder values, or internal IDs.
- Before asking for enterprise parameters, resolve the target enterprise: when an enterprise is named, hinted, or keyword-identifiable, ALWAYS run `seal-use corps search <keyword>` (or `seal-use corps get <corpId>` if an exact ID is known) — DO NOT dump the entire enterprise catalog with `seal-use corps list` when the target is already known. Only run `seal-use corps list` (or `corps list --env <test|production>`) for initial discovery when zero enterprise context is known. Resolve its human name to the returned `id` and pass that value as `--corp`; do not ask the user to know `corpId`. Use `seal-use corps get <corpId>` to inspect rich enterprise attributes (URLs, tenant slugs, staff IDs, environment relations, and config file locations) with sensitive secrets safely redacted.
- If no enterprise is configured, the user is installing for the first time, or the user provides credentials, an assistance link, or a browser-copied cURL, read `references/enterprise-onboarding.md` before asking questions or running setup commands.
- When the user provides a Hose/合思 `thirdparty.html` assistance link, use `seal-use corps add-link <url> [--name ...]`; the command verifies the tenant and records the temporary Seal session without echoing the link token.
- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native.
- When the user provides a Hose/合思 `thirdparty.html` assistance link, use `seal-use corps add-link <url> [--name ...]` for temporary session access, or elevate privileges to permanent developer credentials using `seal-use corps extract-keys <url> --save` (or `seal-use corps add-link <url> --as-hose`). This Hose-exclusive capability extracts `appKey`/`appSecurity`. If the enterprise has multiple keys, specify `--app-key <key>` or `--key-id <id>`.
- **同等凭据原则(Equal Credential Scope Principle)**: A Hose assistance link and a cURL copied from an authenticated **Hose admin** page are both Hose web frontend sessions — structurally different in format only, carrying the same `accesstoken`/`corpid` web session credentials. **When a Hose administrator provides a browser cURL, do NOT silently downgrade it to a plain short-lived session import.** Attempt privilege elevation first by extracting `accesstoken`+`corpid`+`baseUrl` from the cURL and invoking the Hose key interface (`/api/innerapi/v1/key`) to retrieve permanent `appKey`/`appSecurity`. Only fall back to temporary session import if the user is not a Hose administrator or the key interface returns no keys.
- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native. Calling key extraction or `keys` on native Seal enterprises is strictly blocked.
- Never ask a normal user for `corpId`, `staffId`, `proxyStaffBizId`, `tenantId`, or another discoverable internal ID. Discover it first. If discovery fails, explain what the field means, why it could not be discovered, and exactly where the user can find it.
- Prefer compact commands first: `pick`, `--summary`, `--fields`, `attachments --summary`, `rules count`, and `rules list --summary`.
- Parse JSON stdout. Do not scrape human text.
@@ -88,7 +98,7 @@ seal-use corps list
- 规则本地工作流: `seal-use rules pull` 导出草稿规则,`rules lint` 做质量检查,`rules push --dry-run` 预览增量更新,确认后用 `--yes` 写入;`rules map` 查询 `corps sync-test` 生成的跨企业规则映射。规则版本与草稿/发布 code 空间的区别详见 `references/rule-lightweight.md` 和 `references/cli.md`。
- 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|sourceDocumentId|id] --corp <corpId>`, `approval-runs count`, `analytics insight|risks|performance|analyze`, 以及 `approval-runs export`(Excel 报表);需要追踪单据时再使用 `url` 或 `bridge`。
- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] --corp <corpId>`, `approval-runs count`, `analytics insight|risks|performance|analyze`, 以及 `approval-runs export`(Excel 报表,文件名强制追加精确到分钟的 `_YYYYMMDD_HHmm` 时间戳后缀防止覆盖;支持 `--sn <SN1,SN2>` 定向筛选极速导出并跳过全量分页;追加 `--with-flow` 可额外输出 **E人工行为** / **E人工意见** 两列——基于合思原生审批流对齐,含样式 2-B 三行展开式驳回目标与重审规则、中途修改置顶事实且保留时序、动作 Emoji,200 条以上单据约增加 30 秒);需要追踪单据时再使用 `url` 或 `bridge`。
- User-facing 合思 authorization link (合思/易快报授权): `seal-use auth hose-link --corp <corpId> --expire 7200`; read `references/hose-enterprise-auth.md`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
- Delegation links management: `seal-use delegation list --corp <corpId>`, `create [--note ...] --corp <corpId>`, `create --from-link <url> [--note ...]`, `revoke <tokenId> --corp <corpId>`.
- User & Contacts Management (用户搜索、激活与一键代生成授权): `seal-use users search [keyword] --corp <corpId>`, `users delegation <userIdOrPhone> --corp <corpId>` (仅适用于 Seal 本地创建的账号 `provider: local`;对合思同步账号系统拒绝重置密码,需改用 `auth hose-link`), `users activate <userId> --corp <corpId>`, `users create --name ... --phone ... --corp <corpId>`, `users reset-password <userId> --corp <corpId>`, `users get <userId> --corp <corpId>`, `users delete <userId> --corp <corpId>`.
@@ -113,8 +123,8 @@ seal-use corps list
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。
3. 用户或业务负责人明确确认放宽策略后,读取目标 Webhook 当前配置:`seal-use webhook get`/`webhook list`,或等价的 `seal-use tool seal_webhook_get`/`seal_webhook_list`(MCP 下经 `seal_cli` 执行)。
4. 修改最小值、最大值或完整后缀白名单:`seal-use webhook update`,或等价的 `seal-use tool seal_webhook_update`(MCP 下经 `seal_cli_write` 执行,需用户确认)。写入后重新读取核对,再重试原来的材料包 push。
push 会重新读取最新 Webhook 配置;校验通过后才会开始上传附件。CLI 以非零退出码和 `stderr` 返回可恢复的业务错误,MCP 以工具错误返回。没有用户授权或没有修改权限时,不能擅自放宽策略,也不能绕过校验。
@@ -159,6 +169,10 @@ seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation status <batchId> --corp <corpId>
seal-use simulation approval-definitions --corp <corpId>
seal-use approval-runs export --corp <corpId> --downloads --completed-only
# Add --with-flow to also populate E人工行为 / E人工意见 columns (Hose Open API, adds ~30s):
seal-use approval-runs export --corp <corpId> --downloads --with-flow
# Target specific document SNs for instant export without full pagination:
seal-use approval-runs export --corp <corpId> --sn B26002307,B26002144 --with-flow --downloads
seal-use analytics insight --corp <corpId>
seal-use contacts departments --corp <corpId>
seal-use data invoices --corp <corpId> --limit 20
+15 -5
View File
@@ -88,7 +88,11 @@ seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limi
seal-use corps regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]
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 corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--as-hose] [--app-key <key>] [--key-id <id>] [--overwrite]
seal-use corps extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--app-key <key>] [--key-id <id>] [--overwrite]
seal-use corps keys [<url> | <corpId>] [--reveal] [--save] [--app-key <key>] [--key-id <id>]
seal-use auth extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--app-key <key>] [--key-id <id>] [--overwrite]
seal-use auth keys [--corp <corpId>] [--reveal]
seal-use auth diagnose [--corp <corpId>]
seal-use auth hose-link [--corp <corpId>] [--expire 7200]
seal-use delegation list [--corp <corpId>]
@@ -147,7 +151,10 @@ seal-use analytics performance --corp <corpId> [--start-date <ISO|ms>] [--end-da
seal-use analytics analyze <recordId> --corp <corpId>
seal-use analytics export --corp <corpId> [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>] [--force]
seal-use approval-runs count --corp <corpId> [--status APPROVED] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>]
seal-use approval-runs export --corp <corpId> [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads] [--out <file>]
seal-use approval-runs export --corp <corpId> [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads] [--out <file>] [--with-flow]
# --sn / --sns: 定向筛选单据编号(支持逗号/分号/空格分隔,跳过全量分页,秒级定向导出特定单据)
# --with-flow: 启用合思原生审批流对齐,输出 E人工行为 / E人工意见 两列(含样式 2-B 三行展开式驳回目标与重审规则、中途修改置顶事实且保留时序、动作 Emoji,默认关闭以节省合思 API 调用)
# 导出文件名自动追加精确到分钟的 _YYYYMMDD_HHmm 时间戳后缀防止文件覆盖,格式:${企业名称}_审核记录_${时间区间}_${条数}_${导出时间戳}.xlsx
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>
@@ -203,7 +210,10 @@ Enterprise and tenant management:
- `seal-use corps get <corpId>` (rich enterprise attributes with sensitive secrets safely redacted)
- `seal-use corps current [--corp <corpId>]`
- `seal-use corps switch <corpId>`
- `seal-use auth diagnose --corp <corpId>`
- `seal-use corps extract-keys <url> [--reveal] [--save] [--name <name>] [--app-key <key>] [--key-id <id>] [--overwrite]` extracts OpenAPI keys (`appKey` and `appSecurity`) from a Hose assistance link (`thirdparty.html`). **Hose Subdomain Privilege Elevation**: elevates a short-lived session token to permanent Hose OpenAPI developer credentials. If `--save` is specified, registers the enterprise as a durable Hose tenant. If the enterprise has multiple keys, execution halts and candidates are listed unless `--app-key` or `--key-id` is passed.
- `seal-use corps add-link <url> [--name <name>] [--as-hose] [--app-key <key>] [--key-id <id>] [--overwrite]` imports a Hose assistance link. Without `--as-hose`, creates a temporary Seal Bearer session. With `--as-hose`, elevates permissions by extracting Hose OpenAPI developer keys and saving a durable Hose enterprise configuration.
- `seal-use corps keys [<url> | <corpId>] [--reveal] [--save]` reads/displays OpenAPI keys for a Hose assistance link or configured Hose enterprise (masked by default, `--reveal` displays plaintext). Rejects non-Hose/native-Seal tenants with exit code 2.
- `seal-use auth extract-keys <url>` and `seal-use auth keys [--corp <corpId>]` provide auth-domain aliases for key extraction and inspection.
Read-only discovery:
@@ -608,11 +618,11 @@ When a push fails because of the attachment policy, the error is actionable and
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.
The same loop is available through the internal tool registry: read with `seal-use tool seal_webhook_get`/`seal_webhook_list`, update with `seal-use tool seal_webhook_update` and its `materialPackFilePolicy` patch, then retry `seal-use tool seal_webhook_material_pack` in `push` mode. Over MCP these run through `seal_cli` (reads) or `seal_cli_write` (the update and push, which need user confirmation); no separate `seal_webhook_*` MCP tool exists. 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.
The direct local `material-pack preview` command and the tool-registry 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
@@ -34,13 +34,16 @@ All command examples in this reference are for the Agent to run. Do not hand the
Classify both the enterprise identity origin and how the current credential was acquired:
| Enterprise identity origin | Credential material the user may have | Meaning |
| --- | --- | --- |
| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | Stable, refreshable standard integration |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |
| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |
| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |
| Enterprise identity origin | Credential material the user may have | 权限等级与时效 | Meaning |
| --- | --- | --- | --- |
| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | 【最高·永久】自动签名/续期 | Stable, refreshable standard integration; unlocks full OpenAPI and `corps sync-hosecloud`. |
| Hose/合思-sourced Seal tenant | Hose authorization/assistance link (`thirdparty.html`) | 【两极分化】普通导入→短效;提权→永久 | Temporary session that can be **elevated** to permanent `appKey`/`appSecurity` with `extract-keys --save` or `add-link --as-hose`. |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated **Hose admin** page | 【两极分化】普通导入→短效;提权→永久 | **Same session scope as an assistance link.** If the user is a Hose administrator, this carries the same web session credentials (`accesstoken`, `corpid`, cookies) and can equally invoke `/api/innerapi/v1/key` to extract permanent `appKey`/`appSecurity`. |
| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Seal page | 【短效会话快照】 | Snapshot with Seal Bearer token; can set up temporary Seal session access. |
| Seal-native tenant | Seal assistance/delegation link | 【临时·可撤销】 | Temporary delegated access to a Seal tenant. |
| Seal-native tenant | cURL copied from an authenticated Seal page | 【短效会话快照】 | Snapshot containing the Seal host and session authentication. |
**同等凭据原则(Equal Credential Scope Principle)**: A Hose assistance link and a browser cURL from an authenticated Hose admin session are both Hose web frontend sessions — they carry the same underlying `accessToken`/`accesstoken` and `corpid`. The **only** structural difference is delivery format. When a Hose administrator sends you a cURL, treat it with the same privilege elevation potential as an assistance link. Do not downgrade it to a plain Seal session import without first attempting key extraction.
Credential 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.
@@ -73,21 +76,42 @@ seal-use auth diagnose --corp <discovered-id>
Do 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.
## Route 2: Incoming Assistance Link
## Route 2: Incoming Assistance Link & Hose Subdomain Privilege Elevation
First distinguish the link by its host and purpose:
First distinguish the link by its host, purpose, and identity origin:
- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.
- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.
- `seal-use auth hose-link` and `seal-use delegation create` generate links for an enterprise that is already configured. `seal-use corps add-link <url>` imports a received Hose/合思 `thirdparty.html` assistance link and verifies the resulting Seal tenant.
- A **Hose/合思 authorization/assistance link** (`https://<domain>/web/thirdparty.html?...`) opens an upstream Hose session and may continue through Seal SSO. It is not a Seal delegation link.
- A **Seal-native assistance/delegation link** grants temporary delegated access on a Seal tenant. It is not a Hose credential and cannot be elevated to Hose OpenAPI credentials.
- **Hose Subdomain Boundary (合思子域专属提权)**: `seal-use` primarily manages Seal tenants. Tenants sourced from the Hose ecosystem have an upstream Hose enterprise backing them. A received Hose assistance link contains only a temporary session `accessToken`. If you run standard `corps add-link`, it exchanges that temporary token for a short-lived Seal Bearer token—sufficient for basic Seal inspection, but it will expire and cannot call any Hose OpenAPI.
- **Privilege Elevation (权限等级提升)**: To elevate from a short-lived session token to permanent, durable Hose OpenAPI developer credentials, use `corps extract-keys <url> --save` or `corps add-link <url> --as-hose`. This leverages Hose's internal key interface (`GET /api/innerapi/v1/key`) using the session token to retrieve the enterprise's OpenAPI `appKey` and `appSecurity`. Once saved, the enterprise is upgraded to a standard Hose configuration with full OpenAPI support (e.g. `corps sync-hosecloud`).
- **Multi-Key Disambiguation (多套密钥明确抉择)**: If the enterprise owns multiple application keys, the CLI **will not** guess or silently pick the first key. Instead, it terminates with an informative candidate list and requires the user to specify `--app-key <key>` or `--key-id <id>`. If only one key exists, it is selected automatically.
- **Non-Hose Tenants Blocked**: Calling `keys` on native Seal enterprises (`corp.source.type !== "hose"`) is strictly rejected with exit code 2, explaining that this capability belongs exclusively to the Hose ecosystem.
Use the direct import route when the incoming link is an HTTPS `thirdparty.html` URL from a supported `ekuaibao.com` or `hosecloud.com` domain:
### Command Usage
```bash
seal-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=<temporary-token>&ekbCorpId=<corpId>&pageType=home" [--name "企业名称"]
# 1. 提取密钥并脱敏查看(合思子域能力):
seal-use corps extract-keys "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..."
# 2. 显式完整查看密钥明文(--reveal / -r):
seal-use corps extract-keys "<url>" --reveal
# 3. 提权保存为标准持久化合思企业配置:
seal-use corps extract-keys "<url>" --save [--name "企业名称"] [--overwrite]
# 或简写为:
seal-use corps add-link "<url>" --as-hose [--name "企业名称"]
# 4. 多套密钥存在时,显式指定具体应用密钥:
seal-use corps extract-keys "<url>" --save --app-key "ekb_app_..."
# 或按 key ID 选取:
seal-use corps extract-keys "<url>" --save --key-id "key_id_..."
# 5. 查看已配置合思企业当前使用的应用密钥:
seal-use corps keys <corpId> [--reveal]
seal-use auth keys --corp <corpId> [--reveal]
```
The command parses `accessToken` and `ekbCorpId`, exchanges the temporary Hose token at the target Seal tenant, verifies `/api/v1/auth/me`, and stores only the normalized short-lived Seal session. It never prints or persists the original URL. Use `--overwrite` only when intentionally replacing an existing enterprise config. To create a Seal delegation link without persisting the session, use `seal-use delegation create --from-link <url> [--note ...]`.
When using standard `add-link` (without `--as-hose`), it exchanges the temporary Hose token at the target Seal tenant, verifies `/api/v1/auth/me`, and stores only the normalized short-lived Seal session. When `--as-hose` or `extract-keys --save` is used, the CLI executes Hose subdomain privilege elevation to register a durable standard Hose configuration.
Assistance links are credentials. Do not follow a link merely to inspect it when the user's request was only explanatory, and never publish, log, or commit it.
@@ -103,21 +127,51 @@ When the user needs capture instructions, give these concrete steps:
6. Right-click it and choose **Copy → Copy as cURL**.
7. Send that complete cURL only to the local trusted Agent handling setup.
When receiving cURL:
When receiving cURL, immediately classify its origin before deciding on an action path:
### 3a. cURL from an authenticated Hose page (合思/易快报 后台)
This is functionally equivalent to a Hose assistance link. Both carry the same underlying web session credentials (`accesstoken`, `corpid`/`ekbCorpId`, and cookies). The structural difference is only in delivery format.
**Always attempt privilege elevation first when the session user is or may be a Hose administrator:**
1. Treat the entire cURL as a secret. Do not echo it, execute it blindly, paste it into another service, or store it in repository files.
2. Parse it as data. Extract the request host, path, `Authorization` header, cookies, and provider/tenant hints. Ignore the request body unless it is required to identify the tenant.
3. Classify whether the captured request is to Hose or Seal. A Seal request with `Authorization: Bearer ...` can supply `sealUrl` and a session token even when the user's identity origin is Hose.
4. Verify with the narrowest read-only identity endpoint available. For a Seal Bearer session, verify `/api/v1/auth/me` through `seal-use corps add-seal`; use returned provider metadata to retain the actual origin.
5. Persist only the normalized minimum configuration needed by seal-use. Do not preserve the raw cURL, unrelated headers, request body, cookies, or signed URL.
2. Extract: the request hostname (determines `baseUrl`), `accesstoken` header (session token), `corpid` header or cookie, and any other Hose session headers.
3. **Privilege elevation path (preferred)**: Use extracted `accesstoken`, `corpid`, and `baseUrl` to call `/api/innerapi/v1/key`, exactly as `corps extract-keys` does for assistance links. This retrieves permanent `appKey`/`appSecurity` to register a durable Hose enterprise configuration — do not skip this step just because the input is a cURL instead of a URL.
4. **Fallback short-term path**: If the session user is not an administrator and the key interface returns no keys, fall back to the Seal SSO bridge to register a temporary Seal session.
5. If key extraction succeeds, inform the user that credentials have been permanently elevated; if it fails, explain the limitation and suggest the administrator copy a dedicated cURL or provide an assistance link or `appKey`/`appSecurity`.
For a verified Seal Bearer captured from cURL, the existing CLI route is:
```
⚠️ 【同等凭据原则】
合思协助链接与合思管理员登录态 cURL 均属于合思前端会话 (Web Session),本质完全等价。
区别仅在于交付形式:URL vs cURL。
收到合思管理员 cURL 时,优先走提权提取路径,将临时会话升级为永久 OpenAPI 配置,
而非仅作为短期会话导入。
```
### 3b. cURL from an authenticated Seal page (Seal 后台)
1. Treat the entire cURL as a secret.
2. Parse it as data. Extract the request host, path, `Authorization: Bearer ...` header, and provider/tenant hints.
3. Verify with `/api/v1/auth/me` through `seal-use corps add-seal`; use returned provider metadata to retain the actual origin.
4. Persist only the normalized minimum configuration needed by seal-use.
```bash
seal-use corps add-seal --json '{"sealUrl":"https://target-tenant.example","token":"<bearer>"}'
```
The current CLI has no raw-cURL import command and `add-seal` requires a Bearer token. If the captured request contains only cookies or an authentication shape the CLI cannot verify, do not improvise a token. Ask the user to copy another successful Seal Fetch/XHR request that contains the Bearer header, or explain the current limitation.
If the captured request contains only cookies or an authentication shape the CLI cannot verify, do not improvise a token. Ask the user to copy another successful Seal Fetch/XHR request that contains the Bearer header, or explain the current limitation.
### 3c. Advantages and Limitations of F12 cURL
| 维度 | F12 cURL 会话 | 合思 OpenAPI 开发者密钥(提权后)|
|---|---|---|
| 获取难度 | 极低,无需管理员权限,前台业务人员即可操作 | 需要管理员在合思开放平台注册应用,或从管理员 cURL 中提权提取 |
| 权限等级 | 受当前登录用户权限约束 | 拥有开放平台全量 OpenAPI 能力 |
| 时效 | 浏览器 Cookie / Token 过期即失效(通常数小时至数天) | 永久有效,支持自动轮转与续期 |
| HoseCloud 同步 | ❌ 不支持 | ✅ 支持 `corps sync-hosecloud` |
## Verify and Hand Off
+70 -4
View File
@@ -166,6 +166,16 @@ export async function handleApprovalRunsCommand(
if (action === "get") {
const recordId = args.command[2];
if (!recordId) throw new Error("Missing approval run recordId");
if (booleanOption(args.options.flow)) {
await runTool(
"seal_approval_run_flow_get",
client,
corp,
{ recordId },
outputOptions(args.options)
);
return;
}
await runTool(
"seal_approval_run_get",
client,
@@ -313,14 +323,52 @@ export async function handleApprovalRunsCommand(
return;
}
if (action === "flow") {
const target =
maybeName ??
args.command[2] ??
stringOption(args.options.sn) ??
stringOption(args.options.id) ??
stringOption(args.options.recordId);
if (!target) {
throw new Error("Usage: seal-use approval-runs flow <recordId|SN>");
}
await runTool(
"seal_approval_run_flow_get",
client,
corp,
{ target },
outputOptions(args.options)
);
return;
}
if (action === "export") {
const rawSn =
stringOption(args.options.sn) ??
stringOption(args.options.sns) ??
stringOption(args.options.sourceDocumentSN);
const snList = rawSn
? rawSn
.split(/[,;\s]+/)
.map((s) => s.trim())
.filter(Boolean)
: undefined;
const result = await exportApprovalRunsToExcel(client, corp, {
sns: snList,
limit: numberOption(args.options.limit),
startDate:
stringOption(args.options.start) ??
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since),
endDate: stringOption(args.options.end) ?? stringOption(args.options.endDate),
endDate:
stringOption(args.options["end-date"]) ??
stringOption(args.options.endDate) ??
stringOption(args.options.end) ??
stringOption(args.options.until),
status: stringOption(args.options.status),
manualApprovalStatus:
stringOption(args.options["manual-status"]) ??
@@ -332,9 +380,27 @@ export async function handleApprovalRunsCommand(
stringOption(args.options.out) ??
stringOption(args.options.output) ??
stringOption(args.options.file),
toDownloads: booleanOption(args.options.downloads) ?? booleanOption(args.options.download),
force: booleanOption(args.options.force)
toDownloads:
booleanOption(args.options["to-downloads"]) ??
booleanOption(args.options.downloads) ??
booleanOption(args.options.download),
force: booleanOption(args.options.force),
withFlow:
booleanOption(args.options["with-flow"]) ??
(booleanOption(args.options["no-flow"]) ? false : undefined),
flowConcurrency:
numberOption(args.options["flow-concurrency"]) ??
numberOption(args.options.concurrency),
excludeDeleted:
booleanOption(args.options["exclude-deleted"]) ??
(booleanOption(args.options["include-deleted"]) ? false : undefined),
taskMode: stringOption(args.options.taskMode) ?? stringOption(args.options["task-mode"]),
sourceSystem: stringOption(args.options.sourceSystem) ?? stringOption(args.options["source-system"])
});
console.error(`👉 查看导出文件: open "${result.filePath}"`);
if (!args.options["with-flow"] && corp.source.type === "hose") {
console.error(`👉 提示: 追加 --with-flow 可额外拉取合思原生审批流,输出 E人工行为 / E人工意见。`);
}
printJson(result, outputOptions(args.options));
return;
}
+34 -1
View File
@@ -4,9 +4,33 @@ import type { CorpConfig } from "../../core/config/types.js";
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import { getMe } from "../../domains/seal/api.js";
import { numberOption } from "../parser.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson, redactSensitiveText } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import { extractKeysFromLinkAction, showCorpKeysAction } from "./corps.js";
export async function handleAuthExtractKeysCommand(maybeName: string | undefined, args: ParsedArgs) {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error(
"Usage: seal-use auth extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]"
);
}
const reveal =
booleanOption(args.options.reveal) === true ||
booleanOption(args.options.r) === true ||
booleanOption(args.options.plain) === true;
const save = booleanOption(args.options.save) === true || booleanOption(args.options.add) === true;
await extractKeysFromLinkAction(link, {
reveal,
save,
name: stringOption(args.options.name),
overwrite: booleanOption(args.options.overwrite) === true,
force: booleanOption(args.options.force) === true,
appKey: stringOption(args.options["app-key"]) ?? stringOption(args.options.appKey),
keyId: stringOption(args.options["key-id"]) ?? stringOption(args.options.keyId)
});
}
export async function handleAuthCommand(action: string | undefined, corp: CorpConfig, args: ParsedArgs) {
if (action === "diagnose") {
@@ -20,6 +44,15 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
return;
}
if (action === "keys") {
const reveal =
booleanOption(args.options.reveal) === true ||
booleanOption(args.options.r) === true ||
booleanOption(args.options.plain) === true;
await showCorpKeysAction(corp.id, { reveal });
return;
}
throw new Error(`Unknown auth command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+353 -1
View File
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "../runner.js";
@@ -490,3 +490,355 @@ describe("corps list sorting and limit", () => {
expect(limitedItems.map((c: any) => c.id)).toEqual(["corp-05", "corp-02", "corp-11"]);
});
});
describe("Hose OpenAPI key extraction from assistance link", () => {
function mockHoseKeysRequests(options: {
staffId?: string;
corpName?: string;
keys?: Array<{
id: string;
name?: string;
appKey: string;
appSecurity: string;
active?: boolean;
corporationId?: string;
createTime?: number;
}>;
} = {}) {
const staffId = options.staffId ?? "acme-01:admin01";
const corpName = options.corpName ?? "Acme Corporation";
const keys = options.keys ?? [
{
id: "key-1",
name: "生产系统接入",
appKey: "ak_acme_production_123",
appSecurity: "sec_secret_password_456789",
active: true,
corporationId: "acme-01",
createTime: 1700000000000
}
];
const jwtPayload = Buffer.from(
JSON.stringify({
staffId,
corporationName: corpName,
staffName: "Alice Admin"
})
).toString("base64url");
const fakeJwt = `header.${jwtPayload}.signature`;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
const url = new URL(urlStr);
if (url.pathname === "/api/engine/realm/$UNITY/actions/jwt") {
return jsonResponse({ value: fakeJwt });
}
if (url.pathname === "/api/innerapi/v1/key") {
return jsonResponse({ items: keys, count: keys.length });
}
if (url.pathname === "/api/openapi/v1/auth/getAccessToken") {
return jsonResponse({
value: {
accessToken: "openapi-token-xyz",
corporation: { id: "acme-01", name: corpName },
staff: { id: staffId, name: "Alice Admin" }
}
});
}
if (url.pathname === "/api/auth/oauth2/session/oem-hosecloud") {
return jsonResponse({ accessToken: "seal-bearer-token", expiresIn: 1800 });
}
if (url.pathname === "/api/v1/auth/me") {
return jsonResponse({
data: {
user: { id: "u-1", providerUserId: staffId, name: "Alice Admin" },
tenant: { id: "t-1", tenantSlug: "acme-01", name: corpName }
}
});
}
return jsonResponse({ error: `Unexpected request: ${url.pathname}` }, 404);
}) as typeof fetch;
}
test("corps extract-keys masks appSecurity by default", async () => {
setupConfigEnv();
mockHoseKeysRequests();
const link = hoseLink();
const result = await runCli(["corps", "extract-keys", link]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.corpId).toBe("acme-01");
expect(parsed.keys.length).toBe(1);
expect(parsed.keys[0].appKey).toBe("ak_acme_production_123");
expect(parsed.keys[0].appSecurity).toBe("sec_secr...6789");
expect(result.stdout).not.toContain("sec_secret_password_456789");
expect(result.stderr).toContain("附加 --reveal (或 -r) 可查看完整 appSecurity 明文");
});
test("corps extract-keys --reveal outputs plain text appSecurity", async () => {
setupConfigEnv();
mockHoseKeysRequests();
const link = hoseLink();
const result = await runCli(["corps", "extract-keys", link, "--reveal"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.keys[0].appSecurity).toBe("sec_secret_password_456789");
expect(result.stdout).toContain("sec_secret_password_456789");
});
test("corps extract-keys --save saves durable Hose enterprise configuration", async () => {
const enterprises = setupConfigEnv();
mockHoseKeysRequests();
const link = hoseLink();
const result = await runCli(["corps", "extract-keys", link, "--save", "--name", "Acme Hose", "--force"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const savedFile = join(enterprises, "acme-01.json");
expect(existsSync(savedFile)).toBe(true);
const config = JSON.parse(readFileSync(savedFile, "utf-8"));
expect(config.id).toBe("acme-01");
expect(config.name).toBe("Acme Hose");
expect(config.source.type).toBe("hose");
expect(config.source.appKey).toBe("ak_acme_production_123");
expect(config.source.appSecurity).toBe("sec_secret_password_456789");
expect(config.source.domain).toBe("https://wx2.ekuaibao.com");
expect(config.source.staffId).toBe("acme-01:admin01");
});
test("corps add-link --as-hose automatically registers as Hose OpenAPI configuration", async () => {
const enterprises = setupConfigEnv();
mockHoseKeysRequests();
const link = hoseLink();
const result = await runCli(["corps", "add-link", link, "--as-hose", "--name", "Acme Auto Hose", "--force"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const savedFile = join(enterprises, "acme-01.json");
expect(existsSync(savedFile)).toBe(true);
const config = JSON.parse(readFileSync(savedFile, "utf-8"));
expect(config.id).toBe("acme-01");
expect(config.source.type).toBe("hose");
expect(config.source.appKey).toBe("ak_acme_production_123");
expect(config.source.appSecurity).toBe("sec_secret_password_456789");
});
test("auth extract-keys alias works before any enterprise is configured", async () => {
setupConfigEnv();
mockHoseKeysRequests();
const link = hoseLink();
const result = await runCli(["auth", "extract-keys", link]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.corpId).toBe("acme-01");
expect(parsed.keys[0].appKey).toBe("ak_acme_production_123");
});
test("auth keys displays configured Hose keys and supports --reveal", async () => {
const enterprises = setupConfigEnv();
mkdirSync(enterprises, { recursive: true });
writeFileSync(
join(enterprises, "demo-hose.json"),
JSON.stringify({
id: "demo-hose",
name: "Demo Hose Corp",
environment: "production",
seal: { url: "https://demo.sealai.cc", endpoints: { approvalStylePreferences: "" } },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "my-app-key-111",
appSecurity: "my-super-secret-password-222",
corpId: "demo-hose",
staffId: "demo:admin"
},
auth: { refreshTtl: 300 }
})
);
// 1. Default masked
const resMasked = await runCli(["auth", "keys", "--corp", "demo-hose"]);
expect(resMasked.isError).toBe(false);
const parsedMasked = JSON.parse(resMasked.stdout);
expect(parsedMasked.appKey).toBe("my-app-key-111");
expect(parsedMasked.appSecurity).toBe("my-super...-222");
expect(resMasked.stdout).not.toContain("my-super-secret-password-222");
// 2. Revealed
const resRevealed = await runCli(["auth", "keys", "--corp", "demo-hose", "--reveal"]);
expect(resRevealed.isError).toBe(false);
const parsedRevealed = JSON.parse(resRevealed.stdout);
expect(parsedRevealed.appSecurity).toBe("my-super-secret-password-222");
});
test("corps extract-keys --save errors when multiple keys exist and no selector given", async () => {
setupConfigEnv();
mockHoseKeysRequests({
keys: [
{
id: "key-prod",
name: "生产系统",
appKey: "ak_prod_111",
appSecurity: "sec_prod_111",
active: true,
corporationId: "acme-01"
},
{
id: "key-dev",
name: "测试系统",
appKey: "ak_dev_222",
appSecurity: "sec_dev_222",
active: true,
corporationId: "acme-01"
}
]
});
const link = hoseLink();
const result = await runCli(["corps", "extract-keys", link, "--save"]);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("存在多套 (2 套) OpenAPI 应用密钥凭据");
expect(result.stderr).toContain("ak_prod_111");
expect(result.stderr).toContain("ak_dev_222");
expect(result.stderr).toContain("--app-key");
});
test("corps extract-keys --save succeeds with multiple keys when --app-key specified", async () => {
const enterprises = setupConfigEnv();
mockHoseKeysRequests({
keys: [
{
id: "key-prod",
name: "生产系统",
appKey: "ak_prod_111",
appSecurity: "sec_prod_111",
active: true,
corporationId: "acme-01"
},
{
id: "key-dev",
name: "测试系统",
appKey: "ak_dev_222",
appSecurity: "sec_dev_222",
active: true,
corporationId: "acme-01"
}
]
});
const link = hoseLink();
const result = await runCli([
"corps",
"extract-keys",
link,
"--save",
"--app-key",
"ak_dev_222",
"--force"
]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const savedFile = join(enterprises, "acme-01.json");
expect(existsSync(savedFile)).toBe(true);
const config = JSON.parse(readFileSync(savedFile, "utf-8"));
expect(config.source.appKey).toBe("ak_dev_222");
expect(config.source.appSecurity).toBe("sec_dev_222");
});
test("corps extract-keys --save succeeds with multiple keys when --key-id specified", async () => {
const enterprises = setupConfigEnv();
mockHoseKeysRequests({
keys: [
{
id: "key-prod",
name: "生产系统",
appKey: "ak_prod_111",
appSecurity: "sec_prod_111",
active: true,
corporationId: "acme-01"
},
{
id: "key-dev",
name: "测试系统",
appKey: "ak_dev_222",
appSecurity: "sec_dev_222",
active: true,
corporationId: "acme-01"
}
]
});
const link = hoseLink();
const result = await runCli([
"corps",
"extract-keys",
link,
"--save",
"--key-id",
"key-prod",
"--force"
]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const savedFile = join(enterprises, "acme-01.json");
expect(existsSync(savedFile)).toBe(true);
const config = JSON.parse(readFileSync(savedFile, "utf-8"));
expect(config.source.appKey).toBe("ak_prod_111");
expect(config.source.appSecurity).toBe("sec_prod_111");
});
test("corps keys and auth keys reject native Seal enterprise with exit code 2", async () => {
const enterprises = setupConfigEnv();
mkdirSync(enterprises, { recursive: true });
writeFileSync(
join(enterprises, "native-seal.json"),
JSON.stringify({
id: "native-seal",
name: "原生 Seal 企业",
environment: "production",
seal: { url: "https://seal.example.com" },
source: {
type: "seal",
sealUrl: "https://seal.example.com",
token: "token-123"
}
})
);
// 1. corps keys
const corpsResult = await runCli(["corps", "keys", "native-seal"]);
expect(corpsResult.exitCode).toBe(2);
expect(corpsResult.stderr).toContain("合思子域专享能力");
expect(corpsResult.stderr).toContain("原生 Seal (seal) 租户");
// 2. auth keys
const authResult = await runCli(["auth", "keys", "--corp", "native-seal"]);
expect(authResult.exitCode).toBe(2);
expect(authResult.stderr).toContain("合思子域专享能力");
});
});
+256 -3
View File
@@ -5,10 +5,13 @@ import {
assertHoseAssistTenantMatches,
defaultSealUrl,
exchangeHoseAssistLink,
fetchHoseOpenApiKeysFromLink,
fetchHoseRoleDefGroups,
fetchHoseRoleStaffs,
fetchHoseStaffDetails,
probeHoseDomain
maskHoseSecurity,
probeHoseDomain,
type HoseOpenApiKey
} from "../../core/auth/hose.js";
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
@@ -35,7 +38,7 @@ import {
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../domains/seal/webhook-replay.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
import { selectCorp } from "../helpers.js";
import { confirmationRequired, usageError } from "../errors.js";
import { CliError, confirmationRequired, usageError } from "../errors.js";
import {
inferCorpIdFromStaffId,
booleanOption,
@@ -964,13 +967,74 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error(
"Usage: seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]"
"Usage: seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--as-hose] [--overwrite]"
);
}
const asHose = booleanOption(args.options["as-hose"]) === true || booleanOption(args.options.hose) === true;
if (asHose) {
await addLinkAsHoseCorp(
link,
stringOption(args.options.name),
booleanOption(args.options.overwrite) === true,
booleanOption(args.options.force) === true,
{
appKey: stringOption(args.options["app-key"]) ?? stringOption(args.options.appKey),
keyId: stringOption(args.options["key-id"]) ?? stringOption(args.options.keyId)
}
);
return;
}
await addLinkCorp(link, stringOption(args.options.name), booleanOption(args.options.overwrite) === true);
return;
}
if (action === "extract-keys" || action === "extract-key") {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error(
"Usage: seal-use corps extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]"
);
}
const reveal =
booleanOption(args.options.reveal) === true ||
booleanOption(args.options.r) === true ||
booleanOption(args.options.plain) === true;
const save = booleanOption(args.options.save) === true || booleanOption(args.options.add) === true;
await extractKeysFromLinkAction(link, {
reveal,
save,
name: stringOption(args.options.name),
overwrite: booleanOption(args.options.overwrite) === true,
force: booleanOption(args.options.force) === true,
appKey: stringOption(args.options["app-key"]) ?? stringOption(args.options.appKey),
keyId: stringOption(args.options["key-id"]) ?? stringOption(args.options.keyId)
});
return;
}
if (action === "keys") {
const target = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url) ?? stringOption(args.options.corp);
const reveal =
booleanOption(args.options.reveal) === true ||
booleanOption(args.options.r) === true ||
booleanOption(args.options.plain) === true;
if (target && (target.startsWith("http://") || target.startsWith("https://"))) {
const save = booleanOption(args.options.save) === true || booleanOption(args.options.add) === true;
await extractKeysFromLinkAction(target, {
reveal,
save,
name: stringOption(args.options.name),
overwrite: booleanOption(args.options.overwrite) === true,
force: booleanOption(args.options.force) === true,
appKey: stringOption(args.options["app-key"]) ?? stringOption(args.options.appKey),
keyId: stringOption(args.options["key-id"]) ?? stringOption(args.options.keyId)
});
return;
}
await showCorpKeysAction(target, { reveal });
return;
}
throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
@@ -1385,6 +1449,195 @@ async function addLinkCorp(link: string, name: string | undefined, overwrite: bo
);
}
function selectHoseOpenApiKey(
keys: HoseOpenApiKey[],
corpId: string,
selection: { appKey?: string; keyId?: string },
contextCmd: string
): HoseOpenApiKey {
if (keys.length === 0) {
throw new Error(
`[合思子域提权] 未能从协助链接中提取到合思企业 [${corpId}] 的 OpenAPI 密钥凭据。\n` +
`💡 说明:此能力专属于合思 (Hose) 子域,用于将临时会话提权为标准 OpenAPI 开发者接入。需要企业管理员已在合思开放平台创建应用并生成 appKey/appSecurity。`
);
}
if (selection.keyId || selection.appKey) {
const matched = keys.find(
(k) =>
(selection.keyId && k.id === selection.keyId) ||
(selection.appKey && k.appKey === selection.appKey)
);
if (!matched) {
console.error(`\n❌ 未找到指定的合思 OpenAPI 密钥 (${selection.appKey ?? selection.keyId})。`);
console.error(`ℹ️ 该合思企业当前存在以下 ${keys.length} 套候选密钥:`);
for (const k of keys) {
const status = k.active ? "🟢 启用" : "⚪ 停用";
console.error(` • "${k.name || "未命名应用"}" (appKey: ${k.appKey}, keyId: ${k.id}, 状态: ${status})`);
}
throw new CliError(
`指定的合思密钥不存在,请从上述候选列表中选择正确的 appKey 或 keyId。`,
2,
`${contextCmd} --app-key ${keys[0]!.appKey}`
);
}
return matched;
}
if (keys.length === 1) {
return keys[0]!;
}
// Multiple keys exist and user did not specify which one
console.error(`\nℹ️ [合思子域提权] 合思企业 [${corpId}] 存在多套 (${keys.length} 套) OpenAPI 应用密钥凭据:`);
for (let i = 0; i < keys.length; i++) {
const k = keys[i]!;
const status = k.active ? "🟢 启用" : "⚪ 停用";
const name = k.name || "未命名应用";
console.error(` [${i + 1}] "${name}" (appKey: ${k.appKey}, keyId: ${k.id}, 状态: ${status})`);
}
console.error(`\n👉 为确保权限提权绑定正确的业务应用,请显式指定要使用的密钥套件:`);
console.error(` 在命令后追加 --app-key <key> 或 --key-id <id> 参数。\n`);
throw new CliError(
`合思企业 [${corpId}] 存在多套 OpenAPI 密钥,必须指定 --app-key 或 --key-id 明确选择要绑定的密钥。`,
2,
`${contextCmd} --app-key ${keys[0]!.appKey}`
);
}
async function addLinkAsHoseCorp(
link: string,
name: string | undefined,
overwrite: boolean,
force = false,
selection?: { appKey?: string; keyId?: string }
) {
console.error("ℹ️ [合思子域提权] 正在通过合思协助链接提取 OpenAPI 开发者密钥并提升企业权限等级...");
const result = await fetchHoseOpenApiKeysFromLink(link);
const selectedKey = selectHoseOpenApiKey(
result.keys,
result.corpId,
selection ?? {},
`seal-use corps add-link "<url>" --as-hose`
);
console.error(
`ℹ️ [合思子域提权] 已选定合思 OpenAPI 凭据 (appKey: ${selectedKey.appKey}, 应用: "${selectedKey.name || "未命名应用"}"),正在初始化为长期合思标准配置...`
);
await addHoseCorp({
domain: result.baseUrl,
appKey: selectedKey.appKey,
appSecurity: selectedKey.appSecurity,
corpId: result.corpId,
name: name ?? result.corpName ?? result.corpId,
staffId: result.staffId,
overwrite,
force
});
}
export async function extractKeysFromLinkAction(
link: string,
options: {
reveal?: boolean;
save?: boolean;
name?: string;
overwrite?: boolean;
force?: boolean;
appKey?: string;
keyId?: string;
}
) {
const result = await fetchHoseOpenApiKeysFromLink(link);
const reveal = options.reveal === true;
if (options.save) {
const selectedKey = selectHoseOpenApiKey(
result.keys,
result.corpId,
{ appKey: options.appKey, keyId: options.keyId },
`seal-use corps extract-keys "<url>" --save`
);
console.error(
`ℹ️ [合思子域提权] 正在将选定的合思 OpenAPI 密钥 (appKey: ${selectedKey.appKey}, 应用: "${selectedKey.name || "未命名应用"}") 保存为标准合思企业配置...`
);
await addHoseCorp({
domain: result.baseUrl,
appKey: selectedKey.appKey,
appSecurity: selectedKey.appSecurity,
corpId: result.corpId,
name: options.name ?? result.corpName ?? result.corpId,
staffId: result.staffId,
overwrite: options.overwrite,
force: options.force
});
return;
}
if (!reveal) {
console.error(
"ℹ️ [合思子域提权] 成功提取合思 (Hose) OpenAPI 密钥。接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文;附加 --save 可将临时会话提权并持久化为标准合思企业。\n"
);
} else {
console.error(
"⚠️ [合思子域提权] 正在以明文展示合思 (Hose) appSecurity 接入密码,请妥善保管敏感凭据。\n"
);
}
printJson({
provider: "hose",
capability: "privilege-elevation",
corpId: result.corpId,
corpName: result.corpName ?? result.corpId,
baseUrl: result.baseUrl,
staffId: result.staffId,
keyCount: result.keys.length,
keys: result.keys.map((k) => ({
id: k.id,
name: k.name || "-",
appKey: k.appKey,
appSecurity: reveal ? k.appSecurity : maskHoseSecurity(k.appSecurity),
active: k.active,
createTime: k.createTime,
updateTime: k.updateTime
}))
});
}
export async function showCorpKeysAction(targetCorpId: string | undefined, options: { reveal?: boolean }) {
const corp = selectCorp(targetCorpId);
const reveal = options.reveal === true;
if (corp.source.type !== "hose") {
throw new CliError(
`【合思子域专享能力】当前企业「${corp.name}」(id: ${corp.id}) 为原生 Seal (${corp.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。\n` +
`OpenAPI 密钥查询与提权能力专属于合思生态租户(用于从合思协助链接或合思凭据中提取开发者密钥提升权限等级),非合思渠道企业不支持此能力。`,
2
);
}
const appKey = corp.source.appKey ?? (corp.source as any).key;
const appSecurity = corp.source.appSecurity ?? (corp.source as any).password;
if (!reveal) {
console.error("💡 [合思子域] 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文。\n");
} else {
console.error("⚠️ [合思子域] 正在以明文展示合思 appSecurity 接入密码,请妥善保管敏感凭据。\n");
}
printJson({
provider: "hose",
capability: "privilege-elevation",
corpId: corp.id,
corpName: corp.name,
domain: corp.source.domain,
staffId: corp.source.staffId,
appKey: appKey ?? "-",
appSecurity: appSecurity ? (reveal ? appSecurity : maskHoseSecurity(appSecurity)) : "-",
active: true
});
}
type RemoteSealIdentity = {
user: Record<string, unknown>;
tenant: Record<string, unknown>;
+2 -2
View File
@@ -1,4 +1,3 @@
import { startServer } from "../../server.js";
import { printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
@@ -8,7 +7,8 @@ export async function handleMcpCommand(action: string | undefined, args: ParsedA
return;
}
await startServer();
const { startServer } = await import("../../server.js");
startServer();
}
export function printMcpConfig() {
+71 -1
View File
@@ -1,5 +1,75 @@
import { describe, expect, test } from "bun:test";
import { compareSemVer, getMirrorMode, isNewerVersion } from "./update.js";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { compareSemVer, getMirrorMode, isNewerVersion, matchAssetForPlatform } from "./update.js";
type Asset = { name: string; downloadUrl: string; size: number };
function assets(...names: string[]): Asset[] {
return names.map((name) => ({ name, downloadUrl: `https://example.test/${name}`, size: 1024 }));
}
describe("update asset selection", () => {
test("prefers the compressed archive on darwin and linux", () => {
const released = assets(
"seal-use-darwin-arm64",
"seal-use-darwin-arm64.tar.gz",
"seal-use-darwin-x64",
"seal-use-darwin-x64.tar.gz"
);
// ~25 MB instead of ~67 MB, and it is the asset the Gitea mirror publishes first.
expect(matchAssetForPlatform(released, "darwin", "arm64")?.name).toBe("seal-use-darwin-arm64.tar.gz");
expect(matchAssetForPlatform(released, "darwin", "x64")?.name).toBe("seal-use-darwin-x64.tar.gz");
expect(
matchAssetForPlatform(assets("seal-use-linux-x64", "seal-use-linux-x64.tar.gz"), "linux", "x64")?.name
).toBe("seal-use-linux-x64.tar.gz");
});
test("prefers the raw executable on windows, where zip extraction is not reliable", () => {
const released = assets("seal-use-windows-x64.zip", "seal-use-windows-x64.exe");
expect(matchAssetForPlatform(released, "windows", "x64")?.name).toBe("seal-use-windows-x64.exe");
});
test("falls back to whichever asset form the release actually has", () => {
expect(matchAssetForPlatform(assets("seal-use-linux-x64"), "linux", "x64")?.name).toBe("seal-use-linux-x64");
expect(matchAssetForPlatform(assets("seal-use-linux-x64.tgz"), "linux", "x64")?.name).toBe("seal-use-linux-x64.tgz");
expect(matchAssetForPlatform(assets("seal-use-windows-x64.zip"), "windows", "x64")?.name).toBe(
"seal-use-windows-x64.zip"
);
});
test("never selects a checksum sidecar as the asset to install", () => {
expect(matchAssetForPlatform(assets("seal-use-linux-x64.sha256"), "linux", "x64")).toBeUndefined();
});
test("ignores assets for another architecture", () => {
expect(matchAssetForPlatform(assets("seal-use-darwin-x64.tar.gz"), "darwin", "arm64")).toBeUndefined();
});
});
describe("update skill install", () => {
const source = readFileSync(join(import.meta.dir, "update.ts"), "utf8");
// Assert on code, not prose: the rationale for this boundary is written out as a comment next to
// the call, and that comment names the helper it replaced.
const code = source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^[ \t]*\/\/.*$/gm, "");
// This is the one regression a normal unit test cannot reach: the stale-skill bug only appeared
// when the *caller* was the previous release's binary, because an in-process sync writes whatever
// skill was compiled into the running image. Asserting on the source is the cheapest way to keep
// the boundary in place — the skill must be installed by the new binary as a child process, and
// the result read back.
test("installs the Agent Skill through the new binary, never in-process", () => {
expect(code).not.toContain("syncGlobalSkillIfPresent");
expect(code).toContain('spawnSync(execPath, ["skill", "install"]');
expect(code).toContain("readInstalledSkillVersion");
// The read-back is what turns a silently stale skill into a loud failure.
expect(code).toMatch(/version !== targetVersion/);
});
});
describe("update version comparator", () => {
test("correctly identifies newer semantic versions", () => {
+117 -35
View File
@@ -1,8 +1,8 @@
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { basename, 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 { readInstalledSkillVersion } from "../../core/embedded-skill.js";
import { VERSION, IS_RELEASE } from "../../version.js";
import { runServiceCommand, serviceStatus } from "../service.js";
import { printJson } from "../printer.js";
@@ -267,14 +267,23 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
if (wasRunning) await runServiceCommand("start", serviceConfig);
const skillSync = syncGlobalSkillIfPresent();
// Refresh the Agent Skill from the binary that is now on disk — never from this process.
//
// `renameSync` above advanced the file at `execPath`, but this process keeps executing the
// previous image, so its in-memory `EMBEDDED_SKILL_FILES` still holds the release we just
// replaced. Calling `syncGlobalSkillIfPresent()` here therefore wrote the *old* skill over the
// new one, leaving the agent a full release behind (and `skillSynced: <dir>` reported success
// either way). One synchronous child reads the new image's embedded copy; it exits before this
// function returns, and nothing is left running.
const skillSync = installSkillFromInstalledBinary(execPath, latestVersion);
printJson({
updated: true,
fromVersion: VERSION,
toVersion: latestVersion,
serviceRestarted: wasRunning,
skillSynced: skillSync.synced ? skillSync.targetDir : false,
skillSynced: skillSync.targetDir ?? false,
skillVersion: skillSync.version ?? false,
mode: "binary"
});
} finally {
@@ -286,6 +295,47 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
}
}
/**
* Installs the Agent Skill by running the newly installed binary as a child process, then reads
* the file back to prove which version actually landed.
*
* The read-back is the point. Nothing about writing the file distinguishes "wrote the target
* skill" from "wrote my own skill": the previous in-process sync did the latter and still reported
* success, for several releases. Asserting the version turns silent staleness into a loud failure,
* and it happens before the command declares the update complete.
*/
function installSkillFromInstalledBinary(
execPath: string,
targetVersion: string
): { targetDir?: string; version?: string } {
const result = spawnSync(execPath, ["skill", "install"], { encoding: "utf8" });
if (result.status !== 0) {
throw new Error(
`Binary updated to v${targetVersion}, but refreshing the Agent Skill failed ` +
`('${execPath} skill install' exited with ${result.status}). ` +
`Run 'seal-use skill install' to finish the update.`
);
}
let targetDir: string | undefined;
try {
targetDir = (JSON.parse(result.stdout ?? "") as { targetDir?: string }).targetDir;
} catch {
// `skill install` prints JSON; if that ever changes, the read-back below still decides.
}
const version = readInstalledSkillVersion(targetDir ? join(targetDir, "SKILL.md") : undefined);
if (version !== targetVersion) {
throw new Error(
`Binary updated to v${targetVersion}, but the Agent Skill on disk reports ` +
`${version ?? "no version"}${targetDir ? ` (${targetDir})` : ""}. ` +
`Run 'seal-use skill install' to finish the update.`
);
}
return { targetDir, version };
}
function detectPlatform(): "darwin" | "linux" | "windows" {
if (process.platform === "darwin") return "darwin";
if (process.platform === "win32") return "windows";
@@ -487,7 +537,26 @@ async function fetchGitHubRelease(repo: string, targetVersion?: string): Promise
return fallbackRelease;
}
function matchAssetForPlatform(
function isArchiveAsset(name: string): boolean {
return name.endsWith(".tar.gz") || name.endsWith(".tgz") || name.endsWith(".zip");
}
function isRawBinaryAsset(name: string): boolean {
return !isArchiveAsset(name) && !name.endsWith(".sha256");
}
/**
* Picks the release asset for this platform.
*
* Prefer the compressed archive, which is roughly a third of the raw binary (25–39 MB against
* 67–102 MB) — that is the difference between a fast and a slow `seal-use update`, and it matches
* which asset the Gitea mirror uploads first.
*
* Windows still prefers the raw `.exe`: extracting the `.zip` there would depend on an `unzip`
* binary that stock Windows does not ship. Both are published for every platform, so the other one
* remains a working fallback.
*/
export function matchAssetForPlatform(
assets: GitHubAsset[],
platform: "darwin" | "linux" | "windows",
arch: "arm64" | "x64"
@@ -512,17 +581,15 @@ function matchAssetForPlatform(
return matchesP && matchesA;
});
// Prefer direct raw executable over tar.gz / zip if both exist
const directBinary = matched.find(
(asset) => !asset.name.endsWith(".tar.gz") && !asset.name.endsWith(".tgz") && !asset.name.endsWith(".zip") && !asset.name.endsWith(".sha256")
);
if (directBinary) return directBinary;
// A `.sha256` sidecar matches the platform/arch keywords too, and it is never installable.
const candidates = matched.filter((asset) => !asset.name.endsWith(".sha256"));
const archive = candidates.find((asset) => isArchiveAsset(asset.name));
const directBinary = candidates.find((asset) => isRawBinaryAsset(asset.name));
// Fallback to archive
const archive = matched.find(
(asset) => asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz") || asset.name.endsWith(".zip")
);
return archive || matched[0];
if (platform === "windows") {
return directBinary ?? archive ?? candidates[0];
}
return archive ?? directBinary ?? candidates[0];
}
function logProgress(msg: string) {
@@ -715,6 +782,38 @@ async function downloadFile(url: string, destPath: string, tagName?: string, ass
throw new Error(`Failed to download asset from all mirrors: ${lastError?.message}`);
}
/**
* Lists every regular file under `dir`.
*
* Replaces the previous `find` subprocess: `find` is not available on Windows, so the archive
* path could not have worked there even once the download succeeded.
*/
function listFilesRecursive(dir: string): string[] {
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return [];
}
const found: string[] = [];
for (const entry of entries) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
found.push(...listFilesRecursive(full));
} else if (entry.isFile()) {
found.push(full);
}
}
return found;
}
function resolveExtractedBinary(targetDir: string, platform: string, fallback: string): string {
const expectedName = platform === "windows" ? "seal-use.exe" : "seal-use";
const files = listFilesRecursive(targetDir);
return files.find((file) => basename(file) === expectedName) ?? files[0] ?? fallback;
}
function extractTarGz(archivePath: string, targetDir: string, platform: string): string {
const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" });
if (result.status !== 0) {
@@ -722,16 +821,7 @@ function extractTarGz(archivePath: string, targetDir: string, platform: string):
}
unlinkSync(archivePath);
// Look for executable in targetDir
const expectedName = platform === "windows" ? "seal-use.exe" : "seal-use";
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
.stdout.trim()
.split("\n")
.filter(Boolean);
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
if (exact) return exact;
return files[0] || archivePath;
return resolveExtractedBinary(targetDir, platform, archivePath);
}
function extractZip(archivePath: string, targetDir: string, platform: string): string {
@@ -741,15 +831,7 @@ function extractZip(archivePath: string, targetDir: string, platform: string): s
}
unlinkSync(archivePath);
const expectedName = platform === "windows" ? "seal-use.exe" : "seal-use";
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
.stdout.trim()
.split("\n")
.filter(Boolean);
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
if (exact) return exact;
return files[0] || archivePath;
return resolveExtractedBinary(targetDir, platform, archivePath);
}
export function compareSemVer(v1: string, v2: string): number {
+1 -1
View File
@@ -226,7 +226,7 @@ describe("CLI help execution for lifecycle commands", () => {
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("approval-runs count [--status APPROVED] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>]");
expect(result.stdout).toContain("approval-runs export [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only]");
expect(result.stdout).toContain("approval-runs export [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only]");
});
test("analytics export --help prints force parameter usage", async () => {
+82 -3
View File
@@ -144,7 +144,45 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "add-link",
summary: "Import enterprise configuration from a Hose assistance link",
usage: ["seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]"]
usage: [
"seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--as-hose] [--app-key <key>] [--key-id <id>] [--overwrite]"
],
options: [
{ flag: "--name <name>", description: "Optional custom name for the enterprise" },
{ flag: "--as-hose", description: "【合思子域提权】从协助链接提取 OpenAPI 密钥并将临时会话升级为长期合思标准配置" },
{ flag: "--app-key <key>", description: "企业存在多套密钥时,指定使用的 appKey" },
{ flag: "--key-id <id>", description: "企业存在多套密钥时,指定使用的 keyId" },
{ flag: "--overwrite", description: "Overwrite existing enterprise config" }
]
},
{
name: "extract-keys",
aliases: ["extract-key"],
summary: "【合思子域提权】从合思协助链接提取 OpenAPI 开发者密钥 (appKey/appSecurity)",
usage: [
"seal-use corps extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]"
],
options: [
{ flag: "--reveal, -r", description: "显式揭示完整 appSecurity 明文(默认脱敏保护)" },
{ flag: "--save", description: "【提权升级】将提取到的合思 OpenAPI 密钥保存为长期标准配置" },
{ flag: "--app-key <key>", description: "存在多套密钥时指定使用的 appKey" },
{ flag: "--key-id <id>", description: "存在多套密钥时指定使用的 keyId" },
{ flag: "--name <name>", description: "Custom enterprise name when saving" },
{ flag: "--overwrite", description: "Overwrite existing enterprise config" }
],
description: "专属于合思 (Hose/合思云/易快报) 子域的能力。利用协助链接中的内部权限读取 OpenAPI 密钥,将临时会话提权为标准开发者凭据。非合思渠道企业不支持。"
},
{
name: "keys",
summary: "【合思子域】查看企业已配置的合思 OpenAPI 密钥,或从协助链接中提取",
usage: [
"seal-use corps keys [<url> | <corpId>] [--reveal] [--save] [--app-key <key>]"
],
options: [
{ flag: "--reveal, -r", description: "显式揭示完整 appSecurity 明文(默认脱敏保护)" },
{ flag: "--save", description: "从协助链接提取并保存为标准配置" },
{ flag: "--app-key <key>", description: "多套密钥时指定目标 appKey" }
]
},
{
name: "regression",
@@ -350,8 +388,26 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "export",
summary: "Export approval run audit records to Excel workbook",
usage: ["seal-use approval-runs export [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads] [--out <file>] [--corp <corpId>]"]
summary: "Export approval run audit records to Excel workbook. Add --with-flow to include E人工行为 / E人工意见 columns (requires Hose Open API; adds ~30s for large batches).",
usage: ["seal-use approval-runs export [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads|--to-downloads] [--with-flow] [--out <file>] [--corp <corpId>]"],
options: [
{ flag: "--sn, --sns <SNs>", description: "Target specific document SNs (comma-separated, e.g. B26002307,B26002144); fast indexed search bypassing full pagination" },
{ flag: "--with-flow", description: "Enrich export with Hose human actions and opinions in E人工行为 / E人工意见 columns (rejection 2-B, mid-flow modifications, action emojis)" },
{ flag: "--start <date>", description: "Filter records by start date (YYYY-MM-DD or ms timestamp)" },
{ flag: "--end <date>", description: "Filter records by end date (YYYY-MM-DD or ms timestamp)" },
{ flag: "--force", description: "Force export when time range exceeds 180 days" },
{ flag: "--status <status>", description: "Filter by system status (e.g. completed, processing)" },
{ flag: "--manual-status <status>", description: "Filter by manual approval status (e.g. APPROVED, TERMINATED)" },
{ flag: "--completed-only", description: "Only export completed approval runs" },
{ flag: "--limit <n>", description: "Maximum number of records to export" },
{ flag: "--downloads, --to-downloads", description: "Save exported workbook directly to user's ~/Downloads directory" },
{ flag: "--out <file>", description: "Custom output file path" }
]
},
{
name: "flow",
summary: "Get Hose approval flow timeline, staff opinions, and align with AI runs",
usage: ["seal-use approval-runs flow <recordId|SN> [--corp <corpId>]"]
},
{
name: "list",
@@ -622,6 +678,29 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "hose-link",
summary: "Generate Hose third-party assistance link",
usage: ["seal-use auth hose-link [--corp <corpId>] [--expire 7200]"]
},
{
name: "extract-keys",
summary: "【合思子域提权】从合思协助链接提取 OpenAPI 开发者密钥并可选升级配置",
usage: [
"seal-use auth extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]"
],
options: [
{ flag: "--reveal, -r", description: "显式揭示完整 appSecurity 明文(默认脱敏保护)" },
{ flag: "--save", description: "【提权升级】直接将提取到的合思 OpenAPI 密钥持久化为标准企业配置" },
{ flag: "--app-key <key>", description: "存在多套密钥时指定使用的 appKey" },
{ flag: "--key-id <id>", description: "存在多套密钥时指定使用的 keyId" }
],
description: "专属于合思 (Hose/合思云/易快报) 子域的能力。非合思渠道企业不支持。"
},
{
name: "keys",
summary: "【合思子域】查看当前企业已配置的合思 OpenAPI 开发者密钥",
usage: ["seal-use auth keys [--corp <corpId>] [--reveal]"],
options: [
{ flag: "--reveal, -r", description: "显式揭示完整 appSecurity 明文(默认脱敏保护)" }
],
description: "专属于合思 (Hose) 来源企业。原生 Seal 企业不包含 OpenAPI 密钥,不支持此命令。"
}
]
},
+164
View File
@@ -0,0 +1,164 @@
import { describe, expect, test } from "bun:test";
import { readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { HELP_REGISTRY } from "./help.js";
import { KNOWN_AREAS } from "./runner.js";
import { SEAL_MUTATING_TOOLS, SEAL_READ_ONLY_TOOLS, sealTools } from "../domains/seal/tools.js";
import { isReadOnlyCliCommand, listReadOnlyCommands } from "./read-only.js";
describe("CLI read-only classification", () => {
test("the tool registry is classified exhaustively and without overlap", () => {
const all = sealTools.map((tool) => tool.name);
const classified = [...SEAL_READ_ONLY_TOOLS, ...SEAL_MUTATING_TOOLS];
// A newly added tool must fail here rather than silently defaulting into either bucket.
expect(classified.slice().sort()).toEqual(all.slice().sort());
for (const name of SEAL_READ_ONLY_TOOLS) {
expect({ name, alsoMutating: SEAL_MUTATING_TOOLS.has(name) }).toEqual({ name, alsoMutating: false });
}
});
// Actions the dispatcher accepts that carry no help-registry row, so they are documented
// nowhere else. Kept explicit: anything not a registry entry and not listed here fails below.
const ACTIONS_WITHOUT_REGISTRY_ENTRY = new Set(["approval-runs search"]);
test("every allow-listed command exists in the help registry", () => {
const byArea = new Map(HELP_REGISTRY.map((area) => [area.area, area.commands.map((c) => c.name)]));
for (const { area, action } of listReadOnlyCommands()) {
if (ACTIONS_WITHOUT_REGISTRY_ENTRY.has(`${area} ${action}`)) continue;
expect({ area, dispatchable: KNOWN_AREAS.has(area) }).toEqual({ area, dispatchable: true });
expect({ area, action, known: byArea.get(area)?.includes(action) }).toEqual({
area,
action,
known: true
});
}
});
test("allows read-only commands, including through area aliases and positional arguments", () => {
for (const command of [
["corps", "list"],
["corp", "list"],
["corp", "get", "corp-a"],
["approval-runs", "get", "01a09dac-c688-767b-8eb4-37b945095585"],
["approval-runs", "list", "--corp", "corp-a"],
["deploy", "hosecloud", "status", "--corp", "corp-a"],
["preferences", "get"],
["doctor", "tenant", "--corp", "corp-a"],
["openapi"],
["version"],
["mcp-config"]
]) {
expect({ command, readOnly: isReadOnlyCliCommand(command) }).toEqual({ command, readOnly: true });
}
});
test("refuses mutating, unclassified, and server-lifetime commands", () => {
for (const command of [
["corps", "mark", "corp-a", "--env", "production"],
["corps", "switch", "corp-a"],
["corps", "extract-keys", "corp-a"],
["corps", "sync-test", "corp-a"],
["rules", "push"],
["rules", "clear"],
["simulation", "create", "--mode", "hosecloud"],
["deploy", "hosecloud", "sync", "sign-key"],
["deploy", "hosecloud", "configure"],
["webhook", "delete", "hook-1"],
["webhook", "replay"],
["users", "reset-password", "corp-a:u1"],
["users", "create"],
["config", "test-dir", "corp-a"],
["skill", "install"],
["service", "start"],
["service", "run"],
["mcp"],
["http"],
["update"],
["stop"],
["auth", "keys"],
["analytics", "analyze", "record-1"],
["tool", "seal_approval_rule_create", "--json", "{}"],
["tool", "seal_webhook_delete", "--json", "{}"],
["tool", "seal_insight_record_analyze", "--json", "{}"],
["tool"],
["totally-unknown", "list"],
[]
]) {
expect({ command, readOnly: isReadOnlyCliCommand(command) }).toEqual({ command, readOnly: false });
}
});
test("routes `seal-use tool` through the tool registry's own classification", () => {
for (const command of [
["tool", "seal_approval_search", "--json", "{}"],
["tool", "seal_approval_rules_list", "--corp", "corp-a"],
["tool", "seal_whoami"],
["tool", "seal_approval_run_flow_get", "--json", '{"sn":"B26002352"}']
]) {
expect({ command, readOnly: isReadOnlyCliCommand(command) }).toEqual({ command, readOnly: true });
}
});
test("matches whole tokens, so a read prefix cannot smuggle a mutation", () => {
for (const command of [
["corps", "listing"],
["corps", "list-extra"],
["approval-runs", "getter"],
["rules", "listp"]
]) {
expect({ command, readOnly: isReadOnlyCliCommand(command) }).toEqual({ command, readOnly: false });
}
});
test("a bare allow-listed command does not cover its subcommands", () => {
expect(isReadOnlyCliCommand(["doctor"])).toBe(true);
expect(isReadOnlyCliCommand(["doctor", "guide"])).toBe(true);
expect(isReadOnlyCliCommand(["doctor", "unknown-subcommand"])).toBe(false);
// `openapi` is allow-listed as the bare form only.
expect(isReadOnlyCliCommand(["openapi", "extra"])).toBe(false);
});
test("refuses command lines that cannot be parsed", () => {
expect(isReadOnlyCliCommand(["--json"])).toBe(false);
});
});
// The two classifications are maintained by hand, in different files: the CLI allow-list here and
// SEAL_READ_ONLY_TOOLS in the tool registry. Nothing stopped them from disagreeing, and they did —
// `analytics analyze` was allow-listed while its tool POSTs, and three read-only approval-runs verbs
// were simply missing. This derives one from the other and fails on any new disagreement.
describe("CLI allow-list agrees with the tool registry", () => {
// `deploy` only accepts `deploy hosecloud <action>`; the short `deploy <action>` form throws
// "未知的发布目标系统" at runtime, so these pairs are unreachable rather than refused.
const UNREACHABLE_CLI_FORMS = new Set(["deploy requirements", "deploy list", "deploy status"]);
test("every CLI verb dispatching to a read-only tool is itself read-only", () => {
const files = readdirSync(join(import.meta.dir, "commands")).filter(
(f) => f.endsWith(".ts") && !f.endsWith(".test.ts")
);
const pairs: Array<{ area: string; action: string; tool: string }> = [];
for (const file of files) {
const area = file.replace(/\.ts$/, "");
const source = readFileSync(join(import.meta.dir, "commands", file), "utf8");
const pattern = /action === "([a-z0-9-]+)"[\s\S]{0,600}?runTool\(\s*"(seal_[a-z_0-9]+)"/g;
let match;
while ((match = pattern.exec(source))) {
pairs.push({ area, action: match[1]!, tool: match[2]! });
}
}
// If the dispatch shape changes this silently finds nothing, which would make the test vacuous.
expect(pairs.length).toBeGreaterThan(50);
const disagreements = pairs
.filter((pair) => SEAL_READ_ONLY_TOOLS.has(pair.tool))
.filter((pair) => !UNREACHABLE_CLI_FORMS.has(`${pair.area} ${pair.action}`))
.filter((pair) => !isReadOnlyCliCommand([pair.area, pair.action]))
.map((pair) => `${pair.area} ${pair.action} -> ${pair.tool}`);
expect(disagreements).toEqual([]);
});
});
+136
View File
@@ -0,0 +1,136 @@
import { isReadOnlySealTool } from "../domains/seal/tools.js";
import { parseArgs } from "./parser.js";
/**
* Read-only classification for CLI commands, used to decide whether a command may be executed
* through the read-only MCP tool.
*
* This is an allow-list: anything not listed here — including a command added to the CLI later —
* is treated as mutating. The failure mode is therefore a refused read, never an unsafe write.
*
* Matching is token-wise prefix, because positional arguments are parsed into the command: a
* command line of `approval-runs get 01a09dac...` must still match the allowed `approval-runs get`.
* Prefix matching is boundary-safe by construction: `list-evil` does not match `list`.
*/
/** Area aliases the CLI dispatches under an alternative name; mirrors the pairs in runner.ts. */
const AREA_ALIASES: Record<string, string> = {
corp: "corps",
webhooks: "webhook",
preferences: "preference"
};
/**
* Commands that only read tenant state, produce a local file, or inspect local configuration.
* Deliberately excluded even though they look harmless: anything that writes local config
* (`corps switch`, `config test-dir`), mints or prints credentials (`auth keys`, `corps keys`),
* self-updates (`update`), or stands up a long-running server (`http`, `mcp`, `service run`).
*/
const READ_ONLY_COMMANDS: Record<string, string[]> = {
corps: ["list", "search", "get", "current"],
rules: ["count", "list", "versions", "version", "get", "search", "lint", "linters", "pull"],
webhook: ["ready", "status", "list", "get", "resource-pack export", "resource-pack preview"],
"approval-runs": [
"summary",
"stats",
"count",
"export",
"flow",
"list",
// `search` is an accepted alias of `list` in the dispatcher but has no help-registry entry.
"search",
"pick",
"bridge",
"get",
"cited-rules",
"document-summary",
"attachments",
"result",
"url"
],
simulation: [
"batch-records",
"status",
"wait",
"specifications",
"approval-definitions",
"list",
"get",
"templates",
"integrations"
],
deploy: ["hosecloud requirements", "hosecloud list", "hosecloud get", "hosecloud status"],
preference: ["get", "thinking-depth policies list"],
config: ["paths", "get", "mode", "lint"],
auth: ["diagnose"],
delegation: ["list"],
users: ["search", "get", "delegation"],
contacts: ["departments", "children", "users", "sync-time"],
data: ["expenses", "invoices"],
llm: ["config", "providers"],
permissions: ["available", "configs"],
billing: ["status", "plans", "features"],
// `analyze` is deliberately absent: it POSTs and starts an analysis server-side, so it is a
// mutation despite reading like a query. See SEAL_MUTATING_TOOLS.
analytics: ["insight", "risks", "performance", "export"],
source: ["config"],
tools: ["list"],
skill: ["dump", "status"],
service: ["status", "logs"],
doctor: ["", "guide", "paths", "tenant"],
openapi: [""]
};
/**
* Read-only commands handled by the CLI outside the help registry (no area/subcommand shape).
* `help` is limited to the bare form on purpose: `help <topic>` adds nothing over the skill docs.
*/
const TOP_LEVEL_READ_ONLY = new Set(["version", "v", "help", "changelog", "mcp-config"]);
export function describeCliCommand(argv: string[]): { area: string; actionTokens: string[] } {
const { command } = parseArgs(argv);
const area = (command[0] ?? "").toLowerCase();
return {
area: AREA_ALIASES[area] ?? area,
actionTokens: command.slice(1).map((token) => token.toLowerCase())
};
}
export function isReadOnlyCliCommand(argv: string[]): boolean {
let area: string;
let actionTokens: string[];
try {
({ area, actionTokens } = describeCliCommand(argv));
} catch {
// Unparsable command lines are refused rather than guessed at.
return false;
}
if (actionTokens.length === 0 && TOP_LEVEL_READ_ONLY.has(area)) return true;
// `seal-use tool <name>` reaches the internal tool registry, which carries its own exhaustive
// read/write classification. Delegating to it keeps the two from drifting apart.
if (area === "tool") {
const toolName = actionTokens[0];
return toolName !== undefined && isReadOnlySealTool(toolName);
}
const allowed = READ_ONLY_COMMANDS[area];
if (!allowed) return false;
return allowed.some((entry) => {
const allowedTokens = entry.split(" ").filter(Boolean);
// A bare command (empty entry) matches only when no subcommand was given, so that listing
// `doctor` does not also cover every `doctor <subcommand>`.
if (allowedTokens.length === 0) return actionTokens.length === 0;
if (allowedTokens.length > actionTokens.length) return false;
return allowedTokens.every((token, index) => token === actionTokens[index]);
});
}
/** Registry-backed entries only; the top-level commands above have no registry row. */
export function listReadOnlyCommands(): Array<{ area: string; action: string }> {
return Object.entries(READ_ONLY_COMMANDS).flatMap(([area, actions]) =>
actions.map((action) => ({ area, action }))
);
}
+6 -1
View File
@@ -7,7 +7,7 @@ import type { CorpConfig } from "../core/config/types.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 { handleAuthCommand, handleAuthExtractKeysCommand } from "./commands/auth.js";
import { handleBillingCommand } from "./commands/billing.js";
import { handleConfigCommand } from "./commands/config.js";
import { handleContactsCommand } from "./commands/contacts.js";
@@ -328,6 +328,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "auth" && (action === "extract-keys" || action === "extract-key")) {
await handleAuthExtractKeysCommand(maybeName, args);
return;
}
const corp = selectCorp(stringOption(args.options.corp));
if (area === "source") {
+14 -5
View File
@@ -218,16 +218,25 @@ function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
return options.quiet ? undefined : { stopped: true, pid };
}
/**
* A pid file only proves that *some* process holds that pid. Match the recorded identity as argv
* tokens — the exact `service run` subcommand pair plus a path to this app or a seal-use launcher
* — instead of as substrings anywhere in the command line, so a stale pid cannot make an
* unrelated process look like our daemon and get signalled by `service stop`.
*/
function isSealHomeProcess(pid: number, appRoot: string) {
if (!isProcessRunning(pid)) return false;
try {
const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
const matchesTarget =
command.includes(appRoot) ||
command.includes("seal-use") ||
command.includes("src/cli.ts");
return matchesTarget && command.includes("service") && command.includes("run");
const tokens = command.trim().split(/\s+/).filter(Boolean);
const serviceIndex = tokens.indexOf("service");
const runsService = serviceIndex !== -1 && tokens[serviceIndex + 1] === "run";
const isSealUse =
command.includes(appRoot) || tokens.some((token) => /(^|[\\/])(seal-use|seal-home)(\.exe)?$/.test(token));
return runsService && isSealUse;
} catch {
return false;
}
+74
View File
@@ -0,0 +1,74 @@
/**
* Splits a command line into argv tokens without invoking a shell, so that quoted JSON payloads
* reach the CLI intact. Lives in its own module because both the MCP server and the HTTP routes
* need it; importing it from the server entry would make the CLI graph circular.
*/
export function tokenizeCommand(command: string): string[] {
const tokens: string[] = [];
let token = "";
let quote: "'" | '"' | undefined;
let escaped = false;
let tokenStarted = false;
for (const character of command) {
if (escaped) {
token += character;
escaped = false;
tokenStarted = true;
continue;
}
if (character === "\\" && quote !== "'") {
escaped = true;
tokenStarted = true;
continue;
}
if (quote) {
if (character === quote) {
quote = undefined;
} else {
token += character;
}
tokenStarted = true;
continue;
}
if (character === "'" || character === '"') {
quote = character;
tokenStarted = true;
continue;
}
if (/\s/.test(character)) {
if (tokenStarted) {
tokens.push(token);
token = "";
tokenStarted = false;
}
continue;
}
token += character;
tokenStarted = true;
}
if (escaped) throw new Error("Invalid command: trailing escape");
if (quote) throw new Error("Invalid command: unterminated quote");
if (tokenStarted) tokens.push(token);
return tokens;
}
export function normalizeCliArgs(tokens: string[]): string[] {
const first = tokens[0];
if (!first) return [];
if (
first === "seal-use" ||
first === "seal-home" ||
first.endsWith("/seal-use") ||
first.endsWith("/seal-home")
) {
return tokens.slice(1);
}
return tokens;
}
+71 -1
View File
@@ -132,7 +132,8 @@ describe("hose auth helpers", () => {
expect(result).toEqual({
corpId: "acme-01",
accessToken: "temporary-token"
accessToken: "temporary-token",
baseUrl: "https://wx2.ekuaibao.com"
});
});
@@ -197,4 +198,73 @@ describe("hose auth helpers", () => {
hoseCorpConfig: { corporationId: " ACME-01 " }
})).not.toThrow();
});
test("fetchHoseOpenApiKeysFromLink extracts keys with discovered metadata", async () => {
const { fetchHoseOpenApiKeysFromLink, maskHoseSecurity } = await import("./hose.js");
expect(maskHoseSecurity("1234567890abcdef")).toBe("12345678...cdef");
expect(maskHoseSecurity("short")).toBe("******");
expect(maskHoseSecurity("")).toBe("-");
const jwtPayload = Buffer.from(
JSON.stringify({
staffId: "acme-01:admin01",
corporationName: "Acme Corp Ltd",
staffName: "Alice Admin"
})
).toString("base64url");
const fakeJwt = `header.${jwtPayload}.signature`;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
const url = new URL(urlStr);
if (url.pathname === "/api/engine/realm/$UNITY/actions/jwt") {
return new Response(JSON.stringify({ value: fakeJwt }), {
status: 200,
headers: { "content-type": "application/json" }
});
}
if (url.pathname === "/api/innerapi/v1/key") {
const reqHeaders = input instanceof Request ? input.headers : new Headers(init?.headers);
expect(reqHeaders.get("accesstoken")).toBe("test-token");
expect(reqHeaders.get("corpid")).toBe("acme-01");
expect(reqHeaders.get("staffid")).toBe("acme-01:admin01");
return new Response(
JSON.stringify({
items: [
{
id: "key-001",
name: "生产系统接入",
appKey: "ak_acme_production_123",
appSecurity: "sec_secret_password_456789",
active: true,
corporationId: "acme-01",
createTime: 1700000000000
}
],
count: 1
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
return new Response("not found", { status: 404 });
}) as typeof fetch;
const res = await fetchHoseOpenApiKeysFromLink(
"https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=test-token&ekbCorpId=Acme-01"
);
expect(res.corpId).toBe("acme-01");
expect(res.corpName).toBe("Acme Corp Ltd");
expect(res.staffId).toBe("acme-01:admin01");
expect(res.baseUrl).toBe("https://wx2.ekuaibao.com");
expect(res.keys.length).toBe(1);
expect(res.keys[0]!.appKey).toBe("ak_acme_production_123");
expect(res.keys[0]!.appSecurity).toBe("sec_secret_password_456789");
expect(res.keys[0]!.active).toBe(true);
});
});
+190 -3
View File
@@ -45,6 +45,7 @@ type SealTokenResponse = {
export type HoseAssistLink = {
corpId: string;
accessToken: string;
baseUrl?: string;
};
export type HoseAssistSealSession = {
@@ -151,7 +152,8 @@ export function parseHoseAssistLink(value: string): HoseAssistLink {
return {
corpId,
accessToken: accessTokens[0]!
accessToken: accessTokens[0]!,
baseUrl: url.origin
};
}
@@ -221,12 +223,14 @@ function isHoseAssistHost(hostname: string): boolean {
function normalizeHoseAssistLink(value: HoseAssistLink): HoseAssistLink {
const corpId = typeof value?.corpId === "string" ? value.corpId.trim().toLowerCase() : "";
const accessToken = typeof value?.accessToken === "string" ? value.accessToken.trim() : "";
const baseUrl = typeof value?.baseUrl === "string" && value.baseUrl.trim() ? value.baseUrl.trim() : undefined;
if (!CORP_ID_PATTERN.test(corpId) || !accessToken) {
throw new Error("Invalid Hose assistance link: accessToken and ekbCorpId are required");
}
return {
corpId,
accessToken
accessToken,
...(baseUrl ? { baseUrl } : {})
};
}
@@ -357,7 +361,7 @@ export async function fetchHoseCloseApiToken(
};
}
async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<TokenEntry> {
export async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<TokenEntry> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
}
@@ -721,3 +725,186 @@ export async function fetchHoseStaffDetails(
return json.items ?? [];
}
// ── OpenAPI Key Extraction from Assistance Link ──────────────────────────────
export type HoseOpenApiKey = {
id: string;
name?: string;
appKey: string;
appSecurity: string;
active: boolean;
corporationId?: string;
createTime?: number;
updateTime?: number;
};
export type HoseAssistLinkDetails = {
corpId: string;
baseUrl: string;
accessToken: string;
staffId: string;
corpName?: string;
staffName?: string;
isAdmin?: boolean;
cellphone?: string;
};
export type HoseLinkKeysResult = {
corpId: string;
corpName?: string;
baseUrl: string;
staffId: string;
keys: HoseOpenApiKey[];
};
export function maskHoseSecurity(secret: string): string {
if (!secret) return "-";
if (secret.length <= 12) return "******";
return `${secret.slice(0, 8)}...${secret.slice(-4)}`;
}
export async function resolveHoseAssistLinkDetails(
value: string | HoseAssistLink
): Promise<HoseAssistLinkDetails> {
const link = typeof value === "string" ? parseHoseAssistLink(value) : normalizeHoseAssistLink(value);
const baseUrl = link.baseUrl || "https://app.ekuaibao.com";
let staffId: string | undefined;
let corpName: string | undefined;
let staffName: string | undefined;
let isAdmin: boolean | undefined;
let cellphone: string | undefined;
const headers: Record<string, string> = {
accesstoken: link.accessToken,
corpid: link.corpId
};
// 1. Try resolving staffId, corporationName, and staffName via $UNITY JWT
try {
const jwtRes = await ky
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
searchParams: { corpId: link.corpId },
headers,
timeout: 10000
})
.json<{ id?: string; value?: string }>();
const token = jwtRes.id || jwtRes.value;
if (token) {
const parts = token.split(".");
if (parts.length >= 2) {
const base64 = parts[1]!.replace(/-/g, "+").replace(/_/g, "/");
const payload = JSON.parse(Buffer.from(base64, "base64").toString("utf-8")) as Record<string, unknown>;
if (typeof payload.staffId === "string") staffId = payload.staffId;
if (typeof payload.corporationName === "string") corpName = payload.corporationName;
if (typeof payload.staffName === "string") staffName = payload.staffName;
if (typeof payload.cellphone === "string") cellphone = payload.cellphone;
if (payload.isAdmin !== undefined) {
isAdmin = payload.isAdmin === true || payload.isAdmin === "true";
}
}
}
} catch {
// Ignore and fallback
}
// 2. If staffId or corpName is still missing, fallback to /api/account/v2/session
if (!staffId || !corpName) {
try {
const sessionRes = await ky
.get(`${baseUrl}/api/account/v2/session`, {
headers: {
...headers,
...(staffId ? { staffid: staffId } : {})
},
timeout: 10000
})
.json<{
value?: {
id?: string;
userId?: string;
loginStaffId?: string;
corporationId?: string;
corporationName?: string;
privilege?: string;
};
}>();
const s = sessionRes?.value;
if (s) {
if (!staffId && s.loginStaffId) staffId = s.loginStaffId;
if (!corpName && s.corporationName) corpName = s.corporationName;
if (!staffName && s.privilege) staffName = s.privilege;
}
} catch {
// Ignore
}
}
// Default staffId if still unresolved
if (!staffId) {
staffId = `${link.corpId}:admin`;
}
return {
corpId: link.corpId,
baseUrl,
accessToken: link.accessToken,
staffId,
corpName,
staffName,
isAdmin,
cellphone
};
}
export async function fetchHoseOpenApiKeysFromLink(
value: string | HoseAssistLink
): Promise<HoseLinkKeysResult> {
const details = await resolveHoseAssistLinkDetails(value);
const headers: Record<string, string> = {
accesstoken: details.accessToken,
corpid: details.corpId,
staffid: details.staffId
};
let json: { items?: unknown[]; count?: number };
try {
const response = await ky.get(`${details.baseUrl}/api/innerapi/v1/key`, {
searchParams: { corpId: details.corpId },
headers,
timeout: 15000
});
json = (await response.json()) as { items?: unknown[]; count?: number };
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to query Hose OpenAPI keys from assistance link: ${msg}`);
}
const rawItems = json.items ?? [];
const keys: HoseOpenApiKey[] = [];
for (const raw of rawItems) {
if (typeof raw === "object" && raw !== null) {
const item = raw as Record<string, unknown>;
if (typeof item.appKey === "string" && typeof item.appSecurity === "string") {
keys.push({
id: String(item.id ?? item.appKey),
name: typeof item.name === "string" ? item.name : undefined,
appKey: item.appKey,
appSecurity: item.appSecurity,
active: typeof item.active === "boolean" ? item.active : true,
corporationId: typeof item.corporationId === "string" ? item.corporationId : details.corpId,
createTime: typeof item.createTime === "number" ? item.createTime : undefined,
updateTime: typeof item.updateTime === "number" ? item.updateTime : undefined
});
}
}
}
return {
corpId: details.corpId,
corpName: details.corpName,
baseUrl: details.baseUrl,
staffId: details.staffId,
keys
};
}
+52
View File
@@ -5,6 +5,7 @@ import { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR } from "../../domains/seal/li
import { VERSION } from "../../version.js";
import { loadCorpConfigs, loadGlobalConfig } from "../config/loader.js";
import { getDefaultGlobalSkillDir } from "../embedded-skill.js";
import { resolveUsageFilePath } from "../stats/usage-tracker.js";
import {
EMBEDDED_DIRECTORY_SPECS,
EMBEDDED_DOMAIN_CAPABILITIES,
@@ -72,6 +73,37 @@ function isPathWritable(path: string): boolean {
}
}
/**
* Lists the JSON configs in a directory, skipping the shipped `example.*.json` templates: those
* hold placeholders only, so their default mode is not a finding.
*/
function listCredentialFilePaths(dir: string): string[] {
if (!existsSync(dir)) return [];
try {
return readdirSync(dir)
.filter((file) => file.endsWith(".json") && !file.startsWith("example."))
.map((file) => join(dir, file));
} catch {
return [];
}
}
/**
* The tool writes credential-bearing files 0o600 (`core/config/loader.ts`,
* `cli/commands/corps.ts`, `core/auth/token-store.ts`), but a file placed by hand keeps the
* 0o644 default — and `enterprises/local.json` holds a plaintext Hose app key and password.
* Report those rather than assuming the writers' mode.
*/
function findGroupOrWorldReadable(paths: string[]): string[] {
return paths.filter((path) => {
try {
return (statSync(path).mode & 0o077) !== 0;
} catch {
return false;
}
});
}
/**
* Pure, read-only system diagnostic and health inspection.
* Never creates, mutates, or deletes any files on the filesystem.
@@ -247,6 +279,26 @@ export function diagnoseSystem(): DoctorDiagnosis {
});
}
// Check 5: Credential file permissions
const credentialFiles = [
tokenStore,
globalConfigFile,
resolveUsageFilePath(),
...listCredentialFilePaths(enterprisesDir),
...listCredentialFilePaths(join(process.cwd(), "enterprises"))
].filter((path, index, all) => all.indexOf(path) === index && existsSync(path));
const looseCredentialFiles = findGroupOrWorldReadable(credentialFiles);
checks.push({
id: "credential_permissions",
title: "凭据文件权限",
status: looseCredentialFiles.length === 0 ? "ok" : "warn",
message:
looseCredentialFiles.length === 0
? `已检查 ${credentialFiles.length} 个凭据文件,均为仅属主可读 (0600)`
: `${looseCredentialFiles.length} 个凭据文件权限宽于 0600(同机其他用户可读,取决于父目录权限),建议 chmod 600:${looseCredentialFiles.join("、")}`
});
const hasWarning = checks.some((c) => c.status === "warn" || c.status === "error");
const engine = typeof (globalThis as any).Bun !== "undefined"
+35 -1
View File
@@ -2,7 +2,15 @@ import { describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { EMBEDDED_SKILL_FILES, getSkillContent, installSkillFiles } from "./embedded-skill.js";
import packageJson from "../../package.json" with { type: "json" };
import {
EMBEDDED_SKILL_FILES,
EMBEDDED_SKILL_VERSION,
getSkillContent,
installSkillFiles,
parseSkillVersion,
readInstalledSkillVersion
} from "./embedded-skill.js";
describe("embedded-skill", () => {
test("embeds SKILL.md and reference files", () => {
@@ -27,3 +35,29 @@ describe("embedded-skill", () => {
}
});
});
describe("embedded-skill version contract", () => {
// A version-tagged document that nothing asserts on drifts silently: `seal-use update` shipped
// the previous release's skill for several versions, because "the file was written" looked like
// success from every angle. Keeping the skill and the package in step is a failing test now
// rather than a discovery.
test("the skill's version matches the package version", () => {
expect(EMBEDDED_SKILL_VERSION).toBe(packageJson.version);
});
test("parses the version out of SKILL.md front matter", () => {
expect(parseSkillVersion("---\nname: seal-use\nversion: 1.2.3\n---\n")).toBe("1.2.3");
expect(parseSkillVersion("# no front matter here")).toBeUndefined();
});
test("reads back the version of an installed skill", () => {
const tmp = mkdtempSync(join(tmpdir(), "skill-version-"));
try {
const res = installSkillFiles(tmp);
expect(readInstalledSkillVersion(join(res.targetDir, "SKILL.md"))).toBe(EMBEDDED_SKILL_VERSION);
expect(readInstalledSkillVersion(join(tmp, "missing.md"))).toBeUndefined();
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
});
+27 -1
View File
@@ -1,4 +1,4 @@
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
@@ -32,6 +32,32 @@ export function getSkillContent(): string {
return EMBEDDED_SKILL_FILES["SKILL.md"] || "";
}
/**
* Reads the `version:` field out of a SKILL.md front matter block.
*
* The skill is versioned separately from the code that reads it, and that separation is exactly
* how `seal-use update` shipped a stale skill across several releases: writing the file reported
* success either way, so the version is the only signal that says *which generation* of the
* document actually landed on disk.
*/
export function parseSkillVersion(markdown: string): string | undefined {
return markdown.match(/^\s*version:\s*(\S+)\s*$/m)?.[1];
}
/** Reads the version of an installed SKILL.md, or `undefined` when it is missing or unreadable. */
export function readInstalledSkillVersion(
skillFile: string = join(getDefaultGlobalSkillDir(), "SKILL.md")
): string | undefined {
try {
return parseSkillVersion(readFileSync(skillFile, "utf8"));
} catch {
return undefined;
}
}
/** The version of the skill compiled into this build, used to assert what an install wrote. */
export const EMBEDDED_SKILL_VERSION = parseSkillVersion(getSkillContent());
export function getDefaultGlobalSkillDir(): string {
return join(homedir(), ".agents", "skills", "seal-use");
}
+3 -1
View File
@@ -66,7 +66,9 @@ function saveUsageStatsAtomic(stats: CorpUsageStats, targetPath: string = resolv
}
const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2, 8)}.tmp`;
try {
writeFileSync(tempPath, JSON.stringify(stats, null, 2), "utf-8");
// 0o600 like `seal_tokens.json`: usage rows name the enterprises this machine has been
// operating, so keep them owner-only instead of inheriting the 0o644 default.
writeFileSync(tempPath, JSON.stringify(stats, null, 2), { encoding: "utf-8", mode: 0o600 });
renameSync(tempPath, targetPath);
} catch (err) {
try {
+44
View File
@@ -0,0 +1,44 @@
// --- Hose OpenAPI (hose-open) ---
export {
fetchHoseOpenFlowDetails,
fetchHoseOpenAllLogs,
fetchHoseOpenVersioned,
fetchHoseOpenCompositeFlow,
type FetchHoseOpenVersionedOptions
} from "./open/api.js";
// --- Hose CloseAPI (hose-close) ---
export {
searchCloseBacklogs,
getCloseBacklogDetailById,
resolveCloseBacklogId,
fetchRawCloseHoseFlow,
HOSE_CLOSE_LOOKUP_SELECT,
HOSE_CLOSE_DETAIL_SELECT,
HOSE_CLOSE_JOINS,
type SearchCloseBacklogsOptions,
type CloseBacklogDetailOptions
} from "./close/api.js";
// Legacy aliases for backward compatibility
import {
searchCloseBacklogs,
getCloseBacklogDetailById,
resolveCloseBacklogId,
fetchRawCloseHoseFlow,
HOSE_CLOSE_LOOKUP_SELECT,
HOSE_CLOSE_DETAIL_SELECT,
HOSE_CLOSE_JOINS,
type SearchCloseBacklogsOptions,
type CloseBacklogDetailOptions
} from "./close/api.js";
export const HOSE_FLOW_LOOKUP_SELECT = HOSE_CLOSE_LOOKUP_SELECT;
export const HOSE_FLOW_DETAIL_SELECT = HOSE_CLOSE_DETAIL_SELECT;
export const HOSE_FLOW_JOINS = HOSE_CLOSE_JOINS;
export type SearchBacklogsOptions = SearchCloseBacklogsOptions;
export type BacklogDetailOptions = CloseBacklogDetailOptions;
export const searchBacklogs = searchCloseBacklogs;
export const getBacklogDetailById = getCloseBacklogDetailById;
export const resolveBacklogId = resolveCloseBacklogId;
export const fetchRawHoseFlow = fetchRawCloseHoseFlow;
+43
View File
@@ -0,0 +1,43 @@
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../core/config/types.js";
import {
createHoseOpenClient,
createHoseOpenClientWithCredentials,
type HoseOpenClientCredentials
} from "./open/client.js";
import {
createHoseCloseClient,
createHoseCloseClientWithCredentials,
getHoseCloseHeaders,
type HoseCloseClientCredentials
} from "./close/client.js";
// Re-exports with explicit open vs close distinction
export {
createHoseOpenClient,
createHoseOpenClientWithCredentials,
type HoseOpenClientCredentials
} from "./open/client.js";
export {
createHoseCloseClient,
createHoseCloseClientWithCredentials,
getHoseCloseHeaders,
type HoseCloseClientCredentials
} from "./close/client.js";
// Legacy aliases for backward compatibility
export type HoseClientCredentials = HoseCloseClientCredentials;
export const getHoseHeaders = getHoseCloseHeaders;
export const createHoseClientWithCredentials = createHoseCloseClientWithCredentials;
/**
* Default Hose client creator: uses Hose OpenAPI (hose-open).
* Bypasses row-level permission fences and requires no proxy staff ID.
*/
export async function createHoseClient(
corp: CorpConfig,
customHeaders?: Record<string, string>
): Promise<KyInstance> {
return createHoseOpenClient(corp, customHeaders);
}
+118
View File
@@ -0,0 +1,118 @@
import type { KyInstance } from "ky";
import {
RawHoseBacklogItemSchema,
type RawHoseBacklogDetailResponse,
type RawHoseBacklogItem,
type RawHoseBacklogSearchResponse
} from "./types.js";
export const HOSE_CLOSE_LOOKUP_SELECT = "flowId(form(code,title),`...`),`...`";
export const HOSE_CLOSE_DETAIL_SELECT =
"flowId(form(specificationId(id,name,code),`...`),logs(operatorId,nextOperatorId,`...`),plan(`...`),`...`),`...`";
export const HOSE_CLOSE_JOINS = [
"flowId.form.submitterId,submitterId,/v1/organization/staffs?join=defaultDepartment,defaultDepartment,/v1/organization/departments",
"flowId.form.ownerId,ownerId,/v1/organization/staffs?select=id,name,code",
"flowId.form.expenseDepartment,expenseDepartment,/v1/organization/departments",
"flowId.logs.operatorId,operatorId,/v1/organization/staffs?select=id,name,code",
"flowId.logs.nextOperatorId,nextOperatorId,/v1/organization/staffs?select=id,name,code",
"flowId.plan.nodes.approverId,approverId,/v1/organization/staffs?select=id,name,code",
"flowId.plan.nodes.counterSigners.signerId,signerId,/v1/organization/staffs?select=id,name,code"
] as const;
export interface SearchCloseBacklogsOptions {
filterBy: string;
limit?: { start: number; count: number };
select?: string;
}
export interface CloseBacklogDetailOptions {
select?: string;
joins?: readonly string[] | string[];
}
export async function searchCloseBacklogs(
client: KyInstance,
corpId: string,
options: SearchCloseBacklogsOptions
): Promise<RawHoseBacklogItem[]> {
const response = await client.post("api/flow/v2/backlogs/search", {
searchParams: { corpId },
json: {
filterBy: options.filterBy,
limit: options.limit ?? { start: 0, count: 100 },
select: options.select ?? HOSE_CLOSE_LOOKUP_SELECT
}
});
const data = (await response.json()) as RawHoseBacklogSearchResponse;
return (data.items ?? []).map((item) => RawHoseBacklogItemSchema.parse(item));
}
export async function getCloseBacklogDetailById(
client: KyInstance,
corpId: string,
backlogId: string,
options?: CloseBacklogDetailOptions
): Promise<Record<string, unknown> | undefined> {
const params = new URLSearchParams({ corpId });
const joins = options?.joins ?? HOSE_CLOSE_JOINS;
for (const join of joins) {
params.append("join", join);
}
const response = await client.post("api/flow/v2/backlogs/id", {
searchParams: params,
json: {
filterBy: `(id==${JSON.stringify(backlogId)})`,
select: options?.select ?? HOSE_CLOSE_DETAIL_SELECT
}
});
const data = (await response.json()) as RawHoseBacklogDetailResponse;
return data.value ?? data.items?.[0];
}
export async function resolveCloseBacklogId(
client: KyInstance,
corpId: string,
target: string
): Promise<string> {
const cleanTarget = target.trim();
if (!cleanTarget) return target;
const filters = [
`(id==${JSON.stringify(cleanTarget)})||((flowId.id==${JSON.stringify(cleanTarget)})||(flowId.form.code==${JSON.stringify(cleanTarget)}))`,
`(state.in("APPROVING","PROCESSED","REJECTED","DRAFT"))`
];
for (const filterBy of filters) {
try {
const items = await searchCloseBacklogs(client, corpId, {
filterBy,
limit: { start: 0, count: 100 },
select: HOSE_CLOSE_LOOKUP_SELECT
});
const match = items.find((item) => {
const flow = item.flowId && typeof item.flowId === "object" ? (item.flowId as Record<string, unknown>) : {};
const form = flow.form && typeof flow.form === "object" ? (flow.form as Record<string, unknown>) : {};
return item.id === cleanTarget || flow.id === cleanTarget || form.code === cleanTarget;
});
if (match && typeof match.id === "string") {
return match.id;
}
} catch {
// Fall through to next filter or return raw target
}
}
return cleanTarget;
}
export async function fetchRawCloseHoseFlow(
client: KyInstance,
corpId: string,
target: string
): Promise<Record<string, unknown> | undefined> {
const backlogId = await resolveCloseBacklogId(client, corpId, target);
return getCloseBacklogDetailById(client, corpId, backlogId);
}
+64
View File
@@ -0,0 +1,64 @@
import ky, { HTTPError, type KyInstance } from "ky";
import { ensureHoseCloseApiToken, normalizeBaseUrl } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
export interface HoseCloseClientCredentials {
domain: string;
corpId: string;
staffId: string;
accessToken: string;
}
export function getHoseCloseHeaders(credentials: HoseCloseClientCredentials): Record<string, string> {
return {
accesstoken: credentials.accessToken,
corpid: credentials.corpId,
staffid: credentials.staffId
};
}
export function createHoseCloseClientWithCredentials(
credentials: HoseCloseClientCredentials,
customHeaders?: Record<string, string>
): KyInstance {
return ky.create({
prefix: normalizeBaseUrl(credentials.domain),
timeout: 30000,
headers: {
...getHoseCloseHeaders(credentials),
...customHeaders
},
hooks: {
beforeError: [
async ({ error }) => {
const body =
error instanceof HTTPError
? await error.response.text().catch(() => "")
: "";
error.message = `${error.message}${body ? `: ${body}` : ""}`;
return error;
}
]
}
});
}
export async function createHoseCloseClient(
corp: CorpConfig,
customHeaders?: Record<string, string>
): Promise<KyInstance> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Hose source type: ${corp.source.type}. Expected 'hose'.`);
}
const tokenEntry = await ensureHoseCloseApiToken(corp);
return createHoseCloseClientWithCredentials(
{
domain: corp.source.domain,
corpId: corp.source.corpId,
staffId: corp.source.staffId,
accessToken: tokenEntry.token
},
customHeaders
);
}
+3
View File
@@ -0,0 +1,3 @@
export * from "./types.js";
export * from "./client.js";
export * from "./api.js";
+28
View File
@@ -0,0 +1,28 @@
import { z } from "zod";
export const RawHoseBacklogItemSchema = z
.object({
id: z.string(),
state: z.string().optional(),
nodeName: z.string().optional(),
flowId: z.record(z.string(), z.unknown()).optional(),
nodeState: z.record(z.string(), z.unknown()).optional()
})
.passthrough();
export type RawHoseBacklogItem = z.infer<typeof RawHoseBacklogItemSchema>;
export const RawHoseBacklogSearchResponseSchema = z
.object({
count: z.number().optional(),
items: z.array(z.record(z.string(), z.unknown())).default([])
})
.passthrough();
export type RawHoseBacklogSearchResponse = z.infer<typeof RawHoseBacklogSearchResponseSchema>;
export const RawHoseBacklogDetailResponseSchema = z
.object({
value: z.record(z.string(), z.unknown()).optional(),
items: z.array(z.record(z.string(), z.unknown())).optional()
})
.passthrough();
export type RawHoseBacklogDetailResponse = z.infer<typeof RawHoseBacklogDetailResponseSchema>;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
export * from "./types.js";
export * from "./client.js";
export * from "./api.js";
export * from "./flow.js";
export * as hoseOpen from "./open/index.js";
export * as hoseClose from "./close/index.js";
+179
View File
@@ -0,0 +1,179 @@
import type { KyInstance } from "ky";
import { HTTPError } from "ky";
import {
HoseOpenAllLogsResponseSchema,
HoseOpenFlowDetailsResponseSchema,
HoseOpenStaffResponseSchema,
HoseOpenVersionedResponseSchema,
type HoseOpenAllLogsItem,
type HoseOpenCompositeData,
type HoseOpenFlowDetailsValue,
type HoseOpenStaffItem,
type HoseOpenStaffQueryOptions,
type HoseOpenVersionedItem
} from "./types.js";
export async function fetchHoseOpenFlowDetails(
client: KyInstance,
flowId: string
): Promise<HoseOpenFlowDetailsValue | undefined> {
try {
const response = await client
.get("api/openapi/v1.1/flowDetails", {
searchParams: { flowId }
})
.json();
const parsed = HoseOpenFlowDetailsResponseSchema.parse(response);
return parsed.value;
} catch (error) {
if (error instanceof HTTPError && (error.response.status === 404 || error.response.status === 412)) {
return undefined;
}
throw error;
}
}
export async function fetchHoseOpenAllLogs(
client: KyInstance,
flowId: string
): Promise<HoseOpenAllLogsItem[]> {
try {
const response = await client
.get("api/openapi/v1.1/flowDetails/allLogs", {
searchParams: { flowId }
})
.json();
const parsed = HoseOpenAllLogsResponseSchema.parse(response);
return parsed.items;
} catch (error) {
if (error instanceof HTTPError && (error.response.status === 404 || error.response.status === 412)) {
return [];
}
throw error;
}
}
export interface FetchHoseOpenVersionedOptions {
pageNum?: number;
pageSize?: number;
convertFeeType?: boolean;
}
export async function fetchHoseOpenVersioned(
client: KyInstance,
flowId: string,
options?: FetchHoseOpenVersionedOptions
): Promise<HoseOpenVersionedItem[]> {
try {
const response = await client
.get("api/openapi/v1/flow/versioned", {
searchParams: {
flow_id: flowId,
pageNum: options?.pageNum ?? 1,
pageSize: options?.pageSize ?? 20,
convertFeeType: options?.convertFeeType ?? true
}
})
.json();
const parsed = HoseOpenVersionedResponseSchema.parse(response);
return parsed.items;
} catch (error) {
if (error instanceof HTTPError && (error.response.status === 404 || error.response.status === 412)) {
return [];
}
throw error;
}
}
export async function fetchHoseOpenStaffs(
client: KyInstance,
options: HoseOpenStaffQueryOptions
): Promise<HoseOpenStaffItem[]> {
if (!options.conditionIds || options.conditionIds.length === 0) {
return [];
}
try {
const response = await client
.post("api/openapi/v1/staffs/getStaffIds", {
json: {
type: options.type,
conditionIds: options.conditionIds.slice(0, 100)
}
})
.json();
const parsed = HoseOpenStaffResponseSchema.parse(response);
return parsed.items;
} catch (error) {
if (options.conditionIds.length > 1) {
const items: HoseOpenStaffItem[] = [];
for (const id of options.conditionIds) {
try {
const res = await client
.post("api/openapi/v1/staffs/getStaffIds", {
json: { type: options.type, conditionIds: [id] }
})
.json();
const p = HoseOpenStaffResponseSchema.parse(res);
items.push(...p.items);
} catch {
// Gracefully continue on individual failure
}
}
return items;
}
return [];
}
}
export async function fetchHoseOpenCompositeFlow(
client: KyInstance,
flowId: string,
staffCache?: Map<string, HoseOpenStaffItem>
): Promise<HoseOpenCompositeData> {
const [flowDetails, allLogs, versions] = await Promise.all([
fetchHoseOpenFlowDetails(client, flowId),
fetchHoseOpenAllLogs(client, flowId).catch(() => []),
fetchHoseOpenVersioned(client, flowId).catch(() => [])
]);
const staffMap = staffCache ?? new Map<string, HoseOpenStaffItem>();
const missingStaffIds: string[] = [];
const addId = (id?: string | null) => {
if (id && typeof id === "string" && id !== "ebot" && !staffMap.has(id)) {
missingStaffIds.push(id);
}
};
for (const item of allLogs) {
addId(item.ownerId);
}
for (const log of flowDetails?.logs || []) {
addId(log.operatorId);
addId(log.nextOperatorId);
}
const uniqueIds = [...new Set(missingStaffIds)];
if (uniqueIds.length > 0) {
try {
const staffs = await fetchHoseOpenStaffs(client, {
type: "STAFFID",
conditionIds: uniqueIds
});
for (const s of staffs) {
if (s.id) staffMap.set(s.id, s);
if (s.cellphone) staffMap.set(s.cellphone, s);
}
} catch {
// Gracefully continue if staff lookup fails
}
}
return {
flowDetails,
allLogs,
versions,
staffMap
};
}
+55
View File
@@ -0,0 +1,55 @@
import ky, { HTTPError, type KyInstance } from "ky";
import { ensureHoseOpenapiToken, normalizeBaseUrl } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
export interface HoseOpenClientCredentials {
domain?: string;
accessToken: string;
}
export function createHoseOpenClientWithCredentials(
credentials: HoseOpenClientCredentials,
customHeaders?: Record<string, string>
): KyInstance {
const baseUrl = normalizeBaseUrl(credentials.domain || "https://app.ekuaibao.com");
return ky.create({
prefix: baseUrl,
timeout: 30000,
searchParams: {
accessToken: credentials.accessToken
},
headers: {
...customHeaders
},
hooks: {
beforeError: [
async ({ error }) => {
const body =
error instanceof HTTPError
? await error.response.text().catch(() => "")
: "";
error.message = `${error.message}${body ? `: ${body}` : ""}`;
return error;
}
]
}
});
}
export async function createHoseOpenClient(
corp: CorpConfig,
customHeaders?: Record<string, string>
): Promise<KyInstance> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Hose source type: ${corp.source.type}. Expected 'hose'.`);
}
const token = await ensureHoseOpenapiToken(corp);
return createHoseOpenClientWithCredentials(
{
domain: corp.source.domain,
accessToken: token
},
customHeaders
);
}
+3
View File
@@ -0,0 +1,3 @@
export * from "./types.js";
export * from "./client.js";
export * from "./api.js";
+173
View File
@@ -0,0 +1,173 @@
import { z } from "zod";
const nullableString = z.preprocess((v) => (v === null ? undefined : v), z.string().optional());
const nullableBoolean = z.preprocess((v) => (v === null ? undefined : v), z.boolean().optional());
const nullableNumber = z.preprocess((v) => (v === null ? undefined : v), z.number().optional());
// --- Hose OpenAPI: flowDetails ---
export const HoseOpenFlowLogAttributeSchema = z
.object({
nodeId: nullableString,
nodeName: nullableString,
nextId: nullableString,
nextName: nullableString,
comment: nullableString,
isUrgent: nullableBoolean,
isEbotNode: nullableBoolean,
isAuto: nullableBoolean,
isSkip: nullableBoolean,
skipped: nullableBoolean,
counterSign: nullableBoolean,
nextCounterSign: nullableBoolean,
complete: nullableBoolean
})
.passthrough();
export type HoseOpenFlowLogAttribute = z.infer<typeof HoseOpenFlowLogAttributeSchema>;
export const HoseOpenFlowLogSchema = z
.object({
id: nullableString,
action: nullableString,
state: nullableString,
operatorId: nullableString,
nextOperatorId: nullableString,
nextOperatorIds: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(z.string())).default([]),
time: nullableNumber,
attributes: z.preprocess((v) => (v === null ? undefined : v), HoseOpenFlowLogAttributeSchema.optional())
})
.passthrough();
export type HoseOpenFlowLog = z.infer<typeof HoseOpenFlowLogSchema>;
export const HoseOpenFormDetailSchema = z
.object({
code: nullableString,
title: nullableString,
submitterId: nullableString,
submitDate: nullableNumber,
expenseDate: nullableNumber,
rejectionNum: z.preprocess((v) => (v === null ? undefined : v), z.union([z.number(), z.string()]).optional()),
reviewStatus: nullableString,
specificationId: nullableString,
payMoney: z.preprocess((v) => (v === null ? undefined : v), z.record(z.string(), z.unknown()).optional()),
expenseMoney: z.preprocess((v) => (v === null ? undefined : v), z.record(z.string(), z.unknown()).optional()),
details: z.preprocess((v) => (v === null ? undefined : v), z.array(z.record(z.string(), z.unknown())).optional())
})
.passthrough();
export type HoseOpenFormDetail = z.infer<typeof HoseOpenFormDetailSchema>;
export const HoseOpenFlowDetailsValueSchema = z
.object({
id: z.string(),
version: nullableNumber,
state: nullableString,
flowType: nullableString,
formType: nullableString,
ownerId: nullableString,
createTime: nullableNumber,
updateTime: nullableNumber,
form: z.preprocess((v) => (v === null ? undefined : v), HoseOpenFormDetailSchema.optional()),
logs: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenFlowLogSchema)).default([]),
actions: z.preprocess((v) => (v === null ? undefined : v), z.record(z.string(), z.array(z.string())).optional())
})
.passthrough();
export type HoseOpenFlowDetailsValue = z.infer<typeof HoseOpenFlowDetailsValueSchema>;
export const HoseOpenFlowDetailsResponseSchema = z
.object({
value: z.preprocess((v) => (v === null ? undefined : v), HoseOpenFlowDetailsValueSchema.optional())
})
.passthrough();
export type HoseOpenFlowDetailsResponse = z.infer<typeof HoseOpenFlowDetailsResponseSchema>;
// --- Hose OpenAPI: flowDetails/allLogs ---
export const HoseOpenAllLogsItemSchema = z
.object({
id: z.string(),
flowId: nullableString,
nodeId: nullableString,
nodeName: nullableString,
ownerId: nullableString,
state: nullableString,
logId: nullableNumber,
action: nullableString,
createTime: nullableNumber,
updateTime: nullableNumber,
isUrgent: nullableBoolean
})
.passthrough();
export type HoseOpenAllLogsItem = z.infer<typeof HoseOpenAllLogsItemSchema>;
export const HoseOpenAllLogsResponseSchema = z
.object({
count: z.preprocess((v) => (typeof v === "number" ? v : 0), z.number()).default(0),
items: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenAllLogsItemSchema)).default([])
})
.passthrough();
export type HoseOpenAllLogsResponse = z.infer<typeof HoseOpenAllLogsResponseSchema>;
// --- Hose OpenAPI: flow/versioned ---
export const HoseOpenVersionedItemSchema = z
.object({
id: nullableString,
flowId: nullableString,
version: nullableNumber,
state: nullableString,
createTime: nullableNumber,
updateTime: nullableNumber,
form: z.preprocess((v) => (v === null ? undefined : v), HoseOpenFormDetailSchema.optional()),
logs: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenFlowLogSchema)).default([]),
modifyFlowLog: z.preprocess((v) => (Array.isArray(v) ? v : undefined), z.array(z.record(z.string(), z.unknown())).optional())
})
.passthrough();
export type HoseOpenVersionedItem = z.infer<typeof HoseOpenVersionedItemSchema>;
export const HoseOpenVersionedResponseSchema = z
.object({
count: z.preprocess((v) => (typeof v === "number" ? v : 0), z.number()).default(0),
items: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenVersionedItemSchema)).default([])
})
.passthrough();
export type HoseOpenVersionedResponse = z.infer<typeof HoseOpenVersionedResponseSchema>;
// --- Hose OpenAPI Composite Result ---
export interface HoseOpenCompositeData {
flowDetails?: HoseOpenFlowDetailsValue;
allLogs: HoseOpenAllLogsItem[];
versions: HoseOpenVersionedItem[];
staffMap?: Map<string, HoseOpenStaffItem>;
}
// --- Hose OpenAPI: staffs/getStaffIds ---
export const HoseOpenStaffItemSchema = z
.object({
id: z.string(),
name: nullableString,
enName: nullableString,
nickName: nullableString,
code: nullableString,
cellphone: nullableString,
email: nullableString,
active: nullableBoolean,
userId: nullableString,
defaultDepartment: nullableString
})
.passthrough();
export type HoseOpenStaffItem = z.infer<typeof HoseOpenStaffItemSchema>;
export const HoseOpenStaffResponseSchema = z
.object({
items: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenStaffItemSchema)).default([])
})
.passthrough();
export type HoseOpenStaffResponse = z.infer<typeof HoseOpenStaffResponseSchema>;
export interface HoseOpenStaffQueryOptions {
type: "STAFFID" | "CODE" | "CELLPHONE" | "MAIL" | "USERID";
conditionIds: string[];
}
+173
View File
@@ -0,0 +1,173 @@
import { z } from "zod";
export const HOSE_FLOW_ACTION_LABELS: Record<string, string> = {
"freeflow.submit": "提交送审",
"freeflow.agree": "审批同意",
"freeflow.autoAgree": "自动同意",
"freeflow.reject": "审批驳回",
"freeflow.back": "审批退回",
"freeflow.print": "打印单据",
"freeflow.retract": "单据撤回",
"freeflow.addnode": "加签/转交",
"freeflow.comment": "发表评论",
"freeflow.pay": "支付成功",
"freeflow.paying": "发起支付",
"freeflow.carbonCopy": "抄送单据",
"freeflow.cc": "抄送单据"
};
export const HOSE_FLOW_STATE_LABELS: Record<string, string> = {
APPROVING: "审批中",
APPROVED: "审批通过",
REJECTED: "审批驳回",
REVOKED: "已撤回",
CANCELED: "已取消",
CANCELLED: "已取消",
SKIPPED: "已跳过",
SUBMITTED: "已提交",
PENDING: "待审批",
WAITING: "待处理",
COMPLETED: "已完成",
DRAFT: "草稿",
PAID: "已支付",
PAYING: "支付中"
};
export const FlowPersonSchema = z.object({
id: z.string().optional(),
name: z.string().optional(),
code: z.string().optional()
});
export type FlowPerson = z.infer<typeof FlowPersonSchema>;
export const HoseFlowTimelineEntrySchema = z.object({
id: z.string().optional(),
nodeId: z.string().optional(),
time: z.number().optional(),
durationMs: z.number().optional(),
state: z.string().optional(),
rawState: z.string().optional(),
action: z.string().optional(),
rawAction: z.string().optional(),
nodeName: z.string().optional(),
comment: z.string().optional(),
rawComment: z.string().optional(),
automatic: z.boolean().default(false),
isEbot: z.boolean().default(false),
skipped: z.boolean().default(false),
operator: FlowPersonSchema.optional(),
nextOperators: z.array(FlowPersonSchema).default([]),
rejectTargetNodeName: z.string().optional(),
rejectTargetOperator: FlowPersonSchema.optional(),
resubmitRuleText: z.string().optional(),
isModification: z.boolean().default(false)
});
export type HoseFlowTimelineEntry = z.infer<typeof HoseFlowTimelineEntrySchema>;
export const HoseFlowPendingNodeSchema = z.object({
id: z.string().optional(),
name: z.string().optional(),
type: z.string().optional(),
state: z.enum(["当前", "后续", "已完成"]).default("后续"),
isCurrent: z.boolean().default(false),
approver: FlowPersonSchema.optional(),
approvers: z.array(FlowPersonSchema).default([])
});
export type HoseFlowPendingNode = z.infer<typeof HoseFlowPendingNodeSchema>;
export const HoseFlowMetricsSchema = z.object({
rejectionNum: z.number().int().nonnegative().default(0),
submitCount: z.number().int().positive().default(1),
sourceFlowVersion: z.union([z.string(), z.number()]).optional(),
isModifiedAfterReject: z.boolean().default(false),
retractCount: z.number().int().nonnegative().default(0),
isResubmittedAfterRetract: z.boolean().default(false)
});
export type HoseFlowMetrics = z.infer<typeof HoseFlowMetricsSchema>;
export const HoseStaffOpinionSchema = z.object({
nodeName: z.string().optional(),
operator: FlowPersonSchema.optional(),
action: z.string().optional(),
rawAction: z.string().optional(),
time: z.number().optional(),
comment: z.string(),
isEbot: z.boolean().default(false)
});
export type HoseStaffOpinion = z.infer<typeof HoseStaffOpinionSchema>;
export const HoseRejectionDetailSchema = z.object({
time: z.number().optional(),
nodeName: z.string().optional(),
operator: FlowPersonSchema.optional(),
isEbot: z.boolean().default(false),
reason: z.string(),
rawComment: z.string().optional(),
fromNodeName: z.string().optional(),
targetNodeName: z.string().optional(),
targetOperator: FlowPersonSchema.optional(),
resubmitRuleText: z.string().optional()
});
export type HoseRejectionDetail = z.infer<typeof HoseRejectionDetailSchema>;
export const HoseFlowDetailSchema = z.object({
backlogId: z.string(),
flowId: z.string().optional(),
billCode: z.string().optional(),
title: z.string().optional(),
state: z.string().optional(),
rawState: z.string().optional(),
currentNode: z.string().optional(),
specification: z.object({
id: z.string().optional(),
name: z.string().optional(),
code: z.string().optional()
}).optional(),
submitter: FlowPersonSchema.optional(),
owner: FlowPersonSchema.optional(),
submitDate: z.number().optional(),
updateTime: z.number().optional(),
history: z.array(HoseFlowTimelineEntrySchema),
pending: z.array(HoseFlowPendingNodeSchema),
metrics: HoseFlowMetricsSchema,
staffOpinions: z.array(HoseStaffOpinionSchema),
rejections: z.array(HoseRejectionDetailSchema),
raw: z.record(z.string(), z.unknown()).optional()
});
export type HoseFlowDetail = z.infer<typeof HoseFlowDetailSchema>;
export const RawHoseBacklogItemSchema = z.object({
id: z.string(),
state: z.string().optional(),
nodeName: z.string().optional(),
flowId: z.record(z.string(), z.unknown()).optional(),
nodeState: z.record(z.string(), z.unknown()).optional()
}).passthrough();
export type RawHoseBacklogItem = z.infer<typeof RawHoseBacklogItemSchema>;
export const RawHoseBacklogSearchResponseSchema = z.object({
count: z.number().optional(),
items: z.array(z.record(z.string(), z.unknown())).default([])
}).passthrough();
export type RawHoseBacklogSearchResponse = z.infer<typeof RawHoseBacklogSearchResponseSchema>;
export const RawHoseBacklogDetailResponseSchema = z.object({
value: z.record(z.string(), z.unknown()).optional(),
items: z.array(z.record(z.string(), z.unknown())).optional()
}).passthrough();
export type RawHoseBacklogDetailResponse = z.infer<typeof RawHoseBacklogDetailResponseSchema>;
export const HoseRunAlignmentSchema = z.object({
recordId: z.string(),
sourceDocumentSN: z.string().optional(),
taskMode: z.string().optional(),
aiDecision: z.string().optional(),
aiAction: z.string().optional(),
eHumanAction: z.string(),
eHumanComment: z.string(),
auditDrift: z.boolean().default(false),
auditDriftReason: z.string().optional(),
operator: FlowPersonSchema.optional()
});
export type HoseRunAlignment = z.infer<typeof HoseRunAlignmentSchema>;
+155 -5
View File
@@ -6,6 +6,7 @@ import ExcelJS from "exceljs";
import {
formatDate,
formatExportDateTag,
formatExportMinuteTag,
getBeijingDate,
getBeijingDateFrom,
getRuleBriefTitle,
@@ -64,21 +65,29 @@ describe("approval-runs-export helpers", () => {
});
expect(custom).toBe("/tmp/custom-export.xlsx");
const fixedTime = new Date("2026-09-15T10:26:00+08:00");
const dl = resolveOutputFilePath({
toDownloads: true,
corpName: "大黄蜂",
dateTag: "2026-08-07至2026-09-14",
recordCount: 50
recordCount: 50,
exportTime: fixedTime
});
expect(dl).toContain("Downloads/大黄蜂_审核记录_2026-08-07至2026-09-14_50条.xlsx");
expect(dl).toContain("Downloads/大黄蜂_审核记录_2026-08-07至2026-09-14_50条_20260915_1026.xlsx");
const rangeDl = resolveOutputFilePath({
toDownloads: true,
corpName: "华铁大黄蜂",
dateTag: "2026-08-07至2026-09-13",
recordCount: 9780
recordCount: 9780,
exportTime: fixedTime
});
expect(rangeDl).toContain("Downloads/华铁大黄蜂_审核记录_2026-08-07至2026-09-13_9780条.xlsx");
expect(rangeDl).toContain("Downloads/华铁大黄蜂_审核记录_2026-08-07至2026-09-13_9780条_20260915_1026.xlsx");
});
test("formatExportMinuteTag formats in Asia/Shanghai correctly", () => {
const fixedTime = new Date("2026-09-15T10:26:00+08:00");
expect(formatExportMinuteTag(fixedTime)).toBe("20260915_1026");
});
test("formatDate formats dates, epoch timestamps, and strings cleanly in Asia/Shanghai", () => {
@@ -267,14 +276,21 @@ describe("exportApprovalRunsToExcel integration", () => {
expect(result.rejectReasonCount).toBe(1);
expect(existsSync(tmpOut)).toBe(true);
// Verify Excel contents with ExcelJS
// Verify Excel contents with ExcelJS: default export does NOT include E columns (Hose resource optimization)
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(1).getCell(9).value).toBe("人工审核");
expect(ws.getRow(1).getCell(10).value).toBe("人工驳回原因");
expect(ws.getRow(1).getCell(11).value).toBe("创建时间");
expect(ws.getRow(1).getCell(12).value).toBe("任务耗时");
expect(ws.getRow(2).getCell(1).value).toBe("B26001");
expect(ws.getRow(2).getCell(9).value).toBe("已支付/审批完成");
expect(ws.getRow(2).getCell(10).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("请上传正确的行程单凭据");
@@ -285,6 +301,78 @@ describe("exportApprovalRunsToExcel integration", () => {
}
});
test("generates excel workbook with E columns when withFlow is true for hose corp", async () => {
const hoseCorp: CorpConfig = {
...testCorp,
source: { type: "hose", corpId: "corp-hose-1" } as any
};
const mockClient = {
get: (url: string) => {
if (url.includes("api/v1/rules")) {
return {
json: async () => ({
rules: [{ id: "r1", code: 0, description: "发票真实性核验", scope: "全局", strictness: "SHOULD_FOLLOW" }]
})
};
}
if (url.includes("api/v1/approvals")) {
return {
json: async () => ({
total: 1,
records: [
{
id: "run-h1",
sourceDocumentSN: "B26001",
status: "completed",
taskMode: "assisted",
sourceSystem: "hosecloud",
document: { fields: [] },
result: { decision: "APPROVE", rulesResult: [] },
manualApprovalRecord: {
status: { label: "已通过", type: "APPROVED" }
},
createdAt: 1788760000000,
updatedAt: 1788760030000
}
]
})
};
}
throw new Error(`Unexpected url: ${url}`);
}
} as any;
const tmpOut = join(tmpdir(), `test-export-flow-${Date.now()}.xlsx`);
try {
const result = await exportApprovalRunsToExcel(mockClient, hoseCorp, {
outputFile: tmpOut,
limit: 10,
pageDelayMs: 0,
withFlow: true
});
expect(result.recordCount).toBe(1);
// Audit drift is deliberately not aggregated here: a bare count cannot be traced back to a
// record, while the drift itself is already visible in the E人工行为 / E人工意见 columns.
expect("driftCount" in result).toBe(false);
const wb = new ExcelJS.Workbook();
await wb.xlsx.readFile(tmpOut);
const ws = wb.worksheets[0]!;
expect(ws.getRow(1).getCell(1).value).toBe("单据编号");
expect(ws.getRow(1).getCell(9).value).toBe("人工审核");
expect(ws.getRow(1).getCell(10).value).toBe("人工驳回原因");
expect(ws.getRow(1).getCell(11).value).toBe("E人工行为");
expect(ws.getRow(1).getCell(12).value).toBe("E人工意见");
expect(ws.getRow(1).getCell(13).value).toBe("创建时间");
} finally {
if (existsSync(tmpOut)) {
rmSync(tmpOut, { force: true });
}
}
});
test("rejects export without force when time range exceeds 180 days", async () => {
const mockClient = {} as any;
await expect(
@@ -304,4 +392,66 @@ describe("exportApprovalRunsToExcel integration", () => {
})
).rejects.toThrow("起始时间 (2026-09-15) 不能晚于结束时间 (2026-09-13)");
});
test("automatically excludes simulation tasks and records excludedSimulationCount", async () => {
const mockClient = {
get: (url: string) => {
if (url.includes("api/v1/rules")) {
return { json: async () => ({ rules: [] }) };
}
if (url.includes("api/v1/approvals")) {
return {
json: async () => ({
total: 3,
records: [
{
id: "run-sim-1",
sourceDocumentSN: "SIM001",
status: "completed",
taskMode: "simulation",
createdAt: 1788760000000
},
{
id: "run-real-1",
sourceDocumentSN: "REAL001",
status: "completed",
taskMode: "assisted",
createdAt: 1788760010000
},
{
id: "run-sim-2",
sourceDocumentSN: "SIM002",
status: "completed",
taskMode: "simulation",
createdAt: 1788760020000
}
]
})
};
}
throw new Error(`Unexpected url: ${url}`);
}
} as any;
const tmpOut = join(tmpdir(), `test-export-sim-${Date.now()}.xlsx`);
try {
const result = await exportApprovalRunsToExcel(mockClient, testCorp, {
outputFile: tmpOut,
pageDelayMs: 0
});
expect(result.recordCount).toBe(1);
expect(result.excludedSimulationCount).toBe(2);
const wb = new ExcelJS.Workbook();
await wb.xlsx.readFile(tmpOut);
const ws = wb.worksheets[0]!;
expect(ws.rowCount).toBe(2); // 1 header + 1 real row
expect(ws.getRow(2).getCell(1).value).toBe("REAL001");
} finally {
if (existsSync(tmpOut)) {
rmSync(tmpOut, { force: true });
}
}
});
});
+413 -65
View File
@@ -5,6 +5,13 @@ import ExcelJS from "exceljs";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow,
type HoseOpenStaffItem,
type HoseRunAlignment
} from "../hose/index.js";
import type { ApprovalRun, ApprovalRunListData } from "./types.js";
export interface ApprovalRunsExportOptions {
@@ -19,6 +26,14 @@ export interface ApprovalRunsExportOptions {
pageSize?: number;
pageDelayMs?: number;
force?: boolean;
withFlow?: boolean;
flowConcurrency?: number;
flowBatchDelayMs?: number;
excludeDeleted?: boolean;
taskMode?: string;
sourceSystem?: string;
sns?: string[];
exportTime?: Date;
}
export interface ApprovalRunsExportResult {
@@ -31,6 +46,8 @@ export interface ApprovalRunsExportResult {
rejectReasonCount: number;
fileSizeBytes: number;
exportedAt: string;
excludedDeletedCount?: number;
excludedSimulationCount?: number;
}
export function normalizeTimestamp(val?: string | number, endOfDay = false): string | undefined {
@@ -249,12 +266,32 @@ export function getRuleBriefTitle(ruleId: string, desc?: string, scope?: string)
return clean.slice(0, 22);
}
export function formatExportMinuteTag(date: Date = new Date()): string {
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: "Asia/Shanghai",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hour12: false
}).formatToParts(date);
const find = (type: string) => parts.find((p) => p.type === type)?.value || "";
const year = find("year");
const month = find("month");
const day = find("day");
const hour = find("hour");
const minute = find("minute");
return `${year}${month}${day}_${hour}${minute}`;
}
export function resolveOutputFilePath(options: {
outputFile?: string;
toDownloads?: boolean;
corpName: string;
dateTag?: string;
recordCount: number;
exportTime?: Date;
}): string {
if (options.outputFile) {
const p = resolve(options.outputFile);
@@ -268,7 +305,8 @@ export function resolveOutputFilePath(options: {
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`;
const timeTag = formatExportMinuteTag(options.exportTime || new Date());
const fileName = `${safeCorpName}_审核记录_${dateTag}_${countTag}_${timeTag}.xlsx`;
let targetDir: string;
if (options.toDownloads) {
@@ -294,13 +332,21 @@ export async function exportApprovalRunsToExcel(
const pageDelayMs = options.pageDelayMs ?? 250;
const limit = options.limit ?? 100000;
const hasExplicitDate = Boolean(options.startDate || options.endDate);
const targetSns = Array.isArray(options.sns)
? options.sns.map((s) => s.trim()).filter(Boolean)
: [];
const hasTargetSns = targetSns.length > 0;
const targetSnsSet = new Set(targetSns);
const dateRange = resolveExportDateRange({
startDate: options.startDate,
endDate: options.endDate,
force: options.force
force: options.force,
silent: !hasExplicitDate && hasTargetSns
});
const startDateTs = dateRange.startDateTs;
const endDateTs = dateRange.endDateTs;
const { startDateTs, endDateTs } = dateRange;
let dateTag = dateRange.dateTag;
const manualStatusFilter = normalizeManualApprovalStatus(options.manualApprovalStatus);
// 1. 动态加载企业规则集,生成列定义
@@ -331,71 +377,197 @@ export async function exportApprovalRunsToExcel(
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) {
// 1.5 如果是合思企业且显式启用 withFlow,先探测单据规模并做耗时与频控提示
if (options.withFlow === true && corp.source.type === "hose") {
if (hasTargetSns) {
console.error(
`🎯 [单据筛选] 已指定定向筛选单号: [${targetSns.join(", ")}] (共 ${targetSns.length} 个)。`
);
} else {
try {
batch = await api.listApprovalRuns(client, {
limit: pageSize,
offset,
const probeData = await api.listApprovalRuns(client, {
limit: 1,
startDate: startDateTs,
endDate: endDateTs,
status: options.status,
sourceSystem: options.sourceSystem,
taskMode: options.taskMode,
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));
const probeTotal = probeData.total ?? probeData.records?.length ?? 0;
const concurrency = Math.max(1, Math.min(options.flowConcurrency ?? 3, 5));
const estSeconds = Math.max(1, Math.ceil((probeTotal / concurrency) * 0.4));
if (probeTotal > 50) {
console.error(
`⚠️ [审批流对齐提示] 目标区间内单据规模约为 ${probeTotal} 笔。系统已启用合思 Open API 保护限流(并发 ${concurrency}),预计审批流拉取耗时约 ${estSeconds} 秒。`
);
}
} catch {
// ignore probe error
}
}
}
if (!batch || !batch.records || batch.records.length === 0) break;
totalAvailable = batch.total ?? totalAvailable;
// 2. 温和分页拉取单据记录
const fetchedRecords: ApprovalRun[] = [];
let excludedSimulationCount = 0;
let excludedOtherSourceCount = 0;
for (const r of batch.records) {
if (options.includeCompletedOnly && r.status !== "completed") {
continue;
}
if (hasTargetSns && targetSns.length <= 50) {
console.error(`正在定向检索 ${targetSns.length} 个指定单号...`);
for (const sn of targetSns) {
try {
const batch = await api.listApprovalRuns(client, {
search: sn,
limit: 50,
startDate: hasExplicitDate ? startDateTs : undefined,
endDate: hasExplicitDate ? endDateTs : undefined,
status: options.status,
sourceSystem: options.sourceSystem,
taskMode: options.taskMode,
manualApprovalStatus: manualStatusFilter
});
const matched = (batch.records || []).filter((r) => r.sourceDocumentSN === sn);
for (const r of matched) {
if (r.taskMode === "simulation") {
excludedSimulationCount++;
continue;
}
if (options.taskMode && r.taskMode !== options.taskMode) continue;
if (corp.source.type === "hose" && r.sourceSystem && !["hose", "hosecloud"].includes(r.sourceSystem)) {
excludedOtherSourceCount++;
continue;
}
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);
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;
}
} else {
fetchedRecords.push(r);
} catch (e: any) {
console.error(`⚠️ 定向检索单号 [${sn}] 失败: ${e.message}`);
}
if (fetchedRecords.length >= limit) break;
}
console.error(`定向检索完成,成功匹配 ${fetchedRecords.length} 条记录。`);
} else {
let offset = 0;
let totalAvailable = 0;
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} 条`
);
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,
sourceSystem: options.sourceSystem,
taskMode: options.taskMode,
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 (hasTargetSns && (!r.sourceDocumentSN || !targetSnsSet.has(r.sourceDocumentSN))) {
continue;
}
// 过滤测试任务(仅保留真实审批任务)
if (r.taskMode === "simulation") {
excludedSimulationCount++;
continue;
}
if (options.taskMode && r.taskMode !== options.taskMode) {
continue;
}
// 如果企业是合思来源,仅拉取合思来源单据
if (corp.source.type === "hose" && r.sourceSystem && !["hose", "hosecloud"].includes(r.sourceSystem)) {
excludedOtherSourceCount++;
continue;
}
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));
}
}
}
if (batch.records.length < pageSize || offset >= totalAvailable) {
break;
}
if (excludedSimulationCount > 0) {
console.error(
`ℹ️ 已自动排除 ${excludedSimulationCount} 条模拟测试任务 (taskMode="simulation"),仅保留真实审批任务。`
);
}
if (excludedOtherSourceCount > 0) {
console.error(
`ℹ️ 已自动排除 ${excludedOtherSourceCount} 条非合思来源单据,仅保留合思业务单据。`
);
}
if (pageDelayMs > 0) {
await new Promise((r) => setTimeout(r, pageDelayMs));
if (!hasExplicitDate && hasTargetSns && fetchedRecords.length > 0) {
const dates = fetchedRecords
.map((r) => formatDate(r.createdAt || r.updatedAt))
.filter(Boolean) as string[];
if (dates.length > 0) {
dates.sort();
const minDate = dates[0]!;
const maxDate = dates[dates.length - 1]!;
dateTag = minDate === maxDate ? minDate : `${minDate}至${maxDate}`;
}
}
@@ -410,6 +582,8 @@ export async function exportApprovalRunsToExcel(
views: [{ state: "frozen", ySplit: 1, xSplit: 2 }]
});
const withFlow = options.withFlow === true && corp.source.type === "hose";
const baseColumns: Array<{ header: string; key: string; width: number }> = [
{ header: "单据编号", key: "sn", width: 16 },
{ header: "单据模板名称", key: "templateName", width: 26 },
@@ -421,6 +595,12 @@ export async function exportApprovalRunsToExcel(
{ header: "思考深度", key: "thinkingDepth", width: 12 },
{ header: "人工审核", key: "manualStatus", width: 16 },
{ header: "人工驳回原因", key: "humanRejectReason", width: 36 },
...(withFlow
? [
{ header: "E人工行为", key: "eHumanAction", width: 18 },
{ header: "E人工意见", key: "eHumanComment", width: 36 }
]
: []),
{ header: "创建时间", key: "createdAt", width: 20 },
{ header: "任务耗时", key: "duration", width: 12 },
{ header: "关联规则数", key: "hitRuleCount", width: 12 },
@@ -465,8 +645,101 @@ export async function exportApprovalRunsToExcel(
const statusCounts: Record<string, number> = {};
let rejectReasonCount = 0;
// 3.5 如果是合思租户且显式启用 withFlow(--with-flow),获取原生审批流并对齐 E人工行为 / E人工意见
const alignmentsByRecordId = new Map<string, HoseRunAlignment>();
const deletedSNs = new Set<string>();
const excludeDeleted = options.excludeDeleted ?? true;
if (options.withFlow === true && corp.source.type === "hose") {
try {
const runsByDocKey = new Map<string, ApprovalRun[]>();
for (const record of fetchedRecords) {
const docKey = record.sourceDocumentId || record.sourceDocumentSN;
if (docKey) {
const list = runsByDocKey.get(docKey) || [];
list.push(record);
runsByDocKey.set(docKey, list);
}
}
const uniqueDocKeys = Array.from(runsByDocKey.keys());
if (uniqueDocKeys.length > 0) {
const concurrency = Math.max(1, Math.min(options.flowConcurrency ?? 3, 5));
const batchDelayMs = options.flowBatchDelayMs ?? 150;
const estSeconds = Math.max(1, Math.ceil((uniqueDocKeys.length / concurrency) * (0.25 + batchDelayMs / 1000)));
console.error(
`正在拉取合思原生审批流以对齐人工行为与意见 (共 ${uniqueDocKeys.length} 个单据,并发限制: ${concurrency},批次间隔: ${batchDelayMs}ms,预计耗时约 ${estSeconds}s)...`
);
const openClient = await createHoseOpenClient(corp);
const staffCache = new Map<string, HoseOpenStaffItem>();
for (let i = 0; i < uniqueDocKeys.length; i += concurrency) {
const batchKeys = uniqueDocKeys.slice(i, i + concurrency);
await Promise.all(
batchKeys.map(async (docKey) => {
const runsForDoc = runsByDocKey.get(docKey)!;
const displaySN = runsForDoc[0]?.sourceDocumentSN || docKey;
try {
const flow = await getHoseOpenFlow(openClient, docKey, staffCache);
if (!flow) {
deletedSNs.add(displaySN);
const aligned = alignApprovalRunsWithHoseFlow(runsForDoc, undefined);
for (const [recordId, align] of aligned.entries()) {
align.eHumanAction = "单据已删除";
align.eHumanComment = "合思系统中未找到该单据流转记录(可能已在合思端删除或作废)";
alignmentsByRecordId.set(recordId, align);
}
return;
}
const aligned = alignApprovalRunsWithHoseFlow(runsForDoc, flow);
for (const [recordId, align] of aligned.entries()) {
alignmentsByRecordId.set(recordId, align);
}
} catch (err: any) {
console.error(`⚠️ 拉取单据 ${displaySN} 审批流失败: ${err.message},使用降级对齐。`);
const aligned = alignApprovalRunsWithHoseFlow(runsForDoc, undefined);
for (const [recordId, align] of aligned.entries()) {
alignmentsByRecordId.set(recordId, align);
}
}
})
);
if (batchDelayMs > 0 && i + concurrency < uniqueDocKeys.length) {
await new Promise((r) => setTimeout(r, batchDelayMs));
}
if ((i + concurrency) % 20 < concurrency || i + concurrency >= uniqueDocKeys.length) {
const completed = Math.min(i + batchKeys.length, uniqueDocKeys.length);
const pct = Math.round((completed / uniqueDocKeys.length) * 100);
console.error(`[审批流进度] 已对齐: ${completed}/${uniqueDocKeys.length} (${pct}%)...`);
}
}
}
} catch (err: any) {
console.error(`⚠️ 对齐合思审批流失败: ${err.message},E人工行为与意见将使用默认值。`);
}
if (deletedSNs.size > 0) {
console.error(
`ℹ️ 检测到 ${deletedSNs.size} 个单据在合思端已删除或不存在(如: ${Array.from(deletedSNs).slice(0, 3).join(", ")}...)${
excludeDeleted ? ",已按要求自动排除。" : ",已在报表中标记为「单据已删除」。"
}`
);
}
}
let exportedRecordCount = 0;
let excludedDeletedCount = 0;
// 填充数据行
for (const record of fetchedRecords) {
const sn = record.sourceDocumentSN || record.sourceDocumentId;
if (excludeDeleted && sn && deletedSNs.has(sn)) {
excludedDeletedCount++;
continue;
}
exportedRecordCount++;
const res = (record.result as any) || {};
const doc = (record.document as any) || {};
@@ -501,17 +774,24 @@ export async function exportApprovalRunsToExcel(
// 4. AI 决策与行为
const aiDecision = res.decision || (record as any).aiDecision || "-";
let aiDecisionDesc = aiDecision;
const normAiDec = String(aiDecision).toUpperCase();
let aiDecisionDesc = String(aiDecision);
let aiAction = "-";
if (aiDecision === "APPROVE") {
if (normAiDec === "APPROVE" || normAiDec === "通过") {
aiDecisionDesc = "通过";
aiAction = "添加评论";
} else if (aiDecision === "REVIEW") {
} else if (normAiDec === "EXEMPT_APPROVE" || normAiDec === "免审通过" || normAiDec === "备注通过") {
aiDecisionDesc = "备注通过";
aiAction = "添加评论";
} else if (normAiDec === "REVIEW" || normAiDec === "转交复核") {
aiDecisionDesc = "转交复核";
aiAction = "转交复核";
} else if (aiDecision === "REJECT") {
} else if (normAiDec === "REJECT" || normAiDec === "驳回") {
aiDecisionDesc = "驳回";
aiAction = "驳回";
} else if (normAiDec === "ERROR" || normAiDec === "错误") {
aiDecisionDesc = "错误";
aiAction = "-";
}
// 5. 耗时计算
@@ -527,6 +807,7 @@ export async function exportApprovalRunsToExcel(
// 6. 人工审核状态与驳回原因
const mar = (record as any).manualApprovalRecord || {};
const marSourceStatus = String(mar.status?.sourceStatus || "");
let manualStatus = "-";
if (mar.status?.label) {
manualStatus = String(mar.status.label);
@@ -575,6 +856,10 @@ export async function exportApprovalRunsToExcel(
createdAtStr = d.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai", hour12: false });
}
const align = alignmentsByRecordId.get(record.id);
const eHumanAction = align ? align.eHumanAction : "-";
const eHumanComment = align ? align.eHumanComment : "-";
const rowData: Record<string, any> = {
sn: record.sourceDocumentSN || record.sourceDocumentId || "-",
templateName,
@@ -586,6 +871,12 @@ export async function exportApprovalRunsToExcel(
thinkingDepth: "标准",
manualStatus,
humanRejectReason,
...(withFlow
? {
eHumanAction,
eHumanComment
}
: {}),
createdAt: createdAtStr,
duration: durationStr,
hitRuleCount: hitRuleIds.length,
@@ -619,21 +910,41 @@ export async function exportApprovalRunsToExcel(
};
if (colNumber <= baseColumns.length) {
const colDef = baseColumns[colNumber - 1];
const colKey = colDef?.key || "";
const isLeftAligned = [
"sn",
"templateName",
"humanRejectReason",
"eHumanComment",
"hitRulesSummary",
"aiSummary"
].includes(colKey);
const isWrapText = [
"humanRejectReason",
"eHumanComment",
"hitRulesSummary",
"aiSummary"
].includes(colKey);
cell.alignment = {
vertical: "middle",
horizontal: [1, 2, 10, 14, 15].includes(colNumber) ? "left" : "center",
wrapText: [10, 14, 15].includes(colNumber)
horizontal: isLeftAligned ? "left" : "center",
wrapText: isWrapText
};
// AI 决策颜色区分
if (colNumber === 7) {
if (val === "通过") cell.font = { color: { argb: "FF16A34A" }, bold: true };
if (colKey === "aiDecision") {
if (val === "通过" || 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 };
else if (val === "错误" || val === "ERROR") cell.font = { color: { argb: "FFDC2626" }, bold: true };
}
// 人工审核高亮
if (colNumber === 9) {
if (colKey === "manualStatus") {
if (val.includes("驳回")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FFDC2626" }, bold: true };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } };
@@ -643,13 +954,49 @@ export async function exportApprovalRunsToExcel(
} 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" } };
} else if (val.includes("取消") || val.includes("撤回")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF64748B" } };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFF1F5F9" } };
}
}
// 人工驳回原因字体
if (colNumber === 10 && val !== "-") {
if (colKey === "humanRejectReason" && val !== "-") {
cell.font = { name: "Microsoft YaHei", size: 9, color: { argb: "FF991B1B" } };
}
// E人工行为高亮
if (colKey === "eHumanAction") {
if (val.includes("⚠️") || val.includes("修改")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FFD97706" }, bold: true };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEF3C7" } };
} else if (val.includes("驳回") || 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("处理中") ||
val.includes("审核中") ||
val.includes("审批中") ||
val.includes("支付中")
) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF2563EB" }, bold: true };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFEFF6FF" } };
} else if (val.includes("撤回") || val.includes("取消")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF64748B" } };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFF1F5F9" } };
} else if (val === "无操作") {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF94A3B8" } };
}
}
// E人工意见字体
if (colKey === "eHumanComment" && val !== "-") {
cell.font = { name: "Microsoft YaHei", size: 9, color: { argb: "FF334155" } };
}
} else {
cell.alignment = { vertical: "middle", horizontal: "center" };
if (val.includes("不通过")) {
@@ -669,14 +1016,13 @@ export async function exportApprovalRunsToExcel(
}
// 4. 保存文件落地
const dateTag = dateRange.dateTag;
const targetPath = resolveOutputFilePath({
outputFile: options.outputFile,
toDownloads: options.toDownloads,
corpName,
dateTag,
recordCount: fetchedRecords.length
recordCount: exportedRecordCount,
exportTime: options.exportTime
});
await workbook.xlsx.writeFile(targetPath);
@@ -688,11 +1034,13 @@ export async function exportApprovalRunsToExcel(
filePath: targetPath,
corpId: corp.id,
corpName,
recordCount: fetchedRecords.length,
recordCount: exportedRecordCount,
ruleColumnCount: sortedRuleKeys.length,
statusCounts,
rejectReasonCount,
fileSizeBytes: stat.size,
exportedAt: new Date().toISOString()
exportedAt: new Date().toISOString(),
excludedDeletedCount,
excludedSimulationCount
};
}
+276
View File
@@ -29,6 +29,11 @@ import {
extractApprovalRunAttachments
} from "./attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "./approval-runs-export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow
} from "../hose/index.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "./insight-export.js";
import {
ThinkingPolicySchema,
@@ -1521,6 +1526,155 @@ export const sealTools = [
return fields.length > 0 ? pickRunFields(full, fields) : full;
}
},
{
name: "seal_approval_run_flow_get",
description: "获取合思原生审批流流转时间线、待办节点、员工意见、驳回原因及版本变更指标,并对齐 AI 运行记录与人工行为",
parameters: z.object({
target: z.string().optional().describe("合思单号 (sourceDocumentSN) 或 Seal 运行记录 ID (recordId)"),
recordId: z.string().optional().describe("Seal 运行记录 ID"),
sourceDocumentSN: z.string().optional().describe("合思单号 (sourceDocumentSN)")
}),
handler: async (
client: KyInstance,
params: { target?: string; recordId?: string; sourceDocumentSN?: string },
context: ToolContext
) => {
const corp = context.corp;
if (corp.source.type !== "hose") {
throw new Error(
`企业「${corp.name || corp.id}」非合思(hose)租户(来源类型: ${corp.source.type}),暂不支持合思原生审批流分析。`
);
}
const input = (params.target || params.sourceDocumentSN || params.recordId)?.trim();
if (!input) {
throw new Error("必须提供 target、recordId 或 sourceDocumentSN 参数。");
}
let sn = input;
let targetRecord: ApprovalRun | undefined;
try {
targetRecord = await api.getApprovalRun(client, input);
if (targetRecord?.sourceDocumentSN || targetRecord?.sourceDocumentId) {
sn = (targetRecord.sourceDocumentSN || targetRecord.sourceDocumentId)!;
}
} catch {
// Continue as SN
}
let runs: ApprovalRun[] = [];
try {
const runsData = await api.listApprovalRuns(client, {
search: sn,
sourceDocumentSN: sn,
limit: 100
});
runs = (runsData.records || []).filter(
(r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn || r.id === input
);
} catch {
// ignore
}
if (runs.length === 0 && targetRecord) {
runs = [targetRecord];
}
const flowId = targetRecord?.sourceDocumentId || runs[0]?.sourceDocumentId || sn;
const hoseClient = await createHoseOpenClient(corp);
const flow = await getHoseOpenFlow(hoseClient, flowId);
if (!flow) {
console.error(`⚠️ 单据「${sn}」在合思系统中未找到审批流数据(可能已在合思端删除或作废)。`);
const fallbackAlignments = alignApprovalRunsWithHoseFlow(runs, undefined);
const fallbackRuns = runs.map((run) => {
const align = fallbackAlignments.get(run.id);
return {
recordId: run.id,
createdAt: run.createdAt,
createdAtFormatted: run.createdAt
? new Date(Number(run.createdAt)).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })
: undefined,
taskMode: run.taskMode,
status: run.status,
aiDecision: align?.aiDecision || "-",
aiAction: align?.aiAction || "-",
eHumanAction: "单据已删除",
eHumanComment: "合思系统中未找到该单据流转记录(已在合思端删除或作废)",
auditDrift: false,
auditDriftReason: undefined,
operator: undefined
};
});
return {
sourceDocumentSN: sn,
corpId: corp.id,
corpName: corp.name,
sourceSystem: corp.source.type,
found: false,
deleted: true,
message: `单据「${sn}」在合思系统中未找到审批流数据(可能已在合思端删除或作废)。`,
flow: undefined,
runsCount: runs.length,
runs: fallbackRuns,
auditDrift: false
};
}
const alignments = alignApprovalRunsWithHoseFlow(runs, flow);
const alignedRuns = runs.map((run) => {
const align = alignments.get(run.id);
return {
recordId: run.id,
createdAt: run.createdAt,
createdAtFormatted: run.createdAt
? new Date(Number(run.createdAt)).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })
: undefined,
taskMode: run.taskMode,
status: run.status,
aiDecision: align?.aiDecision || "-",
aiAction: align?.aiAction || "-",
eHumanAction: align?.eHumanAction || "-",
eHumanComment: align?.eHumanComment || "-",
auditDrift: align?.auditDrift ?? false,
auditDriftReason: align?.auditDriftReason,
operator: align?.operator
};
});
const hasAuditDrift = alignedRuns.some((r) => r.auditDrift);
return {
sourceDocumentSN: sn,
corpId: corp.id,
corpName: corp.name,
sourceSystem: corp.source.type,
flow: {
backlogId: flow.backlogId,
flowId: flow.flowId,
billCode: flow.billCode,
title: flow.title,
state: flow.state,
rawState: flow.rawState,
currentNode: flow.currentNode,
specification: flow.specification,
submitter: flow.submitter,
owner: flow.owner,
metrics: flow.metrics,
rejections: flow.rejections,
staffOpinions: flow.staffOpinions,
timelineCount: flow.history.length,
pendingCount: flow.pending.length,
timeline: flow.history,
pending: flow.pending
},
runsCount: runs.length,
runs: alignedRuns,
auditDrift: hasAuditDrift
};
}
},
{
name: "seal_approval_run_cited_rules_get",
description: "从审批运行结果中抽取 AI 引用或命中的规则及应用分析",
@@ -2530,6 +2684,128 @@ export const sealTools = [
export type SealTool = (typeof sealTools)[number];
/**
* MCP read/write classification for the tool registry.
*
* The two sets are exhaustive by construction: `tools.test.ts` asserts they partition `sealTools`
* exactly, so a newly added tool fails the suite until it is classified here. The read-only MCP tool
* (`seal_cli`) may only invoke names in {@link SEAL_READ_ONLY_TOOLS}; everything else is reachable
* solely through `seal_cli_write`.
*
* Read-only means it reads tenant state, or writes only a local file. Anything that creates, updates,
* deletes, publishes, pushes, replays, uploads, activates or mints a credential counts as mutating —
* including when it reads like a query. `seal_insight_record_analyze` is the instructive case: it
* sounds like a read but issues a POST that starts an analysis server-side.
*/
export const SEAL_READ_ONLY_TOOLS: ReadonlySet<string> = new Set([
"seal_approval_context_get",
"seal_approval_document_get",
"seal_approval_documents_list",
"seal_approval_rule_get",
"seal_approval_rule_version_get",
"seal_approval_rule_versions_list",
"seal_approval_rules_lint",
"seal_approval_rules_list",
"seal_approval_rules_pull",
"seal_approval_run_attachments_get",
"seal_approval_run_cited_rules_get",
"seal_approval_run_document_summary_get",
"seal_approval_run_flow_get",
"seal_approval_run_get",
"seal_approval_run_langfuse_bridge_get",
"seal_approval_run_pick",
"seal_approval_run_result_get",
"seal_approval_run_url_get",
"seal_approval_runs_count",
"seal_approval_runs_export",
"seal_approval_runs_search",
"seal_approval_runs_stats",
"seal_approval_runs_summary",
"seal_approval_search",
"seal_approval_style_preferences_get",
"seal_billing_features_list",
"seal_billing_plans_list",
"seal_billing_status_get",
"seal_contacts_department_children_list",
"seal_contacts_department_get",
"seal_contacts_department_users_list",
"seal_contacts_departments_root_list",
"seal_contacts_last_sync_time_get",
"seal_delegation_list",
"seal_deploy_hosecloud_get",
"seal_deploy_hosecloud_list",
"seal_deploy_hosecloud_requirements",
"seal_deploy_hosecloud_status",
"seal_expenses_list",
"seal_insight_export",
"seal_insight_performance_get",
"seal_insight_risks_by_tag_get",
"seal_insight_stats_get",
"seal_invoices_list",
"seal_llm_config_get",
"seal_llm_providers_list",
"seal_permissions_available_list",
"seal_permissions_configs_list",
"seal_preference_get",
"seal_preference_thinking_depth_policies_list",
"seal_session_get",
"seal_simulation_batch_get",
"seal_simulation_batch_records_get",
"seal_simulation_batch_status",
"seal_simulation_batch_wait",
"seal_simulation_batches_list",
"seal_simulation_feishu_approval_definitions_list",
"seal_simulation_integrations_get",
"seal_simulation_specifications_list",
"seal_simulation_templates_get",
"seal_user_get",
"seal_user_search",
"seal_webhook_get",
"seal_webhook_list",
"seal_webhook_ready",
"seal_whoami"
]);
export const SEAL_MUTATING_TOOLS: ReadonlySet<string> = new Set([
"seal_approval_delete_document",
"seal_approval_document_create",
"seal_approval_document_update",
"seal_approval_rule_create",
"seal_approval_rule_delete",
"seal_approval_rule_update",
"seal_approval_rule_version_publish",
"seal_approval_rules_clear",
"seal_approval_rules_push",
"seal_approval_style_preferences_update",
"seal_delegation_create",
"seal_delegation_revoke",
"seal_deploy_hosecloud_configure",
"seal_deploy_hosecloud_sync",
"seal_insight_record_analyze",
"seal_preference_decision_update",
"seal_preference_thinking_depth_policies_remove",
"seal_preference_thinking_depth_policies_upsert",
"seal_preference_thinking_depth_set",
"seal_simulation_batch_clean",
"seal_simulation_batch_create",
"seal_simulation_material_package_upload",
"seal_user_activate",
"seal_user_create",
"seal_user_delegation_create",
"seal_user_delete",
"seal_user_reset_password",
"seal_webhook_add",
"seal_webhook_delete",
"seal_webhook_material_pack",
"seal_webhook_replay",
"seal_webhook_update"
]);
export function isReadOnlySealTool(name: string): boolean {
return SEAL_READ_ONLY_TOOLS.has(name);
}
const sealToolByName = new Map<string, SealTool>(
sealTools.map((tool) => [tool.name, tool])
);
+106
View File
@@ -0,0 +1,106 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { getOpenApiSchema } from "../core/embedded-openapi.js";
// The bundled contract is what consumers read: `seal-use http` serves it at /openapi.json and
// `dist/openapi.json` is committed. It had drifted from the adapter in both directions — it
// documented /v1/approval/rules/{ruleId} PATCH/DELETE and /v1/approval/documents* that no route
// serves (a caller following it gets 404), and it omitted /v1/approval-runs/stats, which the
// adapter does serve. Marking each operation here turns that drift into a failing test.
//
// What this proves: every operation claimed `implemented` has a matching route in routes.ts, and
// every exact /v1 route in routes.ts is in the contract. What it does not prove: that a
// `planned` operation's *placeholder* prefix is unrouted (prefix branches are matched loosely),
// nor that an operation's request/response schema matches its handler.
const IMPLEMENTATION_KEY = "x-implementation-status";
const OPERATION_METHODS = ["get", "post", "put", "patch", "delete"] as const;
const VALID_STATUSES = ["implemented", "planned"];
type Operation = { method: string; path: string; status: string };
function collectOperations(): Operation[] {
const schema = getOpenApiSchema() as {
paths?: Record<string, Record<string, unknown>>;
};
const operations: Operation[] = [];
for (const [path, pathItem] of Object.entries(schema.paths ?? {})) {
for (const method of OPERATION_METHODS) {
const operation = pathItem[method];
if (operation === undefined) continue;
if (typeof operation !== "object" || operation === null) continue;
const status = (operation as Record<string, unknown>)[IMPLEMENTATION_KEY];
operations.push({ method, path, status: typeof status === "string" ? status : "" });
}
}
return operations;
}
const routesSource = readFileSync(join(import.meta.dir, "routes.ts"), "utf8");
/** Literals compared with `pathname === "…"`, i.e. routes with no path parameters. */
function exactRouteLiterals(): string[] {
return Array.from(routesSource.matchAll(/pathname === "([^"]+)"/g), (match) => match[1]!).filter(
(literal) => literal.startsWith("/v1/")
);
}
/** Prefix literals compared with `pathname.startsWith("…")`, which carry the path parameters. */
function prefixRouteLiterals(): string[] {
return Array.from(routesSource.matchAll(/pathname\.startsWith\("([^"]+)"\)/g), (match) => match[1]!);
}
describe("OpenAPI contract vs HTTP adapter", () => {
test("every operation declares its implementation status", () => {
const operations = collectOperations();
expect(operations.length).toBeGreaterThan(40);
for (const { method, path, status } of operations) {
expect({ method, path, status, valid: VALID_STATUSES.includes(status) }).toEqual({
method,
path,
status,
valid: true
});
}
});
test("both statuses are in use, so the marking cannot go vacuous", () => {
const operations = collectOperations();
const implemented = operations.filter((operation) => operation.status === "implemented");
const planned = operations.filter((operation) => operation.status === "planned");
// A minimum count fails loudly if `planned` operations are mass-promoted by accident.
expect(implemented.length).toBeGreaterThanOrEqual(15);
expect(planned.length).toBeGreaterThanOrEqual(15);
});
test("every operation claimed implemented is actually routed", () => {
const exactLiterals = new Set(exactRouteLiterals());
const prefixLiterals = new Set(prefixRouteLiterals());
for (const { method, path, status } of collectOperations()) {
if (status !== "implemented") continue;
// `/v1/approval-runs/{recordId}/result` is served by the `/v1/approval-runs/` prefix
// branch, so a placeholder path is proven by its static prefix rather than by equality.
const hasPlaceholder = path.includes("{");
const prefix = path.split("/{")[0]!;
const routed = hasPlaceholder
? prefixLiterals.has(`${prefix}/`)
: exactLiterals.has(path);
expect({ method, path, routed }).toEqual({ method, path, routed: true });
}
});
test("every exact /v1 route is documented", () => {
const documented = new Set(collectOperations().map((operation) => operation.path));
for (const literal of exactRouteLiterals()) {
expect({ literal, documented: documented.has(literal) }).toEqual({ literal, documented: true });
}
});
});
+1 -1
View File
@@ -8,7 +8,7 @@ import { getOpenApiSchema } from "../core/embedded-openapi.js";
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
import { createSealClient } from "../core/http/factory.js";
import { findSealTool, sealTools, type SealTool } from "../domains/seal/tools.js";
import { tokenizeCommand } from "../server.js";
import { tokenizeCommand } from "../cli/tokenize.js";
import { VERSION } from "../version.js";
import { renderDocsHtml } from "./docs.js";
+164 -7
View File
@@ -1,10 +1,13 @@
import { describe, expect, test } from "bun:test";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import {
createServer,
resolveMcpEnabled,
SEAL_CLI_TOOL_NAME,
SEAL_CLI_WRITE_TOOL_NAME,
SEAL_MCP_ENABLED_ENV,
tokenizeCommand
} from "./server.js";
@@ -41,7 +44,7 @@ describe("seal-use MCP server", () => {
}
});
test("advertises one tool and executes version through the CLI runner", async () => {
test("advertises the read-only and write tools and executes version through the CLI runner", async () => {
const server = createServer({ enableCli: true });
const client = new Client({ name: "seal-use-test", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
@@ -53,11 +56,25 @@ describe("seal-use MCP server", () => {
]);
const listed = await client.listTools();
expect(listed.tools).toHaveLength(1);
expect(listed.tools[0]?.name).toBe(SEAL_CLI_TOOL_NAME);
expect(listed.tools.map((tool) => tool.name)).toEqual([SEAL_CLI_TOOL_NAME, SEAL_CLI_WRITE_TOOL_NAME]);
expect(listed.tools[0]?.inputSchema).toMatchObject({
type: "object",
required: ["command"]
required: ["command"],
additionalProperties: false
});
// The read-only tool promises it cannot mutate, so a client may auto-approve it.
expect(listed.tools[0]?.annotations).toMatchObject({
readOnlyHint: true,
destructiveHint: false,
openWorldHint: true
});
// The write tool can reach mutating verbs, so it must not be advertised as safe to auto-run
// or safe to retry.
expect(listed.tools[1]?.annotations).toMatchObject({
readOnlyHint: false,
destructiveHint: true,
idempotentHint: false,
openWorldHint: true
});
const result = await client.callTool({
@@ -81,13 +98,91 @@ describe("seal-use MCP server", () => {
const errorText = invalidContent[0];
expect(errorText?.type).toBe("text");
if (errorText?.type === "text") {
expect(errorText.text).toContain("Unknown command: not-a-command");
expect(errorText.text).toContain(SEAL_CLI_WRITE_TOOL_NAME);
}
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
test("the read-only tool refuses mutating and unclassified commands", async () => {
const server = createServer({ enableCli: true });
const client = new Client({ name: "seal-use-policy-test", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const callRead = async (command: string) => {
const result = await client.callTool({ name: SEAL_CLI_TOOL_NAME, arguments: { command } });
const content = result.content as Array<{ type: "text"; text: string }>;
return { isError: result.isError, text: content[0]?.text ?? "" };
};
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport)
]);
for (const command of [
"seal-use corps mark corp-a --env production --confirm",
"seal-use rules push",
"seal-use simulation create --mode hosecloud",
"seal-use deploy hosecloud sync sign-key",
"seal-use users reset-password corp-a:u1",
"seal-use webhook replay",
"seal-use update",
"seal-use mcp",
"seal-use tool seal_approval_rule_create --json '{}'",
"seal-use tool seal_webhook_replay --json '{}'",
"seal-use totally-unknown-area list",
""
]) {
const refused = await callRead(command);
expect({ command, isError: refused.isError }).toEqual({ command, isError: true });
}
// Read-only commands must get past the policy; `version` is a top-level command with no
// registry row, and `corp` is an area alias the CLI dispatches as `corps`.
for (const command of ["seal-use version", "seal-use corps list", "seal-use corp list", "seal-use tool seal_approval_search --json '{}'"]) {
const allowed = await callRead(command);
expect({ command, refusedByPolicy: allowed.text.includes("only runs read-only commands") }).toEqual({
command,
refusedByPolicy: false
});
}
// A read-only command must survive the policy check and fail (if at all) for its own
// reasons — here the corp is unknown — never because the policy refused it.
const allowed = await callRead("seal-use approval-runs get does-not-exist --corp missing");
expect(allowed.text).not.toContain(`only runs read-only commands`);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
test("the write tool accepts mutating commands that the read-only tool refuses", async () => {
const server = createServer({ enableCli: true });
const client = new Client({ name: "seal-use-write-test", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport)
]);
const result = await client.callTool({
name: SEAL_CLI_WRITE_TOOL_NAME,
arguments: { command: "seal-use corps mark missing-corp --env production --confirm" }
});
const content = result.content as Array<{ type: "text"; text: string }>;
const text = content[0]?.text ?? "";
// It must get past the policy and reach the CLI, which then fails on its own terms.
expect(text).not.toContain("only runs read-only commands");
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
test("does not advertise tools when MCP is disabled", async () => {
const server = createServer({ enableCli: false });
const client = new Client({ name: "seal-home-disabled-test", version: "1.0.0" });
@@ -106,3 +201,65 @@ describe("seal-use MCP server", () => {
}
});
});
// The plugin ships the bundled artifact and runs it with plain node, so a bundle that cannot even
// boot is invisible to the in-memory tests above (which exercise source, not the artifact). This
// guards the entry/module graph that bundling is sensitive to.
describe("packaged MCP bundle", () => {
test("dist/mcp/server.js boots and completes a handshake", async () => {
const bundle = join(import.meta.dir, "..", "dist", "mcp", "server.js");
if (!existsSync(bundle)) {
throw new Error("dist/mcp/server.js is missing. Run 'bun run build:plugin' before testing.");
}
const child = spawn(process.execPath, [bundle], {
env: { ...process.env, [SEAL_MCP_ENABLED_ENV]: "true" },
stdio: ["pipe", "pipe", "pipe"]
});
const messages: any[] = [];
let stdout = "";
let stderr = "";
child.stdout.on("data", (chunk) => {
stdout += chunk.toString();
let newline;
while ((newline = stdout.indexOf("\n")) >= 0) {
const line = stdout.slice(0, newline).trim();
stdout = stdout.slice(newline + 1);
if (line) messages.push(JSON.parse(line));
}
});
child.stderr.on("data", (chunk) => { stderr += chunk.toString(); });
const waitForId = async (id: number) => {
for (let i = 0; i < 200; i++) {
const found = messages.find((m) => m.id === id);
if (found) return found;
await new Promise((r) => setTimeout(r, 50));
}
return undefined;
};
const send = (msg: unknown) => child.stdin.write(`${JSON.stringify(msg)}\n`);
try {
await new Promise((r) => setTimeout(r, 500));
send({
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "bundle-test", version: "1.0.0" } }
});
const initialized = await waitForId(1);
expect(stderr + JSON.stringify(initialized)).not.toContain("is not a constructor");
expect(initialized?.result?.serverInfo?.name).toBe("seal-use");
send({ jsonrpc: "2.0", method: "notifications/initialized" });
send({ jsonrpc: "2.0", id: 2, method: "tools/list" });
const listed = await waitForId(2);
expect(listed?.result?.tools?.map((t: any) => t.name)).toEqual([SEAL_CLI_TOOL_NAME, SEAL_CLI_WRITE_TOOL_NAME]);
} finally {
child.kill("SIGTERM");
await new Promise((r) => setTimeout(r, 100));
}
}, 30000);
});
+129 -143
View File
@@ -1,12 +1,11 @@
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema
} from "@modelcontextprotocol/sdk/types.js";
import { McpServer, type CallToolResult } from "@modelcontextprotocol/server";
import { serveStdio, type StdioServerHandle } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";
import { runCli } from "./cli/runner.js";
import { isReadOnlyCliCommand } from "./cli/read-only.js";
import { normalizeCliArgs, tokenizeCommand } from "./cli/tokenize.js";
import { classifyCliError } from "./cli/errors.js";
import { VERSION } from "./version.js";
@@ -16,6 +15,7 @@ const pluginRoot = serverEntryFile.includes("/dist/mcp/") || serverEntryFile.inc
: dirname(dirname(serverEntryFile));
export const SEAL_CLI_TOOL_NAME = "seal_cli";
export const SEAL_CLI_WRITE_TOOL_NAME = "seal_cli_write";
export const SEAL_MCP_ENABLED_ENV = "SEAL_USE_MCP_ENABLED";
export const LEGACY_SEAL_MCP_ENABLED_ENV = "SEAL_HOME_MCP_ENABLED";
@@ -26,165 +26,149 @@ export function resolveMcpEnabled(
return ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
}
export function createServer(options: { enableCli?: boolean } = {}) {
export function createServer(options: { enableCli?: boolean } = {}): McpServer {
const enableCli = options.enableCli ?? true;
const server = new Server(
const server = new McpServer(
{
name: "seal-use",
version: VERSION
},
{
capabilities: {
tools: {}
}
// Declared explicitly so that `tools/list` answers with an empty list (rather than a
// method-not-found error) when seal_cli is switched off by configuration.
capabilities: { tools: {} }
}
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: enableCli
? [
{
name: SEAL_CLI_TOOL_NAME,
description: "Run seal-use CLI commands. See the seal-use skill for command reference.",
inputSchema: {
type: "object",
properties: {
command: {
type: "string",
description: "A seal-use CLI command, with or without the leading 'seal-use' or 'seal-home'."
}
},
required: ["command"],
additionalProperties: false
}
}
]
: []
}));
if (enableCli) {
const inputSchema = z.strictObject({
command: z
.string()
.describe("A seal-use CLI command, with or without the leading 'seal-use' or 'seal-home'.")
});
if (enableCli) server.setRequestHandler(CallToolRequestSchema, async (request) => {
const args = request.params.arguments;
const command = args && typeof args.command === "string" ? args.command : undefined;
if (!command?.trim()) {
return cliResult({
stdout: "",
stderr: "seal_cli requires a non-empty command string",
isError: true,
exitCode: 2
});
}
try {
const tokens = tokenizeCommand(command);
const cliArgs = normalizeCliArgs(tokens);
if (!cliArgs.length) {
throw new Error("seal_cli requires a non-empty command string");
}
return cliResult(await runCli(cliArgs, {
appRoot: pluginRoot,
entryFile: serverEntryFile,
launcher: {
command: process.execPath,
args: [serverEntryFile, "--seal-home-cli"]
server.registerTool(
SEAL_CLI_TOOL_NAME,
{
title: "Run read-only seal-use CLI command",
description:
"Run a read-only seal-use CLI command and return its JSON stdout. Only commands that " +
"read tenant state without changing it are accepted here; anything that mutates tenant " +
"state, publishes configuration, mints credentials, self-updates or starts a server is " +
`refused — use ${SEAL_CLI_WRITE_TOOL_NAME} for those after confirming with the user.`,
inputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
}));
} catch (error) {
const classification = classifyCliError(error);
return cliResult({
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
isError: true,
exitCode: classification.exitCode
});
}
});
},
async ({ command }): Promise<CallToolResult> =>
executeCliCommand(command, { requireReadOnly: true })
);
server.registerTool(
SEAL_CLI_WRITE_TOOL_NAME,
{
title: "Run mutating seal-use CLI command",
description:
"Run a seal-use CLI command that changes tenant state, publishes configuration, or sends " +
"things outward (create/update/push/mark/bind/sync/deploy/delete/reset-password, rule " +
"publishing, simulation batches, self-update). Confirm the exact command with the user " +
"before calling this tool.",
inputSchema,
annotations: {
readOnlyHint: false,
destructiveHint: true,
idempotentHint: false,
openWorldHint: true
}
},
async ({ command }): Promise<CallToolResult> => executeCliCommand(command, { requireReadOnly: false })
);
}
return server;
}
export async function startServer() {
async function executeCliCommand(
command: string | undefined,
options: { requireReadOnly: boolean }
): Promise<CallToolResult> {
const toolName = options.requireReadOnly ? SEAL_CLI_TOOL_NAME : SEAL_CLI_WRITE_TOOL_NAME;
if (!command?.trim()) {
return cliResult({
stdout: "",
stderr: `${toolName} requires a non-empty command string`,
isError: true,
exitCode: 2
});
}
let cliArgs: string[];
try {
cliArgs = normalizeCliArgs(tokenizeCommand(command));
if (!cliArgs.length) {
throw new Error(`${toolName} requires a non-empty command string`);
}
} catch (error) {
const classification = classifyCliError(error);
return cliResult({
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
isError: true,
exitCode: classification.exitCode
});
}
// Enforced, not just annotated: a client that auto-approves the read-only tool must not be able
// to reach a mutating command through it, and unclassified commands fail closed.
if (options.requireReadOnly && !isReadOnlyCliCommand(cliArgs)) {
return cliResult({
stdout: "",
stderr:
`${SEAL_CLI_TOOL_NAME} only runs read-only commands, and "${cliArgs.join(" ")}" is not one of ` +
`them. Confirm the command with the user, then call ${SEAL_CLI_WRITE_TOOL_NAME}.`,
isError: true,
exitCode: 2
});
}
try {
return cliResult(await runCli(cliArgs, {
appRoot: pluginRoot,
entryFile: serverEntryFile,
launcher: {
command: process.execPath,
args: [serverEntryFile, "--seal-home-cli"]
}
}));
} catch (error) {
const classification = classifyCliError(error);
return cliResult({
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
isError: true,
exitCode: classification.exitCode
});
}
}
export function startServer(): StdioServerHandle {
const enableCli = resolveMcpEnabled();
const server = createServer({ enableCli });
await server.connect(new StdioServerTransport());
const handle = serveStdio(() => createServer({ enableCli }));
console.error(
enableCli
? "seal-use MCP server running on stdio"
: "seal-use MCP server connected with seal_cli disabled by configuration"
);
return handle;
}
export function tokenizeCommand(command: string): string[] {
const tokens: string[] = [];
let token = "";
let quote: "'" | '"' | undefined;
let escaped = false;
let tokenStarted = false;
export { tokenizeCommand };
for (const character of command) {
if (escaped) {
token += character;
escaped = false;
tokenStarted = true;
continue;
}
if (character === "\\" && quote !== "'") {
escaped = true;
tokenStarted = true;
continue;
}
if (quote) {
if (character === quote) {
quote = undefined;
} else {
token += character;
}
tokenStarted = true;
continue;
}
if (character === "'" || character === '"') {
quote = character;
tokenStarted = true;
continue;
}
if (/\s/.test(character)) {
if (tokenStarted) {
tokens.push(token);
token = "";
tokenStarted = false;
}
continue;
}
token += character;
tokenStarted = true;
}
if (escaped) throw new Error("Invalid command: trailing escape");
if (quote) throw new Error("Invalid command: unterminated quote");
if (tokenStarted) tokens.push(token);
return tokens;
}
function normalizeCliArgs(tokens: string[]): string[] {
const first = tokens[0];
if (!first) return [];
if (
first === "seal-use" ||
first === "seal-home" ||
first.endsWith("/seal-use") ||
first.endsWith("/seal-home")
) {
return tokens.slice(1);
}
return tokens;
}
function cliResult(result: { stdout: string; stderr: string; isError: boolean; exitCode: number }) {
function cliResult(result: { stdout: string; stderr: string; isError: boolean; exitCode: number }): CallToolResult {
const text = result.isError ? result.stderr || result.stdout : result.stdout;
return {
content: [
@@ -220,9 +204,11 @@ if (isMainModule) {
if (process.argv[2] === "--seal-use-cli" || process.argv[2] === "--seal-home-cli") {
await runEmbeddedCli();
} else {
startServer().catch((error) => {
try {
startServer();
} catch (error) {
console.error(error);
process.exitCode = 1;
});
}
}
}