Compare commits

..
31 Commits
Author SHA1 Message Date
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
38 changed files with 6049 additions and 342 deletions

No files matched your search

+3
View File
@@ -22,6 +22,7 @@ jobs:
build-and-publish-github:
name: 🚀 Build & Publish GitHub Release
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -75,6 +76,7 @@ jobs:
- name: Upload binaries artifact
uses: actions/upload-artifact@v4
continue-on-error: true
with:
name: release-binaries
path: dist/bin/
@@ -85,6 +87,7 @@ jobs:
needs: build-and-publish-github
if: ${{ always() }}
runs-on: ubuntu-latest
timeout-minutes: 60
continue-on-error: true
steps:
- name: Checkout
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.22",
"version": "0.10.24",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+9 -1
View File
@@ -52,7 +52,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
+41
View File
@@ -7,6 +7,47 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [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
+253 -214
View File
@@ -1,30 +1,30 @@
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
import{createRequire as Uy0}from"node:module";var sS0=Object.create;var{getPrototypeOf:tS0,defineProperty:DA,getOwnPropertyNames:aS0}=Object;var eS0=Object.prototype.hasOwnProperty;function $y0($){return this[$]}var Yy0,qy0,y4=($,Y,q)=>{var z=$!=null&&typeof $==="object";if(z){var J=Y?Yy0??=new WeakMap:qy0??=new WeakMap,U=J.get($);if(U)return U}q=$!=null?sS0(tS0($)):{};let I=Y||!$||!$.__esModule?DA(q,"default",{value:$,enumerable:!0}):q;for(let Q of aS0($))if(!eS0.call(I,Q))DA(I,Q,{get:$y0.bind($,Q),enumerable:!0});if(z)J.set($,I);return I};var M=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);var zy0=($)=>$;function Jy0($,Y){this[$]=zy0.bind(null,Y)}var $$=($,Y)=>{for(var q in Y)DA($,q,{get:Y[q],enumerable:!0,configurable:!0,set:Jy0.bind(Y,q)})};var e=($,Y)=>()=>($&&(Y=$($=0)),Y);var m=Uy0(import.meta.url);function a($,Y,q){function z(Q,K){if(!Q._zod)Object.defineProperty(Q,"_zod",{value:{def:K,constr:I,traits:new Set},enumerable:!1});if(Q._zod.traits.has($))return;Q._zod.traits.add($),Y(Q,K);let G=I.prototype,H=Object.keys(G);for(let Z=0;Z<H.length;Z++){let V=H[Z];if(!(V in Q))Q[V]=G[V].bind(Q)}}let J=q?.Parent??Object;class U extends J{}Object.defineProperty(U,"name",{value:$});function I(Q){var K;let G=q?.Parent?new U:this;z(G,Q),(K=G._zod).deferred??(K.deferred=[]);for(let H of G._zod.deferred)H();return G}return Object.defineProperty(I,"init",{value:z}),Object.defineProperty(I,Symbol.hasInstance,{value:(Q)=>{if(q?.Parent&&Q instanceof q.Parent)return!0;return Q?._zod?.traits?.has($)}}),Object.defineProperty(I,"name",{value:$}),I}function m4($){if($)Object.assign(L2,$);return L2}var gm,PA,AA,T5,w2,L2;var F2=e(()=>{PA=Object.freeze({status:"aborted"});AA=Symbol("zod_brand");T5=class T5 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};w2=class w2 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(gm=globalThis).__zod_globalConfig??(gm.__zod_globalConfig={});L2=globalThis.__zod_globalConfig});var P0={};$$(P0,{unwrapMessage:()=>kI,uint8ArrayToHex:()=>Cy0,uint8ArrayToBase64url:()=>_y0,uint8ArrayToBase64:()=>xm,stringifyPrimitive:()=>O0,slugify:()=>EA,shallowClone:()=>_A,safeExtend:()=>Py0,required:()=>Ty0,randomString:()=>Ly0,propertyKeyTypes:()=>bI,promiseAllObject:()=>Vy0,primitiveTypes:()=>RA,prefixIssues:()=>h8,pick:()=>My0,partial:()=>By0,parsedType:()=>N0,optionalKeys:()=>CA,omit:()=>Ny0,objectClone:()=>Zy0,numKeys:()=>wy0,nullish:()=>B3,normalizeParams:()=>B0,mergeDefs:()=>O9,merge:()=>Ay0,jsonStringifyReplacer:()=>Cq,joinValues:()=>I0,issue:()=>hq,isPlainObject:()=>E3,isObject:()=>O2,hexToUint8Array:()=>Ry0,getSizableOrigin:()=>iI,getParsedType:()=>Fy0,getLengthableOrigin:()=>nI,getEnumValues:()=>uI,getElementAtPath:()=>Xy0,floatSafeRemainder:()=>TA,finalizeIssue:()=>L8,extend:()=>Dy0,explicitlyAborted:()=>gA,escapeRegex:()=>O$,esc:()=>xW,defineLazy:()=>G1,createTransparentProxy:()=>Oy0,cloneDef:()=>Wy0,clone:()=>V8,cleanRegex:()=>fI,cleanEnum:()=>Ey0,captureStackTrace:()=>kW,cached:()=>vq,base64urlToUint8Array:()=>jy0,base64ToUint8Array:()=>ym,assignProp:()=>T3,assertNotEqual:()=>Qy0,assertNever:()=>Gy0,assertIs:()=>Ky0,assertEqual:()=>Iy0,assert:()=>Hy0,allowsEval:()=>jA,aborted:()=>j3,NUMBER_FORMAT_RANGES:()=>vA,Class:()=>km,BIGINT_FORMAT_RANGES:()=>hA});function Iy0($){return $}function Qy0($){return $}function Ky0($){}function Gy0($){throw Error("Unexpected value in exhaustive check")}function Hy0($){}function uI($){let Y=Object.values($).filter((z)=>typeof z==="number");return Object.entries($).filter(([z,J])=>Y.indexOf(+z)===-1).map(([z,J])=>J)}function I0($,Y="|"){return $.map((q)=>O0(q)).join(Y)}function Cq($,Y){if(typeof Y==="bigint")return Y.toString();return Y}function vq($){return{get value(){{let q=$();return Object.defineProperty(this,"value",{value:q}),q}throw Error("cached value already set")}}}function B3($){return $===null||$===void 0}function fI($){let Y=$.startsWith("^")?1:0,q=$.endsWith("$")?$.length-1:$.length;return $.slice(Y,q)}function TA($,Y){let q=$/Y,z=Math.round(q),J=Number.EPSILON*Math.max(Math.abs(q),1);if(Math.abs(q-z)<J)return 0;return q-z}function G1($,Y,q){let z=void 0;Object.defineProperty($,Y,{get(){if(z===Sm)return;if(z===void 0)z=Sm,z=q();return z},set(J){Object.defineProperty($,Y,{value:J})},configurable:!0})}function Zy0($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function T3($,Y,q){Object.defineProperty($,Y,{value:q,writable:!0,enumerable:!0,configurable:!0})}function O9(...$){let Y={};for(let q of $){let z=Object.getOwnPropertyDescriptors(q);Object.assign(Y,z)}return Object.defineProperties({},Y)}function Wy0($){return O9($._zod.def)}function Xy0($,Y){if(!Y)return $;return Y.reduce((q,z)=>q?.[z],$)}function Vy0($){let Y=Object.keys($),q=Y.map((z)=>$[z]);return Promise.all(q).then((z)=>{let J={};for(let U=0;U<Y.length;U++)J[Y[U]]=z[U];return J})}function Ly0($=10){let q=""Line truncated
`)}var um=($,Y)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:Y,enumerable:!1}),$.message=JSON.stringify(Y,Cq,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},cI,g8;var xA=e(()=>{F2();y0();cI=a("$ZodError",um),g8=a("$ZodError",um,{Parent:Error})});var gq=($)=>(Y,q,z,J)=>{let U=z?{...z,async:!1}:{async:!1},I=Y._zod.run({value:q,issues:[]},U);if(I instanceof Promise)throw new T5;if(I.issues.length){let Q=new(J?.Err??$)(I.issues.map((K)=>L8(K,U,m4())));throw kW(Q,J?.callee),Q}return I.value},mI,Sq=($)=>async(Y,q,z,J)=>{let U=z?{...z,async:!0}:{async:!0},I=Y._zod.run({value:q,issues:[]},U);if(I instanceof Promise)I=await I;if(I.issues.length){let Q=new(J?.Err??$)(I.issues.map((K)=>L8(K,U,m4())));throw kW(Q,J?.callee),Q}return I.value},lI,yq=($)=>(Y,q,z)=>{let J=z?{...z,async:!1}:{async:!1},U=Y._zod.run({value:q,issues:[]},J);if(U instanceof Promise)throw new T5;return U.issues.length?{success:!1,error:new($??cI)(U.issues.map((I)=>L8(I,J,m4())))}:{success:!0,data:U.value}},xq,kq=($)=>async(Y,q,z)=>{let J=z?{...z,async:!0}:{async:!0},U=Y._zod.run({value:q,issues:[]},J);if(U instanceof Promise)U=await U;return U.issues.length?{success:!1,error:new $(U.issues.map((I)=>L8(I,J,m4())))}:{success:!0,data:U.value}},oI,uW=($)=>(Y,q,z)=>{let J=z?{...z,direction:"backward"}:{direction:"backward"};return gq($)(Y,q,J)},bm,fW=($)=>(Y,q,z)=>{return gq($)(Y,q,z)},im,bW=($)=>async(Y,q,z)=>{let J=z?{...z,direction:"backward"}:{direction:"backward"};return Sq($)(Y,q,J)},nm,iW=($)=>async(Y,q,z)=>{return Sq($)(Y,q,z)},cm,nW=($)=>(Y,q,z)=>{let J=z?{...z,direction:"backward"}:{direction:"backward"};return yq($)(Y,q,J)},pm,cW=($)=>(Y,q,z)=>{return yq($)(Y,q,z)},dm,pW=($)=>async(Y,q,z)=>{let J=z?{...z,direction:"backward"}:{direction:"backward"};return kq($)(Y,q,J)},mm,dW=($)=>async(Y,q,z)=>{return kq($)(Y,q,z)},lm;var kA=e(()=>{F2();xA();y0();mI=gq(g8),lI=Sq(g8),xq=yq(g8),oI=kq(g8),bm=uW(g8),im=fW(g8),nm=bW(g8),cm=iW(g8),pm=nW(g8),dm=cW(g8),mm=pW(g8),lm=dW(g8)});var Y$={};$$(Y$,{xid:()=>iA,uuid7:()=>yy0,uuid6:()=>Sy0,uuid4:()=>gy0,uuid:()=>M2,uppercase:()=>WB,unicodeEmail:()=>om,undefined:()=>HB,ulid:()=>bA,time:()=>zB,string:()=>UB,sha512_hex:()=>qx0,sha512_base64url:()=>Jx0,sha512_base64:()=>zx0,sha384_hex:()=>ey0,sha384_base64url:()=>Yx0,sha384_base64:()=>$x0,sha256_hex:()=>sy0,sha256_base64url:()=>ay0,sha256_base64:()=>ty0,sha1_hex:()=>ly0,sha1_base64url:()=>ry0,sha1_base64:()=>oy0,rfc5322Email:()=>ky0,number:()=>rI,null:()=>GB,nanoid:()=>cA,md5_hex:()=>py0,md5_base64url:()=>my0,md5_base64:()=>dy0,mac:()=>sA,lowercase:()=>ZB,ksuid:()=>nA,ipv6:()=>rA,ipv4:()=>oA,integer:()=>QB,idnEmail:()=>uy0,httpProtocol:()=>$B,html5Email:()=>xy0,hostname:()=>iy0,hex:()=>cy0,guid:()=>dA,extendedDuration:()=>hy0,emoji:()=>lA,email:()=>mA,e164:()=>YB,duration:()=>pA,domain:()=>ny0,datetime:()=>JB,date:()=>qB,cuid2:()=>fA,cuid:()=>uA,cidrv6:()=>aA,cidrv4:()=>tA,browserEmail:()=>fy0,boolean:()=>KB,bigint:()=>IB,base64url:()=>mW,base64:()=>eA});function lA(){return new RegExp(by0,"u")}function sm($){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 zB($){return new RegExp(`^${sm($)}$`)}function JB($){let Y=sm({precision:$.precision}),q=["Z"];if($.local)q.push("");if($.offset)q.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let z=`${Y}(?:${q.join("|")})`;return new RegExp(`^${rm}T(?:${z})$`)}function sI($,Y){return new RegExp(`^[A-Za-z0-9+/]{${$}}${Y}$`)}function tI($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var uA,fA,bA,iA,nA,cA,pA,hy0,dA,M2=($)=>{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})$`)},gy0,Sy0,yy0,mA,xy0,ky0,om,uy0,fy0,by0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",oA,rA,sA=($)=>{let Y=O$($??":");return new RegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},tA,aA,eA,mW,iy0,ny0,$B,YB,rm="(?:(?:\\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])))",qB,UB=($)=>{let Y=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${Y}$`)},IB,QB,rI,KB,GB,HB,ZB,WB,cy0,py0,dy0,my0,ly0,oy0,ry0,sy0,ty0,ay0,ey0,$x0,Yx0,qx0,zx0,Jx0;var lW=e(()=>{y0();uA=/^[cC][0-9a-z]{6,}$/,fA=/^[0-9a-z]+$/,bA=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,iA=/^[0-9a-vA-V]{20}$/,nA=/^[A-Za-z0-9]{27}$/,cA=/^[a-zA-Z0-9_-]{21}$/,pA=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?Line truncated
`).filter((U)=>U),z=Math.min(...q.map((U)=>U.length-U.trimStart().length)),J=q.map((U)=>U.slice(z)).map((U)=>" ".repeat(this.indent*2)+U);for(let U of J)this.content.push(U)}compile(){let $=Function,Y=this?.args,z=[...(this?.content??[""]).map((J)=>` ${J}`)];return new $(...Y,z.join(`
`))}}var vB;var hB=e(()=>{vB={major:4,minor:4,patch:3}});function $T($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function Vl($){if(!mW.test($))return!1;let Y=$.replace(/[-_]/g,(z)=>z==="-"?"+":"/"),q=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return $T(q)}function Ll($,Y=null){try{let q=$.split(".");if(q.length!==3)return!1;let[z]=q;if(!z)return!1;let J=JSON.parse(atob(z));if("typ"in J&&J?.typ!=="JWT")return!1;if(!J.alg)return!1;if(Y&&(!("alg"in J)||J.alg!==Y))return!1;return!0}catch{return!1}}function $l($,Y,q){if($.issues.length)Y.issues.push(...h8(q,$.issues));Y.value[q]=$.value}function YX($,Y,q,z,J,U){let I=q in z;if($.issues.length){if(J&&U&&!I)return;Y.issues.push(...h8(q,$.issues))}if(!I&&!J){if(!$.issues.length)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[q]});return}if($.value===void 0){if(I)Y.value[q]=void 0}else Y.value[q]=$.value}function wl($){let Y=Object.keys($.shape);for(let z of Y)if(!$.shape?.[z]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${z}": expected a Zod schema`);let q=CA($.shape);return{...$,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(q)}}function Fl($,Y,q,z,J,U){let I=[],Q=J.keySet,K=J.catchall._zod,G=K.def.type,H=K.optin==="optional",Z=K.optout==="optional";for(let V in Y){if(V==="__proto__")continue;if(Q.has(V))continue;if(G==="never"){I.push(V);continue}let X=K.run({value:Y[V],issues:[]},z);if(X instanceof Promise)$.push(X.then((L)=>YX(L,q,V,Y,H,Z)));else YX(X,q,V,Y,H,Z)}if(I.length)q.issues.push({code:"unrecognized_keys",keys:I,input:Y,inst:U});if(!$.length)return q;return Promise.all($).then(()=>{return q})}function Yl($,Y,q,z){for(let U of $)if(U.issues.length===0)return Y.value=U.value,Y;let J=$.filter((U)=>!j3(U));if(J.length===1)return Y.value=J[0].value,J[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:q,errors:$.map((U)=>U.issues.map((I)=>L8(I,z,m4())))}),Y}function ql($,Y,q,z){let J=$.filter((U)=>U.issues.length===0);if(J.length===1)return Y.value=J[0].value,Y;if(J.length===0)Y.issues.push({code:"invalid_union",input:Y.value,inst:q,errors:$.map((U)=>U.issues.map((I)=>L8(I,z,m4())))});else Y.issues.push({code:"invalid_union",input:Y.value,inst:q,errors:[],inclusive:!1});return Y}function gB($,Y){if($===Y)return{valid:!0,data:$};if($ instanceof Date&&Y instanceof Date&&+$===+Y)return{valid:!0,data:$};if(E3($)&&E3(Y)){let q=Object.keys(Y),z=Object.keys($).filter((U)=>q.indexOf(U)!==-1),J={...$,...Y};for(let U of z){let I=gB($[U],Y[U]);if(!I.valid)return{valid:!1,mergeErrorPath:[U,...I.mergeErrorPath]};J[U]=I.data}return{valid:!0,data:J}}if(Array.isArray($)&&Array.isArray(Y)){if($.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let q=[];for(let z=0;z<$.length;z++){let J=$[z],U=Y[z],I=gB(J,U);if(!I.valid)return{valid:!1,mergeErrorPath:[z,...I.mergeErrorPath]};q.push(I.data)}return{valid:!0,data:q}}return{valid:!1,mergeErrorPath:[]}}function zl($,Y,q){let z=new Map,J;for(let Q of Y.issues)if(Q.code==="unrecognized_keys"){J??(J=Q);for(let K of Q.keys){if(!z.has(K))z.set(K,{});z.get(K).l=!0}}else $.issues.push(Q);for(let Q of q.issues)if(Q.code==="unrecognized_keys")for(let K of Q.keys){if(!z.has(K))z.set(K,{});z.get(K).r=!0}else $.issues.push(Q);let U=[...z].filter(([,Q])=>Q.l&&Q.r).map(([Q])=>Q);if(U.length&&J)$.issues.push({...J,keys:U});if(j3($))return $;let I=gB(Y.value,q.value);if(!I.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(I.mergeErrorPath)}`);return $.value=I.data,$}function Jl($,Y){for(let q=$.length-1;q>=0;q--)if($[q]._zod[Y]!=="optional")return q+1;return 0}function Ul($,Y,q){if($.issues.length)Y.issues.push(...h8(q,$.issues));Y.value[q]=$.value}function Il($,Y,q,z,J){for(let U=0;U<q.length;U++){let I=$[U],Q=U<z.length;if(I.issues.length){if(!Q&&U>=J){Y.value.length=U;break}Y.issues.push(...h8(U,I.issues))}Y.value[U]=I.value}for(let U=Y.value.length-1;U>=z.length;U--)if(q[U]._zod.optout==="optional"&&Y.value[U]===void 0)Y.value.length=U;else break;return Y}function Ql($,Y,q,z,J,U,I){if($.issues.length)if(bI.has(typeof z))q.issues.push(...h8(z,$.issues));else q.issues.push({code:"invalid_key",origin:"map",input:J,inst:U,issues:$.issues.map((Q)=>L8(Q,I,m4()))});if(Y.issues.length)if(bI.has(typeof z))q.issues.push(...h8(z,Y.issues));else q.issues.push({origin:"map",code:"invalid_element",input:J,inst:U,key:z,issues:Y.issues.map((Q)=>L8(Q,I,m4()))});q.value.set($.value,Y.value)}function Kl($,Y){if($.issues.length)Y.issues.push(...$.issues);Y.value.add($.value)}function Gl($,Y){if(Y===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function Hl($,Y){if($.value===void 0)$.value=Y.defaultValue;return $}function Zl($,Y){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:Y});return $}function aW($,Y,q){if($.issues.length)return $.aborted=!0,$;return Y._zod.run({value:$.value,issues:$.issues,fa Line truncated
if (${A}.issues.length) {
if (${T} in input) {
if (${E} in input) {
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
...iss,
path: iss.path ? [${T}, ...iss.path] : [${T}]
path: iss.path ? [${E}, ...iss.path] : [${E}]
})));
}
}
if (${A}.value === undefined) {
if (${T} in input) {
newResult[${T}] = undefined;
if (${E} in input) {
newResult[${E}] = undefined;
}
} else {
newResult[${T}] = ${A}.value;
newResult[${E}] = ${A}.value;
}
`);else if(!h)X.write(`
const ${A}_present = ${T} in input;
`);else if(!v)X.write(`
const ${A}_present = ${E} in input;
if (${A}.issues.length) {
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
...iss,
path: iss.path ? [${T}, ...iss.path] : [${T}]
path: iss.path ? [${E}, ...iss.path] : [${E}]
})));
}
if (!${A}_present && !${A}.issues.length) {
@@ -32,15 +32,15 @@ import{createRequire as HS0}from"node:module";var $S0=Object.create;var{getProto
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${T}]
path: [${E}]
});
}
if (${A}_present) {
if (${A}.value === undefined) {
newResult[${T}] = undefined;
newResult[${E}] = undefined;
} else {
newResult[${T}] = ${A}.value;
newResult[${E}] = ${A}.value;
}
}
@@ -48,114 +48,114 @@ import{createRequire as HS0}from"node:module";var $S0=Object.create;var{getProto
if (${A}.issues.length) {
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
...iss,
path: iss.path ? [${T}, ...iss.path] : [${T}]
path: iss.path ? [${E}, ...iss.path] : [${E}]
})));
}
if (${A}.value === undefined) {
if (${T} in input) {
newResult[${T}] = undefined;
if (${E} in input) {
newResult[${E}] = undefined;
}
} else {
newResult[${T}] = ${A}.value;
newResult[${E}] = ${A}.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
`)}X.write("payload.value = newResult;"),X.write("return payload;");let P=X.compile();return(B,A)=>P(V,B,A)},U,I=O2,Q=!L2.jitless,G=Q&&jA.value,H=Y.catchall,Z;$._zod.parse=(V,X)=>{Z??(Z=z.value);let L=V.value;if(!I(L))return V.issues.push({expected:"object",code:"invalid_type",input:L,inst:$}),V;if(Q&&G&&X?.async===!1&&X.jitless!==!0){if(!U)U=J(Y.shape);if(V=U(V,X),!H)return V;return Fl([],L,V,X,Z,$)}return q(V,X)}});eI=a("$ZodUnion",($,Y)=>{s0.init($,Y),G1($._zod,"optin",()=>Y.options.some((z)=>z._zod.optin==="optional")?"optional":void 0),G1($._zod,"optout",()=>Y.options.some((z)=>z._zod.optout==="optional")?"optional":void 0),G1($._zod,"values",()=>{if(Y.options.every((z)=>z._zod.values))return new Set(Y.options.flatMap((z)=>Array.from(z._zod.values)));return}),G1($._zod,"pattern",()=>{if(Y.options.every((z)=>z._zod.pattern)){let z=Y.options.map((J)=>J._zod.pattern);return new RegExp(`^(${z.map((J)=>fI(J.source)).join("|")})$`)}return});let q=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(z,J)=>{if(q)return q(z,J);let U=!1,I=[];for(let Q of Y.options){let K=Q._zod.run({value:z.value,issues:[]},J);if(K instanceof Promise)I.push(K),U=!0;else{if(K.issues.length===0)return K;I.push(K)}}if(!U)return Yl(I,z,$,J);return Promise.all(I).then((Q)=>{return Yl(Q,z,$,J)})}});OT=a("$ZodXor",($,Y)=>{eI.init($,Y),Y.inclusive=!1;let q=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(z,J)=>{if(q)return q(z,J);let U=!1,I=[];for(let Q of Y.options){let K=Q._zod.run({value:z.value,issues:[]},J);if(K instanceof Promise)I.push(K),U=!0;else I.push(K)}if(!U)return ql(I,z,$,J);return Promise.all(I).then((Q)=>{return ql(Q,z,$,J)})}}),MT=a("$ZodDiscriminatedUnion",($,Y)=>{Y.inclusive=!1,eI.init($,Y);let q=$._zod.parse;G1($._zod,"propValues",()=>{let J={};for(let U of Y.options){let I=U._zod.propValues;if(!I||Object.keys(I).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(U)}"`);for(let[Q,K]of Object.entries(I)){if(!J[Q])J[Q]=new Set;for(let G of K)J[Q].add(G)}}return J});let z=vq(()=>{let J=Y.options,U=new Map;for(let I of J){let Q=I._zod.propValues?.[Y.discriminator];if(!Q||Q.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(I)}"`);for(let K of Q){if(U.has(K))throw Error(`Duplicate discriminator value "${String(K)}"`);U.set(K,I)}}return U});$._zod.parse=(J,U)=>{let I=J.value;if(!O2(I))return J.issues.push({code:"invalid_type",expected:"object",input:I,inst:$}),J;let Q=z.value.get(I?.[Y.discriminator]);if(Q)return Q._zod.run(J,U);if(Y.unionFallback||U.direction==="backward")return q(J,U);return J.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,options:Array.from(z.value.keys()),input:I,path:[Y.discriminator],inst:$}),J}}),NT=a("$ZodIntersection",($,Y)=>{s0.init($,Y),$._zod.parse=(q,z)=>{let J=q.value,U=Y.left._zod.run({value:J,issues:[]},z),I=Y.right._zod.run({value:J,issues:[]},z);if(U instanceof Promise||I instanceof Promise)return Promise.all([U,I]).then(([K,G])=>{return zl(q,K,G)});return zl(q,U,I)}});JX=a("$ZodTuple",($,Y)=>{s0.init($,Y);let q=Y.items;$._zod.parse=(z,J)=>{let U=z.value;if(!Array.isArray(U))return z.issues.push({input:U,inst:$,expected:"tuple",code:"invalid_type"}),z;z.value=[];let I=[],Q=Jl(q,"optin"),K=Jl(q,"optout");if(!Y.rest){if(U.length<Q)return z.issues.push({code:"too_small",minimum:Q,inclusive:!0,input:U,inst:$,origin:"array"}),z;if(U.length>q.length)z.issues.push({code:"too_big",maximum:q.length,inclusive:!0,input:U,inst:$,origin:"array"})}let G=Array(q.length);for(let H=0;H<q.length;H++){let Z=q[H]._zod.run({value:U[H],issues:[]},J);if(Z instanceof Promise)I.push(Z.then((V)=>{G[H]=V}));else G[H]=Z}if(Y.rest){let H=q.length-1,Z=U.slice(q.length);for(let V of Z){H++;let X=Y.rest._zod.run({value:V,issues:[]},J);if(X instanceof Promise)I.push(X.then((L)=>Ul(L,z,H)));else Ul(X,z,H)}}if(I.length)return Promise.all(I).then(()=>Il(G,z,q,U,K));return Il(G,z,q,U,K)}});DT=a("$ZodRecord",($,Y)=>{s0.init($,Y),$._zod.parse=(q,z)=>{let J=q.value;if(!E3(J))return q.issues.push({expected:"record",code:"invalid_type",input:J,inst:$}),q;let U=[],I=Y.keyType._zod.values;if(I){q.value={};let Q=new Set;for(let G of I)if(typeof G==="string"||typeof G==="number"||typeof G==="symbol"){Q.add(typeof G==="number"?G.toString():G);let H=Y.keyType._zod.run({value:G,issues:[]},z);if(H instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(H.issues.length){q.issues.push({code:"invalid_key",origin:"record",issues:H.issues.map((X)=>L8(X,z,m4())),input:G,path:[G],inst:$});continue}let Z=H.value,V=Y.valueType._zod.run({value:J[G],issues:[]},z);if(V instanceof Promise)U.push(V.then((X)=>{if(X.issues.length)q.issues.push(...h8(G,X.issues));q.value[Z]=X.value}));else{if(V.issues.length)q.issues.push(...h8(G,V.issues));q.value[Z]=V.value}}let K;for(let G in J)if(!Q.has(G))K=K??[],K.push(G);if(K&&K.length>0)q.issues.push({code:"unrecognize 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 Q=I[1];if(Y===I[0]){U(I);continue}if($.external){let G=$.external.registry.get(I[0])?.id;if(Y!==I[0]&&G){U(I);continue}}if($.metadataRegistry.get(I[0])?.id){U(I);continue}if(Q.cycle){U(I);continue}if(Q.count>1){if($.reused==="ref"){U(I);continue}}}}function h3($,Y){let q=$.seen.get(Y);if(!q)throw Error("Unprocessed schema. This is a bug in Zod.");let z=(Q)=>{let K=$.seen.get(Q);if(K.ref===null)return;let G=K.def??K.schema,H={...G},Z=K.ref;if(K.ref=null,Z){z(Z);let X=$.seen.get(Z),L=X.schema;if(L.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))G.allOf=G.allOf??[],G.allOf.push(L);else Object.assign(G,L);if(Object.assign(G,H),Q._zod.parent===Z)for(let F in G){if(F==="$ref"||F==="allOf")continue;if(!(F in H))delete G[F]}if(L.$ref&&X.def)for(let F in G){if(F==="$ref"||F==="allOf")continue;if(F in X.def&&JSON.stringify(G[F])===JSON.stringify(X.def[F]))delete G[F]}}let V=Q._zod.parent;if(V&&V!==Z){z(V);let X=$.seen.get(V);if(X?.schema.$ref){if(G.$ref=X.schema.$ref,X.def)for(let L in G){if(L==="$ref"||L==="allOf")continue;if(L in X.def&&JSON.stringify(G[L])===JSON.stringify(X.def[L]))delete G[L]}}}$.override({zodSchema:Q,jsonSchema:G,path:K.path??[]})};for(let Q of[...$.seen.entries()].reverse())z(Q[0]);let J={};if($.target==="draft-2020-12")J.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")J.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")J.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let Q=$.external.registry.get(Y)?.id;if(!Q)throw Error("Schema is missing an `id` property");J.$id=$.external.uri(Q)}Object.assign(J,q.def??q.schema);let U=$.metadataRegistry.get(Y)?.id;if(U!==void 0&&J.id===U)delete J.id;let I=$.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;I[K.defId]=K.def}}if($.external);else if(Object.keys(I).length>0)if($.target==="draft-2020-12")J.$defs=I;else J.definitions=I;try{let Q=JSON.parse(JSON.stringify(J));return Object.defineProperty(Q,"~standard",{value:{...Y["~standard"],jsonSchema:{input:eq(Y,"input",$.processors),output:eq(Y,"output",$.processors)}},enumerable:!1,writable:!1}),Q}catch(Q){throw Error("Error converting schema to JSON.")}}function F8($,Y){let q=Y??{seen:new Set};if(q.seen.has($))return!1;q.seen.add($);let z=$._zod.def;if(z.type==="transform")return!0;if(z.type==="array")return F8(z.element,q);if(z.type==="set")return F8(z.valueType,q);if(z.type==="lazy")return F8(z.getter(),q);if(z.type==="promise"||z.type==="optional"||z.type==="nonoptional"||z.type==="nullable"||z.type==="readonly"||z.type==="default"||z.type==="prefault")return F8(z.innerType,q);if(z.type==="intersection")return F8(z.left,q)||F8(z.right,q);if(z.type==="record"||z.type==="map")return F8(z.keyType,q)||F8(z.valueType,q);if(z.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return F8(z.in,q)||F8(z.out,q)}if(z.type==="object"){for(let J in z.shape)if(F8(z.shape[J],q))return!0;return!1}if(z.type==="union"){for(let J of z.options)if(F8(J,q))return!0;return!1}if(z.type==="tuple"){for(let J of z.items)if(F8(J,q))return!0;if(z.rest&&F8(z.rest,q))return!0;return!1}return!1}var vj=($,Y={})=>(q)=>{let z=C3({...q,processors:Y});return s1($,z),v3(z,$),h3(z,$)},eq=($,Y,q={})=>(z)=>{let{libraryOptions:J,target:U}=z??{},I=C3({...J??{},target:U,io:Y,processors:q});return s1($,I),v3(I,$),h3(I,$)};var GQ=e(()=>{IQ()});function xX($,Y){if("_idmap"in $){let z=$,J=C3({...Y,processors:gX}),U={};for(let K of z._idmap.entries()){let[G,H]=K;s1(H,J)}let I={},Q={registry:z,uri:Y?.uri,defs:U};J.external=Q;for(let K of z._idmap.entries()){let[G,H]=K;v3(J,H),I[G]=h3(J,H)}if(Object.keys(U).length>0){let K=J.target==="draft-2020-12"?"$defs":"definitions";I.__shared={[K]:U}}return{schemas:I}}let q=C3({...Y,processors:gX});return s1($,q),v3(q,$),h3(q,$)}var Ek0,hj=($,Y,q,z)=>{let J=q;J.type="string";let{minimum:U,maximum:I,format:Q,patterns:K,contentEncoding:G}=$._zod.bag;if(typeof U==="number")J.minLength=U;if(typeof I==="number")J.maxLength=I;if(Q){if(J.format=Ek0[Q]??Q,J.format==="")delete J.format;if(Q==="time")delete J.format}if(G)J.contentEncoding=G;if(K&&K.size>0){let H=[...K];if(H.length===1)J.pattern=H[0].source;else if(H.length>1)J.allOf=[...H.map((Z)=>({...Y.target==="draft-07"||Y.target==="draft-04"||Y.target==="openapi-3.0"?{type:"string"}:{},pattern:Z.source}))]}},gj=($,Y,q,z)=>{let J=q,{minimum:U,maximum:I,format:Q,multipleOf:K,exclusiveMaximum:G,exclusiveMinimum:H}=$._zod.bag;if(typeof Q==="string"&&Q.includes("int"))J.type="integer";else J.type="number";let Z=typeof H==="number"&&H>=(U??Number.NEGATIVE_INFINITY),V=typeof G==="number"&&G<=(I??Number.POSITIVE_INFINITY),X=Y.target==="draft-04"||Y.target==="openapi-3.0";if(Z)if(X)J.minimum=H,J.exclusiveMinimum=!0;else J.exclusiveMinimuLine truncated
`:""},this._extScope=$,this._scope=new e$.Scope({parent:$}),this._nodes=[new Ds]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,Y){let q=this._extScope.value($,Y);return(this._values[q.prefix]||(this._values[q.prefix]=new Set)).add(q),q}getScopeValue($,Y){return this._extScope.getValue($,Y)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,Y,q,z){let J=this._scope.toName(Y);if(q!==void 0&&z)this._constants[J.str]=q;return this._leafNode(new Ls($,J,q)),J}const($,Y,q){return this._def(e$.varKinds.const,$,Y,q)}let($,Y,q){return this._def(e$.varKinds.let,$,Y,q)}var($,Y,q){return this._def(e$.varKinds.var,$,Y,q)}assign($,Y,q){return this._leafNode(new aR($,Y,q))}add($,Y){return this._leafNode(new ws($,k8.operators.ADD,Y))}code($){if(typeof $=="function")$();else if($!==A1.nil)this._leafNode(new Ns($));return this}object(...$){let Y=["{"];for(let[q,z]of $){if(Y.length>1)Y.push(",");if(Y.push(q),q!==z||this.opts.es5)Y.push(":"),(0,A1.addCodeArg)(Y,z)}return Y.push("}"),new A1._Code(Y)}if($,Y,q){if(this._blockNode(new P9($)),Y&&q)this.code(Y).else().code(q).endIf();else if(Y)this.code(Y).endIf();else if(q)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new P9($))}else(){return this._elseNode(new iQ)}endIf(){return this._endBlockNode(P9,iQ)}_for($,Y){if(this._blockNode($),Y)this.code(Y).endFor();return this}for($,Y){return this._for(new Ps($),Y)}forRange($,Y,q,z,J=this.opts.es5?e$.varKinds.var:e$.varKinds.let){let U=this._scope.toName($);return this._for(new As(J,U,Y,q),()=>z(U))}forOf($,Y,q,z=e$.varKinds.const){let J=this._scope.toName($);if(this.opts.es5){let U=Y instanceof A1.Name?Y:this.var("_arr",Y);return this.forRange("_i",0,A1._`${U}.length`,(I)=>{this.var(J,A1._`${U}[${I}]`),q(J)})}return this._for(new sR("of",z,J,Y),()=>q(J))}forIn($,Y,q,z=this.opts.es5?e$.varKinds.var:e$.varKinds.const){if(this.opts.ownProperties)return this.forOf($,A1._`Object.keys(${Y})`,q);let J=this._scope.toName($);return this._for(new sR("in",z,J,Y),()=>q(J))}endFor(){return this._endBlockNode(Vz)}label($){return this._leafNode(new Fs($))}break($){return this._leafNode(new Os($))}return($){let Y=new gV;if(this._blockNode(Y),this.code($),Y.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(gV)}try($,Y,q){if(!Y&&!q)throw Error('CodeGen: "try" without "catch" and "finally"');let z=new Bs;if(this._blockNode(z),this.code($),Y){let J=this.name("e");this._currNode=z.catch=new SV(J),Y(J)}if(q)this._currNode=z.finally=new yV,this.code(q);return this._endBlockNode(SV,yV)}throw($){return this._leafNode(new Ms($))}block($,Y){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(Y);return this}endBlock($){let Y=this._blockStarts.pop();if(Y===void 0)throw Error("CodeGen: not in self-balancing block");let q=this._nodes.length-Y;if(q<0||$!==void 0&&q!==$)throw Error(`CodeGen: wrong number of nodes: ${q} vs ${$} expected`);return this._nodes.length=Y,this}func($,Y=A1.nil,q,z){if(this._blockNode(new hV($,Y,q)),z)this.code(z).endFunc();return this}endFunc(){return this._endBlockNode(hV)}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($,Y){let q=this._currNode;if(q instanceof $||Y&&q instanceof Y)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${Y?`${$.kind}/${Y.kind}`:$.kind}"`)}_elseNode($){let Y=this._currNode;if(!(Y instanceof P9))throw Error('CodeGen: "else" without "if"');return this._currNode=Y.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let Y=this._nodes;Y[Y.length-1]=$}}k8.CodeGen=Ts;function T2($,Y){for(let q in Y)$[q]=($[q]||0)+(Y[q]||0);return $}function xV($,Y){return Y instanceof A1._CodeOrName?T2($,Y.names):$}function Lz($,Y,q){if($ instanceof A1.Name)return z($);if(!J($))return $;return new A1._Code($._items.reduce((U,I)=>{if(I instanceof A1.Name)I=z(I);if(I instanceof A1._Code)U.push(...I._items);else U.push(I);return U},[]));function z(U){let I=q[U.str];if(I===void 0||Y[U.str]!==1)return U;return delete Y[U.str],I}function J(U){return U instanceof A1._Code&&U._items.some((I)=>I instanceof A1.Name&&Y[I.str]===1&&q[I.str]!==void 0)}}function sf0($,Y){for(let q in Y)$[q]=($[q]||0)-(Y[q]||0)}function Es($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:A1._`!${tR($)}`}k8.not=Es;var tf0=js(k8.operators.AND);function af0(...$){return $.reduce(tf0)}k8.and=af0;var ef0=js(k8.operators.OR);function $b0(...$){return $.reduce(ef0)}k8.or=$b0;function js($){return(Y,q)=>Y===A1.nil?q:q===A1.nil?Y:A1._`${tR(Y)} ${$} ${tR(q)}`}function tR($){return $ instanceof A1.Name?$:A1._`(${Line truncated
|| (${I} == "string" && ${J} && ${J} == +${J})`).assign(Q,U1._`+${J}`);return;case"integer":z.elseIf(U1._`${I} === "boolean" || ${J} === null
|| (${I} === "string" && ${J} && ${J} == +${J} && !(${J} % 1))`).assign(Q,U1._`+${J}`);return;case"boolean":z.elseIf(U1._`${J} === "false" || ${J} === 0 || ${J} === null`).assign(Q,!1).elseIf(U1._`${J} === "true" || ${J} === 1`).assign(Q,!0);return;case"null":z.elseIf(U1._`${J} === "" || ${J} === 0 || ${J} === false`),z.assign(Q,null);return;case"array":z.elseIf(U1._`${I} === "string" || ${I} === "number"
|| ${I} === "boolean" || ${J} === null`).assign(Q,U1._`[${J}]`)}}}function Xi0({gen:$,parentData:Y,parentDataProperty:q},z){$.if(U1._`${Y} !== undefined`,()=>$.assign(U1._`${Y}[${q}]`,z))}function UC($,Y,q,z=wz.Correct){let J=z===wz.Correct?U1.operators.EQ:U1.operators.NEQ,U;switch($){case"null":return U1._`${Y} ${J} null`;case"array":U=U1._`Array.isArray(${Y})`;break;case"object":U=U1._`${Y} && typeof ${Y} == "object" && !Array.isArray(${Y})`;break;case"integer":U=I(U1._`!(${Y} % 1) && !isNaN(${Y})`);break;case"number":U=I();break;default:return U1._`typeof ${Y} ${J} ${$}`}return z===wz.Correct?U:(0,U1.not)(U);function I(Q=U1.nil){return(0,U1.and)(U1._`typeof ${Y} == "number"`,Q,q?U1._`isFinite(${Y})`:U1.nil)}}zt.checkDataType=UC;function IC($,Y,q,z){if($.length===1)return UC($[0],Y,q,z);let J,U=(0,$t.toHash)($);if(U.array&&U.object){let I=U1._`typeof ${Y} != "object"`;J=U.null?I:U1._`!${Y} || ${I}`,delete U.null,delete U.array,delete U.object}else J=U1.nil;if(U.number)delete U.integer;for(let I in U)J=(0,U1.and)(J,UC(I,Y,q,z));return J}zt.checkDataTypes=IC;var Vi0={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:Y})=>typeof $=="string"?U1._`{type: ${$}}`:U1._`{type: ${Y}}`};function QC($){let Y=Li0($);(0,Ki0.reportError)(Y,Vi0)}zt.reportTypeError=QC;function Li0($){let{gen:Y,data:q,schema:z}=$,J=(0,$t.schemaRefOrVal)($,z,"type");return{gen:Y,keyword:"type",data:q,schema:z.type,schemaCode:J,schemaValue:J,parentSchema:z,params:{},it:$}}});var Kt=M((It)=>{Object.defineProperty(It,"__esModule",{value:!0});It.assignDefaults=void 0;var Fz=I1(),Pi0=j1();function Ai0($,Y){let{properties:q,items:z}=$.schema;if(Y==="object"&&q)for(let J in q)Ut($,J,q[J].default);else if(Y==="array"&&Array.isArray(z))z.forEach((J,U)=>Ut($,U,J.default))}It.assignDefaults=Ai0;function Ut($,Y,q){let{gen:z,compositeRule:J,data:U,opts:I}=$;if(q===void 0)return;let Q=Fz._`${U}${(0,Fz.getProperty)(Y)}`;if(J){(0,Pi0.checkStrictMode)($,`default is ignored for: ${Q}`);return}let K=Fz._`${Q} === undefined`;if(I.useDefaults==="empty")K=Fz._`${K} || ${Q} === null || ${Q} === ""`;z.if(K,Fz._`${Q} = ${(0,Fz.stringify)(q)}`)}});var D$=M((Zt)=>{Object.defineProperty(Zt,"__esModule",{value:!0});Zt.validateUnion=Zt.validateArray=Zt.usePattern=Zt.callValidateCode=Zt.schemaProperties=Zt.allSchemaProperties=Zt.noPropertyInData=Zt.propertyInData=Zt.isOwnProperty=Zt.hasPropFunc=Zt.reportMissingProp=Zt.checkMissingProp=Zt.checkReportMissingProp=void 0;var F4=I1(),KC=j1(),b3=A9(),Bi0=j1();function Ti0($,Y){let{gen:q,data:z,it:J}=$;q.if(HC(q,z,Y,J.opts.ownProperties),()=>{$.setParams({missingProperty:F4._`${Y}`},!0),$.error()})}Zt.checkReportMissingProp=Ti0;function Ei0({gen:$,data:Y,it:{opts:q}},z,J){return(0,F4.or)(...z.map((U)=>(0,F4.and)(HC($,Y,U,q.ownProperties),F4._`${J} = ${U}`)))}Zt.checkMissingProp=Ei0;function ji0($,Y){$.setParams({missingProperty:Y},!0),$.error()}Zt.reportMissingProp=ji0;function Gt($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:F4._`Object.prototype.hasOwnProperty`})}Zt.hasPropFunc=Gt;function GC($,Y,q){return F4._`${Gt($)}.call(${Y}, ${q})`}Zt.isOwnProperty=GC;function _i0($,Y,q,z){let J=F4._`${Y}${(0,F4.getProperty)(q)} !== undefined`;return z?F4._`${J} && ${GC($,Y,q)}`:J}Zt.propertyInData=_i0;function HC($,Y,q,z){let J=F4._`${Y}${(0,F4.getProperty)(q)} === undefined`;return z?(0,F4.or)(J,(0,F4.not)(GC($,Y,q))):J}Zt.noPropertyInData=HC;function Ht($){return $?Object.keys($).filter((Y)=>Y!=="__proto__"):[]}Zt.allSchemaProperties=Ht;function Ri0($,Y){return Ht(Y).filter((q)=>!(0,KC.alwaysValidSchema)($,Y[q]))}Zt.schemaProperties=Ri0;function Ci0({schemaCode:$,data:Y,it:{gen:q,topSchemaRef:z,schemaPath:J,errorPath:U},it:I},Q,K,G){let H=G?F4._`${$}, ${Y}, ${z}${J}`:Y,Z=[[b3.default.instancePath,(0,F4.strConcat)(b3.default.instancePath,U)],[b3.default.parentData,I.parentData],[b3.default.parentDataProperty,I.parentDataProperty],[b3.default.rootData,b3.default.rootData]];if(I.opts.dynamicRef)Z.push([b3.default.dynamicAnchors,b3.default.dynamicAnchors]);let V=F4._`${H}, ${q.object(...Z)}`;return K!==F4.nil?F4._`${Q}.call(${K}, ${V})`:F4._`${Q}(${V})`}Zt.callValidateCode=Ci0;var vi0=F4._`new RegExp`;function hi0({gen:$,it:{opts:Y}},q){let z=Y.unicodeRegExp?"u":"",{regExp:J}=Y.code,U=J(q,z);return $.scopeValue("pattern",{key:U.toString(),ref:U,code:F4._`${J.code==="new RegExp"?vi0:(0,Bi0.useFunc)($,J)}(${q}, ${z})`})}Zt.usePattern=hi0;function gi0($){let{gen:Y,data:q,keyword:z,it:J}=$,U=Y.name("valid");if(J.allErrors){let Q=Y.let("valid",!0);return I(()=>Y.assign(Q,!1)),Q}return Y.var(U,!0),I(()=>Y.break()),U;function I(Q){let K=Y.const("len",F4._`${q}.length`);Y.forRange("i",0,K,(G)=>{$.subschema({keyword:z,dataProp:G,dataPropType:KC.Type.Num},U),Y.if((0,F4.not)(U),Q)})}}Zt.validateArray=gi0;function Si0($){let{gen:Y,schema:q,keyword:z,it:J}=$;if(!Array.isArray(q))throw Error("ajv implementation error");if(q.some((K)=>(0,KC.alwaysValidSchema)(J,K))&&!J.opts.unevaluated)return;le Line truncated
missingProperty: ${z},
depsCount: ${Y},
deps: ${q}}`};var ed0={keyword:"dependencies",type:"object",schemaType:"object",error:_e.error,code($){let[Y,q]=$m0($);Ee($,Y),je($,q)}};function $m0({schema:$}){let Y={},q={};for(let z in $){if(z==="__proto__")continue;let J=Array.isArray($[z])?Y:q;J[z]=$[z]}return[Y,q]}function Ee($,Y=$.schema){let{gen:q,data:z,it:J}=$;if(Object.keys(Y).length===0)return;let U=q.let("missing");for(let I in Y){let Q=Y[I];if(Q.length===0)continue;let K=(0,UK.propertyInData)(q,z,I,J.opts.ownProperties);if($.setParams({property:I,depsCount:Q.length,deps:Q.join(", ")}),J.allErrors)q.if(K,()=>{for(let G of Q)(0,UK.checkReportMissingProp)($,G)});else q.if(gC._`${K} && (${(0,UK.checkMissingProp)($,Q,U)})`),(0,UK.reportMissingProp)($,U),q.else()}}_e.validatePropertyDeps=Ee;function je($,Y=$.schema){let{gen:q,data:z,keyword:J,it:U}=$,I=q.name("valid");for(let Q in Y){if((0,ad0.alwaysValidSchema)(U,Y[Q]))continue;q.if((0,UK.propertyInData)(q,z,Q,U.opts.ownProperties),()=>{let K=$.subschema({keyword:J,schemaProp:Q},I);$.mergeValidEvaluated(K,I)},()=>q.var(I,!0)),$.ok(I)}}_e.validateSchemaDeps=je;_e.default=ed0});var Se=M((ge)=>{Object.defineProperty(ge,"__esModule",{value:!0});var he=I1(),zm0=j1(),Jm0={message:"property name must be valid",params:({params:$})=>he._`{propertyName: ${$.propertyName}}`},Um0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Jm0,code($){let{gen:Y,schema:q,data:z,it:J}=$;if((0,zm0.alwaysValidSchema)(J,q))return;let U=Y.name("valid");Y.forIn("key",z,(I)=>{$.setParams({propertyName:I}),$.subschema({keyword:"propertyNames",data:I,dataTypes:["string"],propertyName:I,compositeRule:!0},U),Y.if((0,he.not)(U),()=>{if($.error(!0),!J.allErrors)Y.break()})}),$.ok(U)}};ge.default=Um0});var SC=M((ye)=>{Object.defineProperty(ye,"__esModule",{value:!0});var JL=D$(),q5=I1(),Qm0=A9(),UL=j1(),Km0={message:"must NOT have additional properties",params:({params:$})=>q5._`{additionalProperty: ${$.additionalProperty}}`},Gm0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Km0,code($){let{gen:Y,schema:q,parentSchema:z,data:J,errsCount:U,it:I}=$;if(!U)throw Error("ajv implementation error");let{allErrors:Q,opts:K}=I;if(I.props=!0,K.removeAdditional!=="all"&&(0,UL.alwaysValidSchema)(I,q))return;let G=(0,JL.allSchemaProperties)(z.properties),H=(0,JL.allSchemaProperties)(z.patternProperties);Z(),$.ok(q5._`${U} === ${Qm0.default.errors}`);function Z(){Y.forIn("key",J,(F)=>{if(!G.length&&!H.length)L(F);else Y.if(V(F),()=>L(F))})}function V(F){let O;if(G.length>8){let P=(0,UL.schemaRefOrVal)(I,z.properties,"properties");O=(0,JL.isOwnProperty)(Y,P,F)}else if(G.length)O=(0,q5.or)(...G.map((P)=>q5._`${F} === ${P}`));else O=q5.nil;if(H.length)O=(0,q5.or)(O,...H.map((P)=>q5._`${(0,JL.usePattern)($,P)}.test(${F})`));return(0,q5.not)(O)}function X(F){Y.code(q5._`delete ${J}[${F}]`)}function L(F){if(K.removeAdditional==="all"||K.removeAdditional&&q===!1){X(F);return}if(q===!1){if($.setParams({additionalProperty:F}),$.error(),!Q)Y.break();return}if(typeof q=="object"&&!(0,UL.alwaysValidSchema)(I,q)){let O=Y.name("valid");if(K.removeAdditional==="failing")w(F,O,!1),Y.if((0,q5.not)(O),()=>{$.reset(),X(F)});else if(w(F,O),!Q)Y.if((0,q5.not)(O),()=>Y.break())}}function w(F,O,P){let B={keyword:"additionalProperties",dataProp:F,dataPropType:UL.Type.Str};if(P===!1)Object.assign(B,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(B,O)}}};ye.default=Gm0});var fe=M((ue)=>{Object.defineProperty(ue,"__esModule",{value:!0});var Zm0=lQ(),xe=D$(),yC=j1(),ke=SC(),Wm0={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:Y,schema:q,parentSchema:z,data:J,it:U}=$;if(U.opts.removeAdditional==="all"&&z.additionalProperties===void 0)ke.default.code(new Zm0.KeywordCxt(U,ke.default,"additionalProperties"));let I=(0,xe.allSchemaProperties)(q);for(let Z of I)U.definedProperties.add(Z);if(U.opts.unevaluated&&I.length&&U.props!==!0)U.props=yC.mergeEvaluated.props(Y,(0,yC.toHash)(I),U.props);let Q=I.filter((Z)=>!(0,yC.alwaysValidSchema)(U,q[Z]));if(Q.length===0)return;let K=Y.name("valid");for(let Z of Q){if(G(Z))H(Z);else{if(Y.if((0,xe.propertyInData)(Y,J,Z,U.opts.ownProperties)),H(Z),!U.allErrors)Y.else().var(K,!0);Y.endIf()}$.it.definedProperties.add(Z),$.ok(K)}function G(Z){return U.opts.useDefaults&&!U.compositeRule&&q[Z].default!==void 0}function H(Z){$.subschema({keyword:"properties",schemaProp:Z,dataProp:Z},K)}}};ue.default=Wm0});var pe=M((ce)=>{Object.defineProperty(ce,"__esModule",{value:!0});var be=D$(),IL=I1(),ie=j1(),ne=j1(),Vm0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:Y,schema:q,data:z,parentSchema:J,it:U}=$,{opts:I}=U,Q=(0,be.allSchemaProperties)(q),K=Q.filter((w)=>(0,ie.alwaysValidSchema)(U,q[w]));if(Q.length===0||K.length===Q.length&&(!U.opts.unevaluated||U.props===!0))return;let G=I.strictSchema&&!I.allowMatchingProperties&&J.properties,H=Y.name("valid");if(U.props!==!0&&!(U.props instanceo Line truncated
\x00`,n+=X4(k,2),n+=Q.magic,n+=X4(F,2),n+=X4(O,2),n+=X4(v.crc32,4),n+=X4(v.compressedSize,4),n+=X4(v.uncompressedSize,4),n+=X4(G.length,2),n+=X4(P.length,2);var g=dw.LOCAL_FILE_HEADER+n+G+P,b=dw.CENTRAL_FILE_HEADER+X4(c,2)+n+X4(V.length,2)+"\x00\x00\x00\x00"+X4(C,4)+X4(z,4)+G+P+V;return{fileRecord:g,dirRecord:b}},c11=function($,Y,q,z,J){var U="",I=IJ.transformTo("string",J(z));return U=dw.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+X4($,2)+X4($,2)+X4(Y,4)+X4(q,4)+X4(I.length,2)+I,U},p11=function($){var Y="";return Y=dw.DATA_DESCRIPTOR+X4($.crc32,4)+X4($.compressedSize,4)+X4($.uncompressedSize,4),Y};function H5($,Y,q,z){QJ.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=Y,this.zipPlatform=q,this.encodeFileName=z,this.streamFiles=$,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}IJ.inherits(H5,QJ);H5.prototype.push=function($){var Y=$.meta.percent||0,q=this.entriesCount,z=this._sources.length;if(this.accumulate)this.contentBuffer.push($);else this.bytesWritten+=$.data.length,QJ.prototype.push.call(this,{data:$.data,meta:{currentFile:this.currentFile,percent:q?(Y+100*(q-z-1))/q:100}})};H5.prototype.openedSource=function($){this.currentSourceOffset=this.bytesWritten,this.currentFile=$.file.name;var Y=this.streamFiles&&!$.file.dir;if(Y){var q=l90($,Y,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:q.fileRecord,meta:{percent:0}})}else this.accumulate=!0};H5.prototype.closedSource=function($){this.accumulate=!1;var Y=this.streamFiles&&!$.file.dir,q=l90($,Y,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(q.dirRecord),Y)this.push({data:p11($),meta:{percent:100}});else{this.push({data:q.fileRecord,meta:{percent:0}});while(this.contentBuffer.length)this.push(this.contentBuffer.shift())}this.currentFile=null};H5.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 q=this.bytesWritten-$,z=c11(this.dirRecords.length,q,$,this.zipComment,this.encodeFileName);this.push({data:z,meta:{percent:100}})};H5.prototype.prepareNextSource=function(){if(this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused)this.previous.pause();else this.previous.resume()};H5.prototype.registerPrevious=function($){this._sources.push($);var Y=this;return $.on("data",function(q){Y.processChunk(q)}),$.on("end",function(){if(Y.closedSource(Y.previous.streamInfo),Y._sources.length)Y.prepareNextSource();else Y.end()}),$.on("error",function(q){Y.error(q)}),this};H5.prototype.resume=function(){if(!QJ.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};H5.prototype.error=function($){var Y=this._sources;if(!QJ.prototype.error.call(this,$))return!1;for(var q=0;q<Y.length;q++)try{Y[q].error($)}catch(z){}return!0};H5.prototype.lock=function(){QJ.prototype.lock.call(this);var $=this._sources;for(var Y=0;Y<$.length;Y++)$[Y].lock()};o90.exports=H5});var s90=M((o11)=>{var d11=Bg(),m11=r90(),l11=function($,Y){var q=$||Y,z=d11[q];if(!z)throw Error(q+" is not a valid compression method !");return z};o11.generateWorker=function($,Y,q){var z=new m11(Y.streamFiles,q,Y.platform,Y.encodeFileName),J=0;try{$.forEach(function(U,I){J++;var Q=l11(I.options.compression,Y.compression),K=I.options.compressionOptions||Y.compressionOptions||{},G=I.dir,H=I.date;I._compressWorker(Q,K).withStreamInfo("file",{name:U,dir:G,date:H,comment:I.comment||"",unixPermissions:I.unixPermissions,dosPermissions:I.dosPermissions}).pipe(z)}),z.entriesCount=J}catch(U){z.error(U)}return z}});var a90=M((k04,t90)=>{var s11=u4(),mw=U$();function QG($,Y){mw.call(this,"Nodejs stream input adapter for "+$),this._upstreamEnded=!1,this._bindStream(Y)}s11.inherits(QG,mw);QG.prototype._bindStream=function($){var Y=this;this._stream=$,$.pause(),$.on("data",function(q){Y.push({data:q,meta:{percent:0}})}).on("error",function(q){if(Y.isPaused)this.generatedError=q;else Y.error(q)}).on("end",function(){if(Y.isPaused)Y._upstreamEnded=!0;else Y.end()})};QG.prototype.pause=function(){if(!mw.prototype.pause.call(this))return!1;return this._stream.pause(),!0};QG.prototype.resume=function(){if(!mw.prototype.resume.call(this))return!1;if(this._upstreamEnded)this.end();else this._stream.resume();return!0};t90.exports=QG});var K30=M((u04,Q30)=>{var t11=sz(),KG=u4(),q30=U$(),a11=Ch(),z30=vh(),e90=jw(),e11=$50(),$41=s90(),$30=bK(),Y41=a90(),J30=function($,Y,q){var z=KG.getTypeOf(Y),J,U=KG.extend(q||{},z30);if(U.date=U.date||new Date,U.compression!==null)U.compression=U.compression.toUpperCase();if(typeof U.unixPermissions==="string")U.unixPermissions=parseInt(U.unixPermissions,8);if(U.unixPermissions&&U.unixPermissions&16384)U.dir=!0;if(U.dosPermissions&&U.dosPermission Line truncated
`)}openNode($,Y){let q=this.tos,z=this._xml;if(q&&this.open)z.push(">");this._stack.push($),z.push("<"),z.push($),QS(z,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)a70(this._xml,$,Y)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");QS(this._xml,$)}writeText($){let Y=this._xml;if(this.open)Y.push(">"),this.open=!1;this.leaf=!1,Y.push(t70.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,q){if(this.openNode($,Y),q!==void 0)this.writeText(q);this.closeNode()}closeAll(){while(this._stack.length)this.closeNode()}addRollback(){return this._rollbacks.push({xml:this._xml.length,stack:this._stack.length,leaf:this.leaf,open:this.open}),this.cursor}commit(){this._rollbacks.pop()}rollback(){let $=this._rollbacks.pop();if(this._xml.length>$.xml)this._xml.splice($.xml,this._xml.length-$.xml);if(this._stack.length>$.stack)this._stack.splice($.stack,this._stack.length-$.stack);this.leaf=$.leaf,this.open=$.open}get xml(){return this.closeAll(),this._xml.join("")}}KS.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};e70.exports=KS});var GS=M((m81)=>{var $20=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function d81($){if(typeof $==="string")return $;if($20)return $20.decode($);return $.toString()}m81.bufferToString=d81});var U20=M((q20)=>{Object.defineProperty(q20,"__esModule",{value:!0});q20.CHAR=`
\r -퟿-�\uD800\uDC00-\uDBFF\uDFFF`;q20.S=` \r
`;q20.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";q20.NAME_CHAR="-"+q20.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";q20.CHAR_RE=new RegExp("^["+q20.CHAR+"]$","u");q20.S_RE=new RegExp("^["+q20.S+"]+$","u");q20.NAME_START_CHAR_RE=new RegExp("^["+q20.NAME_START_CHAR+"]$","u");q20.NAME_CHAR_RE=new RegExp("^["+q20.NAME_CHAR+"]$","u");q20.NAME_RE=new RegExp("^["+q20.NAME_START_CHAR+"]["+q20.NAME_CHAR+"]*$","u");q20.NMTOKEN_RE=new RegExp("^["+q20.NAME_CHAR+"]+$","u");var HS=9,ZS=10,WS=13,XS=32;q20.S_LIST=[XS,ZS,WS,HS];function o81($){return $>=XS&&$<=55295||$===ZS||$===WS||$===HS||$>=57344&&$<=65533||$>=65536&&$<=1114111}q20.isChar=o81;function r81($){return $===XS||$===ZS||$===WS||$===HS}q20.isS=r81;function Y20($){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}q20.isNameStartChar=Y20;function s81($){return Y20($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}q20.isNameChar=s81});var L20=M((Z20)=>{Object.defineProperty(Z20,"__esModule",{value:!0});Z20.CHAR="\x01-퟿-�\uD800\uDC00-\uDBFF\uDFFF";Z20.RESTRICTED_CHAR="\x01-\b\v\f\x0E-\x1F-„†-Ÿ";Z20.S=` \r
`;Z20.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";Z20.NAME_CHAR="-"+Z20.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";Z20.CHAR_RE=new RegExp("^["+Z20.CHAR+"]$","u");Z20.RESTRICTED_CHAR_RE=new RegExp("^["+Z20.RESTRICTED_CHAR+"]$","u");Z20.S_RE=new RegExp("^["+Z20.S+"]+$","u");Z20.NAME_START_CHAR_RE=new RegExp("^["+Z20.NAME_START_CHAR+"]$","u");Z20.NAME_CHAR_RE=new RegExp("^["+Z20.NAME_CHAR+"]$","u");Z20.NAME_RE=new RegExp("^["+Z20.NAME_START_CHAR+"]["+Z20.NAME_CHAR+"]*$","u");Z20.NMTOKEN_RE=new RegExp("^["+Z20.NAME_CHAR+"]+$","u");var I20=9,Q20=10,K20=13,G20=32;Z20.S_LIST=[G20,Q20,K20,I20];function K$1($){return $>=1&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}Z20.isChar=K$1;function G$1($){return $>=1&&$<=8||$===11||$===12||$>=14&&$<=31||$>=127&&$<=132||$>=134&&$<=159}Z20.isRestrictedChar=G$1;function H$1($){return $===9||$===10||$===13||$>31&&$<127||$===133||$>159&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}Z20.isCharAndNotRestricted=H$1;function Z$1($){return $===G20||$===Q20||$===K20||$===I20}Z20.isS=Z$1;function H20($){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}Z20.isNameStartChar=H20;function W$1($){return H20($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}Z20.isNameChar=W$1});var O20=M((F20)=>{Object.defineProperty(F20,"__esModule",{value:!0});F20.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";F20.NC_NAME_CHAR="-"+F20.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";F20.NC_NAME_START_CHAR_RE=new RegExp("^["+F20.NC_NAME_START_CHAR+"]$","u");F20.NC_NAME_CHAR_RE=new RegExp("^["+F20.NC_NAME_CHAR+"]$","u");F20.NC_NAME_RE=new RegExp("^["+F20.NC_NAME_START_CHAR+"]["+F20.NC_NAME_CHAR+"]*$","u");function w20($){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}F20.isNCNameStartChar=w20;function j$1($){return w20($)||($===45||$===46||$>=48&&$<=57||$===183||$>=768&&$<=879||$>=8255&&$<=8256)}F20.isNCNameChar=j$1});var b20=M((f20)=>{Object.defineProperty(f20,"__esModule",{value:!0});var MJ=U20(),g$1=L20(),jS=O20(),c8=MJ.isS,S$1=MJ.isChar,DG=MJ.isNameStartChar,M20=MJ.isNameChar,g20=MJ.S_LIST,y$1=MJ.NAME_RE,x$1=g$1.isChar,k$1=jS.isNCNameStartChar,u$1=jS.isNCNameChar,f$1=jS.NC_NAME_RE,DF="http://www.w3.org/XML/1998/namespace",OJ="http://www.w3.org/2000/xmlns/",b$1={__proto__:null,xml:DF,xmlns:OJ},i$1={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},h4=-1,m5=-2,N20=0,n$1=1,LS=2,c$1=3,LJ=4,p$1=5,d$1=6,m$1=7,wS=8,l$1=9,o$1=10,r$1=11,s$1=12,A8=13,wF=14,FS=15,t$1=16,OS=17,a$1=18,e$1=19,MS=20,$51=21,Y51=22,q51=23,D20=24,NS=25,FF=26,P20=27,z51=28,J51=29,A20=30,U51=31,I51=32,e2=33,Q51=34,DS=35,PG=36,PS=37,K51=38,B20=39,T20=40,G51=41,E20=42,H51=43,Z51=44,AS=9,W5=10,BS=13,j20=32,_20=33,S20=34,AG=38,y20=39,OF=45,MF=47,W51=59,Z7=60,wJ=61,O6=62,p6=63,x20=91,FJ=93,R20=133,C20=8232,NF=($)=>$===S20||$===y20,k20=[S20,y20],X51=[...k20,x20,O6],V51=[...k20,Z7,FJ],L51=[wJ,p6,...g20],w51=[...g20,O6,AG,Z7];function ES($,Y,q){switch(Y){case"xml":if(q!==DF)$.fail(`xml prefix must be bound to ${DF}.`);break;case"xmlns":if(q!==OJ)$.fail(`xmlns prefix must be bound to ${OJ}.`);break;default:}switch(q){case OJ:$.fail(Y===""?`the default namespace may not be set to ${q}.`:`may not assign a prefix (even "xmlns") to the URI ${OJ}.`);break;case DF:switch(Y){case"xml":break;case"":$.fail(`the default namespace may not be set to ${q}.`);break;default:$.fail("may not assign the xml namespace to another prefix.")}break;default:}}function F51($,Y){for(let q of Object.keys(Y))ES($,q,Y[q])}var O51=($)=>f$1.test($),M51=($)=>y$1.test($),$Y=0,v20=1,TS=2;f20.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var h20={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 u20{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=k$1,this.nameCheck=u$1,this.isName=O51,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},b$1);let q=this.opt.additionalNamesp Line truncated
`,Y=this.i}}captureToChar($){let{i:Y}=this,{chunk:q}=this;while(!0){let z=this.getCode();switch(z){case m5:this.text+=`${q.slice(Y,this.prevI)}
`,Y=this.i,z=W5;break;case h4:return this.text+=q.slice(Y),!1;default:}if(z===$)return this.text+=q.slice(Y,this.prevI),!0}}captureNameChars(){let{chunk:$,i:Y}=this;while(!0){let q=this.getCode();if(q===h4)return this.name+=$.slice(Y),h4;if(!M20(q))return this.name+=$.slice(Y,this.prevI),q===m5?W5:q}}skipSpaces(){while(!0){let $=this.getCodeNorm();if($===h4||!c8($))return $}}setXMLVersion($){if(this.currentXMLVersion=$,$==="1.0")this.isChar=S$1,this.getCode=this.getCode10;else this.isChar=x$1,this.getCode=this.getCode11}sBegin(){if(this.chunk.charCodeAt(0)===65279)this.i++,this.column++;this.state=n$1}sBeginWhitespace(){let $=this.i,Y=this.skipSpaces();if(this.prevI!==$)this.xmlDeclPossible=!1;switch(Y){case Z7:if(this.state=FS,this.text.length!==0)throw Error("no-empty text at start");break;case h4:break;default:this.unget(),this.state=A8,this.xmlDeclPossible=!1}}sDoctype(){var $;let Y=this.captureTo(X51);switch(Y){case O6:{($=this.doctypeHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=A8,this.doctype=!0;break}case h4:break;default:if(this.text+=String.fromCodePoint(Y),Y===x20)this.state=LJ;else if(NF(Y))this.state=c$1,this.q=Y}}sDoctypeQuote(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.q=null,this.state=LS}sDTD(){let $=this.captureTo(V51);if($===h4)return;if(this.text+=String.fromCodePoint($),$===FJ)this.state=LS;else if($===Z7)this.state=d$1;else if(NF($))this.state=p$1,this.q=$}sDTDQuoted(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.state=LJ,this.q=null}sDTDOpenWaka(){let $=this.getCodeNorm();switch(this.text+=String.fromCodePoint($),$){case _20:this.state=m$1,this.openWakaBang="";break;case p6:this.state=r$1;break;default:this.state=LJ}}sDTDOpenWakaBang(){let $=String.fromCodePoint(this.getCodeNorm()),Y=this.openWakaBang+=$;if(this.text+=$,Y!=="-")this.state=Y==="--"?wS:LJ,this.openWakaBang=""}sDTDComment(){if(this.captureToChar(OF))this.text+="-",this.state=l$1}sDTDCommentEnding(){let $=this.getCodeNorm();this.text+=String.fromCodePoint($),this.state=$===OF?o$1:wS}sDTDCommentEnded(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===O6)this.state=LJ;else this.fail("malformed comment."),this.state=wS}sDTDPI(){if(this.captureToChar(p6))this.text+="?",this.state=s$1}sDTDPIEnding(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===O6)this.state=LJ}sText(){if(this.tags.length!==0)this.handleTextInRoot();else this.handleTextOutsideRoot()}sEntity(){let{i:$}=this,{chunk:Y}=this;$:while(!0)switch(this.getCode()){case m5:this.entity+=`${Y.slice($,this.prevI)}
`,$=this.i;break;case W51:{let{entityReturnState:q}=this,z=this.entity+Y.slice($,this.prevI);this.state=q;let J;if(z==="")this.fail("empty entity name."),J="&;";else J=this.parseEntity(z),this.entity="";if(q!==A8||this.textHandler!==void 0)this.text+=J;break $}case h4:this.entity+=Y.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(DG($))this.state=Q51,this.unget(),this.xmlDeclPossible=!1;else switch($){case MF:this.state=H51,this.xmlDeclPossible=!1;break;case _20:this.state=t$1,this.openWakaBang="",this.xmlDeclPossible=!1;break;case p6:this.state=q51;break;default:this.fail("disallowed character in tag name"),this.state=A8,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=MS,this.openWakaBang="";break;case"--":this.state=OS,this.openWakaBang="";break;case"DOCTYPE":if(this.state=LS,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(OF))this.state=a$1}sCommentEnding(){var $;let Y=this.getCodeNorm();if(Y===OF)this.state=e$1,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(Y)}`,this.state=OS}sCommentEnded(){let $=this.getCodeNorm();if($!==O6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=OS;else this.state=A8}sCData(){if(this.captureToChar(FJ))this.state=$51}sCDataEnding(){let $=this.getCodeNorm();if($===FJ)this.state=Y51;else this.text+=`]${String.fromCodePoint($)}`,this.state=MS}sCDataEnding2(){var $;let Y=this.getCodeNorm();switch(Y){case O6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=A8;break}case FJ:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(Y)}`,this.state=MS}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=D20;else if($===p6||c8($))this.fail("processing instruction without a target."),this.state=$===p6?FF:NS;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=D20}sPIRest(){let{chunk:$,i:Y}=this;while(!0){let q=this.getCodeNorm();if(q===h4){this.piTarget+=$.slice(Y);return}if(!this.nameCheck(q)){this.piTarget+=$.slice(Y,this.prevI);let z=q===p6;if(z||c8(q))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=z?e2:P20}else this.state=z?FF:NS;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(q);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===p6)this.state=FF;else if(!c8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(p6))this.state=FF}sPIEnding(){var $;let Y=this.getCodeNorm();if(Y===O6){let{piTarget:q}=this;if(q.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:q,body:this.text}),this.piTarget=this.text="",this.state=A8}else if(Y===p6)this.text+="?";else this.text+=`?${String.fromCodePoint(Y)}`,this.state=NS;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===p6){this.state=e2;return}if($!==h4)this.state=z51,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(L51);if($===p6){this.state=e2,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(c8($)||$===wJ))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=$===wJ?A20:J51}sXMLDeclEq(){let $=this.getCodeNorm();if($===p6){this.state=e2,this.fail("XML declaration is incomplete.");return}if(c8($))return;if($!==wJ)this.fail("value required.");this.state=A20}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===p6){this.state=e2,this.fail("XML declaration is incomplete.");return}if(c8($))return;if(!NF($))this.fail("value must be quoted."),this.q=j20;else this.q=$;this.state=U51}sXMLDeclValue(){let $=this.captureTo([this.q,p6]);if($===p6){this.state=e2,this.text="",this.fail("XML declaration is incomplete.");return}if($===h4)return;let Y=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let q=Y;if(this.xmlDecl.version=q,!/^1\.[0-9]+$/.test(q))this.fail("ver Line truncated
`;$=this.i,Y=$Y;break;case h4:if(z!==void 0)this.text+=q.slice($);break $;default:Y=$Y}this.forbiddenState=Y}handleTextOutsideRoot(){let{i:$}=this,{chunk:Y,textHandler:q}=this,z=!1;$:while(!0){let J=this.getCode();switch(J){case Z7:{if(this.state=FS,q!==void 0){let{text:U}=this,I=Y.slice($,this.prevI);if(U.length!==0)q(U+I),this.text="";else if(I.length!==0)q(I)}break $}case AG:if(this.state=wF,this.entityReturnState=A8,q!==void 0)this.text+=Y.slice($,this.prevI);z=!0;break $;case m5:if(q!==void 0)this.text+=`${Y.slice($,this.prevI)}
`;$=this.i;break;case h4:if(q!==void 0)this.text+=Y.slice($);break $;default:if(!c8(J))z=!0}}if(!z)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 q;let{prefix:z,local:J}=this.qname($),U={name:$,prefix:z,local:J,value:Y};if(this.attribList.push(U),(q=this.attributeHandler)===null||q===void 0||q.call(this,U),z==="xmlns"){let I=Y.trim();if(this.currentXMLVersion==="1.0"&&I==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[J]=I,ES(this,J,I)}else if($==="xmlns"){let I=Y.trim();this.topNS[""]=I,ES(this,"",I)}}pushAttribPlain($,Y){var q;let z={name:$,value:Y};this.attribList.push(z),(q=this.attributeHandler)===null||q===void 0||q.call(this,z)}end(){var $,Y;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:q}=this;while(q.length>0){let J=q.pop();this.fail(`unclosed tag: ${J.name}`)}if(this.state!==N20&&this.state!==A8)this.fail("unexpected end.");let{text:z}=this;if(z.length!==0)($=this.textHandler)===null||$===void 0||$.call(this,z),this.text="";return this._closed=!0,(Y=this.endHandler)===null||Y===void 0||Y.call(this),this._init(),this}resolve($){var Y,q;let z=this.topNS[$];if(z!==void 0)return z;let{tags:J}=this;for(let U=J.length-1;U>=0;U--)if(z=J[U].ns[$],z!==void 0)return z;if(z=this.ns[$],z!==void 0)return z;return(q=(Y=this.opt).resolvePrefix)===null||q===void 0?void 0:q.call(Y,$)}qname($){let Y=$.indexOf(":");if(Y===-1)return{prefix:"",local:$};let q=$.slice(Y+1),z=$.slice(0,Y);if(z===""||q===""||q.includes(":"))this.fail(`malformed name: ${$}.`);return{prefix:z,local:q}}processAttribsNS(){var $;let{attribList:Y}=this,q=this.tag;{let{prefix:U,local:I}=this.qname(q.name);q.prefix=U,q.local=I;let Q=q.uri=($=this.resolve(U))!==null&&$!==void 0?$:"";if(U!==""){if(U==="xmlns")this.fail('tags may not have "xmlns" as prefix.');if(Q==="")this.fail(`unbound namespace prefix: ${JSON.stringify(U)}.`),q.uri=U}}if(Y.length===0)return;let{attributes:z}=q,J=new Set;for(let U of Y){let{name:I,prefix:Q,local:K}=U,G,H;if(Q==="")G=I==="xmlns"?OJ:"",H=I;else{if(G=this.resolve(Q),G===void 0)this.fail(`unbound namespace prefix: ${JSON.stringify(Q)}.`),G=Q;H=`{${G}}${K}`}if(J.has(H))this.fail(`duplicate attribute: ${H}.`);J.add(H),U.uri=G,z[I]=U}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,Y=this.tag.attributes;for(let{name:q,value:z}of $){if(Y[q]!==void 0)this.fail(`duplicate attribute: ${q}.`);Y[q]=z}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:Y}=this,q=this.tag;q.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,q),Y.push(q),this.state=A8,this.name=""}openSelfClosingTag(){var $,Y,q;this.processAttribs();let{tags:z}=this,J=this.tag;if(J.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,J),(Y=this.closeTagHandler)===null||Y===void 0||Y.call(this,J),(this.tag=(q=z[z.length-1])!==null&&q!==void 0?q:null)===null)this.closedRoot=!0;this.state=A8,this.name=""}closeTag(){let{tags:$,name:Y}=this;if(this.state=A8,this.name="",Y===""){this.fail("weird empty close tag."),this.text+="</>";return}let q=this.closeTagHandler,z=$.length;while(z-- >0){let J=this.tag=$.pop();if(this.topNS=J.ns,q===null||q===void 0||q(J),J.name===Y)break;this.fail("unexpected close tag.")}if(z===0)this.closedRoot=!0;else if(z<0)this.fail(`unmatched closing tag: ${Y}.`),this.text+=`</${Y}>`}parseEntity($){if($[0]!=="#"){let q=this.ENTITIES[$];if(q!==void 0)return q;return this.fail(this.isName($)?"undefined entity.":"disallowed character in entity name."),`&${$};`}let 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)}}f20.SaxesParser=u20});var BG=M((D14,i20)=>{var{SaxesParser:P51}=b20(),{PassThrough:A51}=P8(),{bufferToString:B51}=GS();i20.exports=async function*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(new A51);let Y=new P51,q;Y.on("error",(J)=>{q=J});let z=[];Y.on("opentag",(J)=>z.push({eventType:"opentag",value:J})),Y.on("text",(J)=>z.push({eventType:"text",value:J})),Y.on("closetag",(J)=>z.push({eventType:"closetag",value:J}));for await(let J of $){if(Y.write(B51(J)),q)throw q;yield z,z=[]}}});var D0=M((P14,n20)=>{var T51=BG(),E51=c6();class NJ{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,Y){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($ instanceof NJ)$.reset();else if($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}async parse($){for await(let Y of $)for(let{eventType:q,value:z}of Y)if(q==="opentag")this.parseOpen(z);else if(q==="text")this.parseText(z);else if(q==="closetag"){if(!this.parseClose(z.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}`}}OQ0.FormatterOptions=FQ0});var $O=M((l64,AQ0)=>{var xq1="[object AsyncFunction]",kq1="[object Function]",uq1="[object GeneratorFunction]",fq1="[object Null]",bq1="[object Proxy]",iq1="[object Undefined]",nq1=typeof global=="object"&&global&&global.Object===Object&&global,cq1=typeof self=="object"&&self&&self.Object===Object&&self,pq1=nq1||cq1||Function("return this")(),DQ0=Object.prototype,dq1=DQ0.hasOwnProperty,PQ0=DQ0.toString,NQ0=pq1.Symbol,QY=NQ0?NQ0.toStringTag:void 0;function mq1($){if($==null)return $===void 0?iq1:fq1;return QY&&QY in Object($)?lq1($):oq1($)}function lq1($){var Y=dq1.call($,QY),q=$[QY];try{$[QY]=void 0;var z=!0}catch(U){}var J=PQ0.call($);if(z)if(Y)$[QY]=q;else delete $[QY];return J}function oq1($){return PQ0.call($)}function rq1($){if(!sq1($))return!1;var Y=mq1($);return Y==kq1||Y==uq1||Y==xq1||Y==bq1}function sq1($){var Y=typeof $;return $!=null&&(Y=="object"||Y=="function")}AQ0.exports=rq1});var JK0=M((YO,CJ)=>{var tq1=200,sy="__lodash_hash_undefined__",GO=1,yQ0=2,xQ0=9007199254740991,qO="[object Arguments]",cy="[object Array]",aq1="[object AsyncFunction]",kQ0="[object Boolean]",uQ0="[object Date]",fQ0="[object Error]",bQ0="[object Function]",eq1="[object GeneratorFunction]",zO="[object Map]",iQ0="[object Number]",$z1="[object Null]",RJ="[object Object]",BQ0="[object Promise]",Yz1="[object Proxy]",nQ0="[object RegExp]",JO="[object Set]",cQ0="[object String]",qz1="[object Symbol]",zz1="[object Undefined]",py="[object WeakMap]",pQ0="[object ArrayBuffer]",UO="[object DataView]",Jz1="[object Float32Array]",Uz1="[object Float64Array]",Iz1="[object Int8Array]",Qz1="[object Int16Array]",Kz1="[object Int32Array]",Gz1="[object Uint8Array]",Hz1="[object Uint8ClampedArray]",Zz1="[object Uint16Array]",Wz1="[object Uint32Array]",Xz1=/[\\^$.*+?()[\]{}|]/g,Vz1=/^\[object .+?Constructor\]$/,Lz1=/^(?:0|[1-9]\d*)$/,M4={};M4[Jz1]=M4[Uz1]=M4[Iz1]=M4[Qz1]=M4[Kz1]=M4[Gz1]=M4[Hz1]=M4[Zz1]=M4[Wz1]=!0;M4[qO]=M4[cy]=M4[pQ0]=M4[kQ0]=M4[UO]=M4[uQ0]=M4[fQ0]=M4[bQ0]=M4[zO]=M4[iQ0]=M4[RJ]=M4[nQ0]=M4[JO]=M4[cQ0]=M4[py]=!1;var dQ0=typeof global=="object"&&global&&global.Object===Object&&global,wz1=typeof self=="object"&&self&&self.Object===Object&&self,i9=dQ0||wz1||Function("return this")(),mQ0=typeof YO=="object"&&YO&&!YO.nodeType&&YO,TQ0=mQ0&&typeof CJ=="object"&&CJ&&!CJ.nodeType&&CJ,lQ0=TQ0&&TQ0.exports===mQ0,by=lQ0&&dQ0.process,EQ0=function(){try{return by&&by.binding&&by.binding("util")}catch($){}}(),jQ0=EQ0&&EQ0.isTypedArray;function Fz1($,Y){var q=-1,z=$==null?0:$.length,J=0,U=[];while(++q<z){var I=$[q];if(Y(I,q,$))U[J++]=I}return U}function Oz1($,Y){var q=-1,z=Y.length,J=$.length;while(++q<z)$[J+q]=Y[q];return $}function Mz1($,Y){var q=-1,z=$==null?0:$.length;while(++q<z)if(Y($[q],q,$))return!0;return!1}function Nz1($,Y){var q=-1,z=Array($);while(++q<$)z[q]=Y(q);return z}function Dz1($){return function(Y){return $(Y)}}function Pz1($,Y){return $.has(Y)}function Az1($,Y){return $==null?void 0:$[Y]}function Bz1($){var Y=-1,q=Array($.size);return $.forEach(function(z,J){q[++Y]=[J,z]}),q}function Tz1($,Y){return function(q){return $(Y(q))}}function Ez1($){var Y=-1,q=Array($.size);return $.forEach(function(z){q[++Y]=z}),q}var jz1=Array.prototype,_z1=Function.prototype,HO=Object.prototype,iy=i9["__core-js_shared__"],oQ0=_z1.toString,o5=HO.hasOwnProperty,_Q0=function(){var $=/[^.]+$/.exec(iy&&iy.keys&&iy.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),rQ0=HO.toString,Rz1=RegExp("^"+oQ0.call(o5).replace(Xz1,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),RQ0=lQ0?i9.Buffer:void 0,IO=i9.Symbol,CQ0=i9.Uint8Array,sQ0=HO.propertyIsEnumerable,Cz1=jz1.splice,KY=IO?IO.toStringTag:void 0,vQ0=Object.getOwnPropertySymbols,vz1=RQ0?RQ0.isBuffer:void 0,hz1=Tz1(Object.keys,Object),dy=vJ(i9,"DataView"),vG=vJ(i9,"Map"),my=vJ(i9,"Promise"),ly=vJ(i9,"Set"),oy=vJ(i9,"WeakMap"),hG=vJ(Object,"create"),gz1=ZY(dy),Sz1=ZY(vG),yz1=ZY(my),xz1=ZY(ly),kz1=ZY(oy),hQ0=IO?IO.prototype:void 0,ny=hQ0?hQ0.valueOf:void 0;function GY($){var Y=-1,q=$==null?0:$.length;this.clear();while(++Y<q){var z=$[Y];this.set(z[0],z[1])}}function uz1(){this.__data__=hG?hG(null):{},this.size=0}function fz1($){var Y=this.has($)&&delete this.__data__[$];return this.size-=Y?1:0,Y}function bz1($){var Y=this.__data Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(Y)}set headers($){this._headers=$}shouldQuote($,Y){let q=Y?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(mJ1.default(q))return q;if(Array.isArray(q))return q[$];if(this._headers!==null)return q[this._headers[$]];return!1}format($,Y,q){let z=`${lJ1.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:J}=this;if(J.quote!==""){if(z.indexOf(J.quote)!==-1)return this.quoteField(z.replace(this.REPLACE_REGEXP,J.escapedQuote))}if(z.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(Y,q))return this.quoteField(z);return z}quoteField($){let{quote:Y}=this.formatterOptions;return`${Y}${$}${Y}`}}hJ.FieldFormatter=XK0});var Yx=M((VK0)=>{Object.defineProperty(VK0,"__esModule",{value:!0});VK0.isSyncTransform=void 0;VK0.isSyncTransform=($)=>$.length===1});var FK0=M((gJ)=>{var wK0=gJ&&gJ.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(gJ,"__esModule",{value:!0});gJ.RowFormatter=void 0;var rJ1=wK0($O()),sJ1=wK0(JK0()),tJ1=$x(),aJ1=Yx();class WY{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new tJ1.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(WY.isRowHashArray($))return $.map((Y)=>Y[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(aJ1.isSyncTransform($))return(Y,q)=>{let z=null;try{z=$(Y)}catch(J){return q(J)}return q(null,z)};return(Y,q)=>{$(Y,q)}}set rowTransform($){if(!rJ1.default($))throw TypeError("The transform should be a function");this._rowTransform=WY.createTransform($)}format($,Y){this.callTransformer($,(q,z)=>{if(q)return Y(q);if(!$)return Y(null);let J=[];if(z){let{shouldFormatColumns:U,headers:I}=this.checkHeaders(z);if(this.shouldWriteHeaders&&I&&!this.hasWrittenHeaders)J.push(this.formatColumns(I,!0)),this.hasWrittenHeaders=!0;if(U){let Q=this.gatherColumns(z);J.push(this.formatColumns(Q,!1))}}return Y(null,J)})}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=WY.gatherHeaders($);if(this.headers=Y,this.fieldFormatter.headers=Y,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!sJ1.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(WY.isRowHashArray($))return this.headers.map((Y,q)=>{let z=$[q];if(z)return z[1];return""});if(WY.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((Y,q)=>$[q])}callTransformer($,Y){if(!this._rowTransform)return Y(null,$);return this._rowTransform($,Y)}formatColumns($,Y){let q=$.map((J,U)=>this.fieldFormatter.format(J,U,Y)).join(this.formatterOptions.delimiter),{rowCount:z}=this;if(this.rowCount+=1,z)return[this.formatterOptions.rowDelimiter,q].join("");return q}}gJ.RowFormatter=WY});var OK0=M((XO)=>{Object.defineProperty(XO,"__esModule",{value:!0});XO.FieldFormatter=XO.RowFormatter=void 0;var eJ1=FK0();Object.defineProperty(XO,"RowFormatter",{enumerable:!0,get:function(){return eJ1.RowFormatter}});var $U1=$x();Object.defineProperty(XO,"FieldFormatter",{enumerable:!0,get:function(){return $U1.FieldFormatter}})});var qx=M((NK0)=>{Object.defineProperty(NK0,"__esModule",{value:!0});NK0.CsvFormatterStream=void 0;var qU1=m("stream"),zU1=OK0();class MK0 extends qU1.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new zU1.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,Y,q){let z=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(J,U)=>{if(J)return z=!0,q(J);if(U)U.forEach((I)=>{this.push(Buffer.from(I,"utf8"))});return z=!0,q()})}catch(J){if(z)throw J;q(J)}}_flush($){this.rowFormatter.finish((Y,q)=>{if(Y)return $(Y);if(q)q.forEach((z)=>{this.push(Buffer.from(z,"utf8"))});return $()})}}NK0.CsvFormatterStream=MK0});var AK0=M((u1)=>{var PK0=u1&&u1.__createBinding||(Object.create?function($,Y,q,z){if(z===void 0)z=q;Object.defineProperty($,z,{enumerable:!0,get:function(){return Y[q]}})}:function($,Y,q,z){if(z===void 0)z=q;$[z]=Y[q]}),JU1=u1&&u1.__setModuleDefault||(Object.create?function($,Y){Ob 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}}BG0.Token=AG0});var Ex=M((_G0)=>{Object.defineProperty(_G0,"__esModule",{value:!0});_G0.Scanner=void 0;var EG0=P7(),WK1=/((?:\r\n)|\n|\r)/;class jG0{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 q=Y.exec($);if(q==null)return null;let z=q[1],J=this.cursor+(q.index||0);return new EG0.Token({token:z,startCursor:J,endCursor:J+z.length-1})}get nextCharacterToken(){let{cursor:$,lineLength:Y}=this;if(Y<=$)return null;return new EG0.Token({token:this.line[$],startCursor:$,endCursor:$})}get lineFromCursor(){return this.line.substr(this.cursor)}advancePastLine(){let $=WK1.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}}_G0.Scanner=jG0});var xO=M((vG0)=>{Object.defineProperty(vG0,"__esModule",{value:!0});vG0.ColumnFormatter=void 0;class CG0{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}}vG0.ColumnFormatter=CG0});var jx=M((yG0)=>{Object.defineProperty(yG0,"__esModule",{value:!0});yG0.NonQuotedColumnParser=void 0;var XK1=xO(),gG0=P7();class SG0{constructor($){this.parserOptions=$,this.columnFormatter=new XK1.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let{parserOptions:Y}=this,q=[],z=$.nextCharacterToken;for(;z;z=$.nextCharacterToken){if(gG0.Token.isTokenDelimiter(z,Y)||gG0.Token.isTokenRowDelimiter(z))break;q.push(z.token),$.advancePastToken(z)}return this.columnFormatter.format(q.join(""))}}yG0.NonQuotedColumnParser=SG0});var _x=M((uG0)=>{Object.defineProperty(uG0,"__esModule",{value:!0});uG0.QuotedColumnParser=void 0;var VK1=xO(),pJ=P7();class kG0{constructor($){this.parserOptions=$,this.columnFormatter=new VK1.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let Y=$.cursor,{foundClosingQuote:q,col:z}=this.gatherDataBetweenQuotes($);if(!q){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($),z}gatherDataBetweenQuotes($){let{parserOptions:Y}=this,q=!1,z=!1,J=[],U=$.nextCharacterToken;for(;!z&&U!==null;U=$.nextCharacterToken){let I=pJ.Token.isTokenQuote(U,Y);if(!q&&I)q=!0;else if(q)if(pJ.Token.isTokenEscapeCharacter(U,Y)){$.advancePastToken(U);let Q=$.nextCharacterToken;if(Q!==null&&(pJ.Token.isTokenQuote(Q,Y)||pJ.Token.isTokenEscapeCharacter(Q,Y)))J.push(Q.token),U=Q;else if(I)z=!0;else J.push(U.token)}else if(I)z=!0;else J.push(U.token);$.advancePastToken(U)}return{col:this.columnFormatter.format(J.join("")),foundClosingQuote:z}}checkForMalformedColumn($){let{parserOptions:Y}=this,{nextNonSpaceToken:q}=$;if(q){let z=pJ.Token.isTokenDelimiter(q,Y),J=pJ.Token.isTokenRowDelimiter(q);if(!(z||J)){let U=$.lineFromCursor.substr(0,10).replace(/[\r\n]/g,"\\n'");throw Error(`Parse Error: expected: '${Y.escapedDelimiter}' OR new line got: '${q.token}'. at '${U}`)}$.advanceToToken(q)}else if(!$.hasMoreData)$.advancePastLine()}}uG0.QuotedColumnParser=kG0});var cG0=M((iG0)=>{Object.defineProperty(iG0,"__esModule",{value:!0});iG0.ColumnParser=void 0;var LK1=jx(),wK1=_x(),FK1=P7();class bG0{constructor($){this.parserOptions=$,this.quotedColumnParser=new wK1.QuotedColumnParser($),this.nonQuotedColumnParser=new LK1.NonQuotedColumnParser($)}parse($){let{nextNonSpaceToken:Y}=$;if(Y!==null&&FK1.Token.isTokenQuote(Y,this.parserOptions))return $.advanceToToken(Y),this.quotedColumnParser.parse($);return this.nonQuotedColumnParser.parse($)}}iG0.ColumnParser=bG0});var Rx=M((dJ)=>{Object.defineProperty(dJ,"__esModule",{value:!0});dJ.ColumnFormatter=dJ.QuotedColumnParser=dJ.NonQuotedColumnParser=dJ.ColumnParser=void 0;var OK1=cG0();Object.defineProperty(dJ,"ColumnParser",{enumerable:!0,get:function(){return OK1.ColumnParser}});var MK1=jx();Object.defineProperty(dJ,"NonQuotedColumnParser",{enumerable:!0,get:function(){return MK1.NonQuotedColumnParser}});var NK1=_x();Object.defineProperty(dJ,"QuotedColumnParser",{enumerable:!0,get:function(){re Line truncated
%s`,y,y,X,z);let v=X.type==="*"?px:X.type==="?"?lx:"\\"+X.type;J=!0,z=z.slice(0,X.reStart)+v+"\\("+y}if(B(),U)z+="\\\\";let A=ZG1[z.charAt(0)];for(let y=Q.length-1;y>-1;y--){let v=Q[y],k=z.slice(0,v.reStart),C=z.slice(v.reStart,v.reEnd-8),c=z.slice(v.reEnd),n=z.slice(v.reEnd-8,v.reEnd)+c,g=k.split(")").length,b=k.split("(").length-g,i=c;for(let j=0;j<b;j++)i=i.replace(/\)[+*?]?/,"");c=i;let $0=c===""&&Y!==dx?"(?:$|\\/)":"";z=k+C+c+$0+n}if(z!==""&&J)z="(?=.)"+z;if(A)z=O()+z;if(Y===dx)return[z,J];if(q.nocase&&!J)J=$.toUpperCase()!==$.toLowerCase();if(!J)return XG1($);let E=q.nocase?"i":"";try{return Object.assign(new RegExp("^"+z+"$",E),{_glob:$,_src:z})}catch(y){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,q=Y.noglobstar?px:Y.dot?GG1:HG1,z=Y.nocase?"i":"",J=$.map((U)=>{return U=U.map((I)=>typeof I==="string"?LG1(I):I===B8?B8:I._src).reduce((I,Q)=>{if(!(I[I.length-1]===B8&&Q===B8))I.push(Q);return I},[]),U.forEach((I,Q)=>{if(I!==B8||U[Q-1]===B8)return;if(Q===0)if(U.length>1)U[Q+1]="(?:\\/|"+q+"\\/)?"+U[Q+1];else U[Q]=q;else if(Q===U.length-1)U[Q-1]+="(?:\\/|"+q+")?";else U[Q-1]+="(?:\\/|\\/"+q+"\\/)"+U[Q+1],U[Q+1]=B8}),U.filter((I)=>I!==B8).join("/")}).join("|");if(J="^(?:"+J+")$",this.negate)J="^(?!"+J+").*$";try{this.regexp=new RegExp(J,z)}catch(U){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 q=this.options;if(mx.sep!=="/")$=$.split(mx.sep).join("/");$=$.split(xH0),this.debug(this.pattern,"split",$);let z=this.set;this.debug(this.pattern,"set",z);let J;for(let U=$.length-1;U>=0;U--)if(J=$[U],J)break;for(let U=0;U<z.length;U++){let I=z[U],Q=$;if(q.matchBase&&I.length===1)Q=[J];if(this.matchOne(Q,I,Y)){if(q.flipNegate)return!0;return!this.negate}}if(q.flipNegate)return!1;return this.negate}static defaults($){return K$.defaults($).Minimatch}}K$.Minimatch=bG});var pH0=M((q$4,cH0)=>{cH0.exports=nH0;var sx=m("fs"),{EventEmitter:FG1}=m("events"),{Minimatch:rx}=fH0(),{resolve:OG1}=m("path");function MG1($,Y){return new Promise((q,z)=>{sx.readdir($,{withFileTypes:!0},(J,U)=>{if(J)switch(J.code){case"ENOTDIR":if(Y)z(J);else q([]);break;case"ENOTSUP":case"ENOENT":case"ENAMETOOLONG":case"UNKNOWN":q([]);break;case"ELOOP":default:z(J);break}else q(U)})})}function bH0($,Y){return new Promise((q,z)=>{(Y?sx.stat:sx.lstat)($,(U,I)=>{if(U)switch(U.code){case"ENOENT":if(Y)q(bH0($,!1));else q(null);break;default:q(null);break}else q(I)})})}async function*iH0($,Y,q,z,J,U){let I=await MG1(Y+$,U);for(let Q of I){let K=Q.name;if(K===void 0)K=Q,z=!0;let G=$+"/"+K,H=G.slice(1),Z=Y+"/"+H,V=null;if(z||q)V=await bH0(Z,q);if(!V&&Q.name!==void 0)V=Q;if(V===null)V={isDirectory:()=>!1};if(V.isDirectory()){if(!J(H))yield{relative:H,absolute:Z,stats:V},yield*iH0(G,Y,q,z,J,!1)}else yield{relative:H,absolute:Z,stats:V}}}async function*NG1($,Y,q,z){yield*iH0("",$,Y,q,z,!0)}function DG1($){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 tx extends FG1{constructor($,Y,q){super();if(typeof Y==="function")q=Y,Y=null;if(this.options=DG1(Y||{}),this.matchers=[],this.options.pattern){let z=Array.isArray(this.options.pattern)?this.options.pattern:[this.options.pattern];this.matchers=z.map((J)=>new rx(J,{dot:this.options.dot,noglobstar:this.options.noglobstar,matchBase:this.options.matchBase,nocase:this.options.nocase}))}if(this.ignoreMatchers=[],this.options.ignore){let z=Array.isArray(this.options.ignore)?this.options.ignore:[this.options.ignore];this.ignoreMatchers=z.map((J)=>new rx(J,{dot:!0}))}if(this.skipMatchers=[],this.options.skip){let z=Array.isArray(this.options.skip)?this.options.skip:[this.options.skip];this.skipMatchers=z.map((J)=>new rx(J,{dot:!0}))}if(this.iterator=NG1(OG1($||"."),this.options.follow,this.options.stat,this._shouldSkipDirectory.bind(this)),this.paused=!1,this.inactive=!1,this.aborted=!1,q)this._matches=[],this.on("match",(z)=>this._matches.push(this.options.absolute?z.absolute:z.relative)),this.on("error",(z)=>q(z)),this.on("end",()=>q(null,this._matches));setTimeout(()=>this._next(),0)}_shouldSkipDirectory($){return this.skipMatchers.some((Y)=>Y.match($))}_fileMatches($,Y){let q=$+(Y?"/":"");return(this.matchers.length===0||this.matchers.some((z)=>z.match(q)))&&!this.ignoreMatchers.some((z)=>z.match(q))&&(!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 q=$.value.relative,z=$.value.absolute;if(this.options.mark&&Y)q+="/",z+="/";if(this.options.stat)this.emit("match",{relative:q,absolute:z,stat:$.value.stats});else this.emit("match",{relative:q,ab Line truncated
`,f);f=U0===-1?R.length:U0}else if(s!==-1&&R[f]==="/"&&R[f+1]==="*"){let U0=R.indexOf("*/",f);if(U0!==-1)f=U0+2,s=R.indexOf("*/",f);else S+=R[f],f++}else S+=R[f],f++;return S}function $1(R){let S=b1(R.toString()),f=S.match(C1);if(!f)f=S.match(a0);if(!f)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
`+S);let[,s]=f;return s.replace(/\s/g,"").split(r1).map((U0)=>U0.replace(F1,"").trim())}function J6(R,S){var f={};return Object.keys(R).forEach((s)=>{var U0=R[s],Q0,W0=X(U0),X0=!W0&&U0.length===1||W0&&U0.length===0;if(Array.isArray(U0))Q0=[...U0],U0=Q0.pop(),f[s]=Q0.concat(Q0.length>0?M0:U0);else if(X0)f[s]=U0;else{if(Q0=$1(U0),U0.length===0&&!W0&&Q0.length===0)throw Error("autoInject task functions require explicit parameters.");if(!W0)Q0.pop();f[s]=Q0.concat(M0)}function M0(k0,P1){var S1=Q0.map((T1)=>k0[T1]);S1.push(P1),F(U0)(...S1)}}),c0(f,S)}class a8{constructor(){this.head=this.tail=null,this.length=0}removeLink(R){if(R.prev)R.prev.next=R.next;else this.head=R.next;if(R.next)R.next.prev=R.prev;else this.tail=R.prev;return R.prev=R.next=null,this.length-=1,R}empty(){while(this.head)this.shift();return this}insertAfter(R,S){if(S.prev=R,S.next=R.next,R.next)R.next.prev=S;else this.tail=S;R.next=S,this.length+=1}insertBefore(R,S){if(S.prev=R.prev,S.next=R,R.prev)R.prev.next=S;else this.head=S;R.prev=S,this.length+=1}unshift(R){if(this.head)this.insertBefore(this.head,R);else U6(this,R)}push(R){if(this.tail)this.insertAfter(this.tail,R);else U6(this,R)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){var R=this.head;while(R)yield R.data,R=R.next}remove(R){var S=this.head;while(S){var{next:f}=S;if(R(S))this.removeLink(S);S=f}return this}}function U6(R,S){R.length=1,R.head=R.tail=S}function e8(R,S,f){if(S==null)S=1;else if(S===0)throw RangeError("Concurrency must not be zero");var s=F(R),U0=0,Q0=[];let W0={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};function X0(p0,S0){W0[p0].push(S0)}function M0(p0,S0){let d0=(...E1)=>{k0(p0,d0),S0(...E1)};W0[p0].push(d0)}function k0(p0,S0){if(!p0)return Object.keys(W0).forEach((d0)=>W0[d0]=[]);if(!S0)return W0[p0]=[];W0[p0]=W0[p0].filter((d0)=>d0!==S0)}function P1(p0,...S0){W0[p0].forEach((d0)=>d0(...S0))}var S1=!1;function T1(p0,S0,d0,E1){if(E1!=null&&typeof E1!=="function")throw Error("task callback must be a function");y1.started=!0;var C4,T6;function F$(V2,...xI){if(V2)return d0?T6(V2):C4();if(xI.length<=1)return C4(xI[0]);C4(xI)}var Rq=y1._createTaskItem(p0,d0?F$:E1||F$);if(S0)y1._tasks.unshift(Rq);else y1._tasks.push(Rq);if(!S1)S1=!0,G(()=>{S1=!1,y1.process()});if(d0||!E1)return new Promise((V2,xI)=>{C4=V2,T6=xI})}function w$(p0){return function(S0,...d0){U0-=1;for(var E1=0,C4=p0.length;E1<C4;E1++){var T6=p0[E1],F$=Q0.indexOf(T6);if(F$===0)Q0.shift();else if(F$>0)Q0.splice(F$,1);if(T6.callback(S0,...d0),S0!=null)P1("error",S0,T6.data)}if(U0<=y1.concurrency-y1.buffer)P1("unsaturated");if(y1.idle())P1("drain");y1.process()}}function _q(p0){if(p0.length===0&&y1.idle())return G(()=>P1("drain")),!0;return!1}let X2=(p0)=>(S0)=>{if(!S0)return new Promise((d0,E1)=>{M0(p0,(C4,T6)=>{if(C4)return E1(C4);d0(T6)})});k0(p0),X0(p0,S0)};var yI=!1,y1={_tasks:new a8,_createTaskItem(p0,S0){return{data:p0,callback:S0}},*[Symbol.iterator](){yield*y1._tasks[Symbol.iterator]()},concurrency:S,payload:f,buffer:S/4,started:!1,paused:!1,push(p0,S0){if(Array.isArray(p0)){if(_q(p0))return;return p0.map((d0)=>T1(d0,!1,!1,S0))}return T1(p0,!1,!1,S0)},pushAsync(p0,S0){if(Array.isArray(p0)){if(_q(p0))return;return p0.map((d0)=>T1(d0,!1,!0,S0))}return T1(p0,!1,!0,S0)},kill(){k0(),y1._tasks.empty()},unshift(p0,S0){if(Array.isArray(p0)){if(_q(p0))return;return p0.map((d0)=>T1(d0,!0,!1,S0))}return T1(p0,!0,!1,S0)},unshiftAsync(p0,S0){if(Array.isArray(p0)){if(_q(p0))return;return p0.map((d0)=>T1(d0,!0,!0,S0))}return T1(p0,!0,!0,S0)},remove(p0){y1._tasks.remove(p0)},process(){if(yI)return;yI=!0;while(!y1.paused&&U0<y1.concurrency&&y1._tasks.length){var p0=[],S0=[],d0=y1._tasks.length;if(y1.payload)d0=Math.min(d0,y1.payload);for(var E1=0;E1<d0;E1++){var C4=y1._tasks.shift();p0.push(C4),Q0.push(C4),S0.push(C4.data)}if(U0+=1,y1._tasks.length===0)P1("empty");if(U0===y1.concurrency)P1("saturated");var T6=g(w$(p0));s(S0,T6)}yI=!1},length(){return y1._tasks.length},running(){return U0},workersList(){return Q0},idle(){return y1._tasks.length+U0===0},pause(){y1.paused=!0},resume(){if(y1.paused===!1)return;y1.paused=!1,G(y1.process)}};return Object.defineProperties(y1,{saturated:{writable:!1,value:X2("saturated")},unsaturated:{writable:!1,value:X2("unsaturated")},empty:{writable:!1,value:X2("empty")},drain:{writable:!1,value:X2("drain")},error:{writable:!1,value:X2("error")}}),y1}function w0(R,S){return e8(R,1,S)}function o(R,S,f){return e8(R,S,f)}function N(R,S,f,s){s=y(s);var U0=F(f);return C0(R,(Q0,W0,X0)=>{U0(S,Q0,(M0,k0)=>{S=k0,X0(M0)})},(Q0)=>s(Q0,S))}var D=O(N,4);function h(...R){var S=R.map(F);return function(...f){var s=this,U0=f[f.length-1];if(typeof U0=="function")f.pop();else U0=f0();return D(S,f,(Q0,W0,X0)=>{W0.apply(s,Q0.concat((M0,...k0)=>{X0(M0,k0)}))},(Q0,W0)=>U0(Q0,...W0)),U0[v0]}}function x(...R){return h(...R.reverse())}function Y0(R,S,f,s){return B(i(S),R,f,s)}var r=O(Y0,4);function Line truncated
GFS4: `),console.error($)};if(!b4[m6]){if(ex=global[m6]||[],$Z0(b4,ex),b4.close=function($){function Y(q,z){return $.call(b4,q,function(J){if(!J)eH0();if(typeof z==="function")z.apply(this,arguments)})}return Object.defineProperty(Y,mO,{value:$}),Y}(b4.close),b4.closeSync=function($){function Y(q){$.apply(b4,arguments),eH0()}return Object.defineProperty(Y,mO,{value:$}),Y}(b4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){wY(b4[m6]),m("assert").equal(b4[m6].length,0)})}var ex;if(!global[m6])$Z0(global,b4[m6]);qk.exports=$k(CG1(b4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!b4.__patched)qk.exports=$k(b4),b4.__patched=!0;function $k($){_G1($),$.gracefulify=$k,$.createReadStream=E,$.createWriteStream=y;var Y=$.readFile;$.readFile=q;function q(C,c,n){if(typeof c==="function")n=c,c=null;return g(C,c,n);function g(b,i,$0,j){return Y(b,i,function(u){if(u&&(u.code==="EMFILE"||u.code==="ENFILE"))oJ([g,[b,i,$0],u,j||Date.now(),Date.now()]);else if(typeof $0==="function")$0.apply(this,arguments)})}}var z=$.writeFile;$.writeFile=J;function J(C,c,n,g){if(typeof n==="function")g=n,n=null;return b(C,c,n,g);function b(i,$0,j,u,p){return z(i,$0,j,function(d){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))oJ([b,[i,$0,j,u],d,p||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var U=$.appendFile;if(U)$.appendFile=I;function I(C,c,n,g){if(typeof n==="function")g=n,n=null;return b(C,c,n,g);function b(i,$0,j,u,p){return U(i,$0,j,function(d){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))oJ([b,[i,$0,j,u],d,p||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var Q=$.copyFile;if(Q)$.copyFile=K;function K(C,c,n,g){if(typeof n==="function")g=n,n=0;return b(C,c,n,g);function b(i,$0,j,u,p){return Q(i,$0,j,function(d){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))oJ([b,[i,$0,j,u],d,p||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}var G=$.readdir;$.readdir=Z;var H=/^v[0-5]\./;function Z(C,c,n){if(typeof c==="function")n=c,c=null;var g=H.test(process.version)?function($0,j,u,p){return G($0,b($0,j,u,p))}:function($0,j,u,p){return G($0,j,b($0,j,u,p))};return g(C,c,n);function b(i,$0,j,u){return function(p,d){if(p&&(p.code==="EMFILE"||p.code==="ENFILE"))oJ([g,[i,$0,j],p,u||Date.now(),Date.now()]);else{if(d&&d.sort)d.sort();if(typeof j==="function")j.call(this,p,d)}}}}if(process.version.substr(0,4)==="v0.8"){var V=RG1($);O=V.ReadStream,B=V.WriteStream}var X=$.ReadStream;if(X)O.prototype=Object.create(X.prototype),O.prototype.open=P;var L=$.WriteStream;if(L)B.prototype=Object.create(L.prototype),B.prototype.open=A;Object.defineProperty($,"ReadStream",{get:function(){return O},set:function(C){O=C},enumerable:!0,configurable:!0}),Object.defineProperty($,"WriteStream",{get:function(){return B},set:function(C){B=C},enumerable:!0,configurable:!0});var w=O;Object.defineProperty($,"FileReadStream",{get:function(){return w},set:function(C){w=C},enumerable:!0,configurable:!0});var F=B;Object.defineProperty($,"FileWriteStream",{get:function(){return F},set:function(C){F=C},enumerable:!0,configurable:!0});function O(C,c){if(this instanceof O)return X.apply(this,arguments),this;else return O.apply(Object.create(O.prototype),arguments)}function P(){var C=this;k(C.path,C.flags,C.mode,function(c,n){if(c){if(C.autoClose)C.destroy();C.emit("error",c)}else C.fd=n,C.emit("open",n),C.read()})}function B(C,c){if(this instanceof B)return L.apply(this,arguments),this;else return B.apply(Object.create(B.prototype),arguments)}function A(){var C=this;k(C.path,C.flags,C.mode,function(c,n){if(c)C.destroy(),C.emit("error",c);else C.fd=n,C.emit("open",n)})}function E(C,c){return new $.ReadStream(C,c)}function y(C,c){return new $.WriteStream(C,c)}var v=$.open;$.open=k;function k(C,c,n,g){if(typeof n==="function")g=n,n=null;return b(C,c,n,g);function b(i,$0,j,u,p){return v(i,$0,j,function(d,q0){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))oJ([b,[i,$0,j,u],d,p||Date.now(),Date.now()]);else if(typeof u==="function")u.apply(this,arguments)})}}return $}function oJ($){wY("ENQUEUE",$[0].name,$[1]),b4[m6].push($),Yk()}var dO;function eH0(){var $=Date.now();for(var Y=0;Y<b4[m6].length;++Y)if(b4[m6][Y].length>2)b4[m6][Y][3]=$,b4[m6][Y][4]=$;Yk()}function Yk(){if(clearTimeout(dO),dO=void 0,b4[m6].length===0)return;var $=b4[m6].shift(),Y=$[0],q=$[1],z=$[2],J=$[3],U=$[4];if(J===void 0)wY("RETRY",Y.name,q),Y.apply(null,q);else if(Date.now()-J>=60000){wY("TIMEOUT",Y.name,q);var I=q.pop();if(typeof I==="function")I.call(null,z)}else{var Q=Date.now()-U,K=Math.max(U-J,1),G=Math.min(K*1.2,100);if(Q>=G)wY("RETRY",Y.name,q),Y.apply(null,q.concat([J]));else b4[m6].push($)}if(dO===void 0)dO=setTimeout(Yk,0)}});var qZ0=M((Q$4,zk)=>{function hG1($,Y){if(!($ instanceof Y))throw TypeError("Cannot call a class as a function")}var YZ0=$6().Buffer,iG=m("util");function gG1($,Y,q){$.copy(Y,q)}zk.exports=function(){function $(){hG1(this,$),this.head=null,this.tail=null,th Line truncated
* normalize-path <https://github.com/jonschlinkert/normalize-path>
*
* Copyright (c) 2014-2018, Jon Schlinkert.
* Released under the MIT License.
*/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
*/nZ0.exports=function($,Y){if(typeof $!=="string")throw TypeError("expected path to be a string");if($==="\\"||$==="/")return"/";var q=$.length;if(q<=1)return $;var z="";if(q>4&&$[3]==="\\"){var J=$[2];if((J==="?"||J===".")&&$.slice(0,2)==="\\\\")$=$.slice(2),z="//"}var U=$.split(/[/\\]+/);if(Y!==!1&&U[U.length-1]==="")U.pop();return z+U.join("/")}});var Pk=M((M$4,rZ0)=>{var pZ0=9007199254740991,fH1="[object Arguments]",bH1="[object Function]",iH1="[object GeneratorFunction]",nH1=/^(?:0|[1-9]\d*)$/;function dZ0($,Y,q){switch(q.length){case 0:return $.call(Y);case 1:return $.call(Y,q[0]);case 2:return $.call(Y,q[0],q[1]);case 3:return $.call(Y,q[0],q[1],q[2])}return $.apply(Y,q)}function cH1($,Y){var q=-1,z=Array($);while(++q<$)z[q]=Y(q);return z}var sG=Object.prototype,tG=sG.hasOwnProperty,mZ0=sG.toString,pH1=sG.propertyIsEnumerable,cZ0=Math.max;function dH1($,Y){var q=YZ1($)||$Z1($)?cH1($.length,String):[],z=q.length,J=!!z;for(var U in $)if((Y||tG.call($,U))&&!(J&&(U=="length"||oZ0(U,z))))q.push(U);return q}function mH1($,Y,q,z){if($===void 0||Mk($,sG[q])&&!tG.call(z,q))return Y;return $}function lH1($,Y,q){var z=$[Y];if(!(tG.call($,Y)&&Mk(z,q))||q===void 0&&!(Y in $))$[Y]=q}function oH1($){if(!Dk($))return eH1($);var Y=aH1($),q=[];for(var z in $)if(!(z=="constructor"&&(Y||!tG.call($,z))))q.push(z);return q}function lZ0($,Y){return Y=cZ0(Y===void 0?$.length-1:Y,0),function(){var q=arguments,z=-1,J=cZ0(q.length-Y,0),U=Array(J);while(++z<J)U[z]=q[Y+z];z=-1;var I=Array(Y+1);while(++z<Y)I[z]=q[z];return I[Y]=U,dZ0($,this,I)}}function rH1($,Y,q,z){q||(q={});var J=-1,U=Y.length;while(++J<U){var I=Y[J],Q=z?z(q[I],$[I],I,q,$):void 0;lH1(q,I,Q===void 0?$[I]:Q)}return q}function sH1($){return lZ0(function(Y,q){var z=-1,J=q.length,U=J>1?q[J-1]:void 0,I=J>2?q[2]:void 0;if(U=$.length>3&&typeof U=="function"?(J--,U):void 0,I&&tH1(q[0],q[1],I))U=J<3?void 0:U,J=1;Y=Object(Y);while(++z<J){var Q=q[z];if(Q)$(Y,Q,z,U)}return Y})}function oZ0($,Y){return Y=Y==null?pZ0:Y,!!Y&&(typeof $=="number"||nH1.test($))&&($>-1&&$%1==0&&$<Y)}function tH1($,Y,q){if(!Dk(q))return!1;var z=typeof Y;if(z=="number"?Nk(q)&&oZ0(Y,q.length):z=="string"&&(Y in q))return Mk(q[Y],$);return!1}function aH1($){var Y=$&&$.constructor,q=typeof Y=="function"&&Y.prototype||sG;return $===q}function eH1($){var Y=[];if($!=null)for(var q in Object($))Y.push(q);return Y}function Mk($,Y){return $===Y||$!==$&&Y!==Y}function $Z1($){return qZ1($)&&tG.call($,"callee")&&(!pH1.call($,"callee")||mZ0.call($)==fH1)}var YZ1=Array.isArray;function Nk($){return $!=null&&JZ1($.length)&&!zZ1($)}function qZ1($){return UZ1($)&&Nk($)}function zZ1($){var Y=Dk($)?mZ0.call($):"";return Y==bH1||Y==iH1}function JZ1($){return typeof $=="number"&&$>-1&&$%1==0&&$<=pZ0}function Dk($){var Y=typeof $;return!!$&&(Y=="object"||Y=="function")}function UZ1($){return!!$&&typeof $=="object"}var IZ1=sH1(function($,Y,q,z){rH1(Y,KZ1(Y),$,z)}),QZ1=lZ0(function($){return $.push(void 0,mH1),dZ0(IZ1,void 0,$)});function KZ1($){return Nk($)?dH1($,!0):oH1($)}rZ0.exports=QZ1});var tZ0=M((N$4,Ak)=>{function GZ1($,Y){if(!($ instanceof Y))throw TypeError("Cannot call a class as a function")}var sZ0=$6().Buffer,aG=m("util");function HZ1($,Y,q){$.copy(Y,q)}Ak.exports=function(){function $(){GZ1(this,$),this.head=null,this.tail=null,this.length=0}return $.prototype.push=function(q){var z={data:q,next:null};if(this.length>0)this.tail.next=z;else this.head=z;this.tail=z,++this.length},$.prototype.unshift=function(q){var z={data:q,next:this.head};if(this.length===0)this.tail=z;this.head=z,++this.length},$.prototype.shift=function(){if(this.length===0)return;var q=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,q},$.prototype.clear=function(){this.head=this.tail=null,this.length=0},$.prototype.join=function(q){if(this.length===0)return"";var z=this.head,J=""+z.data;while(z=z.next)J+=q+z.data;return J},$.prototype.concat=function(q){if(this.length===0)return sZ0.alloc(0);var z=sZ0.allocUnsafe(q>>>0),J=this.head,U=0;while(J)HZ1(J.data,z,U),U+=J.data.length,J=J.next;return z},$}();if(aG&&aG.inspect&&aG.inspect.custom)Ak.exports.prototype[aG.inspect.custom]=function(){var $=aG.inspect({length:this.length});return this.constructor.name+" "+$}});var Bk=M((D$4,aZ0)=>{var UM=e4();function ZZ1($,Y){var q=this,z=this._readableState&&this._readableState.destroyed,J=this._writableState&&this._writableState.destroyed;if(z||J){if(Y)Y($);else if($){if(!this._writableState)UM.nextTick(IM,this,$);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,UM.nextTick(IM,this,$)}return this}if(this._readableState)this._readableState.destroyed=!0;if(this._writableState)this._writableState.destroyed=!0;return this._destroy($||null,function(U){if(!Y&&U){if(!q._writableState)UM.nextTick(IM,q,U);else if(!q._writableState.errorEmitted)q._writableState.errorEmitted=!0,UM.nextTick(IM,q,U)}else if(Y)Y(U)}),this}function WZ1(){if(this._readableState)this._readable Line truncated
%s`,E,E,P,z);var y=P.type==="*"?Ku:P.type==="?"?Qu:"\\"+P.type;J=!0,z=z.slice(0,P.reStart)+y+"\\("+E}if(L(),U)z+="\\\\";var v=!1;switch(z.charAt(0)){case"[":case".":case"(":v=!0}for(var k=Q.length-1;k>-1;k--){var C=Q[k],c=z.slice(0,C.reStart),n=z.slice(C.reStart,C.reEnd-8),g=z.slice(C.reEnd-8,C.reEnd),b=z.slice(C.reEnd);g+=b;var i=c.split("(").length-1,$0=b;for(w=0;w<i;w++)$0=$0.replace(/\)[+*?]?/,"");b=$0;var j="";if(b===""&&Y!==PM)j="$";var u=c+n+b+j+g;z=u}if(z!==""&&J)z="(?=.)"+z;if(v)z=V+z;if(Y===PM)return[z,J];if(!J)return vL1($);var p=q.nocase?"i":"";try{var d=new RegExp("^"+z+"$",p)}catch(q0){return new RegExp("$.")}return d._glob=$,d._src=z,d}G$.makeRe=function($,Y){return new H6($,Y||{}).makeRe()};H6.prototype.makeRe=CL1;function CL1(){if(this.regexp||this.regexp===!1)return this.regexp;var $=this.set;if(!$.length)return this.regexp=!1,this.regexp;var Y=this.options,q=Y.noglobstar?Ku:Y.dot?PL1:AL1,z=Y.nocase?"i":"",J=$.map(function(U){return U.map(function(I){return I===TY?q:typeof I==="string"?hL1(I):I._src}).join("\\/")}).join("|");if(J="^(?:"+J+")$",this.negate)J="^(?!"+J+").*$";try{this.regexp=new RegExp(J,z)}catch(U){this.regexp=!1}return this.regexp}G$.match=function($,Y,q){q=q||{};var z=new H6(Y,q);if($=$.filter(function(J){return z.match(J)}),z.options.nonull&&!$.length)$.push(Y);return $};H6.prototype.match=function(Y,q){if(typeof q>"u")q=this.partial;if(this.debug("match",Y,this.pattern),this.comment)return!1;if(this.empty)return Y==="";if(Y==="/"&&q)return!0;var z=this.options;if(HH.sep!=="/")Y=Y.split(HH.sep).join("/");Y=Y.split(vX0),this.debug(this.pattern,"split",Y);var J=this.set;this.debug(this.pattern,"set",J);var U,I;for(I=Y.length-1;I>=0;I--)if(U=Y[I],U)break;for(I=0;I<J.length;I++){var Q=J[I],K=Y;if(z.matchBase&&Q.length===1)K=[U];var G=this.matchOne(K,Q,q);if(G){if(z.flipNegate)return!0;return!this.negate}}if(z.flipNegate)return!1;return this.negate};H6.prototype.matchOne=function($,Y,q){if(Y.indexOf(TY)!==-1)return this._matchGlobstar($,Y,q,0,0);return this._matchOne($,Y,q,0,0)};H6.prototype._matchGlobstar=function($,Y,q,z,J){var U,I=-1;for(U=J;U<Y.length;U++)if(Y[U]===TY){I=U;break}var Q=-1;for(U=Y.length-1;U>=0;U--)if(Y[U]===TY){Q=U;break}var K=Y.slice(J,I),G=q?Y.slice(I+1):Y.slice(I+1,Q),H=q?[]:Y.slice(Q+1);if(K.length){var Z=$.slice(z,z+K.length);if(!this._matchOne(Z,K,q,0,0))return!1;z+=K.length}var V=0;if(H.length){if(H.length+z>$.length)return!1;var X=$.length-H.length;if(this._matchOne($,H,q,X,0))V=H.length;else{if($[$.length-1]!==""||z+H.length===$.length)return!1;if(X--,!this._matchOne($,H,q,X,0))return!1;V=H.length+1}}if(!G.length){var L=!!V;for(U=z;U<$.length-V;U++){var w=String($[U]);if(L=!0,w==="."||w===".."||!this.options.dot&&w.charAt(0)===".")return!1}return q||L}var F=[[[],0]],O=F[0],P=0,B=[0];for(var A=0;A<G.length;A++){var E=G[A];if(E===TY)B.push(P),O=[[],0],F.push(O);else O[0].push(E),P++}var y=F.length-1,v=$.length-V;for(var k=0;k<F.length;k++)F[k][1]=v-(B[y--]+F[k][0].length);return!!this._matchGlobStarBodySections($,F,z,0,q,0,!!V)};H6.prototype._matchGlobStarBodySections=function($,Y,q,z,J,U,I){var Q=Y[z];if(!Q){for(var K=q;K<$.length;K++){I=!0;var G=$[K];if(G==="."||G===".."||!this.options.dot&&G.charAt(0)===".")return!1}return I}var H=Q[0],Z=Q[1];while(q<=Z){var V=this._matchOne($.slice(0,q+H.length),H,J,q,0);if(V&&U<this.maxGlobstarRecursion){var X=this._matchGlobStarBodySections($,Y,q+H.length,z+1,J,U+1,I);if(X!==!1)return X}var G=$[q];if(G==="."||G===".."||!this.options.dot&&G.charAt(0)===".")return!1;q++}return J||null};H6.prototype._matchOne=function($,Y,q,z,J){var U,I,Q,K;for(U=z,I=J,Q=$.length,K=Y.length;U<Q&&I<K;U++,I++){this.debug("matchOne loop");var G=Y[I],H=$[U];if(this.debug(Y,G,H),G===!1||G===TY)return!1;var Z;if(typeof G==="string")Z=H===G,this.debug("string match",G,H,Z);else Z=H.match(G),this.debug("pattern match",G,H,Z);if(!Z)return!1}if(U===Q&&I===K)return!0;else if(U===Q)return q;else if(I===K)return U===Q-1&&$[U]==="";throw Error("wtf?")};function vL1($){return $.replace(/\\(.)/g,"$1")}function hL1($){return $.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var EM=M((i$4,TM)=>{function SX0($){return $.charAt(0)==="/"}function yX0($){var Y=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,q=Y.exec($),z=q[1]||"",J=Boolean(z&&z.charAt(1)!==":");return Boolean(q[2]||J)}TM.exports=process.platform==="win32"?yX0:SX0;TM.exports.posix=SX0;TM.exports.win32=yX0});var Hu=M((nL1)=>{nL1.setopts=uL1;nL1.ownProp=xX0;nL1.makeAbs=ZH;nL1.finish=fL1;nL1.mark=bL1;nL1.isIgnored=uX0;nL1.childrenIgnored=iL1;function xX0($,Y){return Object.prototype.hasOwnProperty.call($,Y)}var gL1=m("fs"),QU=m("path"),SL1=BM(),kX0=EM(),Gu=SL1.Minimatch;function yL1($,Y){return $.localeCompare(Y,"en")}function xL1($,Y){if($.ignore=Y.ignore||[],!Array.isArray($.ignore))$.ignore=[$.ignore];if($.ignore.length)$.ignore=$.ignore.map(kL1)}function kL1($){var Y=null;if($.slice(-3)==="/**"){var q=$.replace(/(\/\*\*)+$/,"");Y=new Gu(q,{dot:!0})}return{matcher Line truncated
See: https://github.com/isaacs/node-glob/issues/167`);return new M6($,Y).found}function M6($,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 M6))return new M6($,Y);if(tL1(this,$,Y),this.noprocess)return this;var q=this.minimatch.set.length;this.matches=Array(q);for(var z=0;z<q;z++)this._process(this.minimatch.set[z],z,!1);this._finish()}M6.prototype._finish=function(){if(bX0.ok(this instanceof M6),this.realpath){var $=this;this.matches.forEach(function(Y,q){var z=$.matches[q]=Object.create(null);for(var J in Y)try{J=$._makeAbs(J);var U=sL1.realpathSync(J,$.realpathCache);z[U]=!0}catch(I){if(I.syscall==="stat")z[$._makeAbs(J)]=!0;else throw I}})}EY.finish(this)};M6.prototype._process=function($,Y,q){bX0.ok(this instanceof M6);var z=0;while(typeof $[z]==="string")z++;var J;switch(z){case $.length:this._processSimple($.join("/"),Y);return;case 0:J=null;break;default:J=$.slice(0,z).join("/");break}var U=$.slice(z),I;if(J===null)I=".";else if(jM(J)||jM($.map(function(G){return typeof G==="string"?G:"[*]"}).join("/"))){if(!J||!jM(J))J="/"+J;I=J}else I=J;var Q=this._makeAbs(I);if(aL1(this,I))return;var K=U[0]===fX0.GLOBSTAR;if(K)this._processGlobStar(J,I,Q,U,Y,q);else this._processReaddir(J,I,Q,U,Y,q)};M6.prototype._processReaddir=function($,Y,q,z,J,U){var I=this._readdir(q,U);if(!I)return;var Q=z[0],K=!!this.minimatch.negate,G=Q._glob,H=this.dot||G.charAt(0)===".",Z=[];for(var V=0;V<I.length;V++){var X=I[V];if(X.charAt(0)!=="."||H){var L;if(K&&!$)L=!X.match(Q);else L=X.match(Q);if(L)Z.push(X)}}var w=Z.length;if(w===0)return;if(z.length===1&&!this.mark&&!this.stat){if(!this.matches[J])this.matches[J]=Object.create(null);for(var V=0;V<w;V++){var X=Z[V];if($)if($.slice(-1)!=="/")X=$+"/"+X;else X=$+X;if(X.charAt(0)==="/"&&!this.nomount)X=Zu.join(this.root,X);this._emitMatch(J,X)}return}z.shift();for(var V=0;V<w;V++){var X=Z[V],F;if($)F=[$,X];else F=[X];this._process(F.concat(z),J,U)}};M6.prototype._emitMatch=function($,Y){if(eL1(this,Y))return;var q=this._makeAbs(Y);if(this.mark)Y=this._mark(Y);if(this.absolute)Y=q;if(this.matches[$][Y])return;if(this.nodir){var z=this.cache[q];if(z==="DIR"||Array.isArray(z))return}if(this.matches[$][Y]=!0,this.stat)this._stat(Y)};M6.prototype._readdirInGlobStar=function($){if(this.follow)return this._readdir($,!1);var Y,q,z;try{q=this.fs.lstatSync($)}catch(U){if(U.code==="ENOENT")return null}var J=q&&q.isSymbolicLink();if(this.symlinks[$]=J,!J&&q&&!q.isDirectory())this.cache[$]="FILE";else Y=this._readdir($,!1);return Y};M6.prototype._readdir=function($,Y){var q;if(Y&&!Wu(this.symlinks,$))return this._readdirInGlobStar($);if(Wu(this.cache,$)){var z=this.cache[$];if(!z||z==="FILE")return null;if(Array.isArray(z))return z}try{return this._readdirEntries($,this.fs.readdirSync($))}catch(J){return this._readdirError($,J),null}};M6.prototype._readdirEntries=function($,Y){if(!this.mark&&!this.stat)for(var q=0;q<Y.length;q++){var z=Y[q];if($==="/")z=$+z;else z=$+"/"+z;this.cache[z]=!0}return this.cache[$]=Y,Y};M6.prototype._readdirError=function($,Y){switch(Y.code){case"ENOTSUP":case"ENOTDIR":var q=this._makeAbs($);if(this.cache[q]="FILE",q===this.cwdAbs){var z=Error(Y.code+" invalid cwd "+this.cwd);throw z.path=this.cwd,z.code=Y.code,z}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}};M6.prototype._processGlobStar=function($,Y,q,z,J,U){var I=this._readdir(q,U);if(!I)return;var Q=z.slice(1),K=$?[$]:[],G=K.concat(Q);this._process(G,J,!1);var H=I.length,Z=this.symlinks[q];if(Z&&U)return;for(var V=0;V<H;V++){var X=I[V];if(X.charAt(0)==="."&&!this.dot)continue;var L=K.concat(I[V],Q);this._process(L,J,!0);var w=K.concat(I[V],z);this._process(w,J,!0)}};M6.prototype._processSimple=function($,Y){var q=this._stat($);if(!this.matches[Y])this.matches[Y]=Object.create(null);if(!q)return;if($&&jM($)&&!this.nomount){var z=/[\/\\]$/.test($);if($.charAt(0)==="/")$=Zu.join(this.root,$);else if($=Zu.resolve(this.root,$),z)$+="/"}if(process.platform==="win32")$=$.replace(/\\/g,"/");this._emitMatch(Y,$)};M6.prototype._stat=function($){var Y=this._makeAbs($),q=$.slice(-1)==="/";if($.length>this.maxLength)return!1;if(!this.stat&&Wu(this.cache,Y)){var I=this.cache[Y];if(Array.isArray(I))I="DIR";if(!q||I==="DIR")return I;if(q&&I==="FILE")return!1}var z,J=this.statCache[Y];if(!J){var U;try{U=this.fs.lstatSync(Y)}catch(Q){if(Q&&(Q.code==="ENOENT"||Q.code==="ENOTDIR"))return this.statCache[Y]=!1,!1}if(U&&U.isSymbolicLink())try{J=this.fs.statSync(Y)}catch(Q){J=U}else J=U}this.statCache[Y]=J;var I=!0;if(J)I=J.isDirectory()?"DIR":"FILE";if(this.cache[Y]=this.cache[Y]||I,q&&I==="FILE")return!1;return I};M6.prototype._mark=function($){return EY.mark(this,$)};M6.prototype._makeAbs=function($){return EY.makeAbs(this,$)}});var Xu=M((l$4,dX0)=>{dX0.exports=pX0;function pX0($,Y){if($&&Y)return pX0($)(Y);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(z){q[z]=$[z]}),q;f Line truncated
`);if($.linkname)Y+=Zf(" linkpath="+$.linkname+`
`);var q=$.pax;if(q)for(var z in q)Y+=Zf(" "+z+"="+q[z]+`
`);return Buffer.from(Y)};GM1.decodePax=function($){var Y={};while($.length){var q=0;while(q<$.length&&$[q]!==32)q++;var z=parseInt($.slice(0,q).toString(),10);if(!z)return Y;var J=$.slice(q+1,z-1).toString(),U=J.indexOf("=");if(U===-1)return Y;Y[J.slice(0,U)]=J.slice(U+1),$=$.slice(z)}return Y};GM1.encode=function($){var Y=aO1(512),q=$.name,z="";if($.typeflag===5&&q[q.length-1]!=="/")q+="/";if(Buffer.byteLength(q)!==q.length)return null;while(Buffer.byteLength(q)>100){var J=q.indexOf("/");if(J===-1)return null;z+=z?"/"+q.slice(0,J):q.slice(0,J),q=q.slice(J+1)}if(Buffer.byteLength(q)>100||Buffer.byteLength(z)>155)return null;if($.linkname&&Buffer.byteLength($.linkname)>100)return null;if(Y.write(q),Y.write(k7($.mode&JM1,6),100),Y.write(k7($.uid,6),108),Y.write(k7($.gid,6),116),Y.write(k7($.size,11),124),Y.write(k7($.mtime.getTime()/1000|0,11),136),Y[156]=Uw0+QM1($.type),$.linkname)Y.write($.linkname,157);if(Iw0.copy(Y,jH),YM1.copy(Y,Wf),$.uname)Y.write($.uname,265);if($.gname)Y.write($.gname,297);if(Y.write(k7($.devmajor||0,6),329),Y.write(k7($.devminor||0,6),337),z)Y.write(z,345);return Y.write(k7(Kw0(Y),6),148),Y};GM1.decode=function($,Y,q){var z=$[156]===0?0:$[156]-Uw0,J=wU($,0,100,Y),U=u7($,100,8),I=u7($,108,8),Q=u7($,116,8),K=u7($,124,12),G=u7($,136,12),H=IM1(z),Z=$[157]===0?null:wU($,157,100,Y),V=wU($,265,32),X=wU($,297,32),L=u7($,329,8),w=u7($,337,8),F=Kw0($);if(F===256)return null;if(F!==u7($,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(Iw0.compare($,jH,jH+6)===0){if($[345])J=wU($,345,155,Y)+"/"+J}else if(qM1.compare($,jH,jH+6)===0&&zM1.compare($,Wf,Wf+2)===0);else if(!q)throw Error("Invalid tar header: unknown format.");if(z===0&&J&&J[J.length-1]==="/")z=5;return{name:J,mode:U,uid:I,gid:Q,size:K,mtime:new Date(1000*G),type:H,linkname:Z,uname:V,gname:X,devmajor:L,devminor:w}}});var Lw0=M((i54,Vw0)=>{var Hw0=m("util"),LM1=Jw0(),_H=Xf(),Zw0=P8().Writable,Ww0=P8().PassThrough,Xw0=function(){},Gw0=function($){return $&=511,$&&512-$},wM1=function($,Y){var q=new lM($,Y);return q.end(),q},FM1=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,$},lM=function($,Y){this._parent=$,this.offset=Y,Ww0.call(this,{autoDestroy:!1})};Hw0.inherits(lM,Ww0);lM.prototype.destroy=function($){this._parent.destroy($)};var a9=function($){if(!(this instanceof a9))return new a9($);Zw0.call(this,$),$=$||{},this._offset=0,this._buffer=LM1(),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 Y=this,q=Y._buffer,z=function(){Y._continue()},J=function(V){if(Y._locked=!1,V)return Y.destroy(V);if(!Y._stream)z()},U=function(){Y._stream=null;var V=Gw0(Y._header.size);if(V)Y._parse(V,I);else Y._parse(512,Z);if(!Y._locked)z()},I=function(){Y._buffer.consume(Gw0(Y._header.size)),Y._parse(512,Z),z()},Q=function(){var V=Y._header.size;Y._paxGlobal=_H.decodePax(q.slice(0,V)),q.consume(V),U()},K=function(){var V=Y._header.size;if(Y._pax=_H.decodePax(q.slice(0,V)),Y._paxGlobal)Y._pax=Object.assign({},Y._paxGlobal,Y._pax);q.consume(V),U()},G=function(){var V=Y._header.size;this._gnuLongPath=_H.decodeLongPath(q.slice(0,V),$.filenameEncoding),q.consume(V),U()},H=function(){var V=Y._header.size;this._gnuLongLinkPath=_H.decodeLongPath(q.slice(0,V),$.filenameEncoding),q.consume(V),U()},Z=function(){var V=Y._offset,X;try{X=Y._header=_H.decode(q.slice(0,512),$.filenameEncoding,$.allowUnknownFormat)}catch(L){Y.emit("error",L)}if(q.consume(512),!X){Y._parse(512,Z),z();return}if(X.type==="gnu-long-path"){Y._parse(X.size,G),z();return}if(X.type==="gnu-long-link-path"){Y._parse(X.size,H),z();return}if(X.type==="pax-global-header"){Y._parse(X.size,Q),z();return}if(X.type==="pax-header"){Y._parse(X.size,K),z();return}if(Y._gnuLongPath)X.name=Y._gnuLongPath,Y._gnuLongPath=null;if(Y._gnuLongLinkPath)X.linkname=Y._gnuLongLinkPath,Y._gnuLongLinkPath=null;if(Y._pax)Y._header=X=FM1(X,Y._pax),Y._pax=null;if(Y._locked=!0,!X.size||X.type==="directory"){Y._parse(512,Z),Y.emit("entry",X,wM1(Y,V),J);return}Y._stream=new lM(Y,V),Y.emit("entry",X,Y._stream,J),Y._parse(X.size,U),z()};this._onheader=Z,this._parse(512,Z)};Hw0.inherits(a9,Zw0);a9.prototype.destroy=function($){if(this._destroyed)return;if(this._destroyed=!0,$)this.emit("error",$);if(this.emit("close"),this._stream)this._stream.emit("close")};a9.prototype._parse=function($,Y){if(this._destroyed)return;if(this._offset+=$,this._missing=$,Y===this._onheader)this._partial=!1;this._onparse=Y};a9.prototype._continue=function(){if(this._destroyed)return;var $=this._cb;if(this._cb=Xw0,this._overflow)this._write(this._overflow,void 0,$);else $()};a9.prototype._write=function($,Y,q){if(this._destroyed)return;var z=this._stream,J=this._buffer,U=this._missing;if($.length)this._partial=!0;if($.length<U){ 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="${xM1.xmlEncode($.Target)}" TargetMode="${$.TargetMode}"/>`);else this.stream.write(`<Relationship Id="${Y}" Type="${$.Type}" Target="${$.Target}"/>`);return Y}_writeClose(){this.stream.write("</Relationships>")}}iw0.exports=bw0});var lw0=M((t54,mw0)=>{var cw0=c6(),pw0=L7(),uM1=k4(),fM1=jy(),bM1=Ry();class dw0{constructor($,Y,q){this.id=q.id,this.count=0,this._worksheet=$,this._workbook=q.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:pw0.Comments,Target:`../comments${this.id}.xml`};this._sheetRelsWriter.addRelationship($);let Y={Type:pw0.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 q=new fM1,z=new cw0;q.render(z,$),this.commentsStream.write(z.xml);let J=new bM1,U=new cw0;J.render(U,$,Y),this.vmlStream.write(U.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=uM1.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()}}mw0.exports=dw0});var ew0=M((a54,aw0)=>{var iM1=l4(),nM1=L7(),wf=k4(),ow0=mv(),rw0=R9(),cM1=IS(),sw0=aL(),Ff=$w(),pM1=nw0(),dM1=lw0(),mM1=pv(),j6=new cM1,Of=W7(),lM1=Yy(),oM1=qy(),rM1=zy(),sM1=tS(),tM1=rS(),aM1=aS(),eM1=Jy(),$N1=Uy(),YN1=Iy(),qN1=Qy(),zN1=Ky(),JN1=Gy(),UN1=Vy(),IN1=Zy(),QN1=Hy(),_6={dataValidations:new lM1,sheetProperties:new oM1,sheetFormatProperties:new rM1,columns:new Of({tag:"cols",length:!1,childXform:new sM1}),row:new tM1,hyperlinks:new Of({tag:"hyperlinks",length:!1,childXform:new aM1}),sheetViews:new Of({tag:"sheetViews",length:!1,childXform:new eM1}),sheetProtection:new $N1,pageMargins:new YN1,pageSeteup:new qN1,autoFilter:new zN1,picture:new JN1,conditionalFormattings:new UN1,headerFooter:new IN1,rowBreaks:new QN1};class tw0{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 pM1($),this._sheetCommentsWriter=new dM1(this,this._sheetRelsWriter,$),this._dimensions=new rw0,this._rowZero=1,this.committed=!1,this.dataValidations=new mM1,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
`)},xf=kf.getNativePromise();if(kf.isNode&&typeof MutationObserver>"u")uf=global.setImmediate,ff=process.nextTick,uY=kf.isRecentNode?function($){uf.call(global,$)}:function($){ff.call(process,$)};else if(typeof xf==="function"&&typeof xf.resolve==="function")bf=xf.resolve(),uY=function($){bf.then($)};else if(typeof MutationObserver<"u"&&!(typeof window<"u"&&window.navigator&&(window.navigator.standalone||window.cordova)))uY=function(){var $=document.createElement("div"),Y={attributes:!0},q=!1,z=document.createElement("div"),J=new MutationObserver(function(){$.classList.toggle("foo"),q=!1});J.observe(z,Y);var U=function(){if(q)return;q=!0,z.classList.toggle("foo")};return function(Q){var K=new MutationObserver(function(){K.disconnect(),Q()});K.observe($,Y),U()}}();else if(typeof setImmediate<"u")uY=function($){setImmediate($)};else if(typeof setTimeout<"u")uY=function($){setTimeout($,0)};else uY=aN1;var uf,ff,bf;hF0.exports=uY});var yF0=M((H94,SF0)=>{function eN1($,Y,q,z,J){for(var U=0;U<J;++U)q[U+z]=$[U+Y],$[U+Y]=void 0}function i7($){this._capacity=$,this._length=0,this._front=0}i7.prototype._willBeOverCapacity=function($){return this._capacity<$};i7.prototype._pushOne=function($){var Y=this.length();this._checkCapacity(Y+1);var q=this._front+Y&this._capacity-1;this[q]=$,this._length=Y+1};i7.prototype.push=function($,Y,q){var z=this.length()+3;if(this._willBeOverCapacity(z)){this._pushOne($),this._pushOne(Y),this._pushOne(q);return}var J=this._front+z-3;this._checkCapacity(z);var U=this._capacity-1;this[J+0&U]=$,this[J+1&U]=Y,this[J+2&U]=q,this._length=z};i7.prototype.shift=function(){var $=this._front,Y=this[$];return this[$]=void 0,this._front=$+1&this._capacity-1,this._length--,Y};i7.prototype.length=function(){return this._length};i7.prototype._checkCapacity=function($){if(this._capacity<$)this._resizeTo(this._capacity<<1)};i7.prototype._resizeTo=function($){var Y=this._capacity;this._capacity=$;var q=this._front,z=this._length,J=q+z&Y-1;eN1(this,0,this,Y,J)};SF0.exports=i7});var nF0=M((Z94,nf)=>{var bF0;try{throw Error()}catch($){bF0=$}var $D1=gF0(),xF0=yF0(),iF0=H4();function R6(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new xF0(16),this._normalQueue=new xF0(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var $=this;this.drainQueues=function(){$._drainQueues()},this._schedule=$D1}R6.prototype.setScheduler=function($){var Y=this._schedule;return this._schedule=$,this._customScheduler=!0,Y};R6.prototype.hasCustomScheduler=function(){return this._customScheduler};R6.prototype.enableTrampoline=function(){this._trampolineEnabled=!0};R6.prototype.disableTrampolineIfNecessary=function(){if(iF0.hasDevTools)this._trampolineEnabled=!1};R6.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};R6.prototype.fatalError=function($,Y){if(Y)process.stderr.write("Fatal "+($ instanceof Error?$.stack:$)+`
`),process.exit(2);else this.throwLater($)};R6.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(q){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 kF0($,Y,q){this._lateQueue.push($,Y,q),this._queueTick()}function uF0($,Y,q){this._normalQueue.push($,Y,q),this._queueTick()}function fF0($){this._normalQueue._pushOne($),this._queueTick()}if(!iF0.hasDevTools)R6.prototype.invokeLater=kF0,R6.prototype.invoke=uF0,R6.prototype.settlePromises=fF0;else R6.prototype.invokeLater=function($,Y,q){if(this._trampolineEnabled)kF0.call(this,$,Y,q);else this._schedule(function(){setTimeout(function(){$.call(Y,q)},100)})},R6.prototype.invoke=function($,Y,q){if(this._trampolineEnabled)uF0.call(this,$,Y,q);else this._schedule(function(){$.call(Y,q)})},R6.prototype.settlePromises=function($){if(this._trampolineEnabled)fF0.call(this,$);else this._schedule(function(){$._settlePromises()})};R6.prototype._drainQueue=function($){while($.length()>0){var Y=$.shift();if(typeof Y!=="function"){Y._settlePromises();continue}var q=$.shift(),z=$.shift();Y.call(q,z)}};R6.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)};R6.prototype._queueTick=function(){if(!this._isTickUsed)this._isTickUsed=!0,this._schedule(this.drainQueues)};R6.prototype._reset=function(){this._isTickUsed=!1};nf.exports=R6;nf.exports.firstLineError=bF0});var $3=M((W94,dF0)=>{var df=kY(),YD1=df.freeze,cF0=H4(),pF0=cF0.inherits,DU=cF0.notEnumerableProp;function PU($,Y){function q(z){if(!(this instanceof q))return new q(z);if(DU(this,"message",typeof z==="string"?z:Y),DU(this,"name",$),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else Error.call(this)}return pF0(q,Error),q}var cf,pf,qD1=PU("Warning","warning"),zD1=PU("CancellationError","cancellation error"),JD1=PU("TimeoutError","timeout error"),SH=PU("AggregateError","aggregate error");try{cf=TypeError,pf=RangeError}catch($){cf=PU("TypeError","type error"),pf=PU("RangeError","range error")}var qN="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" ");for(fY=0;fY<qN.length;++fY)if(typeof Array.prototype[qN[fY]]==="function")SH.prototype[qN[fY]]=Array.prototype[qN[fY]];var fY;df.defineProperty(SH.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0});SH.prototype.isOperational=!0;var zN=0;SH.prototype.toString=function(){var $=Array(zN*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
`;zN++,$=Array(zN*4+1).join(" ");for(var q=0;q<this.length;++q){var z=this[q]===this?"[Circular AggregateError]":this[q]+"",J=z.split(`
`);for(var U=0;U<J.length;++U)J[U]=$+J[U];z=J.join(`
`),Y+=z+`
`}return zN--,Y};function gH($){if(!(this instanceof gH))return new gH($);if(DU(this,"name","OperationalError"),DU(this,"message",$),this.cause=$,this.isOperational=!0,$ instanceof Error)DU(this,"message",$.message),DU(this,"stack",$.stack);else if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}pF0(gH,Error);var bY=Error.__BluebirdErrorTypes__;if(!bY)bY=YD1({CancellationError:zD1,TimeoutError:JD1,OperationalError:gH,RejectionError:gH,AggregateError:SH}),df.defineProperty(Error,"__BluebirdErrorTypes__",{value:bY,writable:!1,enumerable:!1,configurable:!1});dF0.exports={Error,TypeError:cf,RangeError:pf,CancellationError:bY.CancellationError,OperationalError:bY.OperationalError,TimeoutError:bY.TimeoutError,AggregateError:bY.AggregateError,Warning:qD1}});var lF0=M((X94,mF0)=>{mF0.exports=function($,Y){var q=H4(),z=q.errorObj,J=q.isObject;function U(Z,V){if(J(Z)){if(Z instanceof $)return Z;var X=Q(Z);if(X===z){if(V)V._pushContext();var L=$.reject(X.e);if(V)V._popContext();return L}else if(typeof X==="function"){if(G(Z)){var L=new $(Y);return Z._then(L._fulfill,L._reject,void 0,L,null),L}return H(Z,X,V)}}return Z}function I(Z){return Z.then}function Q(Z){try{return I(Z)}catch(V){return z.e=V,z}}var K={}.hasOwnProperty;function G(Z){try{return K.call(Z,"_promise0")}catch(V){return!1}}function H(Z,V,X){var L=new $(Y),w=L;if(X)X._pushContext();if(L._captureStackTrace(),X)X._popContext();var F=!0,O=q.tryCatch(V).call(Z,P,B);if(F=!1,L&&O===z)L._rejectCallback(O.e,!0,!0),L=null;function P(A){if(!L)return;L._resolveCallback(A),L=null}function B(A){if(!L)return;L._rejectCallback(A,F,!0),L=null}return w}return U}});var rF0=M((V94,oF0)=>{oF0.exports=function($,Y,q,z,J){var U=H4(),I=U.isArray;function Q(G){switch(G){case-2:return[];case-3:return{}}}function K(G){var H=this._promise=new $(Y);if(G instanceof $)H._propagateFrom(G,3);H._setOnCancel(this),this._values=G,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return U.inherits(K,J),K.prototype.length=function(){return this._length},K.prototype.promise=function(){return this._promise},K.prototype._init=function G(H,Z){var V=q(this._values,this._promise);if(V instanceof $){V=V._target();var X=V._bitField;if(this._values=V,(X&50397184)===0)return this._promise._setAsyncGuaranteed(),V._then(G,this._reject,void 0,this,Z);else if((X&33554432)!==0)V=V._value();else if((X&16777216)!==0)return this._reject(V._reason());else return this._cancel()}if(V=U.asArray(V),V===null){var L=z("expecting an array or an iterable object but got "+U.classString(V)).reason();this._promise._rejectCallback(L,!1);return}if(V.length===0){if(Z===-5)this._resolveEmptyArray();else this._resolve(Q(Z));return}this._iterate(V)},K.prototype._iterate=function(G){var H=this.getActualLength(G.length);this._length=H,this._values=this.shouldCopyValues()?Array(H):this._values;var Z=this._promise,V=!1,X=null;for(var L=0;L<H;++L){var w=q(G[L],Z);if(w instanceof $)w=w._target(),X=w._bitField;else X=null;if(V){if(X!==null)w.suppressUnhandledRejections()}else if(X!==null)if((X&50397184)===0)w._proxy(this,L),this._values[L]=w;else if((X&33554432)!==0)V=this._promiseFulfilled(w._value(),L);else if((X&16777216)!==0)V=this._promiseRejected(w._reason(),L);else V=this._promiseCancelled(L);else V=this._promiseFulfilled(w,L)}if(!V)Z._setAsyncGuaranteed()},K.prototype._isResolved=function(){return this._values===null},K.prototype._resolve=function(G){this._values=null,this._promise._fulfill(G)},K.prototype._cancel=function(){if(this._isResolved()||!this._promise._isCancellable())return;this._values=null,this._promise._cancel()},K.prototype._reject=function(G){this._values=null,this._promise._rejectCallback(G,!1)},K.prototype._promiseFulfilled=function(G,H){this._values[H]=G;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(G){return this._totalResolved++,this._reject(G),!0},K.prototype._resultCancelled=function(){if(this._isResolved())return;var G=this._values;if(this._cancel(),G instanceof $)G.cancel();else for(var H=0;H<G.length;++H)if(G[H]instanceof $)G[H].cancel()},K.prototype.shouldCopyValues=function(){return!0},K.prototype.getActualLength=function(G){return G},K}});var tF0=M((L94,sF0)=>{sF0.exports=function($){var Y=!1,q=[];$.prototype._promiseCreated=function(){},$.prototype._pushContext=function(){},$.prototype._popContext=function(){return null},$._peekContext=$.prototype._peekContext=function(){};function z(){this._trace=new z.CapturedTrace(U())}z.prototype._pushContext=function(){if(this._trace!==void 0)this._trace._promiseCreated=null,q.push(this._trace)},z.prototype._popContext=function(){if(this._trace!==void 0){var I=q.pop(),Q=I._promiseCreated;return I._promiseCreated=null,Q}return null};function J(){if(Y)return new z}function U(){var I=q.length-1;if(I>=0)return q[I];return}return z.CapturedTrace=null,z.create=J,z.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(!w0.longStackTraces&&F1()){var o=$.prototype._captureStackTrace,N=$.prototype._attachExtraTrace;w0.longStackTraces=!0,A=function(){if(z.haveItemsQueued()&&!w0.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+`
`);$.prototype._captureStackTrace=o,$.prototype._attachExtraTrace=N,Y.deactivateLongStackTraces(),z.enableTrampoline(),w0.longStackTraces=!1},$.prototype._captureStackTrace=q0,$.prototype._attachExtraTrace=t,Y.activateLongStackTraces(),z.disableTrampolineIfNecessary()}},$.hasLongStackTraces=function(){return w0.longStackTraces&&F1()};var E=function(){try{if(typeof CustomEvent==="function"){var o=new CustomEvent("CustomEvent");return U.global.dispatchEvent(o),function(N,D){var h=new CustomEvent(N.toLowerCase(),{detail:D,cancelable:!0});return!U.global.dispatchEvent(h)}}else if(typeof Event==="function"){var o=new Event("CustomEvent");return U.global.dispatchEvent(o),function(D,h){var x=new Event(D.toLowerCase(),{cancelable:!0});return x.detail=h,!U.global.dispatchEvent(x)}}else{var o=document.createEvent("CustomEvent");return o.initCustomEvent("testingtheevent",!1,!0,{}),U.global.dispatchEvent(o),function(D,h){var x=document.createEvent("CustomEvent");return x.initCustomEvent(D.toLowerCase(),!1,!0,h),!U.global.dispatchEvent(x)}}}catch(N){}return function(){return!1}}(),y=function(){if(U.isNode)return function(){return process.emit.apply(process,arguments)};else{if(!U.global)return function(){return!1};return function(o){var N="on"+o.toLowerCase(),D=U.global[N];if(!D)return!1;return D.apply(U.global,[].slice.call(arguments,1)),!0}}}();function v(o,N){return{promise:N}}var k={promiseCreated:v,promiseFulfilled:v,promiseRejected:v,promiseResolved:v,promiseCancelled:v,promiseChained:function(o,N,D){return{promise:N,child:D}},warning:function(o,N){return{warning:N}},unhandledRejection:function(o,N,D){return{reason:N,promise:D}},rejectionHandled:v},C=function(o){var N=!1;try{N=y.apply(null,arguments)}catch(h){z.throwLater(h),N=!0}var D=!1;try{D=E(o,k[o].apply(null,arguments))}catch(h){z.throwLater(h),D=!0}return D||N};$.config=function(o){if(o=Object(o),"longStackTraces"in o){if(o.longStackTraces)$.longStackTraces();else if(!o.longStackTraces&&$.hasLongStackTraces())A()}if("warnings"in o){var N=o.warnings;if(w0.warnings=!!N,B=w0.warnings,U.isObject(N)){if("wForgottenReturn"in N)B=!!N.wForgottenReturn}}if("cancellation"in o&&o.cancellation&&!w0.cancellation){if(z.haveItemsQueued())throw Error("cannot enable cancellation after promises are in use");$.prototype._clearCancellationData=$0,$.prototype._propagateFrom=j,$.prototype._onCancel=b,$.prototype._setOnCancel=i,$.prototype._attachCancellationCallback=g,$.prototype._execute=n,p=j,w0.cancellation=!0}if("monitoring"in o){if(o.monitoring&&!w0.monitoring)w0.monitoring=!0,$.prototype._fireEvent=C;else if(!o.monitoring&&w0.monitoring)w0.monitoring=!1,$.prototype._fireEvent=c}return $};function c(){return!1}$.prototype._fireEvent=c,$.prototype._execute=function(o,N,D){try{o(N,D)}catch(h){return h}},$.prototype._onCancel=function(){},$.prototype._setOnCancel=function(o){},$.prototype._attachCancellationCallback=function(o){},$.prototype._captureStackTrace=function(){},$.prototype._attachExtraTrace=function(){},$.prototype._clearCancellationData=function(){},$.prototype._propagateFrom=function(o,N){};function n(o,N,D){var h=this;try{o(N,D,function(x){if(typeof x!=="function")throw TypeError("onCancel must be a function, got: "+U.toString(x));h._attachCancellationCallback(x)})}catch(x){return x}}function g(o){if(!this._isCancellable())return this;var N=this._onCancel();if(N!==void 0)if(U.isArray(N))N.push(o);else this._setOnCancel([N,o]);else this._setOnCancel(o)}function b(){return this._onCancelField}function i(o){this._onCancelField=o}function $0(){this._cancellationParent=void 0,this._onCancelField=void 0}function j(o,N){if((N&1)!==0){this._cancellationParent=o;var D=o._branchesRemainingToCancel;if(D===void 0)D=0;o._branchesRemainingToCancel=D+1}if((N&2)!==0&&o._isBound())this._setBoundTo(o._boundTo)}function u(o,N){if((N&2)!==0&&o._isBound())this._setBoundTo(o._boundTo)}var p=u;function d(){var o=this._boundTo;if(o!==void 0){if(o instanceof $)if(o.isFulfilled())return o.value();else return}return o}function q0(){this._trace=new U6(this._peekContext())}function t(o,N){if(I(o)){var D=this._trace;if(D!==void 0){if(N)D=D._parent}if(D!==void 0)D.attachExtraTrace(o);else if(!o.__stackCleaned__){var h=f0(o);U.notEnumerableProp(o,"stack",h.message+`
`+h.stack.join(`
`)),U.notEnumerableProp(o,"__stackCleaned__",!0)}}}function H0(o,N,D,h,x){if(o===void 0&&N!==null&&B){if(x!==void 0&&x._returnedNonUndefined())return;if((h._bitField&65535)===0)return;if(D)D=D+" ";var Y0="",r="";if(N._trace){var z0=N._trace.stack.split(`
`),G0=K0(z0);for(var V0=G0.length-1;V0>=0;--V0){var x0=G0[V0];if(!H.test(x0)){var r0=x0.match(Z);if(r0)Y0="at "+r0[1]+":"+r0[2]+":"+r0[3]+" ";break}}if(G0.length>0){var l0=G0[0];for(var V0=0;V0<z0.length;++V0)if(z0[V0]===l0){if(V0>0)r=`
`+z0[V0-1];break}}}var D1="a promise was created in a "+D+"handler "+Y0+"but was not returned from it, see http://goo.gl/rRqMUw"+r;h._warn(D1,!0,N)}}function L0(o,N){var D=o+" is deprecated and will be removed in a future version.";if(N)D+=" Use "+N+" instead.";return T0(D)}function T0(o,N,D){if(!w0.warnings)return;var h=new J(o),x;if(N)D._attachExtraTrace(h);else if(w0.longStackTraces&&(x=$._peekContext()))x.attachExtraTrace(h);else{var Y0=f0(h);h.stack=Y0.message+`
`+Y0.stack.join(`
`)}if(!C("warning",h))c0(h,"",!0)}function C0(o,N){for(var D=0;D<N.length-1;++D)N[D].push("From previous event:"),N[D]=N[D].join(`
`);if(D<N.length)N[D]=N[D].join(`
`);return o+`
`+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
`)}function j0(o){for(var N=0;N<o.length;++N)if(o[N].length===0||N+1<o.length&&o[N][0]===o[N+1][0])o.splice(N,1),N--}function i0(o){var N=o[0];for(var D=1;D<o.length;++D){var h=o[D],x=N.length-1,Y0=N[x],r=-1;for(var z0=h.length-1;z0>=0;--z0)if(h[z0]===Y0){r=z0;break}for(var z0=r;z0>=0;--z0){var G0=h[z0];if(N[x]===G0)N.pop(),x--;else break}N=h}}function K0(o){var N=[];for(var D=0;D<o.length;++D){var h=o[D],x=h===" (No stack trace)"||V.test(h),Y0=x&&b1(h);if(x&&!Y0){if(L&&h.charAt(0)!==" ")h=" "+h;N.push(h)}}return N}function v0(o){var N=o.stack.replace(/\s+$/g,"").split(`
`);for(var D=0;D<N.length;++D){var h=N[D];if(h===" (No stack trace)"||V.test(h))break}if(D>0&&o.name!="SyntaxError")N=N.slice(D);return N}function f0(o){var N=o.stack,D=o.toString();return N=typeof N==="string"&&N.length>0?v0(o):[" (No stack trace)"],{message:D,stack:o.name=="SyntaxError"?N:K0(N)}}function c0(o,N,D){if(typeof console<"u"){var h;if(U.isObject(o)){var x=o.stack;h=N+X(x,o)}else h=N+String(o);if(typeof w==="function")w(h,D);else if(typeof console.log==="function"||typeof console.log==="object")console.log(h)}}function C1(o,N,D,h){var x=!1;try{if(typeof N==="function")if(x=!0,o==="rejectionHandled")N(h);else N(D,h)}catch(Y0){z.throwLater(Y0)}if(o==="unhandledRejection"){if(!C(o,D,h)&&!x)c0(D,"Unhandled rejection ")}else C(o,h)}function a0(o){var N;if(typeof o==="function")N="[function "+(o.name||"anonymous")+"]";else{N=o&&typeof o.toString==="function"?o.toString():U.toString(o);var D=/\[object [a-zA-Z0-9$_]+\]/;if(D.test(N))try{var h=JSON.stringify(o);N=h}catch(x){}if(N.length===0)N="(empty array)"}return"(<"+r1(N)+">, no stack trace)"}function r1(o){var N=41;if(o.length<N)return o;return o.substr(0,N-3)+"..."}function F1(){return typeof e8==="function"}var b1=function(){return!1},$1=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function J6(o){var N=o.match($1);if(N)return{fileName:N[1],line:parseInt(N[2],10)}}function a8(o,N){if(!F1())return;var D=o.stack.split(`
`),h=N.stack.split(`
`),x=-1,Y0=-1,r,z0;for(var G0=0;G0<D.length;++G0){var V0=J6(D[G0]);if(V0){r=V0.fileName,x=V0.line;break}}for(var G0=0;G0<h.length;++G0){var V0=J6(h[G0]);if(V0){z0=V0.fileName,Y0=V0.line;break}}if(x<0||Y0<0||!r||!z0||r!==z0||x>=Y0)return;b1=function(x0){if(G.test(x0))return!0;var r0=J6(x0);if(r0){if(r0.fileName===r&&(x<=r0.line&&r0.line<=Y0))return!0}return!1}}function U6(o){this._parent=o,this._promisesCreated=0;var N=this._length=1+(o===void 0?0:o._length);if(e8(this,U6),N>32)this.uncycle()}U.inherits(U6,Error),Y.CapturedTrace=U6,U6.prototype.uncycle=function(){var o=this._length;if(o<2)return;var N=[],D={};for(var h=0,x=this;x!==void 0;++h)N.push(x),x=x._parent;o=this._length=h;for(var h=o-1;h>=0;--h){var Y0=N[h].stack;if(D[Y0]===void 0)D[Y0]=h}for(var h=0;h<o;++h){var r=N[h].stack,z0=D[r];if(z0!==void 0&&z0!==h){if(z0>0)N[z0-1]._parent=void 0,N[z0-1]._length=1;N[h]._parent=void 0,N[h]._length=1;var G0=h>0?N[h-1]:this;if(z0<o-1)G0._parent=N[z0+1],G0._parent.uncycle(),G0._length=G0._parent._length+1;else G0._parent=void 0,G0._length=1;var V0=G0._length+1;for(var x0=h-2;x0>=0;--x0)N[x0]._length=V0,V0++;return}}},U6.prototype.attachExtraTrace=function(o){if(o.__stackCleaned__)return;this.uncycle();var N=f0(o),D=N.message,h=[N.stack],x=this;while(x!==void 0)h.push(K0(x.stack.split(`
`))),x=x._parent;i0(h),j0(h),U.notEnumerableProp(o,"stack",C0(D,h)),U.notEnumerableProp(o,"__stackCleaned__",!0)};var e8=function(){var N=/^\s*at\s*/,D=function(r,z0){if(typeof r==="string")return r;if(z0.name!==void 0&&z0.message!==void 0)return z0.toString();return a0(z0)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6,V=N,X=D;var h=Error.captureStackTrace;return b1=function(r){return G.test(r)},function(r,z0){Error.stackTraceLimit+=6,h(r,z0),Error.stackTraceLimit-=6}}var x=Error();if(typeof x.stack==="string"&&x.stack.split(`
`)[0].indexOf("stackDetection@")>=0)return V=/@/,X=D,L=!0,function(z0){z0.stack=Error().stack};var Y0;try{throw Error()}catch(r){Y0="stack"in r}if(!("stack"in x)&&Y0&&typeof Error.stackTraceLimit==="number")return V=N,X=D,function(z0){Error.stackTraceLimit+=6;try{throw Error()}catch(G0){z0.stack=G0.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 a0(z0)},null}([]);if(typeof console<"u"&&typeof console.warn<"u"){if(w=function(o){console.warn(o)},U.isNode&&process.stderr.isTTY)w=function(o,N){var D=N?"\x1B[33m":"\x1B[31m";console.warn(D+o+`\x1B[0m
`)};else if(!U.isNode&&typeof Error().stack==="string")w=function(o,N){console.warn("%c"+o,N?"color: darkorange":"color: red")}}var w0={warnings:O,longStackTraces:!1,cancellation:!1,monitoring:!1};if(P)$.longStackTraces();return{longStackTraces:function(){return w0.longStackTraces},warnings:function(){return w0.warnings},cancellation:function(){return w0.cancellation},monitoring:function(){return w0.monitoring},propagateFromFunction:function(){return p},boundValueFunction:function(){return d},checkForgottenReturns:H0,setBounds:a8,warn:T0,deprecated:L0,CapturedTrace:U6,fireDomEvent:E,fireGlobalEvent:y}}});var YO0=M((F94,$O0)=>{$O0.exports=function($,Y){var q=H4(),z=$.CancellationError,J=q.errorObj;function U(Z,V,X){this.promise=Z,this.type=V,this.handler=X,this.called=!1,this.cancelPromise=null}U.prototype.isFinallyHandler=function(){return this.type===0};function I(Z){this.finallyHandler=Z}I.prototype._resultCancelled=function(){Q(this.finallyHandler)};function Q(Z,V){if(Z.cancelPromise!=null){if(arguments.length>1)Z.cancelPromise._reject(V);else Z.cancelPromise._cancel();return Z.cancelPromise=null,!0}return!1}function K(){return H.call(this,this.promise._target()._settledValue())}function G(Z){if(Q(this,Z))return;return J.e=Z,J}function H(Z){var V=this.promise,X=this.handler;if(!this.called){this.called=!0;var L=this.isFinallyHandler()?X.call(V._boundValue()):X.call(V._boundValue(),Z);if(L!==void 0){V._setReturnedNonUndefined();var w=Y(L,V);if(w instanceof $){if(this.cancelPromise!=null){if(w._isCancelled()){var F=new z("late cancellation observer");return V._attachExtraTrace(F),J.e=F,J}else if(w.isPending())w._attachCancellationCallback(new I(this))}return w._then(K,G,void 0,this,void 0)}}}if(V.isRejected())return Q(this),J.e=Z,J;else return Q(this),Z}return $.prototype._passThrough=function(Z,V,X,L){if(typeof Z!=="function")return this.then();return this._then(X,L,void 0,new U(this,V,Z),void 0)},$.prototype.lastly=$.prototype.finally=function(Z){return this._passThrough(Z,0,H,H)},$.prototype.tap=function(Z){return this._passThrough(Z,1,H)},U}});var zO0=M((O94,qO0)=>{qO0.exports=function($){var Y=H4(),q=kY().keys,z=Y.tryCatch,J=Y.errorObj;function U(I,Q,K){return function(G){var H=K._boundValue();$:for(var Z=0;Z<I.length;++Z){var V=I[Z];if(V===Error||V!=null&&V.prototype instanceof Error){if(G instanceof V)return z(Q).call(H,G)}else if(typeof V==="function"){var X=z(V).call(H,G);if(X===J)return X;else if(X)return z(Q).call(H,G)}else if(Y.isObject(G)){var L=q(V);for(var w=0;w<L.length;++w){var F=L[w];if(V[F]!=G[F])continue $}return z(Q).call(H,G)}}return $}}return U}});var mf=M((M94,IO0)=>{var JO0=H4(),UD1=JO0.maybeWrapAsError,ID1=$3(),QD1=ID1.OperationalError,UO0=kY();function KD1($){return $ instanceof Error&&UO0.getPrototypeOf($)===Error.prototype}var GD1=/^(?:name|message|stack|cause)$/;function HD1($){var Y;if(KD1($)){Y=new QD1($),Y.name=$.name,Y.message=$.message,Y.stack=$.stack;var q=UO0.keys($);for(var z=0;z<q.length;++z){var J=q[z];if(!GD1.test(J))Y[J]=$[J]}return Y}return JO0.markAsOriginatingFromRejection($),$}function ZD1($,Y){return function(q,z){if($===null)return;if(q){var J=HD1(UD1(q));$._attachExtraTrace(J),$._reject(J)}else if(!Y)$._fulfill(z);else{var U=arguments.length,I=Array(Math.max(U-1,0));for(var Q=1;Q<U;++Q)I[Q-1]=arguments[Q];$._fulfill(I)}$=null}}IO0.exports=ZD1});var KO0=M((N94,QO0)=>{QO0.exports=function($,Y,q,z,J){var U=H4(),I=U.tryCatch;$.method=function(Q){if(typeof Q!=="function")throw new $.TypeError("expecting a function but got "+U.classString(Q));return function(){var K=new $(Y);K._captureStackTrace(),K._pushContext();var G=I(Q).apply(this,arguments),H=K._popContext();return J.checkForgottenReturns(G,H,"Promise.method",K),K._resolveFromSyncValue(G),K}},$.attempt=$.try=function(Q){if(typeof Q!=="function")return z("expecting a function but got "+U.classString(Q));var K=new $(Y);K._captureStackTrace(),K._pushContext();var G;if(arguments.length>1){J.deprecated("calling Promise.try with more than 1 argument");var H=arguments[1],Z=arguments[2];G=U.isArray(H)?I(Q).apply(Z,H):I(Q).call(Z,H)}else G=I(Q)();var V=K._popContext();return J.checkForgottenReturns(G,V,"Promise.try",K),K._resolveFromSyncValue(G),K},$.prototype._resolveFromSyncValue=function(Q){if(Q===U.errorObj)this._rejectCallback(Q.e,!1);else this._resolveCallback(Q,!0)}}});var HO0=M((D94,GO0)=>{GO0.exports=function($,Y,q,z){var J=!1,U=function(G,H){this._reject(H)},I=function(G,H){H.promiseRejectionQueued=!0,H.bindingPromise._then(U,U,null,this,G)},Q=function(G,H){if((this._bitField&50397184)===0)this._resolveCallback(H.target)},K=function(G,H){if(!H.promiseRejectionQueued)this._reject(G)};$.prototype.bind=function(G){if(!J)J=!0,$.prototype._propagateFrom=z.propagateFromFunction(),$.prototype._boundValue=z.boundValueFunction();var H=q(G),Z=new $(Y);Z._propagateFrom(this,1);var V=this._target();if(Z._setBoundTo(H),H instanceof $){var X={promiseRejectionQueued:!1,promise:Z,target:V,bindingPromise:H};V._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()},z=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()},J=Y.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0},U=Y.prototype.isRejected=function(){return(this._bitField&16777216)!==0},I=Y.prototype.isPending=function(){return(this._bitField&50397184)===0},Q=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 U.call(this._target())},$.prototype.isFulfilled=function(){return J.call(this._target())},$.prototype.isResolved=function(){return Q.call(this._target())},$.prototype.value=function(){return q.call(this._target())},$.prototype.reason=function(){var K=this._target();return K._unsetRejectionIsUnhandled(),z.call(K)},$.prototype._value=function(){return this._settledValue()},$.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},$.PromiseInspection=Y}});var OO0=M((T94,FO0)=>{FO0.exports=function($,Y,q,z,J,U){var I=H4(),Q=I.canEvaluate,K=I.tryCatch,G=I.errorObj,H;if(Q){var Z=function(P){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,P))},V=function(P){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`
promise = `+b+`;
`.replace(/Index/g,P))},X=function(P){var B=Array(P);for(var A=0;A<B.length;++A)B[A]="this.p"+(A+1);var E=B.join(" = ")+" = null;",y=`var promise;
`+B.map(function(c){return`
promise = `+c+`;
if (promise instanceof Promise) {
promise.cancel();
}
`}).join(`
`),h=P.join(", "),f="Holder$"+D,C=`return function(tryCatch, errorObj, Promise, async) {
`),v=B.join(", "),k="Holder$"+P,C=`return function(tryCatch, errorObj, Promise, async) {
'use strict';
function [TheName](fn) {
[TheProperties]
@@ -193,7 +193,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,k).replace(/\[TheTotal\]/g,P).replace(/\[ThePassedArguments\]/g,v).replace(/\[TheProperties\]/g,E).replace(/\[CancellationCode\]/g,y),Function("tryCatch","errorObj","Promise","async",C)(K,G,$,J)},L=[],w=[],F=[];for(var O=0;O<8;++O)L.push(X(O+1)),w.push(Z(O+1)),F.push(V(O+1));H=function(P){this._reject(P)}}$.join=function(){var P=arguments.length-1,B;if(P>0&&typeof arguments[P]==="function"){if(B=arguments[P],P<=8&&Q){var i=new $(z);i._captureStackTrace();var A=L[P-1],E=new A(B),y=w;for(var v=0;v<P;++v){var k=q(arguments[v],i);if(k instanceof $){k=k._target();var C=k._bitField;if((C&50397184)===0)k._then(y[v],H,void 0,i,E),F[v](k,E),E.asyncNeeded=!1;else if((C&33554432)!==0)y[v].call(i,k._value(),E);else if((C&16777216)!==0)i._reject(k._reason());else i._cancel()}else y[v].call(i,k,E)}if(!i._isFateSealed()){if(E.asyncNeeded){var c=U();if(c!==null)E.fn=I.domainBind(c,E.fn)}i._setAsyncGuaranteed(),i._setOnCancel(E)}return i}}var n=arguments.length,g=Array(n);for(var b=0;b<n;++b)g[b]=arguments[b];if(B)g.pop();var i=new Y(g).promise();return B!==void 0?i.spread(B):i}}});var NO0=M((E94,MO0)=>{MO0.exports=function($,Y,q,z,J,U){var I=$._getDomain,Q=H4(),K=Q.tryCatch,G=Q.errorObj,H=$._async;function Z(X,L,w,F){this.constructor$(X),this._promise._captureStackTrace();var O=I();this._callback=O===null?L:Q.domainBind(O,L),this._preservedValues=F===J?Array(this.length()):null,this._limit=w,this._inFlight=0,this._queue=[],H.invoke(this._asyncInit,this,void 0)}Q.inherits(Z,Y),Z.prototype._asyncInit=function(){this._init$(void 0,-2)},Z.prototype._init=function(){},Z.prototype._promiseFulfilled=function(X,L){var w=this._values,F=this.length(),O=this._preservedValues,P=this._limit;if(L<0){if(L=L*-1-1,w[L]=X,P>=1){if(this._inFlight--,this._drainQueue(),this._isResolved())return!0}}else{if(P>=1&&this._inFlight>=P)return w[L]=X,this._queue.push(L),!1;if(O!==null)O[L]=X;var B=this._promise,A=this._callback,E=B._boundValue();B._pushContext();var y=K(A).call(E,X,L,F),v=B._popContext();if(U.checkForgottenReturns(y,v,O!==null?"Promise.filter":"Promise.map",B),y===G)return this._reject(y.e),!0;var k=z(y,this._promise);if(k instanceof $){k=k._target();var C=k._bitField;if((C&50397184)===0){if(P>=1)this._inFlight++;return w[L]=k,k._proxy(this,(L+1)*-1),!1}else if((C&33554432)!==0)y=k._value();else if((C&16777216)!==0)return this._reject(k._reason()),!0;else return this._cancel(),!0}w[L]=y}var c=++this._totalResolved;if(c>=F){if(O!==null)this._filter(w,O);else this._resolve(w);return!0}return!1},Z.prototype._drainQueue=function(){var X=this._queue,L=this._limit,w=this._values;while(X.length>0&&this._inFlight<L){if(this._isResolved())return;var F=X.pop();this._promiseFulfilled(w[F],F)}},Z.prototype._filter=function(X,L){var w=L.length,F=Array(w),O=0;for(var P=0;P<w;++P)if(X[P])F[O++]=L[P];F.length=O,this._resolve(F)},Z.prototype.preservedValues=function(){return this._preservedValues};function V(X,L,w,F){if(typeof L!=="function")return q("expecting a function but got "+Q.classString(L));var O=0;if(w!==void 0)if(typeof w==="object"&&w!==null){if(typeof w.concurrency!=="number")return $.reject(TypeError("'concurrency' must be a number but it is "+Q.classString(w.concurrency)));O=w.concurrency}else return $.reject(TypeError("options argument must be an object but it is "+Q.classString(w)));return O=typeof O==="number"&&isFinite(O)&&O>=1?O:0,new Z(X,L,O,F).promise()}$.prototype.map=function(X,L){return V(this,X,L,null)},$.map=function(X,L,w,F){return V(X,L,w,F)}}});var PO0=M((j94,DO0)=>{var lf=Object.create;if(lf)JN=lf(null),UN=lf(null),JN[" size"]=UN[" size"]=0;var JN,UN;DO0.exports=function($){var Y=H4(),q=Y.canEvaluate,z=Y.isIdentifier,J,U,I=function(X){return Function("ensureMethod",`
return function(obj) {
'use strict'
var len = this.length;
@@ -207,29 +207,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,X))(G)},Q=function(X){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",X))},K=function(X,L,w){var F=w[X];if(typeof F!=="function"){if(!z(X))return null;if(F=L(X),w[X]=F,w[" size"]++,w[" size"]>512){var O=Object.keys(w);for(var P=0;P<256;++P)delete w[O[P]];w[" size"]=O.length-256}}return F};J=function(X){return K(X,I,JN)},U=function(X){return K(X,Q,UN)};function G(X,L){var w;if(X!=null)w=X[L];if(typeof w!=="function"){var F="Object "+Y.classString(X)+" has no method '"+Y.toString(L)+"'";throw new $.TypeError(F)}return w}function H(X){var L=this.pop(),w=G(X,L);return w.apply(X,this)}$.prototype.call=function(X){var L=arguments.length,w=Array(Math.max(L-1,0));for(var F=1;F<L;++F)w[F-1]=arguments[F];if(q){var O=J(X);if(O!==null)return this._then(O,void 0,void 0,w,void 0)}return w.push(X),this._then(H,void 0,void 0,w,void 0)};function Z(X){return X[this]}function V(X){var L=+this;if(L<0)L=Math.max(0,L+X.length);return X[L]}$.prototype.get=function(X){var L=typeof X==="number",w;if(!L)if(q){var F=U(X);w=F!==null?F:Z}else w=Z;else w=V;return this._then(w,void 0,void 0,X,void 0)}}});var BO0=M((_94,AO0)=>{AO0.exports=function($,Y,q,z,J,U){var I=H4(),Q=$3().TypeError,K=H4().inherits,G=I.errorObj,H=I.tryCatch,Z={};function V(B){setTimeout(function(){throw B},0)}function X(B){var A=q(B);if(A!==B&&typeof B._isDisposable==="function"&&typeof B._getDisposer==="function"&&B._isDisposable())A._setDisposable(B._getDisposer());return A}function L(B,A){var E=0,y=B.length,v=new $(J);function k(){if(E>=y)return v._fulfill();var C=X(B[E++]);if(C instanceof $&&C._isDisposable()){try{C=q(C._getDisposer().tryDispose(A),B.promise)}catch(c){return V(c)}if(C instanceof $)return C._then(k,V,null,null,null)}k()}return k(),v}function w(B,A,E){this._data=B,this._promise=A,this._context=E}w.prototype.data=function(){return this._data},w.prototype.promise=function(){return this._promise},w.prototype.resource=function(){if(this.promise().isFulfilled())return this.promise().value();return Z},w.prototype.tryDispose=function(B){var A=this.resource(),E=this._context;if(E!==void 0)E._pushContext();var y=A!==Z?this.doDispose(A,B):null;if(E!==void 0)E._popContext();return this._promise._unsetDisposable(),this._data=null,y},w.isDisposer=function(B){return B!=null&&typeof B.resource==="function"&&typeof B.tryDispose==="function"};function F(B,A,E){this.constructor$(B,A,E)}K(F,w),F.prototype.doDispose=function(B,A){var E=this.data();return E.call(B,B,A)};function O(B){if(w.isDisposer(B))return this.resources[this.index]._setDisposable(B),B.promise();return B}function P(B){this.length=B,this.promise=null,this[B-1]=null}P.prototype._resultCancelled=function(){var B=this.length;for(var A=0;A<B;++A){var E=this[A];if(E instanceof $)E.cancel()}},$.using=function(){var B=arguments.length;if(B<2)return Y("you must pass at least 2 arguments to Promise.using");var A=arguments[B-1];if(typeof A!=="function")return Y("expecting a function but got "+I.classString(A));var E,y=!0;if(B===2&&Array.isArray(arguments[0]))E=arguments[0],B=E.length,y=!1;else E=arguments,B--;var v=new P(B);for(var k=0;k<B;++k){var C=E[k];if(w.isDisposer(C)){var c=C;C=C.promise(),C._setDisposable(c)}else{var n=q(C);if(n instanceof $)C=n._then(O,null,null,{resources:v,index:k},void 0)}v[k]=C}var g=Array(v.length);for(var k=0;k<g.length;++k)g[k]=$.resolve(v[k]).reflect();var b=$.all(g).then(function($0){for(var j=0;j<$0.length;++j){var u=$0[j];if(u.isRejected())return G.e=u.error(),G;else if(!u.isFulfilled()){b.cancel();return}$0[j]=u.value()}i._pushContext(),A=H(A);var p=y?A.apply(void 0,$0):A($0),d=i._popContext();return U.checkForgottenReturns(p,d,"Promise.using",i),p}),i=b.lastly(function(){var $0=new $.PromiseInspection(b);return L(v,$0)});return v.promise=i,i._setOnCancel(v),i},$.prototype._setDisposable=function(B){this._bitField=this._bitField|131072,this._disposer=B},$.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(B){if(typeof B==="function")return new F(B,this,z());throw new Q}}});var EO0=M((R94,TO0)=>{TO0.exports=function($,Y,q){var z=H4(),J=$.TimeoutError;function U(Z){this.handle=Z}U.prototype._resultCancelled=function(){clearTimeout(this.handle)};var I=function(Z){return Q(+this).thenReturn(Z)},Q=$.delay=function(Z,V){var X,L;if(V!==void 0){if(X=$.resolve(V)._then(I,null,null,Z,void 0),q.cancellation()&&V instanceof $)X._setOnCancel(V)}else{if(X=new $(Y),L=setTimeout(function(){X._fulfill()},+Z),q.cancellation())X._setOnCancel(new U(L));X._captureStackTrace()}return X._setAsyncGuaranteed(),X};$.prototype.delay=function(Z){return Q(Z,this)};var K=function(Z,V,X){var L;if(typeof V!=="string")if(V instanceof Error)L=V;else L=new J("operation timed out");else L=new J(V);if(z.markAsOriginatingFromRejection(L),Z._attachExtraTrace(L),Z._reject(L),X!=null)X.cancel()};function G(Z){return clearTimeout(this.handle),Z}f Line truncated
See http://goo.gl/MqrFmX
`.replace("%s",O)+`From coroutine:
`.replace("%s",F)+`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}}O=O._target();var P=O._bitField;if((P&50397184)===0)this._yieldedPromise=O,O._proxy(this,null);else if((P&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,O._value());else if((P&16777216)!==0)$._async.invoke(this._promiseRejected,this,O._reason());else this._promiseCancelled()}},$.coroutine=function(L,w){if(typeof L!=="function")throw new Q(`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 F=Object(w).yieldHandler,O=X,P=Error().stack;return function(){var B=L.apply(this,arguments),A=new O(void 0,void 0,F,P),E=A.promise();return A._generator=B,A._promiseFulfilled(void 0),E}},$.coroutine.addYieldHandler=function(L){if(typeof L!=="function")throw new Q("expecting a function but got "+K.classString(L));Z.push(L)},$.spawn=function(L){if(U.deprecated("Promise.spawn()","Promise.coroutine()"),typeof L!=="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 w=new X(L,this),F=w.promise();return w._run($.spawn),F}}});var CO0=M((v94,RO0)=>{RO0.exports=function($){var Y=H4(),q=$._async,z=Y.tryCatch,J=Y.errorObj;function U(K,G){var H=this;if(!Y.isArray(K))return I.call(H,K,G);var Z=z(G).apply(H._boundValue(),[null].concat(K));if(Z===J)q.throwLater(Z.e)}function I(K,G){var H=this,Z=H._boundValue(),V=K===void 0?z(G).call(Z,null):z(G).call(Z,null,K);if(V===J)q.throwLater(V.e)}function Q(K,G){var H=this;if(!K){var Z=Error(K+"");Z.cause=K,K=Z}var V=z(G).call(H._boundValue(),K);if(V===J)q.throwLater(V.e)}$.prototype.asCallback=$.prototype.nodeify=function(K,G){if(typeof K=="function"){var H=I;if(G!==void 0&&Object(G).spread)H=U;this._then(H,Q,void 0,this,K)}return this}}});var hO0=M((h94,vO0)=>{vO0.exports=function($,Y){var q={},z=H4(),J=mf(),U=z.withAppended,I=z.maybeWrapAsError,Q=z.canEvaluate,K=$3().TypeError,G="Async",H={__isPromisified__:!0},Z=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],V=new RegExp("^(?:"+Z.join("|")+")$"),X=function(b){return z.isIdentifier(b)&&b.charAt(0)!=="_"&&b!=="constructor"};function L(b){return!V.test(b)}function w(b){try{return b.__isPromisified__===!0}catch(i){return!1}}function F(b,i,$0){var j=z.getDataPropertyOrDefault(b,i+$0,H);return j?w(j):!1}function O(b,i,$0){for(var j=0;j<b.length;j+=2){var u=b[j];if($0.test(u)){var p=u.replace($0,"");for(var d=0;d<b.length;d+=2)if(b[d]===p)throw new K(`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",i))}}}function P(b,i,$0,j){var u=z.inheritedDataKeys(b),p=[];for(var d=0;d<u.length;++d){var q0=u[d],t=b[q0],H0=j===X?!0:X(q0,t,b);if(typeof t==="function"&&!w(t)&&!F(b,q0,i)&&j(q0,t,b,H0))p.push(q0,t)}return O(p,i,$0),p}var B=function(b){return b.replace(/([$])/,"\\$")},A,E=function(b){var i=[b],$0=Math.max(0,b-1-3);for(var j=b-1;j>=$0;--j)i.push(j);for(var j=b+1;j<=3;++j)i.push(j);return i},y=function(b){return z.filledRange(b,"_arg","")},v=function(b){return z.filledRange(Math.max(b,3),"_arg","")},k=function(b){if(typeof b.length==="number")return Math.max(Math.min(b.length,1024),0);return 0};A=function(b,i,$0,j,u,p){var d=Math.max(0,k(j)-1),q0=E(d),t=typeof b==="string"||i===q;function H0(j0){var i0=y(j0).join(", "),K0=j0>0?", ":"",v0;if(t)v0=`ret = callback.call(this, {{args}}, nodeback); break;
`;else v0=i===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 v0.replace("{{args}}",i0).replace(", ",K0)}function L0(){var j0="";for(var i0=0;i0<q0.length;++i0)j0+="case "+q0[i0]+":"+H0(q0[i0]);return j0+=`
default:
var args = new Array(len + 1);
var i = 0;
@@ -239,9 +239,9 @@ 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]",t?`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';
`),j0}var T0=typeof b==="string"?"this != null ? this['"+b+"'] : fn":"fn",C0=`'use strict';
var ret = function (Parameters) {
'use strict';
var len = arguments.length;
@@ -261,25 +261,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]",L0()).replace("[GetFunctionCode]",T0);return C0=C0.replace("Parameters",v(d)),Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",C0)($,j,i,U,I,J,z.tryCatch,z.errorObj,z.notEnumerableProp,Y)};function C(b,i,$0,j,u,p){var d=function(){return this}(),q0=b;if(typeof q0==="string")b=j;function t(){var H0=i;if(i===q)H0=this;var L0=new $(Y);L0._captureStackTrace();var T0=typeof q0==="string"&&this!==d?this[q0]:b,C0=J(L0,p);try{T0.apply(H0,U(arguments,C0))}catch(j0){L0._rejectCallback(I(j0),!0,!0)}if(!L0._isFateSealed())L0._setAsyncGuaranteed();return L0}return z.notEnumerableProp(t,"__isPromisified__",!0),t}var c=Q?A:C;function n(b,i,$0,j,u){var p=new RegExp(B(i)+"$"),d=P(b,i,p,$0);for(var q0=0,t=d.length;q0<t;q0+=2){var H0=d[q0],L0=d[q0+1],T0=H0+i;if(j===c)b[T0]=c(H0,q,H0,L0,i,u);else{var C0=j(L0,function(){return c(H0,q,H0,L0,i,u)});z.notEnumerableProp(C0,"__isPromisified__",!0),b[T0]=C0}}return z.toFastProperties(b),b}function g(b,i,$0){return c(b,i,void 0,b,null,$0)}$.promisify=function(b,i){if(typeof b!=="function")throw new K("expecting a function but got "+z.classString(b));if(w(b))return b;i=Object(i);var $0=i.context===void 0?q:i.context,j=!!i.multiArgs,u=g(b,$0,j);return z.copyDescriptors(b,u,L),u},$.promisifyAll=function(b,i){if(typeof b!=="function"&&typeof b!=="object")throw new K(`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
`);i=Object(i);var $0=!!i.multiArgs,j=i.suffix;if(typeof j!=="string")j=G;var u=i.filter;if(typeof u!=="function")u=X;var p=i.promisifier;if(typeof p!=="function")p=c;if(!z.isIdentifier(j))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 d=z.inheritedDataKeys(b);for(var q0=0;q0<d.length;++q0){var t=b[d[q0]];if(d[q0]!=="constructor"&&z.isClass(t))n(t.prototype,j,u,p,$0),n(t,j,u,p,$0)}return n(b,j,u,p,$0)}}});var SO0=M((g94,gO0)=>{gO0.exports=function($,Y,q,z){var J=H4(),U=J.isObject,I=kY(),Q;if(typeof Map==="function")Q=Map;var K=function(){var V=0,X=0;function L(w,F){this[V]=w,this[V+X]=F,V++}return function(F){X=F.size,V=0;var O=Array(F.size*2);return F.forEach(L,O),O}}(),G=function(V){var X=new Q,L=V.length/2|0;for(var w=0;w<L;++w){var F=V[L+w],O=V[w];X.set(F,O)}return X};function H(V){var X=!1,L;if(Q!==void 0&&V instanceof Q)L=K(V),X=!0;else{var w=I.keys(V),F=w.length;L=Array(F*2);for(var O=0;O<F;++O){var P=w[O];L[O]=V[P],L[O+F]=P}}this.constructor$(L),this._isMap=X,this._init$(void 0,-3)}J.inherits(H,Y),H.prototype._init=function(){},H.prototype._promiseFulfilled=function(V,X){this._values[X]=V;var L=++this._totalResolved;if(L>=this._length){var w;if(this._isMap)w=G(this._values);else{w={};var F=this.length();for(var O=0,P=this.length();O<P;++O)w[this._values[O+F]]=this._values[O]}return this._resolve(w),!0}return!1},H.prototype.shouldCopyValues=function(){return!1},H.prototype.getActualLength=function(V){return V>>1};function Z(V){var X,L=q(V);if(!U(L))return z(`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(L instanceof $)X=L._then($.props,void 0,void 0,void 0,void 0);else X=new H(L).promise();if(L instanceof $)X._propagateFrom(L,2);return X}$.prototype.props=function(){return Z(this)},$.props=function(V){return Z(V)}}});var xO0=M((S94,yO0)=>{yO0.exports=function($,Y,q,z){var J=H4(),U=function(Q){return Q.then(function(K){return I(K,Q)})};function I(Q,K){var G=q(Q);if(G instanceof $)return U(G);else if(Q=J.asArray(Q),Q===null)return z("expecting an array or an iterable object but got "+J.classString(Q));var H=new $(Y);if(K!==void 0)H._propagateFrom(K,3);var{_fulfill:Z,_reject:V}=H;for(var X=0,L=Q.length;X<L;++X){var w=Q[X];if(w===void 0&&!(X in Q))continue;$.cast(w)._then(Z,V,void 0,H,null)}return H}$.race=function(Q){return I(Q,void 0)},$.prototype.race=function(){return I(this,void 0)}}});var uO0=M((y94,kO0)=>{kO0.exports=function($,Y,q,z,J,U){var I=$._getDomain,Q=H4(),K=Q.tryCatch;function G(L,w,F,O){this.constructor$(L);var P=I();if(this._fn=P===null?w:Q.domainBind(P,w),F!==void 0)F=$.resolve(F),F._attachCancellationCallback(this);if(this._initialValue=F,this._currentCancellable=null,O===J)this._eachValues=Array(this._length);else if(O===0)this._eachValues=null;else this._eachValues=void 0;this._promise._captureStackTrace(),this._init$(void 0,-5)}Q.inherits(G,Y),G.prototype._gotAccum=function(L){if(this._eachValues!==void 0&&this._eachValues!==null&&L!==J)this._eachValues.push(L)},G.prototype._eachComplete=function(L){if(this._eachValues!==null)this._eachValues.push(L);return this._eachValues},G.prototype._init=function(){},G.prototype._resolveEmptyArray=function(){this._resolve(this._eachValues!==void 0?this._eachValues:this._initialValue)},G.prototype.shouldCopyValues=function(){return!1},G.prototype._resolve=function(L){this._promise._resolveCallback(L),this._values=null},G.prototype._resultCancelled=function(L){if(L===this._initialValue)return this._cancel();if(this._isResolved())return;if(this._resultCancelled$(),this._currentCancellable instanceof $)this._currentCancellable.cancel();if(this._initialValue instanceof $)this._initialValue.cancel()},G.prototype._iterate=function(L){this._values=L;var w,F,O=L.length;if(this._initialValue!==void 0)w=this._initialValue,F=0;else w=$.resolve(L[0]),F=1;if(this._currentCancellable=w,!w.isRejected())for(;F<O;++F){var P={accum:null,value:L[F],index:F,length:O,array:this};w=w._then(V,void 0,void 0,P,void 0)}if(this._eachValues!==void 0)w=w._then(this._eachComplete,void 0,void 0,this,void 0);w._then(H,H,void 0,w,this)},$.prototype.reduce=function(L,w){return Z(this,L,w,null)},$.reduce=function(L,w,F,O){return Z(L,w,F,O)};function H(L,w){if(this.isFulfilled())w._resolve(L);else w._reject(L)}function Z(L,w,F,O){if(typeof w!=="function")return q("expecting a function but got "+Q.classString(w));var P=new G(L,w,F,O);return P.promise()}function V(L){this.accum=L,this.array._gotAccum(L);var w=z(this.value,this.array._promise);if(w instanceof $)return this.array._currentCancellable=w,w._then(X,void 0,void 0,this,void 0);else return X.call(this,w)}function X(L){var w=this.array,F=w._promise,O=K(w._fn);F._pushContext();var P;if(w._eachValues!==void 0)P=O.call(F._boundValue(),L,this.index,this.length);else P=O.call(F._boundValue(),this.accum,L,this.index,this.length);if(P instanceof $)w._currentCancellable=P;var B=F._popContext();return U.checkForgottenReturns(P,B,w._eachValues!==void 0?"Promise.each":"Promise.reduce",F),P}}});var bO0=M((x94,fO0)=>{fO0.exports=function($,Y,q){var z=$.PromiseInspection,J=H4();function U(I){this.constructor$(I)}J.inherits(U,Y),U.prototype._promiseResolved=function(I,Q){this._values[I]=Q;var K=++this._totalResolved;if(K>=this._length)return this._resolve(this._values),!0;return!1},U.prototype._promiseFulfilled=function(I,Q){var K=new z;return K._bitField=33554432,K._settledValueField=I,this._promiseResolved(Q,K)},U.prototype._promiseRejected=function(I,Q){var K=new z;return K._bitField=16777216,K._settledValueField=I,this._promiseResolved(Q,K)},$.settle=function(I){return q.deprecated(".settle()",".reflect()"),new U(I).promise()},$.prototype.settle=function(){return $.settle(this)}}});var nO0=M((k94,iO0)=>{iO0.exports=function($,Y,q){var z=H4(),J=$3().RangeError,U=$3().AggregateError,I=z.isArray,Q={};function K(H){this.constructor$(H),this._howMany=0,this._unwrap=!1,this._initialized=!1}z.inherits(K,Y),K.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()))},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(H){this._howMany=H},K.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 V=new K(H),X=V.promise();return V.setHowMany(Z),V.init(),X}$.some=function(H,Z){return G(H,Z)},$.prototype.some=function(H){return G(this,H)},$._SomePromiseArray=K}});var pO0=M((u94,cO0)=>{cO0.exports=function($,Y){var q=$.map;$.prototype.filter=function(z,J){return q(this,z,J,Y)},$.filter=function(z,J,U){return q(z,J,U,Y)}}});var mO0=M((f94,dO0)=>{dO0.exports=function($,Y){var{reduce:q,all:z}=$;function J(){return z(this)}function U(I,Q){return q(I,Q,Y,Y)}$.prototype.each=function(I){return q(this,I,Y,0)._then(J,void 0,void 0,this,void 0)},$.prototype.mapSeries=function(I){return q(this,I,Y,Y)},$.each=function(I,Q){return q(I,Q,Y,0)._then(J,void 0,void 0,I,void 0)},$.mapSeries=U}});var oO0=M((b94,lO0)=>{lO0.exports=function($){var Y=$._SomePromiseArray;function q(z){var J=new Y(z),U=J.promise();return J.setHowMany(1),J.setUnwrap(),J.init(),U}$.any=function(z){return q(z)},$.prototype.any=function(){return q(this)}}});var rO0=M((i94,of)=>{of.exports=function(){var $=function(){return new Z(`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 g.PromiseInspection(this._target())},q=function(j){return g.reject(new Z(j))};function z(){}var J={},U=H4(),I;if(U.isNode)I=function(){var j=process.domain;if(j===void 0)j=null;return j};else I=function(){return null};U.notEnumerableProp(g,"_getDomain",I);var Q=kY(),K=nF0(),G=new K;Q.defineProperty(g,"_async",{value:G});var H=$3(),Z=g.TypeError=H.TypeError;g.RangeError=H.RangeError;var V=g.CancellationError=H.CancellationError;g.TimeoutError=H.TimeoutError,g.OperationalError=H.OperationalError,g.RejectionError=H.OperationalError,g.AggregateError=H.AggregateError;var X=function(){},L={},w={},F=lF0()(g,X),O=rF0()(g,X,F,q,z),P=tF0()(g),B=P.create,A=eF0()(g,P),E=A.CapturedTrace,y=YO0()(g,F),v=zO0()(w),k=mf(),C=U.errorObj,c=U.tryCatch;function n(j,u){if(typeof u!=="function")throw new Z("expecting a function but got "+U.classString(u));if(j.constructor!==g)throw new Z(`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 g(j){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,j!==X)n(this,j),this._resolveFromExecutor(j);this._promiseCreated(),this._fireEvent("promiseCreated",this)}g.prototype.toString=function(){return"[object Promise]"},g.prototype.caught=g.prototype.catch=function(j){var u=arguments.length;if(u>1){var p=Array(u-1),d=0,q0;for(q0=0;q0<u-1;++q0){var t=arguments[q0];if(U.isObject(t))p[d++]=t;else return q("expecting an object but got A catch statement predicate "+U.classString(t))}return p.length=d,j=arguments[q0],this.then(void 0,v(p,j,this))}return this.then(void 0,j)},g.prototype.reflect=function(){return this._then(Y,Y,void 0,this,void 0)},g.prototype.then=function(j,u){if(A.warnings()&&arguments.length>0&&typeof j!=="function"&&typeof u!=="function"){var p=".then() only accepts functions but was passed: "+U.classString(j);if(arguments.length>1)p+=", "+U.classString(u);this._warn(p)}return this._then(j,u,void 0,void 0,void 0)},g.prototype.done=function(j,u){var p=this._then(j,u,void 0,void 0,void 0);p._setIsFinal()},g.prototype.spread=function(j){if(typeof j!=="function")return q("expecting a function but got "+U.classString(j));return this.all()._then(j,void 0,void 0,L,void 0)},g.prototype.toJSON=function(){var j={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())j.fulfillmentValue=this.value(),j.isFulfilled=!0;else if(this.isRejected())j.rejectionReason=this.reason(),j.isRejected=!0;return j},g.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new O(this).promise()},g.prototype.error=function(j){return this.caught(U.originatesFromRejection,j)},g.getNewLibraryCopy=of.exports,g.is=function(j){return j instanceof g},g.fromNode=g.fromCallback=function(j){var u=new g(X);u._captureStackTrace();var p=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,d=c(j)(k(u,p));if(d===C)u._rejectCallback(d.e,!0);if(!u._isFateSealed())u._setAsyncGuaranteed();return u},g.all=function(j){return new O(j).promise()},g.cast=function(j){var u=F(j);if(!(u instanceof g))u=new g(X),u._captureStackTrace(),u._setFulfilled(),u._rejectionHandler0=j;return u},g.resolve=g.fulfilled=g.cast,g.reject=g.rejected=function(j){var u=new g(X);return u._captureStackTrace(),u._rejectCallback(j,!0),u},g.setScheduler=function(j){if(typeof j!=="function")throw new Z("expecting a function but got "+U.classString(j));return G.setScheduler(j)},g.prototype._then=function(j,u,p,d,q0){var t=q0!==void 0,H0=t?q0:new g(X),L0=this._target(),T0=L0._bitField;if(!t){if(H0._propagateFrom(this,3),H0._captureStackTrace(),d===void 0&&(this._bitField&2097152)!==0)if((T0&50397184)!==0)d=this._boundValue();else d=L0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,H0)}var C0=I();if((T0&50397184)!==0){var j0,i0,K0=L0._settlePromiseCtx;if((T0&33554432)!==0)i0=L0._rejectionHandler0,j0=j;else if((T0&16777216)!==0)i0=L0._fulfillmentHandler0,j0=u,L0._unsetRejectionIsUnhandled();else K0=L0._settlePromiseLateCancellationObserver,i0=new V("late cancellation observer"),L0._attachExtraTrace(i0),j0=u;G.invoke(K0,L0,{handler:C0===null?j0:typeof j0==="function"&&U.domainBind(C0,j0),promise:H0,receiver:d,value:i0})}else L0._addCallbacks(j,u,H0,d,C0);return H0},g.prototype._length=function(){return this._bitField&65535},g.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},g.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},g.prototype._setLength=function(j){this._bitField=this._bitField&-65536|j&65535},g.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},g.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},g.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},g.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},g.prototype._isFinal=function(){return(this._bitField&4194304)>0},g.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},g.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},g.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},g.prototype._setAsyncGuaranteed=function(){if(G.hasCustomScheduler())return;this._bitField=this._bitField|134217728},g.prototype._receiverAt=function(j){var u=j===0?this._receiver0:this[j*4-4+3];if(u===J)return;else if(u===void 0&&this._isBound())return this._boundValue();return u},g.prototype._promiseAt=function(j){return this[j*4-4+2]},g.prototype._fulfillmentHandlerAt=function(j){return this[j*4-4+0]},g.prototype._rejectionHandlerAt=function(j){return this[j*4-4+1]},g.prototype._boundValue=function(){},g.prototype._migrateCallback0=function(j){var{_bitField:u Line truncated
path = %s
syscall = %s
fstream_type = %s
@@ -288,22 +288,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",z.stack,z.path,z.syscall,z.fstream_type,z.fstream_path,z.fstream_unc_path,z.fstream_class,z.fstream_stack.join(`
`));else q.emit("warn",z)};p7.prototype.info=function($,Y){this.emit("info",$,Y)};p7.prototype.error=function($,Y,q){var z=_N0($,Y,this);if(q)throw z;else this.emit("error",z)};function _N0($,Y,q){if(!($ instanceof Error))$=Error($);if($.code=$.code||Y,$.path=$.path||q.path,$.fstream_type=$.fstream_type||q.type,$.fstream_path=$.fstream_path||q.path,q._path!==q.path)$.fstream_unc_path=$.fstream_unc_path||q._path;if(q.linkpath)$.fstream_linkpath=$.fstream_linkpath||q.linkpath;return $.fstream_class=$.fstream_class||q.constructor.name,$.fstream_stack=$.fstream_stack||Error().stack.split(/\n/).slice(3).map(function(z){return z.replace(/^ {4}at /,"")}),$}});var zZ=M((F34,CN0)=>{CN0.exports=pA1;function pA1($){var Y=["Directory","File","SymbolicLink","Link","BlockDevice","CharacterDevice","FIFO","Socket"],q;if($.type&&Y.indexOf($.type)!==-1)return $[$.type]=!0,$.type;for(var z=0,J=Y.length;z<J;z++){q=Y[z];var U=$[q]||$["is"+q];if(typeof U==="function")U=U.call($);if(U)return $[q]=!0,$.type=q,q}return null}});var Sb=M((O34,vN0)=>{vN0.exports=JZ;var dA1=m8(),mA1=m0(),gb=mY();mA1(JZ,gb);function JZ($){var Y=this;if(!(Y instanceof JZ))throw Error("LinkReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="SymbolicLink"&&$.SymbolicLink))throw Error("Non-link type "+$.type);gb.call(Y,$)}JZ.prototype._stat=function($){var Y=this;dA1.readlink(Y._path,function(q,z){if(q)return Y.error(q);Y.linkpath=Y.props.linkpath=z,Y.emit("linkpath",z),gb.prototype._stat.call(Y,$)})};JZ.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var xb=M((M34,SN0)=>{SN0.exports=J9;var gN0=m8(),lA1=m0(),UZ=m("path"),yb=mY(),hN0=m("assert").ok;lA1(J9,yb);function J9($){var Y=this;if(!(Y instanceof J9))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;yb.call(this,$)}J9.prototype._getEntries=function(){var $=this;if($._gotEntries)return;$._gotEntries=!0,gN0.readdir($._path,function(Y,q){if(Y)return $.error(Y);if($.entries=q,$.emit("entries",q),$._paused)$.once("resume",z);else z();function z(){if($._length=$.entries.length,typeof $.sort==="function")$.entries=$.entries.sort($.sort.bind($));$._read()}})};J9.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=UZ.resolve($._path,$.entries[$._index]);hN0(Y!==$._path),hN0($.entries[$._index]),$._currentEntry=Y,gN0[$.props.follow?"stat":"lstat"](Y,function(q,z){if(q)return $.error(q);var J=$._proxy||$;z.path=Y,z.basename=UZ.basename(Y),z.dirname=UZ.dirname(Y);var U=$.getChildProps.call(J,z);U.path=Y,U.basename=UZ.basename(Y),U.dirname=UZ.dirname(Y);var I=yb(U,z);$._currentEntry=I,I.on("pause",function(G){if(!$._paused&&!I._disowned)$.pause(G)}),I.on("resume",function(G){if($._paused&&!I._disowned)$.resume(G)}),I.on("stat",function(G){if($.emit("_entryStat",I,G),I._aborted)return;if(I._paused)I.once("resume",function(){$.emit("entryStat",I,G)});else $.emit("entryStat",I,G)}),I.on("ready",function G(){if($._paused)return I.pause($),$.once("resume",G);if(I.type==="Socket")$.emit("socket",I);else $.emitEntry(I)});var Q=!1;I.on("close",K),I.on("disown",K);function K(){if(Q)return;if(Q=!0,$.emit("childEnd",I),$.emit("entryEnd",I),$._currentEntry=null,!$._paused)$._read()}I.on("error",function(G){if(I._swallowErrors)$.warn(G),I.emit("end"),I.emit("close");else $.emit("error",G)}),["child","childEnd","warn"].forEach(function(G){I.on(G,$.emit.bind($,G))})})};J9.prototype.disown=function($){if($.emit("beforeDisown"),$._disowned=!0,$.parent=$.root=null,$===this._currentEntry)this._currentEntry=null;$.emit("disown")};J9.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}};J9.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",$)};J9.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()};J9.prototype.emitEntry=function($){this.emit("entry",$),this.emit("child",$)}});var kb=M((N34,uN0)=>{uN0.exports=lY;var oA1=m8(),rA1=m0(),yN0=mY(),xN0={EOF:!0},kN0={CLOSE:!0};rA1(lY,yN0);function lY($){var Y=this;if(!(Y instanceof lY))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,yN0.call(Y,$)}lY.prototype._getStream=function(){var $=this,Y=$._stream=oA1.createReadStream($._path,$.pro 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(kN0),$._read();else $.emit("close")}),Y.on("error",function(q){$.emit("error",q)}),$._read()};lY.prototype._read=function(){var $=this;if($._paused)return;if(!$._stream)return $._getStream();if($._buffer.length){var Y=$._buffer;for(var q=0,z=Y.length;q<z;q++){var J=Y[q];if(J===xN0)$.emit("end");else if(J===kN0)$.emit("close");else $.emit("data",J);if($._paused){$._buffer=Y.slice(q);return}}$._buffer.length=0}};lY.prototype.pause=function($){var Y=this;if(Y._paused)return;if($=$||Y,Y._paused=!0,Y._stream)Y._stream.pause();Y.emit("pause",$)};lY.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 iN0=M((D34,bN0)=>{bN0.exports=vN;var sA1=m0(),fN0=mY();sA1(vN,fN0);function vN($){var Y=this;if(!(Y instanceof vN))throw Error("SocketReader must be called as constructor.");if(!($.type==="Socket"&&$.Socket))throw Error("Non-socket type "+$.type);fN0.call(Y,$)}vN.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var fb=M((P34,nN0)=>{nN0.exports=oY;var ub=mY(),tA1=zZ(),aA1=m0(),eA1=m8();aA1(oY,ub);function oY($){var Y=this;if(!(Y instanceof oY))throw Error("ProxyReader must be called as constructor.");Y.props=$,Y._buffer=[],Y.ready=!1,ub.call(Y,$)}oY.prototype._stat=function(){var $=this,Y=$.props,q=Y.follow?"stat":"lstat";eA1[q](Y.path,function(z,J){var U;if(z||!J)U="File";else U=tA1(J);Y[U]=!0,Y.type=$.type=U,$._old=J,$._addProxy(ub(Y,J))})};oY.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(z){$.on(z,Y.emit.bind(Y,z))}),Y.emit("proxy",$),$.on("ready",function(){Y.ready=!0,Y.emit("ready")});var q=Y._buffer;Y._buffer.length=0,q.forEach(function(z){$[z[0]].apply($,z[1])})};oY.prototype.pause=function(){return this._proxyTarget?this._proxyTarget.pause():!1};oY.prototype.resume=function(){return this._proxyTarget?this._proxyTarget.resume():!1}});var mY=M((A34,dN0)=>{dN0.exports=O5;var $B1=m8(),YB1=m("stream").Stream,qB1=m0(),bb=m("path"),ib=zZ(),hN=O5.hardLinks={},cN0=CN();qB1(O5,cN0);var pN0=Sb();function O5($,Y){var q=this;if(!(q instanceof O5))return new O5($,Y);if(typeof $==="string")$={path:$};var z,J;if($.type&&typeof $.type==="function")z=$.type,J=z;else z=ib($),J=O5;if(Y&&!z)z=ib(Y),$[z]=!0,$.type=z;switch(z){case"Directory":J=xb();break;case"Link":case"File":J=kb();break;case"SymbolicLink":J=pN0;break;case"Socket":J=iN0();break;case null:J=fb();break}if(!(q instanceof J))return new J($);if(cN0.call(q),!$.path)q.error("Must provide a path",null,!0);if(q.readable=!0,q.writable=!1,q.type=z,q.props=$,q.depth=$.depth=$.depth||0,q.parent=$.parent||null,q.root=$.root||$.parent&&$.parent.root||q,q._path=q.path=bb.resolve($.path),process.platform==="win32"){if(q.path=q._path=q.path.replace(/\?/g,"_"),q._path.length>=260)q._swallowErrors=!0,q._path="\\\\?\\"+q.path.replace(/\//g,"\\")}if(q.basename=$.basename=bb.basename(q.path),q.dirname=$.dirname=bb.dirname(q.path),$.parent=$.root=null,q.size=$.size,q.filter=typeof $.filter==="function"?$.filter:null,$.sort==="alpha")$.sort=zB1;q._stat(Y)}function zB1($,Y){return $===Y?0:$.toLowerCase()>Y.toLowerCase()?1:$.toLowerCase()<Y.toLowerCase()?-1:$>Y?1:-1}O5.prototype._stat=function($){var Y=this,q=Y.props,z=q.follow?"stat":"lstat";if($)process.nextTick(J.bind(null,null,$));else $B1[z](Y._path,J);function J(U,I){if(U)return Y.error(U);if(Object.keys(I).forEach(function(X){q[X]=I[X]}),Y.size!==void 0&&q.size!==Y.size)return Y.error("incorrect size");Y.size=q.size;var Q=ib(q),K=q.hardlinks!==!1;if(K&&Q!=="Directory"&&q.nlink&&q.nlink>1){var G=q.dev+":"+q.ino;if(hN[G]===Y._path||!hN[G])hN[G]=Y._path;else Q=Y.type=Y.props.type="Link",Y.Link=Y.props.Link=!0,Y.linkpath=Y.props.linkpath=hN[G],Y._stat=Y._read=pN0.prototype._read}if(Y.type&&Y.type!==Q)Y.error("Unexpected type: "+Q);if(Y.filter){var H=Y._proxy||Y;if(!Y.filter.call(H,H,q)){if(!Y._disowned)Y.abort(),Y.emit("end"),Y.emit("close");return}}var Z=["_stat","stat","ready"],V=0;(function X(){if(Y._aborted){Y.emit("end"),Y.emit("close");return}if(Y._paused&&Y.type!=="Directory"){Y.once("resume",X);return}var L=Z[V++];if(!L)return Y._read();Y.emit(L,q),X()})()}};O5.prototype.pipe=function($){var Y=this;if(typeof $.add==="function")Y.on("entry",function(q){var z=$.add(q);if(z===!1)Y.pause()});return YB1.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 db=M((B34,eN0)=>{e 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);cN.prototype._finish.call($)}});var qi=M((n34,nD0)=>{nD0.exports=r7;var Yi=SU(),CB1=zZ(),vB1=m0(),hB1=iN(),gB1=m("fs");vB1(r7,Yi);function r7($){var Y=this;if(!(Y instanceof r7))throw Error("ProxyWriter must be called as constructor.");Y.props=$,Y._needDrain=!1,Yi.call(Y,$)}r7.prototype._stat=function(){var $=this,Y=$.props,q=Y.follow?"stat":"lstat";gB1[q](Y.path,function(z,J){var U;if(z||!J)U="File";else U=CB1(J);Y[U]=!0,Y.type=$.type=U,$._old=J,$._addProxy(Yi(Y,J))})};r7.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(z){$.on(z,Y.emit.bind(Y,z))}),Y.emit("proxy",$);var q=Y._buffer;if(q.forEach(function(z){$[z[0]].apply($,z[1])}),Y._buffer.length=0,Y._needsDrain)Y.emit("drain")};r7.prototype.add=function($){if(hB1($),!this._proxy)return this._buffer.push(["add",[$]]),this._needDrain=!0,!1;return this._proxy.add($)};r7.prototype.write=function($){if(!this._proxy)return this._buffer.push(["write",[$]]),this._needDrain=!0,!1;return this._proxy.write($)};r7.prototype.end=function($){if(!this._proxy)return this._buffer.push(["end",[$]]),!1;return this._proxy.end($)}});var SU=M((c34,tD0)=>{tD0.exports=u$;var k$=m8(),SB1=m0(),yB1=db(),xB1=sb(),GZ=m("path"),pD0=process.platform==="win32"?0:process.umask(),dD0=zZ(),mD0=CN();SB1(u$,mD0);u$.dirmode=parseInt("0777",8)&~pD0;u$.filemode=parseInt("0666",8)&~pD0;var kB1=ab(),uB1=eb(),fB1=$i(),bB1=qi();function u$($,Y){var q=this;if(typeof $==="string")$={path:$};var z=dD0($),J=u$;switch(z){case"Directory":J=kB1;break;case"File":J=fB1;break;case"Link":case"SymbolicLink":J=uB1;break;case null:default:J=bB1;break}if(!(q instanceof J))return new J($);if(mD0.call(q),!$.path)q.error("Must provide a path",null,!0);if(q.type=$.type,q.props=$,q.depth=$.depth||0,q.clobber=$.clobber===!1?$.clobber:!0,q.parent=$.parent||null,q.root=$.root||$.parent&&$.parent.root||q,q._path=q.path=GZ.resolve($.path),process.platform==="win32"){if(q.path=q._path=q.path.replace(/\?/g,"_"),q._path.length>=260)q._swallowErrors=!0,q._path="\\\\?\\"+q.path.replace(/\//g,"\\")}if(q.basename=GZ.basename($.path),q.dirname=GZ.dirname($.path),q.linkpath=$.linkpath||null,$.parent=$.root=null,q.size=$.size,typeof $.mode==="string")$.mode=parseInt($.mode,8);q.readable=!1,q.writable=!0,q._buffer=[],q.ready=!1,q.filter=typeof $.filter==="function"?$.filter:null,q._stat(Y)}u$.prototype._create=function(){var $=this;k$[$.props.follow?"stat":"lstat"]($._path,function(Y){if(Y)return $.warn("Cannot create "+$._path+`
Unsupported type: `+$.type,"ENOTSUP");$._finish()})};u$.prototype._stat=function($){var Y=this,q=Y.props,z=q.follow?"stat":"lstat",J=Y._proxy||Y;if($)U(null,$);else k$[z](Y._path,U);function U(I,Q){if(Y.filter&&!Y.filter.call(J,J,Q)){Y._aborted=!0,Y.emit("end"),Y.emit("close");return}if(I||!Q)return zi(Y);Y._old=Q;var K=dD0(Q);if(K!==Y.type||Y.type==="File"&&Q.nlink>1)return yB1(Y._path,function(G){if(G)return Y.error(G);Y._old=null,zi(Y)});zi(Y)}};function zi($){xB1(GZ.dirname($._path),u$.dirmode,function(Y,q){if(Y)return $.error(Y);return $._madeDir=q,$._create()})}function lD0($,Y,q,z,J){var U=Y.mode,I=Y.follow||$.type!=="SymbolicLink"?"chmod":"lchmod";if(!k$[I])return J();if(typeof U!=="number")return J();var Q=q.mode&parseInt("0777",8);if(U=U&parseInt("0777",8),U===Q)return J();k$[I](z,U,J)}function oD0($,Y,q,z,J){if(process.platform==="win32")return J();if(!process.getuid||process.getuid()!==0)return J();if(typeof Y.uid!=="number"&&typeof Y.gid!=="number")return J();if(q.uid===Y.uid&&q.gid===Y.gid)return J();var U=$.props.follow||$.type!=="SymbolicLink"?"chown":"lchown";if(!k$[U])return J();if(typeof Y.uid!=="number")Y.uid=q.uid;if(typeof Y.gid!=="number")Y.gid=q.gid;k$[U](z,Y.uid,Y.gid,J)}function rD0($,Y,q,z,J){if(!k$.utimes||process.platform==="win32")return J();var U=Y.follow||$.type!=="SymbolicLink"?"utimes":"lutimes";if(U==="lutimes"&&!k$[U])U="utimes";if(!k$[U])return J();var{atime:I,mtime:Q}=q,K=Y.atime,G=Y.mtime;if(K===void 0)K=I;if(G===void 0)G=Q;if(!cD0(K))K=new Date(K);if(!cD0(G))K=new Date(G);if(K.getTime()===I.getTime()&&G.getTime()===Q.getTime())return J();k$[U](z,K,G,J)}u$.prototype._finish=function(){var $=this;if($._finishing)return;$._finishing=!0;var Y=0,q=null,z=!1;if($._old)$._old.atime=new Date(0),$._old.mtime=new Date(0),U($._old);else{var J=$.props.follow?"stat":"lstat";k$[J]($._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);U($._old=K)})}return;function U(Q){Y+=3,lD0($,$.props,Q,$._path,I("chmod")),oD0($,$.props,Q,$._path,I("chown")),rD0($,$.props,Q,$._path,I("utimes"))}function I(Q){return function(K){if(q)return;if(K)return K.fstream_finish_call=Q,$.error(q=K);if(--Y>0)return;if(z)return;if(z=!0,!$._madeDir)return G();else sD0($,$._path,G);function G(H){if(H)return H.fstream_finish_call="setupMadeDir",$.error(H);$.emit("end"),$.emit("close")}}}};function sD0($,Y,q){var z=$._madeDir,J=GZ.dirname(Y);iB1($,J,function(U){if(U)return q(U);if(J===z)return q();sD0($,J,q)})}function iB1($,Y,q){var z={};Object.keys($.props).forEach(function(Q){if(z[Q]=$.props[Q],Q==="mode"&&$.type!=="Directory")z[Q]=z[Q]|parseInt("0111",8)});var J=3,U=null;k$.stat(Y,function(Q,K){if(Q)return q(U=Q);lD0($,z,K,Y,I),oD0($,z,K,Y,I),rD0($,z,K,Y,I)});function I(Q){if(U)return;if(Q)return q(U=Q);if(--J===0)return q()}}u$.prototype.pipe=function(){this.error("Can't pipe from writable stream")};u$.prototype.add=function(){this.error("Can't add to non-Directory type")};u$.prototype.write=function(){return!0};function nB1($){return Object.prototype.toString.call($)}function cD0($){return typeof $==="object"&&nB1($)==="[object Date]"}});var Ki=M((cB1)=>{cB1.Abstract=CN();cB1.Reader=mY();cB1.Writer=SU();cB1.File={Reader:kb(),Writer:$i()};cB1.Dir={Reader:xb(),Writer:ab()};cB1.Link={Reader:Sb(),Writer:eb()};cB1.Proxy={Reader:fb(),Writer:qi()};cB1.Reader.Dir=cB1.DirReader=cB1.Dir.Reader;cB1.Reader.File=cB1.FileReader=cB1.File.Reader;cB1.Reader.Link=cB1.LinkReader=cB1.Link.Reader;cB1.Reader.Proxy=cB1.ProxyReader=cB1.Proxy.Reader;cB1.Writer.Dir=cB1.DirWriter=cB1.Dir.Writer;cB1.Writer.File=cB1.FileWriter=cB1.File.Writer;cB1.Writer.Link=cB1.LinkWriter=cB1.Link.Writer;cB1.Writer.Proxy=cB1.ProxyWriter=cB1.Proxy.Writer;cB1.collect=iN()});var eD0=M((e34,aD0)=>{aD0.exports=tB1;var mB1=DN(),lB1=Ki().Writer,Gi=m("path"),oB1=m("stream"),rB1=vb(),sB1=n7();function tB1($){$.path=Gi.resolve(Gi.normalize($.path));var Y=new mB1($),q=new oB1.Writable({objectMode:!0});q._write=function(J,U,I){if(J.type=="Directory")return I();var Q=Gi.join($.path,J.path);if(Q.indexOf($.path)!=0)return I();let K=$.getWriter?$.getWriter({path:Q}):lB1({path:Q});J.pipe(K).on("error",I).on("close",I)};var z=rB1(Y,q);return Y.once("crx-header",function(J){z.crxHeader=J}),Y.pipe(q).on("finish",function(){z.emit("close")}),z.promise=function(){return new sB1(function(J,U){z.on("close",J),z.on("error",U)})},z}});var $P0=M(($74,pN)=>{var N6=function($){var Y=1e7,q=7,z=9007199254740992,J=V(z),U="0123456789abcdefghijklmnopqrstuvwxyz",I=typeof BigInt==="function";function Q(N,D,h,x){if(typeof N>"u")return Q[0];if(typeof D<"u")return+D===10&&!h?w0(N):F1(N,D,h,x);return w0(N)}function K(N,D){this.value=N,this.sign=D,this.isSmall=!1}K.prototype=Object.create(Q.prototype);function G(N){this.value=N,this.sign=N<0,this.isSmall=!0}G.prototype=Object.create(Q.prototype);function H(N){th 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 I4=m("fs"),sN=m("os"),D6=m("path"),XP0=m("crypto"),U9={fs:I4.constants,os:sN.constants},FP0=/XXXXXX/,OP0=(U9.O_CREAT||U9.fs.O_CREAT)|(U9.O_EXCL||U9.fs.O_EXCL)|(U9.O_RDWR||U9.fs.O_RDWR),DT1=sN.platform()==="win32",PT1=U9.EBADF||U9.os.errno.EBADF,AT1=U9.ENOENT||U9.os.errno.ENOENT,xU=[],MP0=I4.rmdirSync.bind(I4),NP0=!1;function BT1($,Y){return I4.rm($,{recursive:!0},Y)}function DP0($){return I4.rmSync($,{recursive:!0})}function Vi($,Y){let q=kU($,Y),z=q[0],J=q[1];ST1(z,function(U,I){if(U)return J(U);let Q=I.tries;(function K(){try{let G=AP0(I);I4.stat(G,function(H){if(!H){if(Q-- >0)return K();return J(Error("Could not get a unique tmp filename, max tries reached "+G))}J(null,G)})}catch(G){J(G)}})()})}function Li($){let Y=kU($),q=Y[0],z=yT1(q),J=z.tries;do{let U=AP0(z);try{I4.statSync(U)}catch(I){return U}}while(J-- >0);throw Error("Could not get a unique tmp filename, max tries reached")}function TT1($,Y){let q=kU($,Y),z=q[0],J=q[1];Vi(z,function(I,Q){if(I)return J(I);I4.open(Q,OP0,z.mode||384,function(G,H){if(G)return J(G);if(z.discardDescriptor)return I4.close(H,function(V){return J(V,Q,void 0,Wi(Q,-1,z,!1))});else{let Z=z.discardDescriptor||z.detachDescriptor;J(null,Q,H,Wi(Q,Z?-1:H,z,!1))}})})}function ET1($){let Y=kU($),q=Y[0],z=q.discardDescriptor||q.detachDescriptor,J=Li(q),U=I4.openSync(J,OP0,q.mode||384);if(q.discardDescriptor)I4.closeSync(U),U=void 0;return{name:J,fd:U,removeCallback:Wi(J,z?-1:U,q,!0)}}function jT1($,Y){let q=kU($,Y),z=q[0],J=q[1];Vi(z,function(I,Q){if(I)return J(I);I4.mkdir(Q,z.mode||448,function(G){if(G)return J(G);J(null,Q,PP0(Q,z,!1))})})}function _T1($){let Y=kU($),q=Y[0],z=Li(q);return I4.mkdirSync(z,q.mode||448),{name:z,removeCallback:PP0(z,q,!0)}}function RT1($,Y){let q=function(z){if(z&&!Xi(z))return Y(z);Y()};if(0<=$[0])I4.close($[0],function(){I4.unlink($[1],q)});else I4.unlink($[1],q)}function CT1($){let Y=null;try{if(0<=$[0])I4.closeSync($[0])}catch(q){if(!xT1(q)&&!Xi(q))throw q}finally{try{I4.unlinkSync($[1])}catch(q){if(!Xi(q))Y=q}}if(Y!==null)throw Y}function Wi($,Y,q,z){let J=rN(CT1,[Y,$],z),U=rN(RT1,[Y,$],z,J);if(!q.keep)xU.unshift(J);return z?J:U}function PP0($,Y,q){let z=Y.unsafeCleanup?BT1:I4.rmdir.bind(I4),J=Y.unsafeCleanup?DP0:MP0,U=rN(J,$,q),I=rN(z,$,q,U);if(!Y.keep)xU.unshift(U);return q?U:I}function rN($,Y,q,z){let J=!1;return function U(I){if(!J){let Q=z||U,K=xU.indexOf(Q);if(K>=0)xU.splice(K,1);if(J=!0,q||$===MP0||$===DP0)return $(Y);else return $(Y,I||function(){})}}}function vT1(){if(!NP0)return;while(xU.length)try{xU[0]()}catch($){}}function VP0($){let Y=[],q=null;try{q=XP0.randomBytes($)}catch(z){q=XP0.pseudoRandomBytes($)}for(let z=0;z<$;z++)Y.push("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[q[z]%62]);return Y.join("")}function o8($){return typeof $>"u"}function kU($,Y){if(typeof $==="function")return[{},$];if(o8($))return[{},Y];let q={};for(let z of Object.getOwnPropertyNames($))q[z]=$[z];return[q,Y]}function hT1($,Y,q){let z=D6.isAbsolute($)?$:D6.join(Y,$);I4.stat(z,function(J){if(J)I4.realpath(D6.dirname(z),function(U,I){if(U)return q(U);q(null,D6.join(I,D6.basename(z)))});else I4.realpath(z,q)})}function gT1($,Y){let q=D6.isAbsolute($)?$:D6.join(Y,$);try{return I4.statSync(q),I4.realpathSync(q)}catch(z){let J=I4.realpathSync(D6.dirname(q));return D6.join(J,D6.basename(q))}}function AP0($){let Y=$.tmpdir;if(!o8($.name))return D6.join(Y,$.dir,$.name);if(!o8($.template))return D6.join(Y,$.dir,$.template).replace(FP0,VP0(6));let q=[$.prefix?$.prefix:"tmp","-",process.pid,"-",VP0(12),$.postfix?"-"+$.postfix:""].join("");return D6.join(Y,$.dir,q)}function Zi($,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 BP0($){if(!o8($.name)){let Y=$.name;if(D6.isAbsolute(Y))throw Error(`name option must not contain an absolute path, found "${Y}".`);let q=D6.basename(Y);if(q===".."||q==="."||q!==Y)throw Error(`name option must not contain a path, found "${Y}".`)}if(!o8($.template)){if(typeof $.template!=="string")throw Error(`template option must be a string, got "${typeof $.template}".`);if(!$.template.match(FP0))throw Error(`Invalid template, found "${$.template}".`)}if(!o8($.tries)&&isNaN($.tries)||$.tries<0)throw Error(`Invalid tries, found "${$.tries}".`);$.tries=o8($.name)?$.tries||3:1,$.keep=!!$.keep,$.detachDescriptor=!!$.detachDescriptor,$.discardDescriptor=!!$.discardDescriptor,$.unsafeCleanup=!!$.unsafeCleanup,$.prefix=o8($.prefix)?"":Zi("prefix",$.prefix),$.postfix=o8($.postfix)?"":Zi("postfix",$.postfix),$.template=o8($.template)?void 0:Zi("template",$.template)}function LP0($,Y,q,z){if(o8(Y))return z(null);hT1(Y,q,function(J,U){if(J)return z(J);let I=D6.relative(q,U);if(I.startsWith("..")||D6.isAbsolute(I))return z(Error(`${$} option must be relative to "${q}", found "${I}".`));z(null,I)})}function wP0($,Y,q){if(o8(Y))return;let z=gT1(Y,q),J=D6.relative(q,z);if(J.startsWith("..")||D6.isAbsolute(J))throw ELine truncated
`)}let z=[];Y.forEach((J,U)=>{let I=$.length+U+1,Q=U===0?"⏳ ":"";z.push(`${Q}${I}. ${J}`)});for(let J=$.length-1;J>=0;J--){let U=J+1;z.push(`${U}. ${$[J]}`)}return z.join(`
`)}function Ei($,Y,q,z,J){let U=$?.operator||Y?.operator||q?.operator,I=U?.name||U?.id||q?.operatorName||"",Q=($?.nodeName||Y?.fromNodeName||Y?.nodeName||q?.nodeName||"").trim();if(Q==="合思审批节点"||Q==="外部审批节点"||Q.includes("合思审批")||Q.includes("外部审批"))Q="";if((!Q||Q==="提交人"||Q==="审批节点")&&I&&z){let F=z.find((O)=>O.operator?.name===I&&O.nodeName&&O.nodeName.trim()!=="提交人"&&!O.isEbot&&O.rawAction!=="freeflow.reject");if(F?.nodeName)Q=F.nodeName.trim()}let G=$?.comment||Y?.reason||q?.rejectComment||"修改";if(G.includes(":")){let F=G.split(":");if(F.length>1)G=F.slice(1).join(":").trim()}let H=G;if(Q&&I)H=`${Q}(${I}) ❌: ${G}`;else if(I)H=`${I} ❌: ${G}`;else if(Q)H=`${Q} ❌: ${G}`;else H=G;let Z=$?.rejectTargetNodeName||Y?.targetNodeName||"提交人",V=$?.rejectTargetOperator?.name||Y?.targetOperator?.name||J?.submitter?.name,X=V?`${Z}(${V})`:Z,L=$?.resubmitRuleText||Y?.resubmitRuleText||(I?`重新提交后由${I}继续审批`:"重新提交后继续审批");return{comment:`${H}
↳ 驳回至: ${X}
↳ ${L}`,operator:U}}function QA0($){if(!$)return[];let Y=$.pending||[],q=String($.rawState||"").toUpperCase(),z=String($.state||"").toUpperCase(),J=[];if(Y.length>0)for(let U of Y){let I=U.approver?.name||U.approver?.id||"待定",Q=(U.name||$.currentNode||"").trim(),K=Q?`${Q}(${I})`:I,H=U.type?.toUpperCase()==="PAYING"||Q.includes("支付")||q==="PAYING"||z==="支付中"?"待支付":"待审批";J.push(`${K}: ${H}`)}else if($.currentNode?.trim()){let I=$.currentNode.includes("支付")||q==="PAYING"||z==="支付中"?"待支付":"待审批";J.push(`${$.currentNode.trim()}: ${I}`)}return J}function tY($,Y){let q=new Map;if(!$||$.length===0)return q;if(!Y){for(let X of $){let w=(X.result||{}).decision||X.aiDecision||"-";q.set(X.id,{recordId:X.id,sourceDocumentSN:X.sourceDocumentSN,taskMode:X.taskMode,aiDecision:IA0(typeof w==="string"?w:"-"),aiAction:"-",eHumanAction:"-",eHumanComment:"-",auditDrift:!1})}return q}let z=[...$].sort((X,L)=>(Number(X.createdAt)||0)-(Number(L.createdAt)||0)),J=Y.history||[],U=String(Y.rawState||"").toUpperCase(),I=String(Y.state||"").toUpperCase(),Q=U==="DRAFT"||U==="REVOKED"||U==="CANCELED"||U==="CANCELLED"||I==="草稿"||I==="已撤回"||I==="已取消",K=U==="REJECTED"||U==="TERMINATED"||I==="审批驳回"||I==="已驳回",G=!Q&&!K&&(U==="PAID"||I==="已支付"||J.some((X)=>!X.isEbot&&(X.rawAction==="freeflow.pay"||X.action==="支付成功"||X.action==="支付完成"))),H=!Q&&!K&&!G&&(U==="PAYING"||I==="支付中"||(Y.pending||[]).some((X)=>X.isCurrent&&(X.type?.toUpperCase()==="PAYING"||X.name?.includes("支付")))||Y.currentNode?.includes("支付")===!0),V=G||!Q&&!K&&!H&&(U==="COMPLETED"||U==="APPROVED"||I==="已完成"||I==="审批通过");for(let X=0;X<z.length;X++){let L=z[X];if(!L)continue;let w=Number(L.createdAt)||0,F=L.document||{},O=L.manualApprovalRecord||L.result?.manualApprovalRecord||F.manualApprovalRecord||{},P=typeof L.sourceExtendData?.nodeId==="string"?String(L.sourceExtendData.nodeId):void 0,B=typeof O.nodeId==="string"?String(O.nodeId):void 0,A=B?decodeURIComponent(B).replace(/^hcnode_/,"").replace(/_r\d+$/,""):void 0,E=P||A,y=E?J.find((w0)=>w0.nodeId&&(w0.nodeId===E||E.includes(w0.nodeId))):void 0,v=y?.time??w,k=z[X+1],C=k?Number(k.createdAt)||1/0:1/0,c=X===z.length-1,n=J.find((w0)=>(w0.time??0)>v+5000&&w0.isEbot&&(w0.nodeName?.includes("智能")||w0.nodeName?.includes("AI")||w0.action?.includes("智能")||w0.comment?.includes("AI")||w0.comment?.includes("approval-result"))&&!w0.nodeName?.includes("费用标准检查")&&!w0.nodeName?.includes("标准检查")&&!w0.nodeName?.includes("预算"));if(n){if(c=!1,(n.time??1/0)<C)C=n.time}let g=L.result||{},b=g.decision||L.aiDecision||"-",i=typeof b==="string"?b:"-",$0=i.toUpperCase(),j=$0==="REJECT"||$0==="驳回",u=$0==="APPROVE"||$0==="通过",p=$0==="EXEMPT_APPROVE"||$0==="免审通过"||$0==="备注通过",d=L.taskMode||L.finalExecutionMode||"",t=String(d).toLowerCase().includes("auto")||L.finalExecutionMode==="automatic"||d==="automatic"||d==="fully_automatic",H0="-";if(u||p)H0="添加评论";else if(j)H0=t?"驳回":"添加评论";else if($0==="REVIEW"||$0==="转交复核")H0="转交复核";let L0=typeof O.status==="object"&&O.status!==null?String(O.status.type||O.status.label||"").toUpperCase():"",T0=typeof O.status==="object"&&O.status!==null?String(O.status.sourceStatus||""):"",C0=F.manualApprovalStatus||g.manualApprovalStatus||L.manualApprovalStatus,j0=typeof C0==="string"?C0.toUpperCase():"",i0=j0==="CANCELLED"||j0==="CANCELED"||j0==="已取消"||j0==="已撤回"||j0==="REVOKED"||L0==="CANCELLED"||L0==="CANCELED"||T0.includes("撤回")||T0.includes("取消"),K0=j0==="APPROVED"||j0==="已支付/审批完成"||j0==="已通过"||j0==="已完成"||j0==="已支付"||L0==="APPROVED",f0=!(T0.includes("补偿")||T0.includes("已支付"))&&(j0==="TERMINATED"||j0==="REJECTED"||j0==="REJECT"||j0==="已驳回"||j0==="被驳回"||L0==="TERMINATED"||L0==="REJECTED"||L0==="已驳回"||L0==="被驳回"),c0=y?1000:60000,C1=J.filter((w0)=>{let o=w0.time??0;return o>=v-c0&&o<C}),a0="-",r1="-",F1=!1,b1,$1,J6=u||p,a8=J.filter((w0)=>(w0.time??0)>v+5000),U6=a8.some((w0)=>w0.rawAction==="freeflow.retract"||w0.action==="单据撤回"),e8=a8.some((w0)=>w0.rawAction==="freeflow.submit"||w0.action==="提交送审");if(J6&&c&&(U6||e8))F1=!0,b1="AI通过后单据发生撤回/修改重提,后续未经AI复审";if(t&&j)a0="无操作",r1="-";else{let w0=C1.filter((D)=>(D.time??0)>=v-1000&&!D.isEbot&&D.rawAction!=="freeflow.submit"&&D.action!=="提交送审"&&!((D.rawAction==="freeflow.comment"||D.action==="发表评论")&&!D.comment)&&!((D.rawAction==="freeflow.print"||D.action==="打印提醒")&&!D.comment)&&!(D.rawAction==="freeflow.carbonCopy"||D.rawAction==="freeflow.cc"||D.action==="抄送通知")),o=w0.find((D)=>D.rawAction==="freeflow.retract"||D.action==="单据撤回"),N=w0.find((D)=>D.rawAction==="freeflow.reject"||D.action==="审批驳回");if(!c)if(N||!Y&&f0){a0="审批驳回",F1=!1,b1=void 0;let D=Ei(N,void 0,O,J,Y); Line truncated
`,{mode:384}),Y}function bi($){let Y=EA0();for(let q of Y){if(!X$(q))continue;for(let z of GD(q).filter((J)=>J.endsWith(".json")).filter((J)=>!J.startsWith("example."))){let J=Q9(q,z);try{let U=ZD(J,"utf-8"),I=JSON.parse(U);if(I&&typeof I==="object"&&I.id===$)return J}catch{}}}return}function e7($,Y){let q=bi($);if(!q)throw Error(`Enterprise config not found: ${$}`);let J={...JSON.parse(ZD(q,"utf-8")),...Y};for(let I of Object.keys(Y))if(Y[I]===void 0)delete J[I];let U=xi.parse(J);return NA0(q,`${JSON.stringify(U,null,2)}
`,"utf-8"),U}var ui="SEAL_USE_ENTERPRISES_DIR",DA0="SEAL_HOME_ENTERPRISES_DIR",PA0="SEAL_USE_USER_ENTERPRISES_DIR",AA0="SEAL_HOME_USER_ENTERPRISES_DIR",BA0="SEAL_USE_CONFIG_FILE",TA0="SEAL_HOME_CONFIG_FILE",iU,HD,KD,OA0;var K3=e(()=>{ki();iU=Q9(WD(),".config","seal-use","enterprises"),HD=Q9(WD(),".config","seal-home","enterprises"),KD=Q9(WD(),".config","seal-use","config.json"),OA0=Q9(WD(),".config","seal-home","config.json")});function $2($,Y,q=[]){let z=Y.corpId?.trim()||void 0,J=Y.stateful?Y.defaultCorpId?.trim()||void 0:void 0,U=z??J;if(U){let Q=$.find((H)=>H.id===U);if(Q)return Q;let K=$.find((H)=>H.id.toLowerCase()===U.toLowerCase());if(K)return K;let G=$.find((H)=>H.name.toLowerCase()===U.toLowerCase());if(G)return G;throw Error(`No enterprise config found for ${U}`)}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: "+(q.length?q.join(", "):"the configured enterprise directories"))}import{existsSync as ii,mkdirSync as Lj1,readFileSync as wj1,renameSync as Fj1,unlinkSync as Oj1,writeFileSync as Mj1}from"node:fs";import{homedir as Nj1}from"node:os";import{dirname as Dj1,join as Pj1}from"node:path";function ci(){let $=process.env[Aj1]?.trim();if($)return $;return Bj1}function jA0($=new Date){return $.toISOString().slice(0,10)}function _A0($=ni,Y=new Date){let q=Y.getTime()-Math.max(0,$-1)*86400000;return new Date(q).toISOString().slice(0,10)}function RA0($=ci()){if(!ii($))return{};try{let Y=wj1($,"utf-8"),q=JSON.parse(Y);if(q&&typeof q==="object"&&!Array.isArray(q))return q;return{}}catch{return{}}}function Tj1($,Y){let q={};for(let[z,J]of Object.entries($)){if(!J||typeof J!=="object")continue;let U={},I=!1;for(let[Q,K]of Object.entries(J))if(typeof K==="number"&&K>0&&Q>=Y)U[Q]=K,I=!0;if(I)q[z]=U}return q}function Ej1($,Y=ci()){let q=Dj1(Y);if(!ii(q))Lj1(q,{recursive:!0,mode:448});let z=`${Y}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{Mj1(z,JSON.stringify($,null,2),"utf-8"),Fj1(z,Y)}catch(J){try{if(ii(z))Oj1(z)}catch{}throw J}}function CA0($,Y=new Date){if(!$||typeof $!=="string")return;try{let q=ci(),z=RA0(q),J=jA0(Y),U=_A0(ni,Y),I=Tj1(z,U);I[$]=I[$]||{},I[$][J]=(I[$][J]??0)+1,Ej1(I,q)}catch{}}function jj1($,Y=ni,q=new Date){let z=new Map;try{let J=RA0(),U=_A0(Y,q),I=jA0(q),Q=$??Object.keys(J);for(let K of Q){let G=J[K];if(!G){z.set(K,0);continue}let H=0;for(let[Z,V]of Object.entries(G))if(Z>=U&&Z<=I&&typeof V==="number")H+=V;z.set(K,H)}}catch{if($)for(let J of $)z.set(J,0)}return z}function vA0($,Y,q){let z=q??jj1($.map((J)=>J.id));return[...$].sort((J,U)=>{if(Y){if(J.id===Y&&U.id!==Y)return-1;if(U.id===Y&&J.id!==Y)return 1}let I=z.get(J.id)??0,Q=z.get(U.id)??0;if(I!==Q)return Q-I;let K=J.name??J.id,G=U.name??U.id,H=K.localeCompare(G,"zh-CN");if(H!==0)return H;return J.id.localeCompare(U.id)})}var Aj1="SEAL_USE_USAGE_FILE",Bj1,ni=7;var pi=e(()=>{Bj1=Pj1(Nj1(),".config","seal-use","usage.json")});function _j1($,Y){return $.map((q)=>q.trim()).filter(Boolean).map((q)=>Y?q:q.toLowerCase())}function Rj1($,Y){return Y?$:$.toLowerCase()}function Cj1($,Y,q,z){let J=Rj1($,z),U=Y.filter((I)=>J.includes(I));if(q==="all"&&U.length!==Y.length)return[];return U}function vj1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function hj1($,Y){if(Y.fields&&!Y.fields.has($.field))return[];let q=vj1($.value),z=[];return q.forEach((J,U)=>{let I=Cj1(J,Y.keywords,Y.matchMode,Y.caseSensitive);if(I.length===0)return;let Q=Math.max(0,U-Y.contextLines),K=Math.min(q.length,U+Y.contextLines+1),G={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:U+1,matchedKeywords:I,matchedText:XD(J,Y.maxChars),context:{before:Y.snippetOnly?[]:q.slice(Q,U).map((H)=>XD(H,Y.maxChars)),line:XD(J,Y.maxChars),after:Y.snippetOnly?[]:q.slice(U+1,K).map((H)=>XD(H,Y.maxChars))},metadata:$.metadata};if(Y.snippetOnly)G.context={before:[],line:G.context.line,after:[]};z.push(G)}),z}function XD($,Y){if(!Y||$.length<=Y)return $;return`${$.slice(0,Math.max(0,Y))}...`}function gj1($){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 gA0($){return $.rules.flatMap((Y,q)=>{let z=`${$.id}:${Y.description.slice(0,32)}`,J={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:q};return[{area:"rules",entityType:"rule",entityId:z,title:`${$.versionName} / ${Y.scope}`,field:"history.description", Line truncated
`+"为防止测试单据污染生产审批流,禁止向生产环境重放单据。请指定测试企业 (--target-corp <testCorpId>),或在确有需要时添加 --force。",1,`seal-use webhook replay --target-corp <testCorpId>${q.id!==z.id?` --source-corp ${q.id}`:""}`);return{sourceCorp:q,targetCorp:z}}async function li($,Y,q){let z=Y.seal?.endpoints?.approvalStylePreferences??"api/v1/agent/ai-approval/config",J=await J$($,z);if(q||J.length>0)return uA0(J,q,Y.id);if(Y.environment==="test"||Y.id.toLowerCase().includes("test")){console.error(`[webhook-replay] 测试企业「${Y.name}」未配置 Webhook 通道,正在自动创建「(Seal测-回放通道)」...`);let U=(Y.seal.url??Y.source?.sealUrl??`https://${Y.id.toLowerCase()}.sealai.cc`).replace(/\/+$/,"");return await nL($,U,{name:"(Seal测-回放通道)",mode:"assisted",outgoingResultWebhook:`${U}/api/v1/integrations/webhook/replay-mock-callback`},Y.seal.endpoints.approvalStylePreferences)}throw new Z4(`当前租户「${Y.name}」未配置任何 Webhook 集成通道。`,1,`seal-use webhook add --name <name> --result-url <url> --corp ${Y.id}`)}async function nU($){let{query:Y,sourceClient:q,targetClient:z,sourceCorp:J,targetCorp:U,webhookSelector:I,snPrefix:Q,snSuffix:K,docIdPrefix:G,docIdSuffix:H,dryRun:Z,fetchFn:V=fetch}=$,X=[];if(Y.recordId){let E=await e1(q,Y.recordId);X.push(E)}else if(Y.recordIds&&Y.recordIds.length>0)for(let E of Y.recordIds)X.push(await e1(q,E));else if(Y.sn){let E=await x4(q,{sourceDocumentSN:Y.sn,limit:1});if(!E.records.length)throw Error(`在企业「${J.name}」中未找到单据编号为「${Y.sn}」的审批记录。`);X.push(E.records[0])}else if(Y.sns&&Y.sns.length>0)for(let E of Y.sns){let y=await x4(q,{sourceDocumentSN:E,limit:1});if(!y.records.length)throw Error(`在企业「${J.name}」中未找到单据编号为「${E}」的审批记录。`);X.push(y.records[0])}else if(Y.limit!==void 0){let E=await x4(q,{limit:Y.limit,status:Y.status,startDate:Y.startDate,endDate:Y.endDate});if(!E.records.length)throw Error(`在企业「${J.name}」中未检索到符合条件的审批记录。`);X=E.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 L=X.map((E)=>({run:E,doc:di(E,{snPrefix:Q,snSuffix:K,docIdPrefix:G,docIdSuffix:H})}));if(Z){let E={id:"preview-webhook",name:I??"预览目标通道",mode:"assisted",incomingDocumentWebhookUrl:`${U.seal.url}/api/v1/integrations/webhook/preview`};try{let k=await J$(z,U.seal.endpoints.approvalStylePreferences);if(k.length>0){let C=uA0(k,I,U.id);E={id:C.id,name:C.name,mode:C.mode,incomingDocumentWebhookUrl:C.incomingDocumentWebhook.url}}}catch{}let y=L.map(({run:k,doc:C})=>({originalRecord:{id:k.id,sourceSystem:k.sourceSystem,sourceDocumentSN:k.sourceDocumentSN,sourceDocumentId:k.sourceDocumentId},document:C,success:!0})),v=y.length===1;return{dryRun:!0,success:!0,sourceCorp:{id:J.id,name:J.name,environment:J.environment},targetCorp:{id:U.id,name:U.name,environment:U.environment},targetWebhook:E,totalCount:y.length,successCount:y.length,failureCount:0,originalRecord:v?y[0].originalRecord:void 0,document:v?y[0].document:void 0,records:y}}let w=await li(z,U,I),F={id:w.id,name:w.name,mode:w.mode,incomingDocumentWebhookUrl:w.incomingDocumentWebhook.url},O=[],P=0,B=0;for(let{run:E,doc:y}of L){console.error(`[webhook-replay] 正在向 Webhook 通道「${w.name}」推送单据: ${y.documentSN}...`);try{let v=await mi(w.incomingDocumentWebhook.url,w.secret,y,V,w6(U.seal));O.push({originalRecord:{id:E.id,sourceSystem:E.sourceSystem,sourceDocumentSN:E.sourceDocumentSN,sourceDocumentId:E.sourceDocumentId},replayedDocument:{documentSN:y.documentSN,documentId:y.documentId,fieldCount:y.fields.length},pushResult:v,success:!0}),P+=1}catch(v){let k=v instanceof Error?v.message:String(v);O.push({originalRecord:{id:E.id,sourceSystem:E.sourceSystem,sourceDocumentSN:E.sourceDocumentSN,sourceDocumentId:E.sourceDocumentId},replayedDocument:{documentSN:y.documentSN,documentId:y.documentId,fieldCount:y.fields.length},error:k,success:!1}),B+=1}}let A=O.length===1;return{success:B===0,dryRun:!1,sourceCorp:{id:J.id,name:J.name,environment:J.environment},targetCorp:{id:U.id,name:U.name,environment:U.environment},targetWebhook:F,totalCount:O.length,successCount:P,failureCount:B,originalRecord:A?O[0].originalRecord:void 0,replayedDocument:A?O[0].replayedDocument:void 0,pushResult:A?O[0].pushResult:void 0,records:O}}var cj1;var DZ=e(()=>{VD();V$();I6();cj1=new Set(["TEXT","NUMBER","DATE","AMOUNT","PERSON","ATTACHMENT","DATE_RANGE","DEPARTMENT","LIST","CITY","OBJECT"])});var fA0,i24,dj1,n24;var bA0=e(()=>{I5();fA0=W.object({level:W.enum(["error","warning","info"]),code:W.string(),message:W.string(),snippet:W.string().optional(),suggestion:W.string().optional()}),i24=W.object({score:W.number().min(0).max(100),passed:W.boolean(),issues:W.array(fA0)}),dj1=W.object({ruleId:W.string Line truncated
* ==============================================================================
* Seal 官方标准规则校验器 (Official Standard Rule Linter)
* ==============================================================================
@@ -866,55 +870,65 @@ 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 $q,mkdirSync as U_1,readFileSync as I_1,readdirSync as dA0,rmSync as Q_1,unlinkSync as K_1,writeFileSync as G_1}from"node:fs";import{homedir as H_1}from"node:os";import{isAbsolute as Z_1,join as C6,resolve as W_1}from"node:path";import{pathToFileURL as cA0}from"node:url";function mA0($=i$){let Y=[],q=[];try{if(!$q($))U_1($,{recursive:!0});let z=Object.keys(ti);for(let[U,I]of Object.entries(ti)){let Q=C6($,U),K=!0;if($q(Q))try{if(I_1(Q,"utf8")===I)K=!1}catch{K=!0}if(K)G_1(Q,I,"utf8");Y.push(U)}let J=dA0($,{withFileTypes:!0});for(let U of J)if(!z.includes(U.name)){let I=C6($,U.name);try{if(U.isDirectory())Q_1(I,{recursive:!0,force:!0});else K_1(I);q.push(U.name)}catch{}}}catch{}return{synced:Y,pruned:q}}function lA0($={syncOfficial:!0}){if($.syncOfficial!==!1)mA0();let Y=[{name:"builtin",type:"builtin",path:C6(i$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:C6(i$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:C6(i$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],q=[b$,OD];for(let z of q)if($q(z))try{let J=dA0(z,{withFileTypes:!0});for(let U of J){if(U.isDirectory())continue;let I=U.name;if(I.endsWith(".ts")||I.endsWith(".js")||I.endsWith(".mjs")){let Q=I.replace(/\.(ts|js|mjs)$/,"");if(!Y.some((K)=>K.name===Q))Y.push({name:Q,type:"custom",path:C6(z,I),description:`用户自定义规则校验器 (${I})`})}}}catch{}return Y}function V_1($){let Y=($||"").trim();if(!Y||Y==="builtin"||Y==="default"||Y==="official/builtin"||Y==="official/builtin.ts")return{path:C6(i$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(Y==="strict"||Y==="official/strict"||Y==="official/strict.ts")return{path:C6(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:C6(i$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(Z_1(Y)||Y.startsWith("./")||Y.startsWith("../")){let z=W_1(Y);if($q(z))return{path:z};for(let J of[".ts",".js",".mjs"])if($q(`${z}${J}`))return{path:`${z}${J}`}}let q=[C6(b$,`${Y}.ts`),C6(b$,`${Y}.js`),C6(b$,`${Y}.mjs`),C6(OD,`${Y}.ts`),C6(OD,`${Y}.js`),C6(OD,`${Y}.mjs`)];for(let z of q)if($q(z))return{path:z};return{}}async function ei($){mA0();let Y=V_1($??"builtin");if(Y.isOfficial){let z=Y.officialKind==="strict"?iA0:Y.officialKind==="hlab"?nA0:cU,J=Y.officialKind==="builtin"?"builtin":"official",U=Y.path;if(U&&$q(U))try{let Q=await import(cA0(U).href),K=Q.default??Q.lintRule??Q.linter??Q.lint;if(typeof K==="function")return{name:Y.officialKind??"builtin",type:J,filePath:U,linter:pA0(K,z)}}catch{}return{name:Y.officialKind??"builtin",type:J,filePath:U,linter:z}}let q=Y.path;if(!q)return console.error(`⚠️ [linter] 未找到自定义校验器 "${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:cU};try{let J=await import(cA0(q).href),U=J.default??J.lintRule??J.linter??J.lint;if(typeof U!=="function")return console.error(`⚠️ [linter] 自定义校验器 "${q}" 未导出标准函数 (default / lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:cU};return{name:$??"custom",type:"custom",filePath:q,linter:pA0(U,cU)}}catch(z){return console.error(`⚠️ [linter] 加载自定义校验器脚本 "${q}" 失败(语法错误或依赖缺失: ${z?.message??z}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:cU}}}function pA0($,Y){return async(q,z)=>{try{let J=await $(q,z);if(J&&typeof J==="object"&&typeof J.score==="number"&&Array.isArray(J.issues))return J;return console.error("⚠️ [linter] 自定义校验器返回值格式不符合 RuleLintResult 契约,已回退至内置结果。"),Y(q,z)}catch(J){return console.error("⚠️ [linter] 自定义校验器执行异常:",J),Y(q,z)}}}var b$,X_1="official",i$,OD;var $n=e(()=>{oi();si();ai();ri();b$=C6(H_1(),".config","seal-use","linters"),i$=C6(b$,X_1),OD=C6(process.cwd(),"linters")});async function Yn($,Y,q){let z=await Y.linter($,q);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:z.score,passed:z.passed,issues:z.issues,description:$.description}}async function oA0($,Y,q,z){let J=z?.minScore??0,U=z?.level??"all",I=[],Q=0;for(let X of $){let L=await Yn(X,Y,q);Q+=L.score;let w=L.issues;if(U==="error")w=L.issues.filter((O)=>O.level==="error");else if(U==="warning")w=L.issues.filter((O)=>O.level==="warning"||O.level==="error");let F=w.every((O)=>O.level!=="error");if(z?.summary){if(w.length>0)I.push({...L,passed:F,issues:w})}else I.push({...L,passed:F,issues:w})}let K=$.length,G=K===0?100:Math.round(Q/K),H=I.filter((X)=>X.issues.length>0).length,Z=K-Line truncated
`,"utf8"),q}function aA0($){return $.map((Y,q)=>{let z;if(typeof Y.code==="number")z=`#${String(Y.code).padStart(4,"0")}`;else if(typeof Y.code==="string")z=Y.code.startsWith("#")?Y.code:`#${Y.code}`;else z=`#${String(q+1).padStart(4,"0")}`;return{id:Y.id,code:z,name:Y.name,description:Y.description,scope:Y.scope,strictness:Y.strictness}})}var eA0=()=>{};var $B0,N5;var pU=e(()=>{$B0=class $B0 extends Error{errors;warnings;constructor($,Y=[]){super([`webhook 资源包校验失败:${$.length} 个错误`,...$.map((q)=>`- ${q}`)].join(`
`));this.errors=$;this.warnings=Y;this.name="ResourcePackValidationError"}};N5=$B0});var JB0=M((wY4,zB0)=>{zB0.exports=MD;function MD(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}MD.prototype.go=function($){if(this.pending<this.max)qB0(this,$);else this.waiting.push($)};MD.prototype.wait=function($){if(this.pending===0)$(this.error);else this.listeners.push($)};MD.prototype.hold=function(){return YB0(this)};function YB0($){$.pending+=1;var Y=!1;return q;function q(J){if(Y)throw Error("callback called twice");if(Y=!0,$.error=$.error||J,$.pending-=1,$.waiting.length>0&&$.pending<$.max)qB0($,$.waiting.shift());else if($.pending===0){var U=$.listeners;$.listeners=[],U.forEach(z)}}function z(J){J($.error)}}function qB0($,Y){Y(YB0($))}});var QB0=M((A_1)=>{var Jn=m("fs"),Un=m("util"),UB0=m("stream"),IB0=UB0.Readable,D_1=UB0.PassThrough,P_1=JB0(),ND=m("events").EventEmitter;A_1.BufferSlicer=mU;A_1.FdSlicer=dU;Un.inherits(dU,ND);function dU($){ND.call(this),this.fd=$,this.pend=new P_1,this.pend.max=1,this.refCount=0}dU.prototype.read=function($,Y,q,z,J){var U=this;U.pend.go(function(I){Jn.read(U.fd,$,Y,q,z,function(Q,K,G){I(),J(Q,K,G)})})};dU.prototype.createReadStream=function($){return new PZ(this,$)};dU.prototype.ref=function(){this.refCount+=1};dU.prototype.unref=function(){var $=this;if($.refCount-=1,$.refCount<0)throw Error("invalid unref");if($.refCount>0)return;Jn.close($.fd,Y);function Y(q){if(q)$.emit("error",q);else $.emit("close")}};Un.inherits(PZ,IB0);function PZ($,Y){Y=Y||{},IB0.call(this,Y),this.context=$,this.context.ref(),this.start=Y.start||0,this.endOffset=Y.end,this.pos=this.start}PZ.prototype._read=function($){var Y=this,q=Math.min(Y._readableState.highWaterMark,$);if(Y.endOffset!=null)q=Math.min(q,Y.endOffset-Y.pos);if(q<=0){Y.push(null),this._cleanup();return}Y.context.pend.go(function(z){var J=Buffer.allocUnsafe(q);Jn.read(Y.context.fd,J,0,q,Y.pos,function(U,I){if(U)Y.destroy(U);else if(I===0)Y.push(null),Y._cleanup();else Y.pos+=I,Y.push(J.slice(0,I));z()})})};PZ.prototype._destroy=function($,Y){this._cleanup(),Y($)};PZ.prototype._cleanup=function(){if(this.context!=null)this.context.unref(),this.context=null};Un.inherits(mU,ND);function mU($){ND.call(this),this.refCount=0,this.buffer=$}mU.prototype.read=function($,Y,q,z,J){if(!(0<=Y&&Y<=$.length))throw RangeError("offset outside buffer: 0 <= "+Y+" <= "+$.length);if(z<0)throw RangeError("position is negative: "+z);if(Y+q>$.length)q=$.length-Y;if(z+q>this.buffer.length)q=this.buffer.length-z;if(q<=0){setImmediate(function(){J(null,0)});return}this.buffer.copy($,Y,z,z+q),setImmediate(function(){J(null,q)})};mU.prototype.createReadStream=function($){$=$||{};var Y=new D_1($);Y.start=$.start||0,Y.endOffset=$.end,Y.pos=Y.endOffset||this.buffer.length;var q=this.buffer.slice(Y.start,Y.pos),z=65536,J=0;while(!0){var U=J+z;if(U>=q.length){if(J<q.length)Y.write(q.slice(J,q.length));break}Y.write(q.slice(J,U)),J=U}return Y.end(),Y};mU.prototype.ref=function(){this.refCount+=1};mU.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw Error("invalid unref")}});var GB0=M((OY4,KB0)=>{var E_1=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
\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}
\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 iB0=M((BR1)=>{var nn=H3().Buffer;BR1._dbcs=W3;var a6=-1,bB0=-2,p$=-10,j8=-1000,eU=Array(256),TZ=-1;for(BZ=0;BZ<256;BZ++)eU[BZ]=a6;var BZ;function W3($,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 q=$.table();this.decodeTables=[],this.decodeTables[0]=eU.slice(0),this.decodeTableSeq=[];for(var z=0;z<q.length;z++)this._addDecodeChunk(q[z]);if(typeof $.gb18030==="function"){this.gb18030=$.gb18030();var J=this.decodeTables.length;this.decodeTables.push(eU.slice(0));var U=this.decodeTables.length;this.decodeTables.push(eU.slice(0));var I=this.decodeTables[0];for(var z=129;z<=254;z++){var Q=this.decodeTables[j8-I[z]];for(var K=48;K<=57;K++){if(Q[K]===a6)Q[K]=j8-J;else if(Q[K]>j8)throw Error("gb18030 decode tables conflict at byte 2");var G=this.decodeTables[j8-Q[K]];for(var H=129;H<=254;H++){if(G[H]===a6)G[H]=j8-U;else if(G[H]===j8-U)continue;else if(G[H]>j8)throw Error("gb18030 decode tables conflict at byte 3");var Z=this.decodeTables[j8-G[H]];for(var V=48;V<=57;V++)if(Z[V]===a6)Z[V]=bB0}}}}this.defaultCharUnicode=Y.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var X={};if($.encodeSkipVals)for(var z=0;z<$.encodeSkipVals.length;z++){var L=$.encodeSkipVals[z];if(typeof L==="number")X[L]=!0;else for(var K=L.from;K<=L.to;K++)X[K]=!0}if(this._fillEncodeTable(0,0,X),$.encodeAdd){for(var w in $.encodeAdd)if(Object.prototype.hasOwnProperty.call($.encodeAdd,w))this._setEncodeChar(w.charCodeAt(0),$.encodeAdd[w])}if(this.defCharSB=this.encodeTable[0][Y.defaultCharSingleByte.charCodeAt(0)],this.defCharSB===a6)this.defCharSB=this.encodeTable[0]["?"];if(this.defCharSB===a6)this.defCharSB=63}W3.prototype.encoder=gD;W3.prototype.decoder=cn;W3.prototype._getDecodeTrieNode=function($){var Y=[];for(;$>0;$>>>=8)Y.push($&255);if(Y.length==0)Y.push(0);var q=this.decodeTables[0];for(var z=Y.length-1;z>0;z--){var J=q[Y[z]];if(J==a6)q[Y[z]]=j8-this.decodeTables.length,this.decodeTables.push(q=eU.slice(0));else if(J<=j8)q=this.decodeTables[j8-J];else throw Error("Overwrite byte in "+this.encodingName+", addr: "+$.toString(16))}return q};W3.prototype._addDecodeChunk=function($){var Y=parseInt($[0],16),q=this._getDecodeTrieNode(Y);Y=Y&255;for(var z=1;z<$.length;z++){var J=$[z];if(typeof J==="string")for(var U=0;U<J.length;){var I=J.charCodeAt(U++);if(I>=55296&&I<56320){var Q=J.charCodeAt(U++);if(Q>=56320&&Q<57344)q[Y++]=65536+(I-55296)*1024+(Q-56320);else throw Error("Incorrect surrogate pair in "+this.encodingName+" at chunk "+$[0])}else if(I>4080&&I<=4095){var K=4095-I+2,G=[];for(var H=0;H<K;H++)G.push(J.charCodeAt(U++));q[Y++]=p$-this.decodeTableSeq.length,this.decodeTableSeq.push(G)}else q[Y++]=I}else if(typeof J==="number"){var Z=q[Y-1]+1;for(var U=0;U<J;U++)q[Y++]=Z++}else throw Error("Incorrect type '"+typeof J+"' 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=$}}sT0.exports={AggregateError:rT0,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,q){return $.slice(Y,q)},Error,FunctionPrototypeCall($,Y,...q){return $.call(Y,...q)},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,q){return Object.defineProperty($,Y,q)},ObjectGetOwnPropertyDescriptor($,Y){return Object.getOwnPropertyDescriptor($,Y)},ObjectKeys($){return Object.keys($)},ObjectSetPrototypeOf($,Y){return Object.setPrototypeOf($,Y)},Promise,PromisePrototypeCatch($,Y){return $.catch(Y)},PromisePrototypeThen($,Y,q){return $.then(Y,q)},PromiseReject($){return Promise.reject($)},PromiseResolve($){return Promise.resolve($)},ReflectApply:Reflect.apply,RegExpPrototypeTest($,Y){return $.test(Y)},SafeSet:Set,String,StringPrototypeSlice($,Y,q){return $.slice(Y,q)},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,q){return $.set(Y,q)},Boolean,Uint8Array}});var Wc=M((Pq4,tT0)=>{tT0.exports={format($,...Y){return $.replace(/%([sdifj])/g,function(...[q,z]){let J=Y.shift();if(z==="f")return J.toFixed(6);else if(z==="j")return JSON.stringify(J);else if(z==="s"&&typeof J==="object")return`${J.constructor!==Object?J.constructor.name:""} {}`.trim();else return J.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 Z8=M((Aq4,YE0)=>{var{format:Fv1,inspect:fD}=Wc(),{AggregateError:Ov1}=g4(),Mv1=globalThis.AggregateError||Ov1,Nv1=Symbol("kIsNodeError"),Dv1=["string","function","number","object","Function","Object","boolean","bigint","symbol"],Pv1=/^([A-Z][a-z0-9]*)+$/,bD={};function zq($,Y){if(!$)throw new bD.ERR_INTERNAL_ASSERTION(Y)}function aT0($){let Y="",q=$.length,z=$[0]==="-"?1:0;for(;q>=z+4;q-=3)Y=`_${$.slice(q-3,q)}${Y}`;return`${$.slice(0,q)}${Y}`}function Av1($,Y,q){if(typeof Y==="function")return zq(Y.length<=q.length,`Code: ${$}; The provided arguments length (${q.length}) does not match the required ones (${Y.length}).`),Y(...q);let z=(Y.match(/%[dfijoOs]/g)||[]).length;if(zq(z===q.length,`Code: ${$}; The provided arguments length (${q.length}) does not match the required ones (${z}).`),q.length===0)return Y;return Fv1(Y,...q)}function e6($,Y,q){if(!q)q=Error;class z extends q{constructor(...J){super(Av1($,Y,J))}toString(){return`${this.name} [${$}]: ${this.message}`}}Object.defineProperties(z.prototype,{name:{value:q.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${$}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),z.prototype.code=$,z.prototype[Nv1]=!0,bD[$]=z}function eT0($){let Y="__node_internal_"+$.name;return Object.defineProperty($,"name",{value:Y}),$}function Bv1($,Y){if($&&Y&&$!==Y){if(Array.isArray(Y.errors))return Y.errors.push($),Y;let q=new Mv1([Y,$],Y.message);return q.code=Y.code,q}return $||Y}class $E0 extends Error{constructor($="The operation was aborted",Y=void 0){if(Y!==void 0&&typeof Y!=="object")throw new bD.ERR_INVALID_ARG_TYPE("options","Object",Y);super($,Y);this.code="ABORT_ERR",this.name="AbortError"}}e6("ERR_ASSERTION","%s",Error);e6("ERR_INVALID_ARG_TYPE",($,Y,q)=>{if(zq(typeof $==="string","'name' must be a string"),!Array.isArray(Y))Y=[Y];let z="The ";if($.endsWith(" argument"))z+=`${$} `;else z+=`"${$}" ${$.includes(".")?"property":"argument"} `;z+="must be ";let J=[],U=[],I=[];for(let K of Y)if(zq(typeof K==="string","All expected entries have to be of type string"),Dv1.includes(K))J.push(K.toLowerCase());else if(Pv1.test(K))U.push(K);else zq(K!=="object",'The value "object" should be written as "Object"'),I.push(K);if(U.length>0){let K=J.indexOf("object");if(K!==-1)J.splice(J,K,1),U.push("Object")}if(J.length>0){switch(J.length){case 1:z+=`of type ${J[Line truncated
`);if(Y.linkname)q+=np(" linkpath="+Y.linkname+`
`);let z=Y.pax;if(z)for(let J in z)q+=np(" "+J+"="+z[J]+`
`);return R1.from(q)};Du1.decodePax=function(Y){let q={};while(Y.length){let z=0;while(z<Y.length&&Y[z]!==32)z++;let J=parseInt(R1.toString(Y.subarray(0,z)),10);if(!J)return q;let U=R1.toString(Y.subarray(z+1,J-1)),I=U.indexOf("=");if(I===-1)return q;q[U.slice(0,I)]=U.slice(I+1),Y=Y.subarray(J)}return q};Du1.encode=function(Y){let q=R1.alloc(512),z=Y.name,J="";if(Y.typeflag===5&&z[z.length-1]!=="/")z+="/";if(R1.byteLength(z)!==z.length)return null;while(R1.byteLength(z)>100){let U=z.indexOf("/");if(U===-1)return null;J+=J?"/"+z.slice(0,U):z.slice(0,U),z=z.slice(U+1)}if(R1.byteLength(z)>100||R1.byteLength(J)>155)return null;if(Y.linkname&&R1.byteLength(Y.linkname)>100)return null;if(R1.write(q,z),R1.write(q,K2(Y.mode&4095,6),100),R1.write(q,K2(Y.uid,6),108),R1.write(q,K2(Y.gid,6),116),Mu1(Y.size,q,124),R1.write(q,K2(Y.mtime.getTime()/1000|0,11),136),q[156]=48+Fu1(Y.type),Y.linkname)R1.write(q,Y.linkname,157);if(R1.copy(TC0,q,257),R1.copy(Hu1,q,263),Y.uname)R1.write(q,Y.uname,265);if(Y.gname)R1.write(q,Y.gname,297);if(R1.write(q,K2(Y.devmajor||0,6),329),R1.write(q,K2(Y.devminor||0,6),337),J)R1.write(q,J,345);return R1.write(q,K2(jC0(q),6),148),q};Du1.decode=function(Y,q,z){let J=Y[156]===0?0:Y[156]-48,U=MI(Y,0,100,q),I=Q2(Y,100,8),Q=Q2(Y,108,8),K=Q2(Y,116,8),G=Q2(Y,124,12),H=Q2(Y,136,12),Z=wu1(J),V=Y[157]===0?null:MI(Y,157,100,q),X=MI(Y,265,32),L=MI(Y,297,32),w=Q2(Y,329,8),F=Q2(Y,337,8),O=jC0(Y);if(O===256)return null;if(O!==Q2(Y,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(Xu1(Y)){if(Y[345])U=MI(Y,345,155,q)+"/"+U}else if(Vu1(Y));else if(!z)throw Error("Invalid tar header: unknown format.");if(J===0&&U&&U[U.length-1]==="/")J=5;return{name:U,mode:I,uid:Q,gid:K,size:G,byteOffset:0,mtime:new Date(1000*H),type:Z,linkname:V,uname:X,gname:L,devmajor:w,devminor:F,pax:null}};function Xu1($){return R1.equals(TC0,$.subarray(257,263))}function Vu1($){return R1.equals(Zu1,$.subarray(257,263))&&R1.equals(Wu1,$.subarray(263,265))}function Lu1($,Y,q){if(typeof $!=="number")return q;if($=~~$,$>=Y)return Y;if($>=0)return $;if($+=Y,$>=0)return $;return 0}function wu1($){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 Fu1($){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 EC0($,Y,q,z){for(;q<z;q++)if($[q]===Y)return q;return z}function jC0($){let Y=256;for(let q=0;q<148;q++)Y+=$[q];for(let q=156;q<512;q++)Y+=$[q];return Y}function K2($,Y){if($=$.toString(8),$.length>Y)return"7777777777777777777".slice(0,Y)+" ";return"0000000000000000000".slice(0,Y-$.length)+$+" "}function Ou1($,Y,q){Y[q]=128;for(let z=11;z>0;z--)Y[q+z]=$&255,$=Math.floor($/256)}function Mu1($,Y,q){if($.toString(8).length>11)Ou1($,Y,q);else R1.write(Y,K2($,11),q)}function Nu1($){let Y;if($[0]===128)Y=!0;else if($[0]===255)Y=!1;else return null;let q=[],z;for(z=$.length-1;z>0;z--){let I=$[z];if(Y)q.push(I);else q.push(255-I)}let J=0,U=q.length;for(z=0;z<U;z++)J+=q[z]*Math.pow(256,z);return Y?J:-1*J}function Q2($,Y,q){if($=$.subarray(Y,Y+q),Y=0,$[Y]&128)return Nu1($);else{while(Y<$.length&&$[Y]===32)Y++;let z=Lu1(EC0($,32,Y,$.length),$.length,$.length);while(Y<z&&$[Y]===0)Y++;if(z===Y)return 0;return parseInt(R1.toString($.subarray(Y,z)),8)}}function MI($,Y,q,z){return R1.toString($.subarray(Y,EC0($,0,Y,Y+q)),z)}function np($){let Y=R1.byteLength($),q=Math.floor(Math.log(Y)/Math.log(10))+1;if(Y+q>=Math.pow(10,q))q++;return Y+q+$}});var yC0=M((XJ4,SC0)=>{var{Writable:ju1,Readable:_u1,getStreamError:_C0}=ip(),Ru1=gp(),RC0=OI(),NI=cp(),Cu1=RC0.alloc(0);class CC0{constructor(){this.buffered=0,this.shifted=0,this.queue=new Ru1,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 Cu1;let Y=this._next($);if($===Y.byteLength)return Y;let q=[Y];while(($-=Y.byteLength)>0)Y=this._next($),q.push(Y);return RC0.concat(q)}_next($){let Y=this.queue.peek(),q=Y.byteLength-this._offset;if($>=q){let z=this._offset?Y.subarray(this._offset,Y.byteLength):Y;return this.queue.shift(),this._offset=0,this.buffered-=q,this.shifted+=q,z}return this.buffered-=$,this.shifted+=$,Y.subarray(this._offset,this._offset+=$)}}class vC0 extends _u1{constructor($,Y,q){super();this.header=Y,this.offset=q,this._parent=$}_read($){if(this.header.size===0)this.push(null);if(this._parent._stream===this)this._parent._update();$(null)}_predestroy(){this._parent.destroy(_C0(this))}_detach(){if(this._parent._stream= Line truncated
`),z=[await e1($,q.recordId)];else if(q.recordIds&&q.recordIds.length>0)process.stderr.write(`\uD83D\uDD0D 批量查询 ${q.recordIds.length} 条单据记录...
`),z=await Promise.all(q.recordIds.map((O)=>e1($,O)));else{let O=q.limit??10;process.stderr.write(`\uD83D\uDD0D 检索企业「${Y.name}」(${Y.id}) 的线上审核记录 (限制 ${O} 条)...
`);let B=(await x4($,{limit:O,status:q.status,startDate:q.startDate!==void 0?String(q.startDate):void 0,endDate:q.endDate!==void 0?String(q.endDate):void 0})).records??[];if(B.length===0)throw Error("未检索到符合条件的线上审核记录,无法导出 webhook 资源包。");process.stderr.write(`\uD83D\uDCE5 正在拉取 ${B.length} 条审核记录完整详情...
`),z=await Promise.all(B.map((A)=>e1($,A.id)))}let J=new Map,U=0;for(let O of z){let P=O.document,B=O.sourceDocumentId??(typeof P?.id==="string"?P.id:void 0)??(typeof P?.sourceDocumentId==="string"?P.sourceDocumentId:void 0)??O.documentId??O.id,A=`${q.docIdPrefix??""}${B}${q.docIdSuffix??""}`,E=[];if(q.includeAttachments!==!1){let v=a7(O,{summary:!1}).attachments,k=new Set;for(let C of v){let c=C.ossSignedUrl??C.url;if(!c)continue;let n=C.fileName??C.fileId??"attachment",g=gi(n),b=g,i=g.lastIndexOf("."),$0=i>0?g.slice(0,i):g,j=i>0?g.slice(i):"",u=1;while(k.has(b.toLowerCase()))b=`${$0}_${u}${j}`,u++;k.add(b.toLowerCase());try{process.stderr.write(`⬇ 下载单据「${A}」附件: ${n}...
`);let p=await fetch(c);if(p.ok){let d=await p.arrayBuffer(),q0=Buffer.from(d);E.push({fileName:b,zipPath:`${A}/${b}`,buffer:q0,sourceField:C.sourceField??"附件"}),U++}}catch(p){process.stderr.write(`⚠️ [跳过附件] 下载失败 ${n}: ${p}
`)}}}J.set(A,E)}let I=new eC0.default.Workbook;I.creator="seal-use",I.created=new Date;let Q=new Set;for(let O of J.values())for(let P of O)Q.add(P.sourceField);if(Q.size===0)Q.add("附件");let K=new Set;for(let O of z){let P=O.document,B=Array.isArray(P?.fields)?P.fields:[];for(let A of B)if(A&&typeof A==="object"){let E=A,y=typeof E.label==="string"?E.label.trim():typeof E.key==="string"?E.key.trim():"",v=typeof E.type==="string"?E.type.toUpperCase():"";if(y&&v!=="ATTACHMENT"&&v!=="LIST")K.add(y)}}let G=["会议编号","会议名称","状态","总金额","报销事由","申请日期"],H=Array.from(K).filter((O)=>!G.includes(O)&&O!=="单据编号"&&O!=="单号"),Z=Array.from(Q).map((O)=>`[附件]${O}`),V=[...G,...H,...Z],X=I.addWorksheet("主表");X.addRow(V),X.getRow(1).font={bold:!0};for(let O of z){let P=O.document,B=O.sourceDocumentSN??(typeof P?.sn==="string"?P.sn:void 0)??(typeof P?.sourceDocumentSN==="string"?P.sourceDocumentSN:void 0)??O.id,A=O.sourceDocumentId??(typeof P?.id==="string"?P.id:void 0)??(typeof P?.sourceDocumentId==="string"?P.sourceDocumentId:void 0)??O.documentId??O.id,E=`${q.docIdPrefix??""}${A}${q.docIdSuffix??""}`,y=`${q.docIdPrefix??""}${B}${q.docIdSuffix??""}`,v=(typeof P?.title==="string"?P.title:void 0)??(typeof P?.name==="string"?P.name:void 0)??y,k="";if(typeof P?.sourceStartTime==="number")k=new Date(P.sourceStartTime*1000).toLocaleDateString("en-CA",{timeZone:"Asia/Shanghai"});else if(typeof O.createdAt==="number")k=new Date(O.createdAt).toLocaleDateString("en-CA",{timeZone:"Asia/Shanghai"});else if(typeof O.createdAt==="string")k=O.createdAt.slice(0,10);let C=new Map,c=Array.isArray(P?.fields)?P.fields:[];for(let $0 of c)if($0&&typeof $0==="object"){let j=$0,u=typeof j.label==="string"?j.label.trim():typeof j.key==="string"?j.key.trim():"";if(u)C.set(u,j.value)}let n,g=C.get("总金额")??C.get("报销金额")??C.get("total_amount");if(typeof g==="number")n=g;else if(g&&typeof g==="object"&&"amount"in g&&typeof g.amount==="number")n=g.amount;let b=[];b.push(E),b.push(v),b.push(O.status??"已审批"),b.push(n??""),b.push(C.get("报销事由")??C.get("事由")??v),b.push(k);for(let $0 of H){let j=C.get($0);if(j===void 0||j===null)b.push("");else if(typeof j==="object")if("amount"in j)b.push(j.amount);else b.push(JSON.stringify(j));else b.push(j)}let i=J.get(E)??[];for(let $0 of Q){let j=i.filter((u)=>u.sourceField===$0||Q.size===1);if(j.length>0)b.push(j.map((u)=>u.zipPath).join(`
`));else b.push("")}X.addRow(b)}let L=ru1(q,Y);pu1(lu1(L),{recursive:!0});let w=await I.xlsx.writeBuffer();process.stderr.write(`\uD83D\uDCE6 正在压缩生成 Webhook 资源包: ${L}...
`),await new Promise((O,P)=>{let B=cu1(L),A=new op({zlib:{level:9}});B.on("close",()=>O()),A.on("error",(E)=>P(E)),A.pipe(B),A.append(Buffer.from(w),{name:"信息表.xlsx"});for(let E of J.values())for(let y of E)A.append(y.buffer,{name:y.zipPath});A.finalize()});let F=du1(L);return{filePath:L,corpId:Y.id,corpName:Y.name,recordCount:z.length,attachmentCount:U,fileSizeBytes:F.size,exportedAt:new Date().toISOString(),nextAction:`seal-use webhook resource-pack push ${L} --corp <targetCorpId>`}}var eC0;var rp=e(()=>{tC0();I6();ID();eC0=y4(FZ(),1)});import{readFileSync as su1}from"node:fs";function tu1($){let Y=new URL($),q=Y.pathname.match(/\/webhook\/([^/]+)/);if(!q)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${Y.protocol}//${Y.host}`,webhookId:q[1]}}function au1($,Y){return Y.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!Y.toLowerCase().endsWith(".xlsx")}function eu1($,Y){if(!$.length)return;let q=new Set($.map((U)=>{let I=U.fileName.split("/")[0],Q=I.indexOf("@");return Q>=0?I.slice(0,Q):I}).filter((U)=>U!=="信息表.xlsx")),z=[];for(let U of Y){let I=U.document.documentId;if((U.documentAttachments.length>0||Object.values(U.expenseAttachments).some((K)=>K.length>0)||Object.values(U.personAttachments).some((K)=>K.length>0))&&!q.has(I))z.push(`Excel 会议编号「${I}」声明了附件,但在 ZIP 中找不到对应的根目录「${I}/」或「${I}@.../」。`)}let J=new Set(Y.map((U)=>U.document.documentId));for(let U of q)if(!J.has(U))z.push(`ZIP 根目录对应的编号「${U}」在信息表中找不到对应的会议编号。`);if(z.length)throw new N5(z)}async function $v0($,Y,q){let z=[],J=$;if(au1($,Y)){z=await HT0($),WT0(z,q);let K=z.find((G)=>G.fileName==="信息表.xlsx");if(!K)throw Error("ZIP 根目录缺少信息表.xlsx");J=await rn($,K)}let U=await MT0(J);eu1(z,U);let I=NT0(z,U),Q=U.map((K)=>K.document);return{entries:z,parsed:U,plans:I,documents:Q,fileBuffer:$}}async function Dq($,Y,q){let z=await $v0($,Y,q),J=z.parsed.map((U,I)=>Yc(U.document,z.plans[I],new Map));return{warnings:[],documents:J,attachmentPlan:z.plans}}async function RP($,Y,q){let z=await $v0($,Y,q.materialPackFilePolicy),{baseUrl:J,webhookId:U}=tu1(q.webhookUrl),I=[];for(let Q=0;Q<z.parsed.length;Q+=1){let K=z.parsed[Q],G=z.plans[Q],H=new Map,Z=[...G.categoryFields,...Object.values(G.personAttachments).flat(),...Object.values(G.expenseAttachments).flat()];for(let L of Z)for(let w of L.paths){if(H.has(w))continue;let F=z.entries.find((y)=>y.fileName===w);if(!F)continue;process.stderr.write(`⬆ 上传附件: ${w}
`);let O=new FormData,P=await rn(z.fileBuffer,F),B=w.split("/").pop()??w;O.append("files",new File([new Uint8Array(P)],B));let A=await fetch(`${J}/api/v1/integrations/webhook/${encodeURIComponent(U)}/attachments`,{method:"POST",headers:{...q.customHeaders??{},...NZ({},q.secret)},body:O});if(!A.ok)throw Error(`附件上传失败 ${A.status}: ${await A.text()}`);let E=await A.json();H.set(w,E.attachments?.map((y)=>y.data)??(E.data===void 0?[]:[E.data])),process.stderr.write(`✓ 附件上传成功: ${w}
`)}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}
`);let V=Yc(K.document,G,H),X=await fetch(`${J}/api/v1/integrations/webhook/${encodeURIComponent(U)}/document`,{method:"POST",headers:{...q.customHeaders??{},"Content-Type":"application/json",...NZ({webhookId:U,...V},q.secret)},body:JSON.stringify(V)});if(!X.ok)throw Error(`Webhook 单据推送失败 ${X.status}: ${await X.text()}`);I.push({documentId:V.documentId,document:V,pushResult:await X.json()}),process.stderr.write(`✓ 单据推送成功: ${V.documentId}
`)}return{warnings:[],results:I}}function Pq($){return{fileBuffer:su1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}var sp=e(()=>{VD();qc();$c();sn();pU();rp()});import{existsSync as $f1}from"node:fs";async function CP($,Y,q={}){let J=T4().stateful?"stateful":"stateless",U="ok",I,Q,K;try{let A=await z8($);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){U="error",I=A instanceof Error?A.message:String(A)}let G=[];if(U==="ok")try{G=await J$($,Y.seal.endpoints.approvalStylePreferences)}catch(A){U="error",I=`读取 Webhook 配置失败: ${A instanceof Error?A.message:String(A)}`}let H=G.length===1,Z=G.map((A)=>({id:A.id,name:A.name,mode:A.mode,incomingDocumentWebhookUrl:A.incomingDocumentWebhook.url,outgoingResultWebhookUrl:A.outgoingResultWebhook,autoApprovalRate:A.autoApprovalRate,...H?{isDefault:!0}:{}})),V=H?{id:G[0].id,name:G[0].name,mode:G[0].mode}:null,X=q.webhook?l3(G,q.webhook):H?G[0]:void 0,L;if(q.filePath)if(!$f1(q.filePath))L={valid:!1,filePath:q.filePath,fileName:q.filePath.split(/[\\/]/).pop()??q.filePath,documentCount:0,errors:[`文件不存在: ${q.filePath}`]};else try{let A=Pq(q.filePath),E=await Dq(A.fileBuffer,A.fileName,X?.materialPackFilePolicy);L={valid:!0,filePath:q.filePath,fileName:A.fileName,documentCount:E.documents.length,warnings:E.warnings}}catch(A){L={valid:!1,filePath:q.filePath,fileName:q.filePath.split(/[\\/]/).pop()??q.filePath,documentCount:0,errors:[A instanceof Error?A.message:String(A)]}}let w=L?L.valid:!0,F=U==="ok"&&Z.length>0&&w,O=J==="stateful"?"":` --corp ${Y.id}`,P="",B="";if(U!=="ok")B=`凭证鉴权异常: ${I}`,P=`seal-use auth diagnose${O}`;else if(Z.length===0)B="当前企业尚未配置任何 Webhook 集成通道",P=`seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${O}`;else if(L&&!L.valid)B=`资源包预检失败: ${L.errors?.join("; ")}`,P=`seal-use webhook resource-pack preview ${L.filePath}${O}`;else{B=H?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到 ${Z.length} 个 Webhook 通道,等待载入`;let A=L?.filePath??"<资源包.zip>",E=H?"":` --webhook ${V?V.id:"<webhookIdOrName>"}`;P=`seal-use webhook resource-pack push ${A}${E}${O}`}return{ready:F,corp:{id:Y.id,name:Y.name,sourceType:Y.source.type,tenant:Q,user:K},stateMode:J,authStatus:U,authError:I,activeWebhooks:Z,defaultWebhook:V,resourcePack:L,materialPack:L,statusMessage:B,nextAction:P}}var Yv0=e(()=>{K3();I6();sp()});var tp=e(()=>{pU();xz();VD();sn();$c();qc();sp();Yv0();rp()});import{existsSync as qv0,mkdirSync as zv0,statSync as Yf1}from"node:fs";import{homedir as qf1}from"node:os";import{dirname as zf1,resolve as vP}from"node:path";function Jf1($){if($.outputFile){let I=vP($.outputFile),Q=zf1(I);if(!qv0(Q))zv0(Q,{recursive:!0});return I}let q=($.corpName||$.corpId||"企业").replace(/[/\\?%*:|"<>]/g,"_").trim()||"企业",z=$.dateTag||new Date().toISOString().slice(0,10),J=`${q}_智能洞察报告_${z}.xlsx`,U;if($.toDownloads)U=vP(qf1(),"Downloads");else U=vP(process.cwd(),"exports");if(!qv0(U))zv0(U,{recursive:!0});return vP(U,J)}async function hP($,Y,q={}){let z=Y.name||Y.id,J=Ci({startDate:q.startDate,endDate:q.endDate,force:q.force}),U=new Date().toISOString(),[I,Q]=await Promise.all([lL($,{startDate:J.startDateStr,endDate:J.endDateStr,limit:q.limit??100}),rL($,{startDate:J.startDateStr,endDate:J.endDateStr}).catch(()=>({metrics:{},sankeyData:{nodes:[],links:[]}}))]),K=I.tagStats||[],G=[],H=Math.min(K.length,q.limit??50);for(let C=0;C<H;C++){let c=K[C];if(!c?.tagId)continue;try{let n=await oL($,{tagId:c.tagId,startDate:J.startDateStr,endDate:J.endDateStr});for(let g of n.risks||[])G.push({tagId:c.tagId,tagName:c.tagName||c.tagId,documentSN:g.documentSN||"-",documentType:g.documentType||"-",riskLevel:g.riskLevel||"warning",confidence:g.confidence??0,riskDetails:g.riskDetails||"-",reasoning:g.reasoning||"-",sourceDocumentURL:g.sourceDocumentURL,createdAt:g.createdAt})}catch{}}let Z=new Jv0.default.Workbook;Z.creator="seal-use",Z.lastModifiedBy="seal-use",Z.created=new Date,Z.modified=new Date;let V={type:"pattern",pattern:"solid",fgColor:{argb:"FF1E293B"}},X={name:"Microsoft YaHei",size:11,bold:!0,color:{argb:"FFFFFFFF"}},L={top:{style:"thin",color:{argb:"FFE2E8F0"}},bottom:{style:"thin",color:{argb:"FFE2E8F0"}},left:{style:"thin",color:{argb:"FFE2E8F0"}},right:{style:"thin",color:{argb:"FFE2E8F0"}}},w=Z.addWorksheet("审核效能与决策流向",{views:[{showGridLines:!0}]});w.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}],w.getRow(1).height=28,w.getRow(1).font=X,w.getRow(1).fill=V,w.getRow(1).alignment={vertical:"middle",horizontal:"center"};let F=Q.metrics||{},O=[{c Line truncated
`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:PI({id:Y?.id,sn:Y?.sn??Y?.sourceDocumentSN??$.sourceDocumentSN,title:Y?.title??Y?.name,template:uP(Y,["template.name","templateName","form.name","formName","formTitle"]),amount:SP(q,["金额","报销金额","付款金额","合计","价税合计"])??uP(Y,["amount","totalAmount","expenseAmount"]),expenseType:SP(q,["费用类型","费用类别","报销类型"]),costCompany:SP(q,["费用承担公司","承担公司","成本中心","费用归属"]),payee:SP(q,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:q.slice(0,30)}),invoices:Df1($),attachments:a7($,{summary:!0}).attachments,aiResult:bP($),manualResult:Bq($)?.value,hints:PI({amountMentions:Kv0(z,["金额","合计","税率"],8),partyMentions:Kv0(z,["买方","卖方","甲方","乙方","收款"],8)})}}function Ff1($){let Y=[["result.citedRules",O3($,"result.citedRules")],["result.matchedRules",O3($,"result.matchedRules")],["result.ruleResults",O3($,"result.ruleResults")],["result.rules",O3($,"result.rules")],["pipelineData.citedRules",O3($,"pipelineData.citedRules")],["pipelineData.matchedRules",O3($,"pipelineData.matchedRules")]],q=[],z=new Set;for(let[J,U]of Y)(Array.isArray(U)?U:U&&typeof U==="object"?Object.values(U):[]).forEach((Q,K)=>{let G=zW(Q);if(!G)return;let H=_4(G.runtimeRuleId)??_4(G.runtimeId)??_4(G.id)??_4(G.ruleId),Z=_4(G.ruleCode)??_4(G.code)??(H?Bf1(H):void 0),V=PI({runtimeRuleId:H,ruleCode:Z,versionNumber:Mf1(G.versionNumber)??$.ruleSetVersionNumber,scope:_4(G.scope),strictness:_4(G.strictness),appliedAnalysis:G.appliedAnalysis??G.analysis??G.reasoning,checkResult:G.checkResult??G.result??G.decision,findings:G.findings??G.riskPoints??G.evidence,sourcePath:`${J}.${K}`}),X=JSON.stringify(V);if(!z.has(X))z.add(X),q.push(V)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:q.length,rules:q}}function uP($,Y){if(!$)return;for(let q of Y){let z=O3($,q);if(z!==void 0)return z}return}function Qv0($,Y){if(!$)return 0;for(let q of Y){let z=O3($,q);if(Array.isArray(z))return z.length;if(z&&typeof z==="object")return Object.keys(z).length;if(typeof z==="number")return z}return 0}function O3($,Y){return Y.split(".").reduce((q,z)=>{if(q===void 0||q===null)return;if(Array.isArray(q)){let J=Number(z);return Number.isInteger(J)?q[J]:void 0}if(typeof q==="object")return q[z];return},$)}function Of1($,Y,q){let z=Y.split("."),J=$;for(let U of z.slice(0,-1)){let I=J[U];if(!I||typeof I!=="object"||Array.isArray(I))J[U]={};J=J[U]}J[z[z.length-1]??Y]=q}function PI($){return Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))}function zW($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function Mf1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Nf1($){let Y=[];return Yd($,"document",Y),Y}function Yd($,Y,q){if(Array.isArray($)){$.forEach((I,Q)=>Yd(I,`${Y}.${Q}`,q));return}let z=zW($);if(!z)return;let J=_4(z.label)??_4(z.name)??_4(z.title)??_4(z.fieldName),U=z.value??z.displayValue??z.text??z.content;if(J&&U!==void 0&&typeof U!=="object")q.push(PI({path:Y,label:J,value:U,type:_4(z.type)??_4(z.fieldType)}));for(let[I,Q]of Object.entries(z)){if(I==="attachments")continue;Yd(Q,`${Y}.${I}`,q)}}function SP($,Y){return $.find((z)=>{let J=_4(z.label)??"";return Y.some((U)=>J.includes(U))})?.value}function Df1($){let Y=[];return fP($.result,"result",Y),fP($.document,"document",Y),Y.slice(0,20)}function fP($,Y,q){if(Array.isArray($)){$.forEach((J,U)=>fP(J,`${Y}.${U}`,q));return}let z=zW($);if(!z)return;if(/invoice|发票/i.test(Y))q.push(PI({path:Y,fileName:_4(z.fileName)??_4(z.filename)??_4(z.name),buyer:z.buyer??z.buyerName??z.purchaserName,seller:z.seller??z.sellerName,amount:z.amount??z.totalAmount??z.total,taxRate:z.taxRate,category:z.category??z.type}));for(let[J,U]of Object.entries(z))fP(U,`${Y}.${J}`,q)}function Kv0($,Y,q){return $.split(/\r?\n/).filter((z)=>Y.some((J)=>z.includes(J))).slice(0,q)}function yP($){return $.map((Y)=>{let q=Aq(Y);return{recordId:q.id,tenantId:q.tenantId,agentId:q.agentId,sourceDocumentSN:q.sourceDocumentSN,sourceDocumentId:q.sourceDocumentId,simulationBatchId:q.simulationBatchId,langfuseTraceId:q.langfuseTraceId,langfuseSessionFallback:q.langfuseSessionFallback,ruleSetVersionNumber:q.ruleSetVersionNumber,ruleSetPublishedAt:q.ruleSetPublishedAt,ruleSetPublishedByName:q.ruleSetPublishedByName,resolution:q.langfuseTraceId?"trace":q.langfuseSessionFallback?"session-fallback":"unresolved"}})}function ep($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function Pf1($,Y){if(Y.recordId&&!Y.versionId&&!Y.versionNumber&&!Y.latest){let q=await e1($,Y.recordId);if(!q.ruleSetVersionNumber)throw Er Line truncated
`+`• 身份主体:${O}${P}
`+`• 权限范围:持有该链接者在 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
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:Y.sso?H:G,sealResultUrl:G,ssoUrl:H,type:Y.sso?"sso_link":"deep_link",expiresIn:Y.sso?X:void 0,identity:Z,warning:V,enterpriseAssistUrl:I,enterpriseUrl:I,hoseDomain:U.type==="hose"?_f1(U.domain):void 0,documentUrl:Q,recordId:J?.id,sourceDocumentSN:J?.sourceDocumentSN,sourceDocumentId:J?.sourceDocumentId,sourceSystem:J?.sourceSystem,missing:{enterpriseAssistUrl:I?void 0:"Current enterprise source is not Hose, so no Hose enterprise assist URL is configured.",documentUrl:z&&!Q?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:W.object({query:W.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:W.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:W.string().optional().describe("模拟批次 ID"),latest:W.boolean().optional().describe("只返回最新一条匹配记录"),fields:W.union([W.string(),W.array(W.string())]).optional().describe("限制返回字段"),limit:W.number().int().positive().max(100).optional(),maxScan:W.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:W.boolean().optional()}),handler:async($,Y)=>{let q=Y.sn??Y.query;if(!q)throw Error("query or sn is required");let z=await Rf1($,{query:q,sn:Y.sn,batchId:Y.batchId,latest:Y.latest,limit:Y.latest?1:Y.limit??20,maxScan:Y.maxScan??1000}),J=await Promise.all(z.records.map((Q)=>e1($,Q.id))),U=Iv0(Y.fields),I=J.map((Q)=>Tf1(Q,U));return{query:q,sourceDocumentSN:Y.sn,simulationBatchId:Y.batchId,latest:Y.latest??!1,total:z.total,scanned:z.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:yP(J)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:W.object({batchId:W.string().describe("simulation batch ID"),query:W.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,Y)=>{let q=Qd(await kv($,Y.batchId),Y.query);return{batchId:Y.batchId,count:q.length,records:q.map(Aq),bridge:yP(q)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:W.object({mode:W.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:W.array(W.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:W.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:W.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:W.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:W.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:W.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:W.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:W.array(W.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:W.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:W.record(W.string(),W.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),noWait:W.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),rawParams:W.record(W.string(),W.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,Y)=>{let q=Y.mode??"hosecloud",z=Y.signKey;if(q==="hosecloud"&&!z){if(z=(await fv($)).find((Q)=>Q.signKey)?.signKey,!z)throw Error("未找到合思集成 signKey, 请通过 signKey Line truncated
`)}function ff1($){let Y=[];if(Y.push(`seal-use ${$.area} - ${$.title}`),$.description)Y.push($.description);Y.push(""),Y.push("Usage:");for(let q of $.commands)for(let z of q.usage)Y.push(` ${z}`);if($.commands.some((q)=>q.name))Y.push(""),Y.push(`Run 'seal-use ${$.area} <command> --help' for details on a specific command.`);return Y.join(`
`)}function Tv0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let Y of Ev0)for(let q of Y.commands)for(let z of q.usage)$.push(` ${z}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var Ev0;var Vd=e(()=>{V$();Ev0=[{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 UW($){return $.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function E0($,Y={}){pf1($,Y);let q=`${JSON.stringify($,null,2)}
`;if(Y.outputFile){bf1(Y.outputFile,q),console.log(JSON.stringify({outputFile:Y.outputFile,bytes:Buffer.byteLength(q,"utf-8")},null,2));return}console.log(q.trimEnd())}function pf1($,Y={}){if(Y.allowFull||Y.outputFile)return;let q=Buffer.byteLength(JSON.stringify($),"utf-8");if(q>cf1)throw new LD(`Output is large (${q} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function Cv0($,Y){if(Y)return;let q=$&&typeof $==="object"?$:{},z=typeof q.count==="number"?q.count:void 0,J=Array.isArray(q.rules)?q.rules.length:void 0,U=Buffer.byteLength(JSON.stringify($),"utf-8"),I=z??J??0;if(I>if1||U>nf1)throw new LD(`Rule list is large (${I} rules, ${U} 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 F0($){return{allowFull:J0($.full)===!0,outputFile:T($.outputFile)??T($["output-file"])}}function vv0($=[]){console.log(_v0($))}var if1=100,nf1=120000,Rv0,cf1=200000;var o1=e(()=>{R4();V$();Vd();Rv0=["id","code","status","strictness","scope","createdAt","updatedAt"]});var hv0={};$$(hv0,{selectCorp:()=>W1,runToolResult:()=>H2,runTool:()=>A0,globalConfigSummary:()=>G2});function W1($){let Y=r8(),q=T4(),z=$2(Y,{stateful:q.stateful,defaultCorpId:q.defaultCorpId,corpId:$},Q3());return CA0(z.id),z}function G2($=T4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:aY()}}async function A0($,Y,q,z,J={}){E0(await H2($,Y,q,z),J)}async function H2($,Y,q,z){let J=qW.find((Q)=>Q.name===$);if(!J)throw Error(`Unknown Seal tool: ${$}`);let U=Object.fromEntries(Object.entries(z).filter(([,Q])=>Q!==void 0)),I=J.handler;return I(Y,U,{corp:q})}var p4=e(()=>{K3();pi();iP();o1()});var vg0={};$$(vg0,{formatTenantDoctorDashboard:()=>tb1,diagnoseTenantContract:()=>sb1});async function sb1($,Y){let q=[],z=Y.environment==="test"?"test":"production",J=z==="test"?Y.prodCorpId:Y.testCorpId,U=z==="test"?"prodParent":"testTarget",I=null,Q=null;try{let F=await z8($);if(I=F.user,Q=F.tenant,Boolean(I?.isAdmin||I?.permissions?.includes("*")))q.push({id:"auth_identity",name:"身份与权限契约",status:"pass",summary:`已认证为管理员「${I.name??"未知"}」(${I.id??""}),具备完整操作权限`,details:{userId:I.id,userName:I.name,isAdmin:!0,tenantSlug:Q?.tenantSlug,permissions:I.permissions}});else q.push({id:"auth_identity",name:"身份与权限契约",status:"warn",summary:`已认证为普通用户「${I.name??"未知"}」,非超级管理员,部分配置操作可能受限`,details:{userId:I.id,userName:I.name,isAdmin:!1,permissions:I.permissions},recommendation:"建议使用具有管理权限的企业主账号执行规则修改与集成发布"})}catch(F){q.push({id:"auth_identity",name:"身份与权限契约",status:"fail",summary:`鉴权握手失败:${F instanceof Error?F.message:String(F)}`,details:{error:String(F)},recommendation:`请执行 seal-use auth login --corp ${Y.id} 重新登录或更新 Token`})}let K={featureCode:"ai-approval",balance:0,deductionAmount:120,estimatedRuns:0,status:"exhausted"},G={used:0,remaining:0};try{let F=await g2($),O=Array.isArray(F.features)?F.features:[],P=O.find((A)=>A?.code==="ai-approval");if(P){let A=typeof P.balance==="number"?P.balance:0,E=typeof P.deductionAmount==="number"&&P.deductionAmount>0?P.deductionAmount:120,y=Math.floor(A/E);if(K.balance=A,K.deductionAmount=E,K.estimatedRuns=y,A<=0)K.status="exhausted",q.push({id:"billing_quota",name:"AI 审批额度余量",status:"fail",summary:"当前额度已耗尽 (余量 0 点),无法执行审批模拟或回归测试",details:{balance:A,deductionAmount:E,estimatedRuns:y},recommendation:"请联系管理员为企业充值 AI 审批额度"});else if(y<10)K.status="low",q.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`额度偏低:剩余 ${A} 点 (单笔扣除 ${E} 点),仅可支持约 ${y} 笔审核`,details:{balance:A,deductionAmount:E,estimatedRuns:y},recommendation:"建议在发起大规模自动化回归前充值补充额度"});else K.status="sufficient",q.push({id:"billing_quota",name:"AI 审批额度余量",status:"pass",summary:`额度充裕:剩余 ${A} 点,预估可支持 ${y} 笔审核单据`,details:{balance:A,deductionAmount:E,estimatedRuns:y}})}else q.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:"未检索到「ai-approval」功能包额度明细,按默认通道运行",details:{features:O.map((A)=>A?.code)}});let B=O.find((A)=>A?.code==="approval-rules");if(B)G.used=typeof B.used==="number"?B.used:0,G.remaining=typeof B.remaining==="number"?B.remaining:0}catch(F){q.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`读取计费状态失败:${F instanceof Error?F.message:String(F)}Line truncated
`)}var hg0=e(()=>{I6()});import{dirname as LW,resolve as FS0}from"node:path";import{fileURLToPath as Ci1}from"node:url";S8();function $z($){return!!$._zod}function g3($,Y){if($z($))return xq($,Y);return $.safeParse(Y)}function kX($){if(!$)return;let Y;if($z($))Y=$._zod?.def?.shape;else Y=$.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function Bo($){if($z($)){let U=$._zod?.def;if(U){if(U.value!==void 0)return U.value;if(Array.isArray(U.values)&&U.values.length>0)return U.values[0]}}let q=$._def;if(q){if(q.value!==void 0)return q.value;if(Array.isArray(q.values)&&q.values.length>0)return q.values[0]}let z=$.value;if(z!==void 0)return z;return}var BR="2025-11-25";var nr=[BR,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],y3="io.modelcontextprotocol/related-task",wV="2.0",V6=VV(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),cr=U4([Z0(),v1().int()]),pr=Z0(),bp1=S6({ttl:v1().optional(),pollInterval:v1().optional()}),ik0=h0({ttl:v1().optional()}),nk0=h0({taskId:Z0()}),TR=S6({progressToken:cr.optional(),[y3]:nk0.optional()}),z$=h0({_meta:TR.optional()}),jQ=z$.extend({task:ik0.optional()}),dr=($)=>jQ.safeParse($).success,x6=h0({method:Z0(),params:z$.loose().optional()}),M$=h0({_meta:TR.optional()}),N$=h0({method:Z0(),params:M$.loose().optional()}),k6=S6({_meta:TR.optional()}),FV=U4([Z0(),v1().int()]),mr=h0({jsonrpc:u0(wV),id:FV,...x6.shape}).strict(),ER=($)=>mr.safeParse($).success,lr=h0({jsonrpc:u0(wV),...N$.shape}).strict(),or=($)=>lr.safeParse($).success,jR=h0({jsonrpc:u0(wV),id:FV,result:k6}).strict(),_Q=($)=>jR.safeParse($).success;var O1;(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"})(O1||(O1={}));var _R=h0({jsonrpc:u0(wV),id:FV.optional(),error:h0({code:v1().int(),message:Z0(),data:J4().optional()})}).strict();var rr=($)=>_R.safeParse($).success;var sr=U4([mr,lr,jR,_R]),ip1=U4([jR,_R]),OV=k6.strict(),ck0=M$.extend({requestId:FV.optional(),reason:Z0().optional()}),MV=N$.extend({method:u0("notifications/cancelled"),params:ck0}),pk0=h0({src:Z0(),mimeType:Z0().optional(),sizes:H1(Z0()).optional(),theme:y6(["light","dark"]).optional()}),RQ=h0({icons:H1(pk0).optional()}),Gz=h0({name:Z0(),title:Z0().optional()}),tr=Gz.extend({...Gz.shape,...RQ.shape,version:Z0(),websiteUrl:Z0().optional(),description:Z0().optional()}),dk0=Kz(h0({applyDefaults:t4().optional()}),a1(Z0(),J4())),mk0=EQ(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},Kz(h0({form:dk0.optional(),url:V6.optional()}),a1(Z0(),J4()).optional())),lk0=S6({list:V6.optional(),cancel:V6.optional(),requests:S6({sampling:S6({createMessage:V6.optional()}).optional(),elicitation:S6({create:V6.optional()}).optional()}).optional()}),ok0=S6({list:V6.optional(),cancel:V6.optional(),requests:S6({tools:S6({call:V6.optional()}).optional()}).optional()}),rk0=h0({experimental:a1(Z0(),V6).optional(),sampling:h0({context:V6.optional(),tools:V6.optional()}).optional(),elicitation:mk0.optional(),roots:h0({listChanged:t4().optional()}).optional(),tasks:lk0.optional(),extensions:a1(Z0(),V6).optional()}),sk0=z$.extend({protocolVersion:Z0(),capabilities:rk0,clientInfo:tr}),RR=x6.extend({method:u0("initialize"),params:sk0});var tk0=h0({experimental:a1(Z0(),V6).optional(),logging:V6.optional(),completions:V6.optional(),prompts:h0({listChanged:t4().optional()}).optional(),resources:h0({subscribe:t4().optional(),listChanged:t4().optional()}).optional(),tools:h0({listChanged:t4().optional()}).optional(),tasks:ok0.optional(),extensions:a1(Z0(),V6).optional()}),ak0=k6.extend({protocolVersion:Z0(),capabilities:tk0,serverInfo:tr,instructions:Z0().optional()}),CR=N$.extend({method:u0("notifications/initialized"),params:M$.optional()});var NV=x6.extend({method:u0("ping"),params:z$.optional()}),ek0=h0({progress:v1(),total:K4(v1()),message:K4(Z0())}),$u0=h0({...M$.shape,...ek0.shape,progressToken:cr}),DV=N$.extend({method:u0("notifications/progress"),params:$u0}),Yu0=z$.extend({cursor:pr.optional()}),CQ=x6.extend({params:Yu0.optional()}),vQ=k6.extend({nextCursor:pr.optional()}),qu0=y6(["working","input_required","completed","failed","cancelled"]),hQ=h0({taskId:Z0(),status:qu0,ttl:U4([v1(),OQ()]),createdAt:Z0(),lastUpdatedAt:Z0(),pollInterval:K4(v1()),statusMessage:K4(Z0())}),Hz=k6.extend({task:hQ}),zu0=M$.merge(hQ),gQ=N$.extend({method:u0("notifications/tasks/status"),params:zu0}),PV=x6.extend({method:u0("tasks/get"),params:z$.extend({taskId:Z0()})}),AV=k6.merge(hQ),BV=x6.extend({method:u0("tasks/result"),params:z$.extend({taskId:Z0()})}),np1=k6.loose(),TV=CQ.extend({method:u0("tasks/list")}),EV=vQ.extend({tasks:H1(hQ)}),jV=x6.extend({method:u0("tasks/cancel"),para Line truncated
`);if($===-1)return null;let Y=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),ol0(Y)}clear(){this._buffer=void 0}}function ol0($){return sr.parse(JSON.parse($))}function m00($){return JSON.stringify($)+`
`}class aC{constructor($=l00.stdin,Y=l00.stdout){this._stdin=$,this._stdout=Y,this._readBuffer=new tC,this._started=!1,this._ondata=(q)=>{this._readBuffer.append(q),this.processReadBuffer()},this._onerror=(q)=>{this.onerror?.(q)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((Y)=>{let q=m00($);if(this._stdout.write(q))Y();else this._stdout.once("drain",Y)})}}b8();import{dirname as sd,join as Bi1}from"node:path";import{fileURLToPath as Ti1}from"node:url";import{spawnSync as o10}from"node:child_process";var wK={name:"seal-use",version:"0.10.24",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 xo0($,Y=wK.version){let q=$.trim();if(!q)return null;let z=q.endsWith("-dirty"),J=z?q.slice(0,-6):q,U=J.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/);if(U&&U[1]&&U[2]&&U[3])return{baseVersion:U[1],commitsAhead:Number.parseInt(U[2],10),commit:U[3],dirty:z,describe:q};let I=J.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)$/);if(I&&I[1])return{baseVersion:I[1],commitsAhead:0,commit:"",dirty:z,describe:q};let Q=J.match(/^([0-9a-f]{7,40})$/);if(Q&&Q[1])return{baseVersion:Y,commitsAhead:0,commit:Q[1],dirty:z,describe:q};return null}function ko0($,Y,q,z){let U=q?`+g${q}${z?".dirty":""}`:z?"+dirty":"";return`${$}-dev.${Y}${U}`}function uo0($){let Y=$?.env,q=Y?.SEAL_BUILD_VERSION??process.env.SEAL_BUILD_VERSION,z=Y?.SEAL_BUILD_IS_RELEASE??process.env.SEAL_BUILD_IS_RELEASE,J=Y?.SEAL_BUILD_CHANNEL??process.env.SEAL_BUILD_CHANNEL,U=Y?.SEAL_BUILD_GIT_BASE??process.env.SEAL_BUILD_GIT_BASE,I=Y?.SEAL_BUILD_GIT_COMMITS_AHEAD??process.env.SEAL_BUILD_GIT_COMMITS_AHEAD,Q=Y?.SEAL_BUILD_GIT_COMMIT??process.env.SEAL_BUILD_GIT_COMMIT,K=Y?.SEAL_BUILD_GIT_DIRTY??process.env.SEAL_BUILD_GIT_DIRTY,G=Y?.SEAL_BUILD_GIT_DESCRIBE??process.env.SEAL_BUILD_GIT_DESCRIBE,H=Y?.SEAL_FORCE_RELEASE??process.env.SEAL_FORCE_RELEASE,Z=$?.cwd;if(q){let V=z==="true",L={name:"seal-use",version:q,channel:J||(V?"release":"dev"),isRelease:V};if(U)L.git={baseVersion:U,commitsAhead:Number.parseInt(I||"0",10),commit:Q||"",dirty:K==="true",describe:G||q};return L}if(z==="true"||H==="1")return{name:"seal-use",version:wK.version,channel:"release",isRelease:!0};try{let V=o10("git",["describe","--tags","--long","--dirty","--always"],{cwd:Z,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(V.status===0&&V.stdout){let X=xo0(V.stdout.trim(),wK.version);if(X){if(!X.commit){let w=o10("git",["rev-parse","--short","HEAD"],{cwd:Z,encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(w.status===0&&w.stdout)X.commit=w.stdout.trim()}return{name:"seal-use",version:ko0(X.baseVersion,X.commitsAhead,X.commit,X.dirty),channel:"dev",isRelease:!1,git:X}}}}catch{}return{name:"seal-use",version:`${wK.version}-dev.0+local`,channel:"dev",isRelease:!1}}var FK=uo0(),Q1=FK.version,Av=FK.isRelease,Qa1=FK.channel;I6();JD();ID();p4();R4();o1();b8();p4();I6();I6();DZ();tp();R4();o1();V$();import{existsSync as gv0}from"node:fs";async function Sv0($,Y){if(!gv0($))throw Error(`File not found: ${$}`);let q=Pq($);console.log(JSON.stringify(await Dq(q.fileBuffer,q.fileName,Y),null,2))}async function mP($,Y,q,z,J){if($==="ready"||$==="status"){let U=Y??T(J.options.file)??T(J.options.input),I=await CP(q,z,{filePath:U,webhook:T(J.options.webhook)??T(J.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.erro 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>")}E0(O.map((P)=>({id:P.id,name:P.name,environment:P.environment??"production",sourceType:P.source.type,provider:P.source.provider??P.source.type,staffId:P.source.staffId,testCorpId:P.testCorpId,prodCorpId:P.prodCorpId,current:P.id===G})));return}if($==="get"||$==="show"){let z=Y??T(q.options.corp);if(!z)throw i4("Usage: seal-use corps get <corpId>");let J=W1(z),U=bi(J.id),I=Ob1(J);E0({id:J.id,name:J.name,environment:J.environment??"production",configFile:U,seal:{url:I,tenantSlug:J.seal.tenantSlug??J.source.tenantSlug,customHeaderNames:J.seal.headers?Object.keys(J.seal.headers):[],customCookieNames:J.seal.cookies?Object.keys(J.seal.cookies):[],endpoints:J.seal.endpoints},source:Mb1(J.source),relations:{testCorpId:J.testCorpId,prodCorpId:J.prodCorpId},auth:{refreshTtl:J.auth.refreshTtl}});return}if($==="current"){let z=W1(T(q.options.corp));E0({id:z.id,name:z.name,environment:z.environment??"production",sourceType:z.source.type,provider:z.source.provider??z.source.type,staffId:z.source.staffId,testCorpId:z.testCorpId,prodCorpId:z.prodCorpId});return}if($==="mark"||$==="mark-test"||$==="mark-prod"){let z=Y??T(q.options.corp);if(!z)throw i4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");let J=W1(z),U=$==="mark-test"?"test":$==="mark-prod"?"production":T(q.options.env)??T(q.options.environment);if(U!=="production"&&U!=="test")throw i4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");if(!(J0(q.options.confirm)===!0||J0(q.options.yes)===!0))throw K9(`Refusing to change environment tag of enterprise '${J.name}' (${J.id}) to '${U}' without --confirm. Marking alters synchronization safety guards.`,`seal-use corps mark ${J.id} --env ${U} --confirm`);let Q=e7(J.id,{environment:U});E0({id:Q.id,name:Q.name,environment:Q.environment,testCorpId:Q.testCorpId,prodCorpId:Q.prodCorpId});return}if($==="bind-test"){let z,J;if(Y&&q.command[3])z=Y,J=q.command[3];else if(Y){let Z=T(q.options.corp),V=T(q.options["test-corp"])??T(q.options.testCorp);if(Z)z=Z,J=Y;else if(V)z=Y,J=V}if(!z||!J)throw i4(`Usage: seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
or: seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]`);let U=W1(z),I=W1(J);if(U.id===I.id)throw i4(`Cannot bind enterprise '${U.id}' to itself.`);if(U.prodCorpId&&U.prodCorpId!==I.id)throw i4(`Cannot use '${U.id}' as a production enterprise because it is already registered as a test enterprise for '${U.prodCorpId}'. Multi-tier chaining is not permitted.`);if(I.testCorpId&&I.testCorpId!==U.id)throw i4(`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 Q=J0(q.options.force)===!0;if(U.testCorpId&&U.testCorpId!==I.id||I.prodCorpId&&I.prodCorpId!==U.id){if(!Q)throw K9(`Enterprise binding conflict: production enterprise '${U.id}' is bound to '${U.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 ${U.id} ${I.id} --confirm --force`)}if(!(J0(q.options.confirm)===!0||J0(q.options.yes)===!0)){let Z=Q?" --force":"";throw K9(`Refusing to bind test enterprise '${I.name}' (${I.id}) to production enterprise '${U.name}' (${U.id}) without --confirm. Enterprise binding establishes 1-to-1 sync pairing and marks '${I.id}' as a test environment.`,`seal-use corps bind-test ${U.id} ${I.id} --confirm${Z}`)}if(U.testCorpId&&U.testCorpId!==I.id)try{e7(U.testCorpId,{prodCorpId:void 0})}catch{}if(I.prodCorpId&&I.prodCorpId!==U.id)try{e7(I.prodCorpId,{testCorpId:void 0})}catch{}let G=e7(U.id,{environment:"production",testCorpId:I.id}),H=e7(I.id,{environment:"test",prodCorpId:U.id});E0({success:!0,productionEnterprise:{id:G.id,name:G.name,environment:G.environment,testCorpId:G.testCorpId},testEnterprise:{id:H.id,name:H.name,environment:H.environment,prodCorpId:H.prodCorpId}});return}if($==="unbind-test"){let z=Y??T(q.options.corp),J=W1(z);if(!J.testCorpId&&!J.prodCorpId){E0({unbound:!1,message:`Enterprise '${J.name}' (${J.id}) does not have an active test enterprise binding.`});return}let U=J.testCorpId?J.id:J.prodCorpId,I=J.testCorpId?J.testCorpId:J.id;if(!(J0(q.options.confirm)===!0||J0(q.options.yes)===!0))throw K9(`Refusing to unbind production enterprise '${U}' and test enterprise '${I}' without --confirm.`,`seal-use corps unbind-test ${J.id} --confirm`);e7(U,{testCorpId:void 0});try{e7(I,{prodCorpId:void 0})}catch{}E0({success:!0,unboundProduction:U,unboundTest:I});return}if($==="sync-test"){let z=Y??T(q.options.corp),J=W1(z);if(!J.testCorpId)throw i4(`Production enterprise '${J.name}' (${J.id}) has no bound test enterprise.
Run 'seal-use corps bind-test ${J.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`);let U=W1(J.testCorpId);if(U.environment!=="test")throw Error(`Target enterprise '${U.name}' (${U.id}) is marked as '${U.environment}', NOT 'test'. Aborting sync to protect non-test environments.`);let I=await Z1(J),Q=await Z1(U),[K,G,H,Z,V,X,L,w]=await Promise.all([x1(I,J.seal.endpoints.approvalStylePreferences).catch(()=>({})),x1(Q,U.seal.endpoints.approvalStylePreferences).catch(()=>({})),b6(I),b6(Q),B$(I).catch(()=>[]),B$(Q).catch(()=>[]),m3(I,{limit:100}).catch(()=>({articles:[]})),m3(Q,{limit:100}).catch(()=>({articles:[]}))]),F=(L.articles||[]).filter((K0)=>!K0.isDeleted),O=(w.articles||[]).filter((K0)=>!K0.isDeleted),P=new Map(O.map((K0)=>[K0.title.trim(),K0])),B=[],A=[],E=new Set(F.map((K0)=>K0.title.trim()));for(let K0 of F){let v0=K0.title.trim(),f0=P.get(v0);if(!f0)B.push(K0);else{let c0=f0.content!==K0.content,C1=(f0.purpose??"")!==(K0.purpose??""),a0=f0.enabled!==K0.enabled,r1=f0.contentType!==K0.contentType,F1=(f0.status??"")!==(K0.status??""),b1=JSON.stringify([...f0.scenarios??[]].sort())!==JSON.stringify([...K0.scenarios??[]].sort()),$1=JSON.stringify([...f0.tags??[]].sort())!==JSON.stringify([...K0.tags??[]].sort());if(c0||C1||a0||r1||F1||b1||$1)A.push({testId:f0.id,prodDoc:K0,reasons:[...c0?["content"]:[],...C1?["purpose"]:[],...a0?["enabled"]:[],...r1?["contentType"]:[],...F1?["status"]:[],...b1?["scenarios"]:[],...$1?["tags"]:[]]})}}let y=O.filter((K0)=>!E.has(K0.title.trim())),k=[...V].sort((K0,v0)=>v0.versionNumber-K0.versionNumber)[0],C=k?.versionNumber,n=([...X].sort((K0,v0)=>v0.versionNumber-K0.versionNumber)[0]?.versionNumber??0)+1,g=nh0(J.name,C,X),i=T(q.options["version-name"])??T(q.options.versionName)??ch0(J.name,C,g,n),$0={...G,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(J0(q.options["dry-run"])===!0||J0(q.options.dryRun)===!0){E0({dryRun:!0,source:{id:J.id,name:J.name,environment:J.environment,latestPublishedVersion:k?{versionNumber:k.versionNumber,versionName:k.versionName}:null,documentsCount:F.length},target:{id:U.id,name:U.name,environment:U.environment},versionMappingPlan:{sourceProdVersionNumber:C??null,sourceProdVersionName:k?.versionName??null,targetTestExpectedVersionNumber:n,targetTestPublishVersionName:i,iteration:g},preferencesDiff:{decisionPreferences:{before:G.decisionPreferences,after:K.decisionPreferences},thinkingDepthPreference:{before:G.thinkingDepthPreference,after:K.thinkingDepthPreference}},rulesPlan:{sourceDraftRuleCount:H.rules.length,targetExistingDraftRuleCount:Z.rules.length,toDeleteCount:Z.rules.length,toCreateCount:H.rules.length,rulesToSync:H.rules.map((K0,v0)=>({index:v0+1,sourceRuleId:K0.id,sourceRuleCode:K0.code??v0+1,expectedTargetCode:`rule-${v0+1}`,description:K0.description,scope:K0.scope,strictness:K0.strictness}))},documentsPlan:{sourceDocumentCount:F.length,targetExistingDocumentCount:O.length,toCreateCount:B.length,toCreate:B.map((K0)=>({title:K0.title,purpose:K0.purpose,contentType:K0.contentType,scenarios:K0.scenarios})),toUpdateCount:A.length,toUpdate:A.map((K0)=>({targetDocumentId:K0.testId,title:K0.prodDoc.title,reasons:K0.reasons})),toDeleteCount:y.length,toDelete:y.map((K0)=>({targetDocumentId:K0.id,title:K0.title}))},publishingPlan:{targetCorpId:U.id,publishVersionName:i,publishTarget:"test"},hosecloudSyncPlan:(()=>{if(J.source.type!=="hose")return{sourceType:J.source.type,skipped:!0,reason:"prod source is not hose; no hosecloud credentials available"};let K0=(K.integrations??[]).filter((c0)=>c0.type==="hosecloud"),v0=new Set,f0=K0.filter((c0)=>{let C1=c0.corporationId??J.id;if(v0.has(C1))return!1;return v0.add(C1),!0});return{sourceType:"hose",outboundName:rh0(J.name),targetMode:"assisted",integrationsCount:f0.length,integrations:f0.map((c0)=>({corporationId:c0.corporationId,apiOrigin:c0.apiOrigin,customApiUrl:c0.customApiUrl}))}})(),productionGuarantees:{prodRulesStayDraft:!0,prodVersionPublished:!1}});return}if(!(J0(q.options.yes)===!0||J0(q.options.confirm)===!0))throw K9(`Refusing to overwrite test enterprise '${U.name}' (${U.id}) with preferences, ${H.rules.length} draft rules, and ${F.length} knowledge documents from production enterprise '${J.name}' (${J.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,`seal-use corps sync-test ${J.id} --yes`);await g5(Q,$0,U.seal.endpoints.approvalStylePreferences);let p=[];for(let K0 of y)await iL(Q,K0.id),p.push({id:K0.id,title:K0.title});let d=[];for(let K0 of A)await bL(Q,K0.testId,{title:K0.prodDoc.title,purpose:K0.prodDoc.purpose,content:K0.prodDoc.content,contentType:K0.prodDoc.contentType,status:K0.prodDoc.status,enabled:K0.prodDoc.ena Line truncated
Run 'seal-use corps bind-test ${J.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=J}else if(I=W1(J.testCorpId),I.environment!=="test"&&!U)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 Q=T(q.options.recordId)??T(q.options["record-id"])??T(q.options.id),K=T(q.options.recordIds)??T(q.options["record-ids"]),G=K?K.split(",").map((n)=>n.trim()).filter(Boolean):void 0,H=T(q.options.sn)??T(q.options.documentSn)??T(q.options["document-sn"]),Z=T(q.options.sns)??T(q.options["document-sns"]),V=Z?Z.split(",").map((n)=>n.trim()).filter(Boolean):void 0,X=g0(q.options.limit)??(!Q&&!G&&!H&&!V?1:void 0),L=T(q.options.status),w=T(q.options.startDate)??T(q.options["start-date"]),F=T(q.options.endDate)??T(q.options["end-date"]),O=await Z1(J),P=J.id===I.id?O:await Z1(I),B=T(q.options.webhook)??T(q.options.selector),A=T(q.options.snSuffix)??T(q.options["sn-suffix"]),E=T(q.options.snPrefix)??T(q.options["sn-prefix"]),y=T(q.options.docIdSuffix)??T(q.options["doc-id-suffix"]),v=T(q.options.docIdPrefix)??T(q.options["doc-id-prefix"]),k=J0(q.options.dryRun)??J0(q.options["dry-run"]),C={recordId:Q,recordIds:G,sn:H,sns:V,limit:X,status:L,startDate:w,endDate:F};console.error(`[corps-replay-test] 正式企业「${J.name}」(${J.id}) -> 测试企业「${I.name}」(${I.id})`);let c=await nU({query:C,sourceClient:O,targetClient:P,sourceCorp:J,targetCorp:I,webhookSelector:B,snPrefix:E,snSuffix:A,docIdPrefix:v,docIdSuffix:y,dryRun:k});if(k){console.error(`[corps-replay-test] 预览模式:已成功从 ${J.name} 提取单据并转换为 Webhook Payload(未实际推送)。`),console.log(JSON.stringify(c,null,2));return}if(c.success)if(c.totalCount===1&&c.replayedDocument)console.error(`\uD83D\uDFE2 成功重放单据「${c.replayedDocument.documentSN}」至 ${I.name} (${c.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDFE2 成功重放 ${c.successCount} 条单据(来自「${J.name}」)至「${I.name}」(${c.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDD34 单据重放部分或全部失败(成功 ${c.successCount} 条,失败 ${c.failureCount} 条)至「${I.name}」`);if(console.error(`\uD83D\uDC49 Next action: seal-use approval-runs list --corp ${I.id} --limit ${c.totalCount}`),console.log(JSON.stringify(c,null,2)),!c.success)process.exitCode=1;return}if($==="switch"){let z=Y;if(!z)throw Error("Usage: seal-use corps switch <corpId>");let J=T4();if(!J.stateful)throw Error("Cannot switch the default enterprise while stateless mode is enabled. Use `seal-use config mode stateful` first.");let U=W1(z);eY({...J,stateful:!0,defaultCorpId:U.id}),E0({current:!0,id:U.id,name:U.name});return}if($==="probe-hose"){await Db1(C8(q.json));return}if($==="hose-staffs"){await Pb1(C8(q.json));return}if($==="add-hose"){await Td(C8(q.json));return}if($==="add-seal"){await Ab1(C8(q.json));return}if($==="add-link"){let z=Y??T(q.options.link)??T(q.options.url);if(!z)throw Error("Usage: seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--as-hose] [--overwrite]");if(J0(q.options["as-hose"])===!0||J0(q.options.hose)===!0){await Tb1(z,T(q.options.name),J0(q.options.overwrite)===!0,J0(q.options.force)===!0,{appKey:T(q.options["app-key"])??T(q.options.appKey),keyId:T(q.options["key-id"])??T(q.options.keyId)});return}await Bb1(z,T(q.options.name),J0(q.options.overwrite)===!0);return}if($==="extract-keys"||$==="extract-key"){let z=Y??T(q.options.link)??T(q.options.url);if(!z)throw Error("Usage: seal-use corps extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]");let J=J0(q.options.reveal)===!0||J0(q.options.r)===!0||J0(q.options.plain)===!0,U=J0(q.options.save)===!0||J0(q.options.add)===!0;await eP(z,{reveal:J,save:U,name:T(q.options.name),overwrite:J0(q.options.overwrite)===!0,force:J0(q.options.force)===!0,appKey:T(q.options["app-key"])??T(q.options.appKey),keyId:T(q.options["key-id"])??T(q.options.keyId)});return}if($==="keys"){let z=Y??T(q.options.link)??T(q.options.url)??T(q.options.corp),J=J0(q.options.reveal)===!0||J0(q.options.r)===!0||J0(q.options.plain)===!0;if(z&&(z.startsWith("http://")||z.startsWith("https://"))){let U=J0(q.options.save)===!0||J0(q.options.add)===!0;await eP(z,{reveal:J,save:U,name:T(q.options.name),overwrite:J0(q.options.overwrite)===!0,force:J0(q.options.force)===!0,appKey:T(q.options["app-key"])??T(q.options.appKey),keyId:T(q.options["key-id"])??T(q.options.keyId)});return}await Ed(z,{reveal:J});return}throw Error(`Unknown corps command: ${$??""}. Run 'seal-use help' for available commands.`)}function rh0($){return[...$].slice(0,6).join("")+"(Seal测)"}async function Nb1($,Y,q,z){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]
- ${c}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!w)if(!H&&U)w=U;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-use corps hose-staffs' to discover available administrators.");let F=Y4($,"id")??V,O=X??V,P=Y4($,"sealUrl")??`https://${V.toLowerCase()}.sealai.cc`,B={id:F,name:O,environment:"production",seal:{url:P,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:Z,appKey:q,appSecurity:z,corpId:V,staffId:w},auth:{refreshTtl:300}};if(H)AL(F),await jI(B);let A=fi();dh0(A,{recursive:!0,mode:448});let E=lh0(A,`${nP(F)}.json`);if(ph0(E)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${E}. Pass "overwrite": true to replace it.`);mh0(E,`${JSON.stringify(B,null,2)}
`,{mode:384}),E0({id:F,name:O,corpId:V,domain:Z,staffId:w,verified:H,path:E})}async function Ab1($){let Y=M3($,"token"),q=(Y4($,"sealUrl")??Y4($,"url")??"").replace(/\/+$/,"");if(!q)throw Error("Missing required JSON field: sealUrl");let z=Gd($,"expiresIn")??2592000,J=$.force===!0||$.verify===!1?!1:!0,U=sh0($),I=J?await Eb1(q,Y,w6(U)):void 0;ah0($,{token:Y,sealUrl:q,expiresIn:z,verify:J,remote:I,custom:U})}function sh0($){return{headers:Si.parse($.headers),cookies:yi.parse($.cookies)}}async function Bb1($,Y,q){let z=await BL($),J=N8(z.sealUrl,z.token),U=await z8(J),I={user:U.user,tenant:U.tenant};TL(z.corpId,I.tenant),ah0({id:z.corpId,corpId:z.corpId,name:Y,provider:"hosecloud",overwrite:q},{token:z.token,sealUrl:z.sealUrl,expiresIn:z.expiresIn,verify:!0,remote:I})}function th0($,Y,q,z){if($.length===0)throw Error(`[合思子域提权] 未能从协助链接中提取到合思企业 [${Y}] 的 OpenAPI 密钥凭据。
`+"\uD83D\uDCA1 说明:此能力专属于合思 (Hose) 子域,用于将临时会话提权为标准 OpenAPI 开发者接入。需要企业管理员已在合思开放平台创建应用并生成 appKey/appSecurity。");if(q.keyId||q.appKey){let J=$.find((U)=>q.keyId&&U.id===q.keyId||q.appKey&&U.appKey===q.appKey);if(!J){console.error(`
❌ 未找到指定的合思 OpenAPI 密钥 (${q.appKey??q.keyId})。`),console.error(`ℹ️ 该合思企业当前存在以下 ${$.length} 套候选密钥:`);for(let U of $){let I=U.active?"\uD83D\uDFE2 启用":"⚪ 停用";console.error(` • "${U.name||"未命名应用"}" (appKey: ${U.appKey}, keyId: ${U.id}, 状态: ${I})`)}throw new Z4("指定的合思密钥不存在,请从上述候选列表中选择正确的 appKey 或 keyId。",2,`${z} --app-key ${$[0].appKey}`)}return J}if($.length===1)return $[0];console.error(`
ℹ️ [合思子域提权] 合思企业 [${Y}] 存在多套 (${$.length} 套) OpenAPI 应用密钥凭据:`);for(let J=0;J<$.length;J++){let U=$[J],I=U.active?"\uD83D\uDFE2 启用":"⚪ 停用",Q=U.name||"未命名应用";console.error(` [${J+1}] "${Q}" (appKey: ${U.appKey}, keyId: ${U.id}, 状态: ${I})`)}throw console.error(`
\uD83D\uDC49 为确保权限提权绑定正确的业务应用,请显式指定要使用的密钥套件:`),console.error(` 在命令后追加 --app-key <key> 或 --key-id <id> 参数。
`),new Z4(`合思企业 [${Y}] 存在多套 OpenAPI 密钥,必须指定 --app-key 或 --key-id 明确选择要绑定的密钥。`,2,`${z} --app-key ${$[0].appKey}`)}async function Tb1($,Y,q,z=!1,J){console.error("ℹ️ [合思子域提权] 正在通过合思协助链接提取 OpenAPI 开发者密钥并提升企业权限等级...");let U=await Nv($),I=th0(U.keys,U.corpId,J??{},'seal-use corps add-link "<url>" --as-hose');console.error(`ℹ️ [合思子域提权] 已选定合思 OpenAPI 凭据 (appKey: ${I.appKey}, 应用: "${I.name||"未命名应用"}"),正在初始化为长期合思标准配置...`),await Td({domain:U.baseUrl,appKey:I.appKey,appSecurity:I.appSecurity,corpId:U.corpId,name:Y??U.corpName??U.corpId,staffId:U.staffId,overwrite:q,force:z})}async function eP($,Y){let q=await Nv($),z=Y.reveal===!0;if(Y.save){let J=th0(q.keys,q.corpId,{appKey:Y.appKey,keyId:Y.keyId},'seal-use corps extract-keys "<url>" --save');console.error(`ℹ️ [合思子域提权] 正在将选定的合思 OpenAPI 密钥 (appKey: ${J.appKey}, 应用: "${J.name||"未命名应用"}") 保存为标准合思企业配置...`),await Td({domain:q.baseUrl,appKey:J.appKey,appSecurity:J.appSecurity,corpId:q.corpId,name:Y.name??q.corpName??q.corpId,staffId:q.staffId,overwrite:Y.overwrite,force:Y.force});return}if(!z)console.error(`ℹ️ [合思子域提权] 成功提取合思 (Hose) OpenAPI 密钥。接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文;附加 --save 可将临时会话提权并持久化为标准合思企业。
`);else console.error(`⚠️ [合思子域提权] 正在以明文展示合思 (Hose) appSecurity 接入密码,请妥善保管敏感凭据。
`);E0({provider:"hose",capability:"privilege-elevation",corpId:q.corpId,corpName:q.corpName??q.corpId,baseUrl:q.baseUrl,staffId:q.staffId,keyCount:q.keys.length,keys:q.keys.map((J)=>({id:J.id,name:J.name||"-",appKey:J.appKey,appSecurity:z?J.appSecurity:Mv(J.appSecurity),active:J.active,createTime:J.createTime,updateTime:J.updateTime}))})}async function Ed($,Y){let q=W1($),z=Y.reveal===!0;if(q.source.type!=="hose")throw new Z4(`【合思子域专享能力】当前企业「${q.name}」(id: ${q.id}) 为原生 Seal (${q.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。
`+"OpenAPI 密钥查询与提权能力专属于合思生态租户(用于从合思协助链接或合思凭据中提取开发者密钥提升权限等级),非合思渠道企业不支持此能力。",2);let J=q.source.appKey??q.source.key,U=q.source.appSecurity??q.source.password;if(!z)console.error(`\uD83D\uDCA1 [合思子域] 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文。
`);else console.error(`⚠️ [合思子域] 正在以明文展示合思 appSecurity 接入密码,请妥善保管敏感凭据。
`);E0({provider:"hose",capability:"privilege-elevation",corpId:q.id,corpName:q.name,domain:q.source.domain,staffId:q.source.staffId,appKey:J??"-",appSecurity:U?z?U:Mv(U):"-",active:!0})}function ah0($,Y){let{token:q,sealUrl:z,expiresIn:J,verify:U,remote:I}=Y,Q=Y.custom??sh0($),K=I?.user,G=I?.tenant,H=Y4($,"tenantSlug")??W2(G?.tenantSlug),Z=Y4($,"tenantId")??W2(G?.id),V=Y4($,"tenantName")??W2(G?.name),X=Y4($,"id")??H??Z;if(!X)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let L=Y4($,"staffId")??W2(K?.providerUserId)??W2(K?.id)??"seal",w=Y4($,"provider")??W2(K?.provider)??W2(G?.providerConfig?.provider),F=Y4($,"corpId")??H??Z??X,O={id:X,name:Y4($,"name")??V??X,environment:"production",seal:{url:z,tenantSlug:H,headers:Q.headers,cookies:Q.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:q,sealUrl:z,expiresIn:J,staffId:L,corpId:F,tenantId:Z,tenantSlug:H,tenantName:V,providerUserId:W2(K?.providerUserId),provider:w},auth:{refreshTtl:300}},P=fi();dh0(P,{recursive:!0,mode:448});let B=lh0(P,`${nP(X)}.json`);if(ph0(B)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${B}. Pass "overwrite": true to replace it.`);mh0(B,`${JSON.stringify(O,null,2)}
`,{mode:384}),E0({id:X,name:O.name,tenantId:Z,tenantSlug:H,verified:U,path:B})}async function Eb1($,Y,q={}){let z=N8($,Y,q),J=await z8(z);return{user:J.user??{},tenant:J.tenant??{}}}function W2($){return typeof $==="string"&&$?$:void 0}async function $g0($,Y){let q=$??T(Y.options.link)??T(Y.options.url);if(!q)throw Error("Usage: seal-use auth extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]");let z=J0(Y.options.reveal)===!0||J0(Y.options.r)===!0||J0(Y.options.plain)===!0,J=J0(Y.options.save)===!0||J0(Y.options.add)===!0;await eP(q,{reveal:z,save:J,name:T(Y.options.name),overwrite:J0(Y.options.overwrite)===!0,force:J0(Y.options.force)===!0,appKey:T(Y.options["app-key"])??T(Y.options.appKey),keyId:T(Y.options["key-id"])??T(Y.options.keyId)})}async function Yg0($,Y,q){if($==="diagnose"){E0(await jb1(Y));return}if($==="hose-link"){let z=g0(q.options.expire)??7200;E0(await jL(Y,z));return}if($==="keys"){let z=J0(q.options.reveal)===!0||J0(q.options.r)===!0||J0(q.options.plain)===!0;await Ed(Y.id,{reveal:z});return}throw Error(`Unknown auth command: ${$??""}. Run 'seal-use help' for available commands.`)}async function jb1($){if($.source.type!=="hose"){let w=await Z1($),F=await z8(w);return{corp:{id:$.id,name:$.name,sourceType:$.source.type},ok:!0,stages:[{name:"seal.whoami",ok:!0,user:F.user,tenant:F.tenant}]}}AL($.id);let Y=$.source,q=Y.appKey??Y.key,z=Y.appSecurity??Y.password,J=($.seal.url??Y.sealUrl??`https://${Y.corpId.toLowerCase()}.sealai.cc`).replace(/\/+$/,""),U=Y.staffId.includes(":")?Y.staffId:`${Y.corpId}:${Y.staffId}`,I=[];if(!q||!z)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 Q=await $A("hose.openapi",async()=>{let w=await eh0(`${Y.domain.replace(/\/+$/,"")}/api/openapi/v1/auth/getAccessToken`,{appKey:q,appSecurity:z}),F=N3(w.value),O=h6(F.accessToken)??h6(w.accessToken)??h6(w.token);if(!O)throw Error("Hose login did not return an access token");return{token:O,public:{corporationId:h6(F.corporationId)??h6(N3(F.corporation).id),expireTime:HW(F.expireTime)}}});I.push(Q.public);let K=Q.private?.token,G=K?await $A("hose.provisional",async()=>{let w=await eh0(`${Y.domain.replace(/\/+$/,"")}/api/openapi/v1.1/provisional/getProvisionalAuth?accessToken=${encodeURIComponent(K)}`,{uid:U,pageType:"home",expireDate:7200}),F=h6(N3(w.value).message);if(!F)throw Error("Hose CloseAPI did not return a provisional auth URL");let O=new URL(F).searchParams.get("accessToken");if(!O)throw Error("Hose provisional auth URL did not include accessToken");return{token:O,public:{uid:U,enterpriseUrl:UW(F)}}}):jd("hose.provisional");I.push(G.public);let H=w6($.seal),Z=G.private?.token,V=Z?await $A("seal.sso",async()=>{let F=await N8(J,void 0,H).get(`api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(Z)}&returnToken=1`).json(),O=N3(F.data),P=h6(F.token)??h6(F.accessToken)??h6(O.token)??h6(O.accessToken);if(!P)throw Error("Seal SSO did not return a bearer token");return{token:P,public:{sealUrl:J,expiresIn:HW(F.expiresIn)??HW(F.expires_in)??HW(O.expiresIn)??HW(O.expires_in)}}}):jd("seal.sso");I.push(V.public);let X=V.private?.token,L=X?await $A("seal.whoami",async()=>{let F=await N8(J,X,H).get("api/v1/auth/me").json(),O=N3(F.data),P=N3(O.user??F.user),B=N3(O.tenant??F.tenant);return{public:{user:{id:h6(P.id),name:h6(P.name),isAdmin:Rb1(P.isAdmin),providerUserId:h6(P.providerUserId)},tenant:{id:h6(B.id),name:h6(B.name),tenantSlug:h6(B.tenantSlug),hoseCorpConfig:Cb1(B.hoseCorpConfig)}}}}):jd("seal.whoami");return I.push(L.public),{corp:{id:$.id,name:$.name,sourceType:$.source.type},ok:I.every((w)=>w.ok===!0),stages:I}}async function $A($,Y){try{let q=await Y();return{public:{name:$,ok:!0,...qg0(q.public)},private:q.token?{token:q.token}:void 0}}catch(q){return{public:{name:$,ok:!1,error:UW(q instanceof Error?q.message:String(q))}}}}function jd($){return{public:{name:$,ok:!1,skipped:!0}}}async function eh0($,Y){let q=await fetch($,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Y)});return _b1(q)}async function _b1($){let Y=await $.text();if(!$.ok)throw Error(`${$.status} ${Y}`);let q=JSON.parse(Y);return N3(q)}function N3($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function h6($){return typeof $==="string"&&$?$:void 0}function HW($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Rb1($){return typeof $==="boolean"?$:void 0}function Cb1($){let Y=N3($);return qg0({corporationId:h6(Y.corporationId),corporationName:h6(Y.corporationName)})}function qg0($){return Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))}p4();o1();async function zg0($,Y,q,z){if($==="status"||$==="get"){await A0("seal_billing_status_get",Y,q,{},F0(z.options));return}if($==="plans"){await A0("seal_billing_plans_list",Y,q,{},F0(z.options));return}if($==="features"){await A0("seal_billing_features Line truncated
`+`支持的审批系统与发布目标:
`+` • hosecloud (合思费控): seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>
@@ -922,22 +936,22 @@ 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 G=$==="maycur"?"每刻报销":"汇联易";throw Error(`${G}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${G}' --result-url <url> --corp <corpId>`)}let I=$==="hosecloud",Q=$==="hosecloud"?Y:$,K=$==="hosecloud"?q:Y;if(!I)throw Error(`未知的发布目标系统: ${$}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);if(Q==="requirements"){await A0("seal_deploy_hosecloud_requirements",z,J,{},F0(U.options));return}if(Q==="list"){await A0("seal_deploy_hosecloud_list",z,J,{},F0(U.options));return}if(Q==="get"){let G=K??T(U.options.signKey)??T(U.options["sign-key"]);if(!G){let Z=((await x1(z)).integrations??[]).filter((V)=>V.type==="hosecloud");if(Z.length===0)throw Error(`当前企业 (${J.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${J.id}`);console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${J.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let X=V.outboundName??"SealAI 审批",L=V.signKey,w=V.apiOrigin??"production";console.error(` • "${X}" (signKey: ${L}, 环境: ${w})`),console.error(` \uD83D\uDC49 查看命令: seal-use deploy hosecloud get ${L} --corp ${J.id}
`)}throw new Z4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。",2,Z.length===1?`seal-use deploy hosecloud get ${Z[0].signKey} --corp ${J.id}`:void 0)}await A0("seal_deploy_hosecloud_get",z,J,{signKey:G},F0(U.options));return}if(Q==="status"){await A0("seal_deploy_hosecloud_status",z,J,{},F0(U.options));return}if(Q==="configure"){let G=T(U.options.input),H=G?JSON.parse(vb1(G,"utf8")):C8(U.json);if(!H||Object.keys(H).length===0)throw Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");await A0("seal_deploy_hosecloud_configure",z,J,{...H,dryRun:J0(U.options.dryRun)??J0(U.options["dry-run"])},F0(U.options));return}if(Q==="sync"){let G=K??T(U.options.signKey)??T(U.options["sign-key"]),H=J0(U.options.auto)??J0(U.options.yes);if(!G){let V=((await x1(z)).integrations??[]).filter((L)=>L.type==="hosecloud");if(V.length===0)throw Error(`当前企业 (${J.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${J.id}`);let X=V[0];if(X&&V.length===1&&H){let L=X.signKey;console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${L})`),await A0("seal_deploy_hosecloud_sync",z,J,{signKey:L},F0(U.options));return}console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${J.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let L of V){let w=L.outboundName??"SealAI 审批",F=L.signKey,O=L.apiOrigin??"production";console.error(` • "${w}" (signKey: ${F}, 环境: ${O})`),console.error(` \uD83D\uDC49 同步命令: seal-use deploy hosecloud sync ${F} --corp ${J.id}
`)}if(V.length===1)console.error(`\uD83D\uDCA1 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${J.id}
`);throw new Z4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,V.length===1?`seal-use deploy hosecloud sync ${V[0].signKey} --corp ${J.id}`:void 0)}await A0("seal_deploy_hosecloud_sync",z,J,{signKey:G},F0(U.options));return}throw Error(`Unknown deploy hosecloud action: ${Q??""}. Available: requirements, list, get, status, configure, sync.`)}$n();import{accessSync as mb1,constants as lb1,existsSync as X8,readdirSync as ob1}from"node:fs";import{homedir as rb1}from"node:os";import{join as D3}from"node:path";K3();import{existsSync as _d,mkdirSync as Pg0,rmSync as cb1,writeFileSync as pb1}from"node:fs";import{homedir as Ag0}from"node:os";import{dirname as db1,join as Rd}from"node:path";var Zg0=`---
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.24: 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.24
short-description: Seal tenant and Hose approval automation (v0.10.24)
---
# Seal Use (v0.10.22)
# Seal Use (v0.10.24)
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.
@@ -974,8 +988,8 @@ 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>\`.
- 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 +1033,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>\`.
@@ -1090,6 +1104,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 +1143,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 Wg0=`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 Xg0=`# 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 +1258,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 Vg0=`# 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 +1308,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 Lg0="# 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://.../web/thirdparLine 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 +1529,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 Og0=`# 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 +1699,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 Mg0=`# 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.
@@ -1756,21 +1774,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.
@@ -1815,7 +1854,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 Ng0=`# Hose Enterprise Auth
Use this reference for Hose/合思 enterprise configuration and user-facing Hose authorization links.
@@ -1880,7 +1919,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 Dg0=`# 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 +2025,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 Bg0={"SKILL.md":Zg0,"agents/openai.yaml":Wg0,"references/rule-lightweight.md":Xg0,"references/approval-bad-cases.md":Vg0,"references/cli.md":Lg0,"references/approval-run-lightweight.md":wg0,"references/approval-attachment-trace.md":Fg0,"references/customer-feedback-rule-remediation.md":Og0,"references/enterprise-onboarding.md":Mg0,"references/hose-enterprise-auth.md":Ng0,"references/hose-enterprise-init.md":Dg0};function Tg0(){return Bg0["SKILL.md"]||""}function Tq(){return Rd(Ag0(),".agents","skills","seal-use")}function Eg0(){return Rd(Ag0(),".agents","skills","seal-home")}function jg0(){let $=Eg0();if(_d($))try{return cb1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function Cd($=Tq()){jg0(),Pg0($,{recursive:!0});let Y=[];for(let[q,z]of Object.entries(Bg0)){let J=Rd($,q);Pg0(db1(J),{recursive:!0}),pb1(J,z,"utf8"),Y.push(q)}return{targetDir:$,files:Y}}function vd(){let $=Eg0(),Y=Tq(),q=_d($),z=_d(Y);if(q||z)return jg0(),Cd(Y),{synced:!0,targetDir:Y};return{synced:!1}}var hd=[{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"}],gd=[{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 路径杜绝写文件与环境篡改。"}],Sd=[{domain:"corps (企业管理)",summary:"多租户接入、智能软搜索、富属性查看、环境标记、测试绑定与配置规则同 Line truncated
> 本文档由 \`seal-use\` 单文件二进制程序内嵌提供,纯内存只读,未向用户电脑写入任何临时文件。
@@ -2009,14 +2048,14 @@ seal-use corps hose-staffs --json '{
| 目录名称 | 类别 | 规范路径 | 作用与生命周期 |
| :--- | :--- | :--- | :--- |
${zd.map(($)=>`| **${$.name}** | \`${$.category}\` | \`${$.standardPath}\` | ${$.purpose} (${$.retention}) |`).join(`
${hd.map(($)=>`| **${$.name}** | \`${$.category}\` | \`${$.standardPath}\` | ${$.purpose} (${$.retention}) |`).join(`
`)}
---
## 3. 安全与数据隐私保证
${qd.map(($,I)=>`### 3.${I+1} ${$.topic}
${gd.map(($,Y)=>`### 3.${Y+1} ${$.topic}
- **安全承诺**:${$.guarantee}
- **实现约束**:${$.enforcement}
`).join(`
@@ -2026,9 +2065,9 @@ ${qd.map(($,I)=>`### 3.${I+1} ${$.topic}
## 4. 业务域能力图谱
${Ud.map(($)=>`### \`seal-use ${$.domain}\`
${Sd.map(($)=>`### \`seal-use ${$.domain}\`
* **能力定位**:${$.summary}
* **核心命令**:${$.primaryCommands.map((I)=>`\`seal-use ${I}\``).join("、")}
* **核心命令**:${$.primaryCommands.map((Y)=>`\`seal-use ${Y}\``).join("、")}
`).join(`
`)}
@@ -2039,20 +2078,20 @@ ${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.
`}function Rg0($){if(!X8($))return 0;try{return ob1($).filter((Y)=>Y.endsWith(".json")).length}catch{return 0}}function YA($){try{return mb1($,lb1.W_OK),!0}catch{return!1}}function yd(){let $=rb1(),Y=D3($,".config","seal-use"),q=D3(Y,"enterprises"),z=D3(Y,"config.json"),J=D3(Y,"seal_tokens.json"),U=D3(Y,"mappings"),I=Tq(),Q=D3($,"Downloads"),G=["/opt/homebrew/bin/seal-use","/usr/local/bin/seal-use",D3($,".local","bin","seal-use"),D3($,"bin","seal-use")].find((A)=>X8(A))??process.execPath,H={configDir:{name:"配置根目录",path:Y,exists:X8(Y),writable:X8(Y)?YA(Y):!1,description:"用户持久化配置与企业状态根目录"},enterprisesDir:{name:"企业配置目录",path:q,exists:X8(q),writable:X8(q)?YA(q):!1,fileCount:Rg0(q),description:"企业连接配置(JSON)保存路径"},globalConfigFile:{name:"全局配置文件",path:z,exists:X8(z),description:"全局工作模式与默认企业配置"},tokenStore:{name:"凭据缓存",path:J,exists:X8(J),description:"会话凭据与令牌缓存"},mappingsDir:{name:"规则版本映射快照",path:U,exists:X8(U),fileCount:Rg0(U),description:"生产与测试规则版本映射对照表"},agentSkillDir:{name:"AI Agent 技能目录",path:I,exists:X8(D3(I,"SKILL.md")),description:"本地 Agent 技能主目录"},exportDefaultDir:{name:"报表默认导出目录",path:Q,exists:X8(Q),writable:X8(Q)?YA(Q):!1,description:"审核大盘报表默认写入目录"},lintersDir:{name:"规则校验器目录 (用户自定义)",path:b$,exists:X8(b$),writable:X8(b$)?YA(b$):!1,description:"用户私有规则校验脚本存放目录"},officialLintersDir:{name:"官方内置规则校验器目录",path:i$,exists:X8(i$),description:"官方标准与严格风控校验脚本目录 (系统自动保护与重写)"},globalBinary:{name:"全局命令行二进制",path:G,exists:X8(G),description:"系统全局命令执行入口"}},Z=[];try{Z=r8()}catch{Z=[]}let X=T4().defaultCorpId??Z[0]?.id,L=Z.find((A)=>A.id===X),w=Z.filter((A)=>(A.environment??"production").toLowerCase()==="test").length,F=Z.length-w,O=[];if(O.push({id:"executable",title:"命令行二进制",status:"ok",message:`当前执行路径: ${process.execPath}`}),H.configDir?.exists&&H.configDir.writable)O.push({id:"config_dir",title:"配置目录访问",status:"ok",message:`${Y} (正常读写)`});else if(H.configDir?.exists)O.push({id:"config_dir",title:"配置目录访问",status:"warn",message:`${Y} (存在但可能不可写)`});else O.push({id:"config_dir",title:"配置目录访问",status:"warn",message:`未检测到配置目录 ${Y},首次运行配置命令时将自动创建`});if(Z.length>0)O.push({id:"enterprises",title:"企业接入状态",status:"ok",message:`已接入 ${Z.length} 家企业 (正式: ${F}, 测试: ${w})`});else O.push({id:"enterprises",title:"企业接入状态",status:"warn",message:"当前未检测到企业配置,请使用 seal-use corps add-hose 或 add-seal 接入企业"});if(H.agentSkillDir?.exists)O.push({id:"agent_skill",title:"AI Agent 技能",status:"ok",message:`已就绪于 ${I}`});else O.push({id:"agent_skill",title:"AI Agent 技能",status:"warn",message:`未在 ${I} 检测到技能,可运行 'seal-use skill sync' 安装`});let P=O.some((A)=>A.status==="warn"||A.status==="error"),B=typeof globalThis.Bun<"u"?`Bun ${globalThis.Bun.version}`:`Node ${process.version}`;return{doctor:P?"warning":"ok",timestamp:new Date().toISOString(),runtime:{version:Q1,executablePath:process.execPath,platform:`${process.platform} (${process.arch})`,engine:B},directories:H,enterprises:{total:Z.length,productionCount:F,testCount:w,activeCorpId:L?.id,activeCorpName:L?.name},checks:O,knowledge:{summary:"内嵌系统架构与目录规范白皮书(纯内存只读,零写入依赖)",directorySpecsCount:hd.length,securityPoliciesCount:gd.length,domainCapabilitiesCount:Sd.length,guideCommand:"seal-use doctor guide"}}}function Cg0($){let Y=[],q=$.doctor==="ok"?"✨":"⚠️";Y.push(`\uD83E\uDE7A [Seal Use Doctor] 系统健康诊断看板 ${q}`),Y.push("─────────────────────────────────────────────────────────────"),Y.push("【运行环境】"),Y.push(` 版本号: ${$.runtime.version}`),Y.push(` 程序路径: ${$.runtime.executablePath}`),Y.push(` 操作系统: ${$.runtime.platform}`),Y.push(` 执行引擎: ${$.runtime.engine}`),Y.push(""),Y.push("【核心路径状态】");for(let[,z]of Object.entries($.directories)){let J=z.exists?"✓":"○",U=z.exists?z.fileCount!==void 0?`(${z.fileCount} 个文件)`:z.writable?"(就绪/可写)":"(存在)":"(未创建)";Y.push(` ${J} ${z.name.padEnd(16," ")}: ${z.path} ${U}`)}if(Y.push(""),Y.push("【企业资产概览】"),Y.push(` 接入企业总计: ${$.enterprises.total} 家 (生产: ${$.enterprises.productionCount}, 测试: ${$.enterprises.testCount})`),$.enterprises.activeCorpId)Y.push(` 当前激活企业: ${$.enterprises.activeCLine truncated
`)}R4();o1();async function gg0($,Y,q){let z=($??Y??"").toLowerCase();if(z==="guide"||z==="doc"||z==="knowledge"||z==="book"){console.error(`\uD83D\uDCD6 [Seal Use Doctor] 正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(_g0());return}if(z==="paths"||z==="dirs"||z==="directories"){let I=yd();E0(I.directories);return}if(z==="tenant"||z==="corp"||z==="enterprise"){let{selectCorp:I}=await Promise.resolve().then(() => (p4(),hv0)),{createSealClient:Q}=await Promise.resolve().then(() => (b8(),l10)),{stringOption:K}=await Promise.resolve().then(() => (R4(),Bv0)),{diagnoseTenantContract:G,formatTenantDoctorDashboard:H}=await Promise.resolve().then(() => (hg0(),vg0)),Z=K(q.options.corp)??(Y&&Y!==z?Y:void 0)??(q.command[2]&&q.command[2]!==z?q.command[2]:void 0),V=I(Z),X=await Q(V),L=await G(X,V);if(!(J0(q.options.quiet)||J0(q.options.silent)))console.error(H(L));E0(L);return}let J=yd();if(!(J0(q.options.quiet)||J0(q.options.silent)))console.error(Cg0(J));E0(J)}R4();import{createServer as qi1}from"node:http";p4();import{URL as eb1}from"node:url";var Sg0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.24",description:`Planned HTTP contract for the seal-use wrapped backend API.
These endpoints describe the intended stable API for frontend developers and agents once
the HTTP adapter is implemented.
They are not the raw downstream Seal endpoints. seal-use is responsible for enterprise
selection, source authentication, response compaction, and diagnostics-friendly fields.
`},servers:[{url:"http://localhost:8787",description:"Reserved for a future local HTTP adapter; the current service uses MCP stdio."}],security:[{localSession:[]}],tags:[{name:"Corps",description:"Local enterprise configuration selection."},{name:"Source",description:"Source-derived Seal enterprise configuration."},{name:"Auth",description:"Wrapped authentication diagnostics and current identity."},{name:"Approval Runs",description:"Wrapped approval run history, summaries, document URLs, and trace bridge helpers."},{name:"Approval Knowledge",description:"Wrapped approval rules, documents, preferences, and search."},{name:"Simulation",description:"Wrapped simulation batch record access."}],paths:{"/v1/corps":{get:{tags:["Corps"],operationId:"listCorps",summary:"List configured enterprises",responses:{"200":{description:"Configured enterprises.",content:{"application/json":{schema:{type:"array",items:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp",summary:"Get current enterprise",description:"Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",responses:{"200":{description:"Current enterprise.",content:{"application/json":{schema:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp",summary:"Switch current enterprise",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}}}}},responses:{"200":{description:"Switched enterprise.",content:{"application/json":{schema:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}}}}},"404":{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/source/config":{get:{tags:["Source"],operationId:"getSourceConfig",summary:"Resolve source-derived Seal enterprise config",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Redacted Seal enterprise config.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/auth/diagnose":{get:{tags:["Auth"],operationId:"diagnoseAuth",summary:"Diagnose wrapped source-to-Seal authentication",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Authentication stage diagnosis.",content:{"application/json":{schema:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}}}}}}}},"/v1/whoami":{get:{tags:["Auth"],operationId:"whoami",summary:"Get current wrapped Seal identity",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Current Seal user and tenant.",content:{"application/json":{schema:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/session":{get:{tags:["Auth"],operationId:"getSession",summary:"Get current wrapped Seal session metadata",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"2 Line truncated
`},servers:[{url:"http://localhost:8787",description:"Reserved for a future local HTTP adapter; the current service uses MCP stdio."}],security:[{localSession:[]}],tags:[{name:"Corps",description:"Local enterprise configuration selection."},{name:"Source",description:"Source-derived Seal enterprise configuration."},{name:"Auth",description:"Wrapped authentication diagnostics and current identity."},{name:"Approval Runs",description:"Wrapped approval run history, summaries, document URLs, and trace bridge helpers."},{name:"Approval Knowledge",description:"Wrapped approval rules, documents, preferences, and search."},{name:"Simulation",description:"Wrapped simulation batch record access."}],paths:{"/v1/corps":{get:{tags:["Corps"],operationId:"listCorps",summary:"List configured enterprises",responses:{"200":{description:"Configured enterprises.",content:{"application/json":{schema:{type:"array",items:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp",summary:"Get current enterprise",description:"Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",responses:{"200":{description:"Current enterprise.",content:{"application/json":{schema:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp",summary:"Switch current enterprise",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}}}}},responses:{"200":{description:"Switched enterprise.",content:{"application/json":{schema:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}}}}},"404":{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/source/config":{get:{tags:["Source"],operationId:"getSourceConfig",summary:"Resolve source-derived Seal enterprise config",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Redacted Seal enterprise config.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/auth/diagnose":{get:{tags:["Auth"],operationId:"diagnoseAuth",summary:"Diagnose wrapped source-to-Seal authentication",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Authentication stage diagnosis.",content:{"application/json":{schema:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}}}}}}}},"/v1/whoami":{get:{tags:["Auth"],operationId:"whoami",summary:"Get current wrapped Seal identity",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Current Seal user and tenant.",content:{"application/json":{schema:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/session":{get:{tags:["Auth"],operationId:"getSession",summary:"Get current wrapped Seal session metadata",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"2 Line truncated
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>Seal Home API Docs (v${q1})</title>
<title>Seal Home API Docs (v${Q1})</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 +2110,24 @@ 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>`}async function B6($,Y,q,z){let J=$.handler;return J(Y,q,{corp:z})}async function xg0($,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 q=$.headers.host||"localhost",z=$.headers["x-forwarded-proto"]||"http",J=new eb1($.url||"/",`${z}://${q}`),U=J.pathname.replace(/\/+$/,"")||"/",I=($.method||"GET").toUpperCase();try{if(I==="GET"&&U==="/"){L4(Y,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(I==="GET"&&U==="/docs"){Yi1(Y,200,yg0());return}if(I==="GET"&&U==="/openapi.json"){L4(Y,200,qA());return}if(I==="GET"&&U==="/health"){L4(Y,200,{status:"ok",version:Q1,name:"seal-use",timestamp:new Date().toISOString()});return}if(I==="POST"&&(U==="/shutdown"||U==="/api/shutdown")){L4(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"&&U==="/api/cli"){let Q=await JA($),K=(typeof Q?.command==="string"?Q.command:"").trim();if(!K){zA(Y,400,"Missing 'command' property in request body");return}let G=xd(K),H=G[0]==="seal-use"||G[0]==="seal-home"||G[0]?.endsWith("/seal-use")||G[0]?.endsWith("/seal-home")?G.slice(1):G,Z=await ZW(H),V=void 0;try{if(Z.stdout.trim().startsWith("{")||Z.stdout.trim().startsWith("["))V=JSON.parse(Z.stdout)}catch{}L4(Y,Z.isError?400:200,{success:!Z.isError,stdout:Z.stdout,stderr:Z.stderr,exitCode:Z.exitCode,data:V});return}if(I==="POST"&&U.startsWith("/api/tool/")){let Q=U.slice(10).trim(),K=X6(Q);if(!K){zA(Y,404,`Tool not found: '${Q}'`);return}let G=await JA($)||{},H=v8($,J,G),Z=W1(H),V=await Z1(Z),X={...G};delete X.corp;let L=await B6(K,V,X,Z);L4(Y,200,L);return}if(U.startsWith("/v1/")){if(await $i1($,Y,I,U,J))return}zA(Y,404,`Cannot ${I} ${U}. Visit /docs for available endpoints.`)}catch(Q){let K=Q instanceof Error?Q.message:String(Q);zA(Y,500,K)}}async function $i1($,Y,q,z,J){let U=Object.fromEntries(J.searchParams.entries());if(q==="GET"&&z==="/v1/corps"){let I=r8(),Q=T4();return L4(Y,200,{count:I.length,mode:Q.stateful?"stateful":"stateless",defaultCorpId:Q.defaultCorpId,corps:I.map((K)=>({id:K.id,name:K.name,sourceType:K.source.type,sealUrl:K.seal?.url}))}),!0}if(q==="GET"&&z==="/v1/whoami"){let I=v8($,J,U),Q=W1(I),K=await Z1(Q),G=X6("seal_whoami"),H=await B6(G,K,{},Q);return L4(Y,200,H),!0}if(q==="GET"&&z==="/v1/session"){let I=v8($,J,U),Q=W1(I),K=await Z1(Q),G=X6("seal_session_get"),H=await B6(G,K,{},Q);return L4(Y,200,H),!0}if(q==="GET"&&z==="/v1/approval-runs/summary"){let I=v8($,J,U),Q=W1(I),K=await Z1(Q),G=X6("seal_approval_runs_summary"),H=await B6(G,K,U,Q);return L4(Y,200,H),!0}if(q==="GET"&&z==="/v1/approval-runs/stats"){let I=v8($,J,U),Q=W1(I),K=await Z1(Q),G=X6("seal_approval_runs_stats"),H=await B6(G,K,U,Q);return L4(Y,200,H),!0}if(q==="GET"&&z==="/v1/approval-runs/pick"){let I=v8($,J,U),Q=W1(I),K=await Z1(Q),G=X6("seal_approval_run_pick"),H=await B6(G,K,U,Q);return L4(Y,200,H),!0}if(q==="GET"&&z==="/v1/approval-runs/url"){let I=v8($,J,U),Q=W1(I),K=await Z1(Q),G=X6("seal_approval_run_url_get"),H=await B6(G,K,U,Q);return L4(Y,200,H),!0}if(z.startsWith("/v1/approval-runs/")){let I=z.slice(18).split("/"),Q=I[0],K=I[1];if(Q&&!["summary","pick","stats","url","bridge"].includes(Q)){let G=v8($,J,U),H=W1(G),Z=await Z1(H);if(!K){let V=X6("seal_approval_run_get"),X=await B6(V,Z,{recordId:Q,...U},H);return L4(Y,200,X),!0}if(K==="attachments"){let V=X6("seal_approval_run_attachments_get"),X=await B6(V,Z,{recordId:Q,...U},H);return L4(Y,200,X),!0}if(K==="cited-rules"){let V=X6("seal_approval_run_cited_rules_get"),X=await B6(V,Z,{recordId:Q,...U},H);return L4(Y,200,X),!0}if(K==="document-summary"){let V=X6("seal_approval_run_document_summary_get"),X=await B6(V,Z,{recordId:Q,...U},H);return L4(Y,200,X),!0}if(K==="result"){let V=X6("seal_approval_run_result_get"),X=await B6(V,Z,{recordId:Q,...U},H);return L4(Y,200,X),!0}}}if(q==="GET"&&z==="/v1/approval-runs"){let I=v8($,J,U),Q=W1(I),K=await Z1(Q),G=X6("seal_approval_runs_search"),H=await B6(G,K,{...U,limit:U.limit?Number(U.limit):void 0,offset:U.offset?Number(U.offset):void 0,includeBridge:U.includeBridge==="true"},Q);return L4(Y,200,H),!0}if(q==="GET"&&z==="/v1/approval/rules"){let I=v8($,J,U),Q=W1(I),K=await Z1(Q),G=X6("seal_approval_rules_list"),H=await B6(G,K,U,Q);return L4(Y,200,H),!0}if(q==="GET"&&z==="/v1/simulation/batches"){let I=v8($,J,U),Q=W1(I),K=await Z1(Q),G=X6("seal_simulation_batches_list"),H=await B6(G,K,U,Q);return L4(Y,200,H),!0}if(q==="POST"&&z==="/v1/simulation/create-batch"){let I=await JA($)||{},Q=v8($,J,I),K=W1(Q),G=await Z1Line truncated
\uD83D\uDE80 seal-use HTTP Server (v${Q1}) started`),console.error(` URL: http://${q}:${Y}`),console.error(` Docs: http://${q}:${Y}/docs`),console.error(` OpenAPI: http://${q}:${Y}/openapi.json`),console.error(` CLI Exec: POST http://${q}:${Y}/api/cli`),console.error(` REST API: http://${q}:${Y}/v1/...
`);J(z)})})}async function kg0($){let Y=g0($.options.port)??g0($.options.p),q=T($.options.host)??T($.options.h),z=await QA({port:Y,host:q}),J=()=>{z.close(()=>{process.exit(0)})};process.on("SIGINT",J),process.on("SIGTERM",J),await new Promise(()=>{})}p4();o1();async function ug0($,Y,q,z){if($==="config"||$==="get"){await A0("seal_llm_config_get",Y,q,{},F0(z.options));return}if($==="providers"||$==="list"){await A0("seal_llm_providers_list",Y,q,{},F0(z.options));return}throw Error(`Unknown llm command: ${$??""}. Run 'seal-use help' for available commands.`)}o1();async function fg0($,Y){if($==="config"||$==="json"){kd();return}await ud()}function kd(){E0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}o1();function bg0($){let Y=qA();E0(Y,{...F0($.options),allowFull:!0})}p4();o1();async function ig0($,Y,q,z){if($==="available"){await A0("seal_permissions_available_list",Y,q,{},F0(z.options));return}if($==="configs"||$==="list"){await A0("seal_permissions_configs_list",Y,q,{},F0(z.options));return}throw Error(`Unknown permissions command: ${$??""}. Run 'seal-use help' for available commands.`)}p4();R4();o1();import{readFileSync as ng0}from"node:fs";async function cg0($,Y,q,z,J,U,I){if(!$||$==="get"){await A0("seal_preference_get",J,U,{},F0(I.options));return}if($==="decision"){if(Y==="update"||!Y){let Q=T(I.options.input),K=Q?JSON.parse(ng0(Q,"utf8")):C8(I.json);if(!K||Object.keys(K).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await A0("seal_preference_decision_update",J,U,{...K,dryRun:J0(I.options.dryRun)??J0(I.options["dry-run"])},F0(I.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(Y==="set"){let Q=T(I.options.default)??T(I.options.level)??z;if(Q!=="medium"&&Q!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await A0("seal_preference_thinking_depth_set",J,U,{defaultLevel:Q,dryRun:J0(I.options.dryRun)??J0(I.options["dry-run"])},F0(I.options));return}if(Y==="policies"){if(q==="list"||!q){await A0("seal_preference_thinking_depth_policies_list",J,U,{},F0(I.options));return}if(q==="upsert"){let Q=T(I.options.input),K=Q?JSON.parse(ng0(Q,"utf8")):C8(I.json);if(!K||!K.id||!K.name)throw Error(`Usage: seal-use preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await A0("seal_preference_thinking_depth_policies_upsert",J,U,{...K,dryRun:J0(I.options.dryRun)??J0(I.options["dry-run"])},F0(I.options));return}if(q==="remove"||q==="delete"){let Q=z??T(I.options.id)??T(I.options.policyId);if(!Q)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await A0("seal_preference_thinking_depth_policies_remove",J,U,{policyId:Q,dryRun:J0(I.options.dryRun)??J0(I.options["dry-run"])},F0(I.options));return}}}throw Error(`Unknown preference action: ${$??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}K3();b8();I6();async function pg0($={}){let Y=r8(),q=T4(),z=$2(Y,{stateful:q.stateful,defaultCorpId:q.defaultCorpId,corpId:$.corpId},Q3());console.log(`[probe] corp=${z.id} source=${z.source.type}`);let J=await jI(z);console.log("[probe] seal enterprise"),console.log(JSON.stringify(J,null,2));let U=await Z1(z),I=await dL(U,{documentLimit:20,stylePreferencesEndpoint:z.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))}R4();async function dg0($,Y,q){let z=Y??T(q.options.corp)??($&&$!=="--corp"?$:void 0);await pg0({corpId:z})}qn();p4();V$();R4();o1();async function fd($,Y,q,z,J){if($==="count"){await A0("seal_approval_rules_list",q,z,{countOnly:!0},F0(J.options));return}if($==="list"){if(J0(J.options.count)){await A0("seal_approval_rules_list",q,z,{countOnly:!0},F0(J.options));return}let U=g0(J.options.limit),I=g0(J.options.offset);if(J0(J.options.summary)){await A0("seal_approval_rules_list",q,z,{fields:Rv0,limit:U,offset:I},F0(J.options));return}let Q=await H2("seal_approval_rules_list",q,z,{limit:U,offset:I});Cv0(Q,J0(J.options.full)===!0),E0(Q);return}if($==="clear"){let U=J0(J.options.yes)===!0,I=J0(J.options.dryRun)??J0(J.options["dry-run"])??!U;if(!U&&!I)throw K9("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-use rules clear --corp ${z.id} --dry-run`);let Q=await H2("seal_approval_rules_clear",q,z,{dryRun:I,recode:J0(J.options.recode)});if(!U&&I&&Q&&typeof Q==="object"){E0({...Q,nextCommand:`seal-use rules clear --corp ${z.id} --yes`},F0(J.options));return}E0(Q,F0(J.options));return}if($==="versions"){await A0("seal_approval_rule_versions_list",q,z,{},F0(J.options));return}if($==="version"){let U=Y??T(J.op Line truncated
`).filter(Boolean),U=J.slice(-Y);return{logFile:q,lines:U,totalLines:J.length}}async function Qi1($){let Y=ZA($),q=nd($),z=WW($);rg0($.stateDir);let J=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):UA),U=$.host??(process.env.HOST?process.env.HOST:IA);GA(Y,`${process.pid}
`,{mode:384}),GA(q,JSON.stringify({pid:process.pid,port:J,host:U,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),_I(z,`service starting on http://${U}:${J} pid=${process.pid}`);let I=null;try{I=await QA({port:J,host:U,silent:!0}),_I(z,`service listening pid=${process.pid}`)}catch(K){if(_I(z,`service failed to bind port ${J}: ${K instanceof Error?K.message:String(K)}`),HA(Y)===process.pid)F9(Y,{force:!0}),F9(q,{force:!0});throw K}let Q=()=>{if(I)I.close(),I=null;if(HA(Y)===process.pid)F9(Y,{force:!0}),F9(q,{force:!0});_I(z,`stopped pid=${process.pid}`)};await new Promise((K)=>{let G=!1,H=()=>{if(G)return;G=!0,Q(),process.off("SIGTERM",H),process.off("SIGINT",H),K()};process.once("SIGTERM",H),process.once("SIGINT",H)})}function mg0($){rg0($.stateDir);let Y=RI($);if(Y.running)return Y;let q=$.launcher??{command:process.execPath,args:[$.entryFile]},z=[...q.args??[],"service","run"];if($.port)z.push("--port",String($.port));if($.host)z.push("--host",String($.host));let J=zi1(q.command,z,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});J.unref();let U=ZA($);return GA(U,`${J.pid}
`,{mode:384}),_I(WW($),`started pid=${J.pid}`),{started:!0,...RI($)}}function lg0($,Y={}){let q=ZA($),z=nd($),J=HA(q);if(!J||!og0(J,$.appRoot))return F9(q,{force:!0}),F9(z,{force:!0}),Y.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(J,"SIGTERM"),F9(q,{force:!0}),F9(z,{force:!0}),_I(WW($),`stop requested pid=${J}`),Y.quiet?void 0:{stopped:!0,pid:J}}function og0($,Y){if(!Ki1($))return!1;try{let q=Ji1("ps",["-p",String($),"-o","command="],{encoding:"utf8"});return(q.includes(Y)||q.includes("seal-use")||q.includes("src/cli.ts"))&&q.includes("service")&&q.includes("run")}catch{return!1}}function Ki1($){try{return process.kill($,0),!0}catch{return!1}}function ZA($){return id($.stateDir,"service.pid")}function nd($){return id($.stateDir,"service.json")}function WW($){return id($.stateDir,"service.log")}function HA($){if(!KA($))return;let Y=Number(bd($,"utf8").trim());return Number.isInteger(Y)&&Y>0?Y:void 0}function rg0($){Ui1($,{recursive:!0,mode:448})}function _I($,Y){GA($,`${new Date().toISOString()} ${Y}
`,{flag:"a",mode:384})}o1();R4();var cd=Hi1(Gi1(),".config","seal-use");async function pd($,Y,q){let z=q?g0(q.options.port)??g0(q.options.p):void 0,J=q?T(q.options.host)??T(q.options.h):void 0,U=q?g0(q.options.lines)??g0(q.options.n):void 0,I=await Eq($,{appRoot:Y.appRoot,entryFile:Y.entryFile,stateDir:cd,version:Q1,launcher:Y.launcher,port:z,host:J},{maxLines:U});if(I!==void 0)E0(I)}p4();R4();o1();import{existsSync as Zi1,readFileSync as sg0}from"node:fs";async function tg0($,Y,q,z,J){if($==="batch-records"||$==="records"){let U=Y??T(J.options.batchId)??T(J.options["batch-id"]);if(!U)throw Error("Usage: seal-use simulation batch-records <batchId>");await A0("seal_simulation_batch_records_get",q,z,{batchId:U,query:T(J.options.query)},F0(J.options));return}if($==="create"||$==="run"){let U=T(J.options.mode)??T(J.options.sourceSystem)??T(J.options["source-system"])??"hosecloud",I=U==="material-pack"?"material_pack":U,Q=T(J.options.schemaConfig)??T(J.options["schema-config"]),K=Q?JSON.parse(sg0(Q,"utf8")):void 0,G=T(J.options.input),H=G?JSON.parse(sg0(G,"utf8")):C8(J.json),Z=T(J.options.packageId)??T(J.options["package-id"]),V=v6(J.options.packageIds)??v6(J.options["package-ids"])??(Z?[Z]:void 0),X=v6(J.options.flowIds)??v6(J.options["flow-ids"])??v6(J.options.documentSn)??v6(J.options["document-sn"]),L=T(J.options.signKey)??T(J.options["sign-key"])??T(J.options.integration),w=J0(J.options.noWait)??J0(J.options["no-wait"]);await A0("seal_simulation_batch_create",q,z,{mode:I,sourceSystem:I,flowIds:X,documentSn:X,rejectNodeName:T(J.options.rejectNode)??T(J.options["reject-node"])??null,thinkingDepthOverride:T(J.options.thinkingDepth)??T(J.options["thinking-depth"]),skipInvoiceGeneration:J0(J.options.skipInvoiceGeneration)??J0(J.options["skip-invoice-generation"]),skipExpenseExtraction:J0(J.options.skipExpenseExtraction)??J0(J.options["skip-expense-extraction"]),disableAttachmentCache:J0(J.options.disableAttachmentCache)??J0(J.options["disable-attachment-cache"]),signKey:L,packageIds:V,packageId:Z,templateId:T(J.options.templateId)??T(J.options["template-id"]),schemaConfig:K,requestIds:v6(J.options.requestIds)??v6(J.options["request-ids"]),workflowTypeId:T(J.options.workflowTypeId)??T(J.options["workflow-type-id"]),flowStatusList:v6(J.options.flowStatusList)?.map(Number)??v6(J.options["flow-status-list"])?.map(Number),businessCodes:v6(J.options.businessCodes)??v6(J.options["business-codes"]),documentType:T(J.options.documentType)??T(J.options["document-type"]),startTime:g0(J.options.startTime)??g0(J.options["start-time"]),endTime:g0(J.options.endTime)??g0(J.options["end-time"]),status:v6(J.options.status),limit:g0(J.options.limit),noWait:w,rawParams:H},F0(J.options));return}if($==="wait"){let U=Y??T(J.options.batchId)??T(J.options["batch-id"]);if(!U)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await A0("seal_simulation_batch_wait",q,z,{batchId:U,timeout:T(J.options.timeout),pollInterval:T(J.options.pollInterval)??T(J.options["poll-interval"])},F0(J.options));return}if($==="status"){let U=Y??T(J.options.batchId)??T(J.options["batch-id"]);if(!U)throw Error("Usage: seal-use simulation status <batchId>");await A0("seal_simulation_batch_status",q,z,{batchId:U},F0(J.options));return}if($==="clean"||$==="delete"){let U=Y??T(J.options.batchId)??T(J.options["batch-id"]);if(!U)throw Error("Usage: seal-use simulation clean <batchId>");await A0("seal_simulation_batch_clean",q,z,{batchId:U},F0(J.options));return}if($==="specifications"){let U=Y??T(J.options.integration)??T(J.options.signKey)??T(J.options["sign-key"]);await A0("seal_simulation_specifications_list",q,z,{signKey:U},F0(J.options));return}if($==="approval-definitions"||$==="definitions"){await A0("seal_simulation_feishu_approval_definitions_list",q,z,{},F0(J.options));return}if($==="list"){await A0("seal_simulation_batches_list",q,z,{limit:g0(J.options.limit)},F0(J.options));return}if($==="get"){let U=Y??T(J.options.batchId)??T(J.options["batch-id"]);if(!U)throw Error("Usage: seal-use simulation get <batchId>");await A0("seal_simulation_batch_get",q,z,{batchId:U},F0(J.options));return}if($==="templates"){await A0("seal_simulation_templates_get",q,z,{},F0(J.options));return}if($==="integrations"){await A0("seal_simulation_integrations_get",q,z,{},F0(J.options));return}if($==="package-upload"){let U=Y??T(J.options.file);if(!U)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!Zi1(U))throw Error(`File not found: ${U}`);await A0("seal_simulation_material_package_upload",q,z,{filePath:U},F0(J.options));return}throw Error(`Unknown simulation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as ag0}from"node:fs";import{join as WA}from"node:path";R4();o1();function eg0($,Y,q){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${Tg0()}
`);return}if($==="install"||$==="init"||$==="sync"){let z=J0(q.options.local)||J0(q.options.workspace),J=T(q.options.dir)??T(q.options.target)??Y,U=J?J:z?WA(process.cwd(),".agents","skills","seal-use"):Tq(),I=Cd(U);E0({installed:!0,targetDir:I.targetDir,fileCount:I.files.length,files:I.files});return}if($==="status"||$==="get"||!$){let z=Tq(),J=WA(process.cwd(),".agents","skills","seal-use");E0({global:{dir:z,installed:ag0(WA(z,"SKILL.md"))},local:{dir:J,installed:ag0(WA(J,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${$}. Run 'seal-use help' for available commands.`)}o1();async function $S0($,Y){if($==="config"){E0(await jI(Y));return}throw Error(`Unknown source command: ${$??""}. Run 'seal-use help' for available commands.`)}V$();p4();R4();o1();b8();V$();I6();DZ();function dd($){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 YS0($){let{sourceCorp:Y,targetCorp:q,sourceClient:z,targetClient:J,samples:U=10,dryRun:I=!1,pollIntervalMs:Q=2000,timeoutMs:K=45000,snPrefix:G="REG_",fetchFn:H=fetch}=$;if(q.environment!=="test")throw new Z4(`重放目标企业「${q.name}」(${q.id}) 的环境为「${q.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${Y.id} <testCorpId>`);let Z=await g2(J),X=(Array.isArray(Z.features)?Z.features:[]).find((u)=>u?.code==="ai-approval"),L=typeof X?.balance==="number"?X.balance:0,w=typeof X?.deductionAmount==="number"&&X.deductionAmount>0?X.deductionAmount:120,F=U*w;if(L<F)throw new Z4(`测试企业「${q.name}」AI 审批额度不足:当前剩余 ${L} 点,本次回归抽样 ${U} 笔需要约 ${F} 点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${q.id}」充值 AI 审批额度,或降低抽样笔数 (--samples ${Math.max(1,Math.floor(L/w))})`);let O=await x4(z,{limit:U,status:"completed"}),P=Array.isArray(O.records)?O.records:[];if(P.length===0){let u=await x4(z,{limit:U});P=Array.isArray(u.records)?u.records:[]}if(P.length===0)throw new Z4(`在母企业「${Y.name}」(${Y.id}) 中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(P=P.slice(0,U),I){let u=P.map((p)=>{let d=p.sourceDocumentSN??p.id,q0=p?.result?.decision??p.aiDecision??p?.decision,t=dd(q0),H0=p?.result?.summary??p.aiSummary;return{sn:d,sourceRecordId:p.id,prodDecision:t,prodSummary:H0,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:q.id,name:q.name,environment:q.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:L,deductionAmount:w,estimatedRequired:F},metrics:{sampleCount:u.length,successCount:u.length,failureCount:0,matchCount:u.length,flipCount:0,concordanceRate:1},flips:[],records:u}}let B=await li(J,q),A=[];for(let u of P){let p=Date.now(),d=u.sourceDocumentSN??u.id,q0=dd(u?.result?.decision??u.aiDecision??u?.decision),t=u?.result?.summary??u.aiSummary;try{let H0=await e1(z,u.id),L0=`${G}${d}`,T0=di(H0,{snPrefix:G,docIdPrefix:G});await mi(B.incomingDocumentWebhook.url,B.secret,T0,H,w6(q.seal));let C0=null,j0=Date.now();while(Date.now()-j0<K){await new Promise((a0)=>setTimeout(a0,Q));let C1=await x4(J,{sourceDocumentSN:L0,limit:1});if(C1.records&&C1.records.length>0){let a0=C1.records[0];if(a0.status==="completed"||a0.status==="failed"){C0=a0;break}}}if(!C0){A.push({sn:d,sourceRecordId:u.id,prodDecision:q0,prodSummary:t,status:"FAILED",error:`测试租户单据审核超时 (${Math.round(K/1000)}s 未完成)`,durationMs:Date.now()-p});continue}let i0=dd(C0?.result?.decision??C0.aiDecision??C0?.decision??(C0.status==="completed"?"APPROVE":"ERROR")),K0=C0?.result?.summary??C0.aiSummary,v0=q0===i0,f0=v0?"MATCHED":"FLIPPED",c0={sn:d,sourceRecordId:u.id,prodDecision:q0,prodSummary:t,testRecordId:C0.id,testDecision:i0,testSummary:K0,status:f0,durationMs:Date.now()-p};if(!v0)c0.diff={from:q0,to:i0,reasonDiff:K0&&t&&K0!==t?`生产: ${t.slice(0,60)}... -> 测试: ${K0.slice(0,60)}...`:void 0};A.push(c0)}catch(H0){A.push({sn:d,sourceRecordId:u.id,prodDecision:q0,prodSummary:t,status:"FAILED",error:H0 instanceof Error?H0.message:String(H0),durationMs:Date.now()-p})}}let E=A.filter((u)=>u.status==="MATCHED"||u.status==="FLIPPED"),y=A.filter((u)=>u.status==="MATCHED"),v=A.filter((u)=>u.status==="FLIPPED"),k=A.filter((u)=>u.status==="FAILED").length,C=y.length,c=v.length,n=C+c,g=n>0?C/n:0,b=c>0,i=b?"REGRESSIONS_DETECTED":"CLEAN",$0=!b&&k===0,j;try{let u=await g2(J),d=(Array.isArray(u.features)?u.features:[]).find((q0)=>q0?.code==="ai-approval");if(typeof d?.balance==="number")j=d.balance}catch{}return{ok:!b&&k===0,verdict:i,safeToPublish:$0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:q.id,name:q.name,environment:q.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:L,deductionAmount:w,estimatedRequired:F,balanceAfter:j},metrics:{sampleCount:A.length,successCount:E.length,failureCount:k,matchCount:C,flipCount:c,concordanceRate:Number(g.toFixed(4))},flips:v,records:A}}function qS0($){let{sourceCorp:Y,targetCorp:q,verdict:z,safeToPublish:J,metrics:U,quota:I,flips:Q,records:K}=$,G=z==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":z==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",H=["",`\uD83E\uDDEA [Seal Use Test] 规则回归测试矩阵: 生产「${Y.name}」-> 测试靶场「${q.name}」`,` 判定: ${G} · 准许发布: ${J?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),` 样本总数: ${U.sampleCount} | 一致通过: ${U.matchCount} | 决策翻转: ${U.flipCount} | 异常失败: ${U.failureCount}`,` 一致率: ${(U.concordanceRate*100).toFixed(1)}% | 消耗预估: ${I.estimatedRequired} 点 (余量: ${I.balanceBefore}${I.balanceAfter!==void 0?` -> ${I.balanceAfter}`:""})`," "+"─".repeat(65)];if(Q.length>0){H.push(` ⚠️ 决策翻转清单 (${Q.length} 笔单据在新规则下结果改变):`);for(let Z of Q)if(H.push(` • 单据 [${Z.sn}]: 原生产判定「${Z.prodDecision}」 ➔ 测试新判定「${Z.testDecision}」`),Z.diff?.reasonDiff)H.push(` 理由差异: ${Z.diff.reasonDiff}`);H.push(" "+"─".repeat(65)),H.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(z==="CLEAN")H.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100% Line truncated
`)}async function md($,Y,q){let z=($??Y??"regression").toLowerCase();if(z==="regression"||z==="regress"||z==="matrix"){let J=T(q.options.corp)??(Y&&Y!==z?Y:void 0),U=W1(J),I=U,Q=U;if(U.environment==="test"){Q=U;let P=T(q.options["prod-corp"])??T(q.options.prod)??U.prodCorpId;if(!P)throw new Z4(`测试企业「${U.name}」(${U.id}) 未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-use corps bind-test <prodCorpId> ${U.id}`);I=W1(P)}else{I=U;let P=T(q.options["test-corp"])??T(q.options.test)??U.testCorpId;if(!P)throw new Z4(`生产企业「${U.name}」(${U.id}) 未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${U.id} <testCorpId>`);Q=W1(P)}let K=await Z1(I),G=await Z1(Q),H=g0(q.options.samples)??g0(q.options.limit)??g0(q.options.n)??10,Z=J0(q.options["dry-run"]),V=J0(q.options["fail-on-flips"]),X=g0(q.options["poll-interval"])??2000,L=g0(q.options.timeout)??45000,w=T(q.options["sn-prefix"])??"REG_",F=await YS0({sourceCorp:I,targetCorp:Q,sourceClient:K,targetClient:G,samples:H,dryRun:Z,pollIntervalMs:X,timeoutMs:L,snPrefix:w,failOnFlips:V});if(!(J0(q.options.quiet)||J0(q.options.silent)))console.error(qS0(F));if(E0(F),V&&!F.ok)throw new Z4(`回归测试发现 ${F.metrics.flipCount} 笔单据决策翻转,已按 --fail-on-flips 策略非零终止。`,1);return}throw new Z4(`未知的 test 子命令: "${z}"。
可用子命令: seal-use test regression [--corp <id>] [--samples <N>] [--dry-run]`,2,"seal-use test regression --help")}p4();R4();o1();async function zS0($,Y,q,z){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await A0($,Y,q,C8(z.json),F0(z.options))}iP();o1();function JS0(){E0(qW.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as Wi1,mkdirSync as Xi1,renameSync as ld,rmSync as Vi1,unlinkSync as GS0,writeFileSync as US0}from"node:fs";import{dirname as Li1,join as IS0}from"node:path";import{spawnSync as jq}from"node:child_process";function XA($=process.execPath,Y=import.meta.url){if(Y.includes("/$bunfs/")||Y.includes("\\$bunfs\\"))return!0;let q=$.toLowerCase().replace(/\\/g,"/");return!q.endsWith("/bun")&&!q.endsWith("/bun.exe")&&!q.endsWith("/node")&&!q.endsWith("/node.exe")}o1();var HS0="yunyingk/seal-use",VW="yunyingk/seal-home";var wi1="SEAL_USE_GITHUB_REPO",Fi1="SEAL_HOME_GITHUB_REPO";async function ZS0($,Y={}){let q={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:cd,version:Q1,launcher:$.launcher},z=Y.repo||process.env[wi1]?.trim()||process.env[Fi1]?.trim()||HS0,J=Y.targetVersion?.trim(),U=J&&J.toLowerCase()!=="latest"?J:void 0;if(U){let A=U.replace(/^v/,""),E=WS0(A,Q1);if(E<0)if(!Av&&Y.force);else{E0({updated:!1,currentVersion:Q1,targetVersion:A,mode:XA()?"binary":"source",message:!Av?`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(E===0&&!Y.force){E0({updated:!1,currentVersion:Q1,targetVersion:A,mode:XA()?"binary":"source",message:`seal-use is already at version v${Q1}. Use --force to reinstall.`});return}}if(Y.changelogOnly){let A=await od(z,Y.limit??10);E0({currentVersion:Q1,totalQueried:A.length,releases:A.map((E)=>({version:E.version,tagName:E.tagName,publishedAt:E.publishedAt,author:E.author,releaseNotes:E.notes,releaseUrl:E.htmlUrl,isCurrent:E.version===Q1,isNewer:XW(E.version,Q1)}))});return}if(!XA()){if(Y.checkOnly){let E=await od(z,30),y=E[0],v=y?.version??Q1,k=E.find((n)=>n.version===Q1),C=XW(v,Q1),c=E.filter((n)=>XW(n.version,Q1));E0({updated:!1,updateAvailable:C,currentVersion:Q1,currentVersionPublishedAt:k?.publishedAt,latestVersion:v,latestVersionPublishedAt:y?.publishedAt,behindCount:c.length,pendingReleases:c.map((n)=>({version:n.version,tagName:n.tagName,publishedAt:n.publishedAt,author:n.author,releaseNotes:n.notes,releaseUrl:n.htmlUrl})),releaseNotes:y?.notes??"",releaseUrl:y?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let A=RI(q).running;if(A)await Eq("stop",q);try{KS0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(E){console.error(`git pull skipped: ${E instanceof Error?E.message:String(E)}`)}if(KS0("bun",["install"],{cwd:$.appRoot}),A)await Eq("start",q);E0({updated:!0,serviceRestarted:A,version:Q1,mode:"source"});return}let I=Oi1(),Q=Mi1(),K=await od(z,30),G=U?K.find((A)=>A.version===U||A.tagName===U||A.tagName===`v${U}`)??await QS0(z,U):K[0]??await QS0(z);if(!G){E0({updated:!1,currentVersion:Q1,mode:"binary",message:`Failed to query releases from repository '${z}'`});return}let H=G.version,Z=K.find((A)=>A.version===Q1),V=XW(H,Q1),X=V||Boolean(Y.force),L=K.filter((A)=>XW(A.version,Q1));if(Y.checkOnly){E0({updated:!1,updateAvailable:V,currentVersion:Q1,currentVersionPublishedAt:Z?.publishedAt,latestVersion:H,latestVersionPublishedAt:G.publishedAt,behindCount:L.length,pendingReleases:L.map((A)=>({version:A.version,tagName:A.tagName,publishedAt:A.publishedAt,author:A.author,releaseNotes:A.notes,releaseUrl:A.htmlUrl})),releaseNotes:G.notes,releaseUrl:G.htmlUrl,mode:"binary"});return}if(!X){E0({updated:!1,currentVersion:Q1,currentVersionPublishedAt:Z?.publishedAt,latestVersion:H,latestVersionPublishedAt:G.publishedAt,mode:"binary",message:`seal-use is already up to date (v${Q1})`});return}let w=Ni1(G.assets,I,Q);if(!w)throw Error(`No compatible binary found for ${I}-${Q} in release v${H}. Available assets: ${G.assets.map((A)=>A.name).join(", ")}`);let F=RI(q).running;if(F)await Eq("stop",q);let O=process.execPath,P=Li1(O),B=IS0(P,`.tmp-update-${Date.now()}`);Xi1(B,{recursive:!0});try{let A=IS0(B,w.name);await Di1(w.downloadUrl,A,G.tagName,w.name);let E=A;if(w.name.endsWith(".tar.gz")||w.name.endsWith(".tgz"))E=Pi1(A,B,I);else if(w.name.endsWith(".zip"))E=Ai1(A,B,I);if(Wi1(E,493),process.platform==="darwin")try{jq("/usr/bin/codesign",["--remove-signature",E],{stdio:"ignore"}),jq("/usr/bin/codesign",["--force","--sign","-",E],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let v=`${O}.old.${Date.now()}`;try{ld(O,v)}catch{}ld(E,O)}else ld(E,O);if(F)await Eq("start",q);let y=vd();E0({updated:!0,fromVersion:Q1,toVersion:H,serviceRestarted:F,skillSynced:y.synced?y.targetDir:!1,mode:"binary"})}finally{try{Vi1(B,{recursive:!0,force:!0})}catch{}}}function Oi1(){if(process.platform==="darwin")retur Line truncated
`)}catch{}}async function Di1($,Y,q,z){let J=rd(),U=[],I=q?q.startsWith("v")?q:`v${q}`:void 0,Q=z||$.split("/").pop()||"";if(J!=="github"){if(I&&Q)U.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${I}/${Q}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${I}/${Q}`);if($.startsWith("https://git.ying-qing.cn"))U.push($)}if(J!=="gitea")if(I&&Q){let w=`https://github.com/${HS0}/releases/download/${I}/${Q}`;if(!process.env.CI)U.push(`https://ghfast.top/${w}`,`https://gh.ddlc.top/${w}`);U.push(w)}else if($.includes("github.com")){if(!process.env.CI)U.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);U.push($)}else U.push($);let K=Array.from(new Set(U)),G,H=6000,Z=6000,V=307200,X=1e4,L=180000;for(let w=0;w<K.length;w++){let F=K[w],O=new AbortController,P="",B=(v)=>{P=v;try{O.abort()}catch{}},A=setTimeout(()=>{B("Connection timed out (no response headers within 6s)")},H),E,y;try{VA(`==> [${w+1}/${K.length}] Downloading via: ${F}`);let v=await fetch(F,{signal:O.signal});if(A)clearTimeout(A),A=void 0;if(!v.ok)throw Error(`HTTP ${v.status} ${v.statusText}`);E=setTimeout(()=>{B("Overall download time exceeded 3 minutes")},L);let k=Number(v.headers.get("content-length"))||0,C=v.body?.getReader();if(!C){let i=Buffer.from(await v.arrayBuffer());if(i.length<1000)throw Error(`Downloaded content is suspiciously small (${i.length} bytes)`);US0(Y,i),VA(`✓ Download succeeded (${(i.length/1024/1024).toFixed(1)} MB)`);return}let c=[],n=0,g=0;y=setTimeout(()=>{if(n<V){let i=(n/1024).toFixed(1);B(`Initial transfer too slow (${i} KB < 300 KB in 6s), switching mirror...`)}},Z);while(!0){let i=C.read(),$0,j=new Promise((q0,t)=>{$0=setTimeout(()=>{t(Error("Data transfer stalled (no chunk received for 10s)"))},X)}),u;try{u=await Promise.race([i,j])}finally{if($0)clearTimeout($0)}let{done:p,value:d}=u;if(p)break;if(d){if(c.push(d),n+=d.length,y&&n>=V)clearTimeout(y),y=void 0;let q0=Date.now();if(q0-g>200){g=q0;let t=k?Math.round(n/k*100):0,H0=(n/1048576).toFixed(1),L0=k?(k/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${t}% (${H0} / ${L0} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let b=Buffer.concat(c);if(b.length<1000)throw Error(`Downloaded content is suspiciously small (${b.length} bytes)`);US0(Y,b),VA(`✓ Download completed successfully (${(b.length/1024/1024).toFixed(1)} MB)`);return}catch(v){if(A)clearTimeout(A);if(y)clearTimeout(y);if(E)clearTimeout(E);let k=P||(v instanceof Error?v.message:String(v));G=Error(k),VA(`
↳ Mirror failed: ${G.message}`)}finally{if(A)clearTimeout(A);if(y)clearTimeout(y);if(E)clearTimeout(E)}}throw Error(`Failed to download asset from all mirrors: ${G?.message}`)}function Pi1($,Y,q){let z=jq("tar",["-xzf",$,"-C",Y],{stdio:"pipe"});if(z.status!==0)throw Error(`Failed to extract tar archive: ${z.stderr.toString()}`);GS0($);let J=q==="windows"?"seal-use.exe":"seal-use",U=jq("find",[Y,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),I=U.find((Q)=>Q.endsWith(`/${J}`)||Q.endsWith(J));if(I)return I;return U[0]||$}function Ai1($,Y,q){let z=jq("unzip",["-q","-o",$,"-d",Y],{stdio:"pipe"});if(z.status!==0)throw Error(`Failed to extract zip archive: ${z.stderr.toString()}`);GS0($);let J=q==="windows"?"seal-use.exe":"seal-use",U=jq("find",[Y,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),I=U.find((Q)=>Q.endsWith(`/${J}`)||Q.endsWith(J));if(I)return I;return U[0]||$}function WS0($,Y){let q=$.replace(/^v/,"").split(".").map((J)=>Number.parseInt(J,10)||0),z=Y.replace(/^v/,"").split(".").map((J)=>Number.parseInt(J,10)||0);for(let J=0;J<Math.max(q.length,z.length);J++){let U=q[J]??0,I=z[J]??0;if(U>I)return 1;if(U<I)return-1}return 0}function XW($,Y){return WS0($,Y)>0}function KS0($,Y,q={}){let z=jq($,Y,{cwd:q.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(z.stdout)console.error(z.stdout.trimEnd());if(z.stderr)console.error(z.stderr.trimEnd());if(z.status!==0)throw Error(`${$} ${Y.join(" ")} failed with status ${z.status}`)}p4();R4();o1();async function XS0($,Y,q,z,J){if($==="create"){let U=T(J.options.name)??Y,I=T(J.options.phone);if(!U||!I)throw Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");let Q=T(J.options.dept)??T(J.options.departmentId);await A0("seal_user_create",q,z,{name:U,phone:I,departmentIds:Q?[Q]:void 0},F0(J.options));return}if($==="reset-password"){let U=Y??T(J.options.userId);if(!U)throw Error("Usage: seal-use users reset-password <userId>");await A0("seal_user_reset_password",q,z,{userId:U},F0(J.options));return}if($==="search"||$==="list"){let U=Y??T(J.options.keyword)??T(J.options.query)??"";await A0("seal_user_search",q,z,{keyword:U},F0(J.options));return}if($==="get"){let U=Y??T(J.options.userId);if(!U)throw Error("Usage: seal-use users get <userId>");await A0("seal_user_get",q,z,{userId:U},F0(J.options));return}if($==="delete"){let U=Y??T(J.options.userId);if(!U)throw Error("Usage: seal-use users delete <userId>");await A0("seal_user_delete",q,z,{userId:U},F0(J.options));return}if($==="activate"){let U=Y??T(J.options.userId);if(!U)throw Error("Usage: seal-use users activate <userId>");await A0("seal_user_activate",q,z,{userId:U},F0(J.options));return}if($==="delegation"||$==="impersonate"){let U=Y??T(J.options.userId)??T(J.options.phone);if(!U)throw Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");let I=T(J.options.note);await A0("seal_user_delegation_create",q,z,{userIdOrPhone:U,note:I},F0(J.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}V$();p4();R4();Vd();o1();var VS0=sd(sd(sd(Ti1(import.meta.url)))),Ei1=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"]),ji1=new Set(["http","server","web","mcp"]);function _i1($){if(!$.length)return!1;let Y=$[0]?.toLowerCase(),q=$[1]?.toLowerCase();if(Y&&ji1.has(Y))return!0;if((Y==="service"||Y==="daemon")&&q==="run")return!0;return!1}var LS0=Promise.resolve();function ZW($,Y={}){if(_i1($))return wS0($,Y);let q=LS0.then(()=>wS0($,Y));return LS0=q.then(()=>{return},()=>{return}),q}async function wS0($,Y){let q=[],z=[],J=console.log,U=console.error,I={appRoot:Y.appRoot??VS0,entryFile:Y.entryFile??Bi1(Y.appRoot??VS0,"src","cli.ts"),launcher:Y.launcher};console.log=(...Q)=>{q.push(Ld(Q))},console.error=(...Q)=>{z.push(Ld(Q))};try{return await Ri1($,I),{stdout:JW(q),stderr:JW(z),isError:!1,exitCode:0}}catch(Q){let K=UW(Q instanceof Error?Q.message:String(Q)),G=wD(Q);if(z.push(K),G.nextAction&&!K.includes("Next action:"))z.push(`\uD83D\uDC49 Next action: ${G.nextAction}`);return{stdout:JW(q),stderr:JW(z),isError:!0,exitCode:G.exitCode}}finally{console.log=J,console.error=U}}async function Ri1($,Y){let q=Kd($),[z,J,U]=q.command;if(z==="version"||z==="v"||Boolean(q.options.version)||Boolean(q.options.v)||Boolean(q.options.V)){E0(FK);return}let I=jv0(q);if(I.isHelp){vv0(I.target);return}if(!z||!Ei1.has(z))throw Error(`Unknown command: ${q.command.join(" ")}. Run 'seal-use help' for available commands.`);if(z==="webhook"&&(J==="resource-pack"||J==="pack"||J==="material-pack")&&U==="preview"){let G=q.command[3]??T(q.options.file)??T(q.options.input);if(!G)throw Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");await Sv0(G,BI(q.options));return}if(z==="openapi"){bg0(q);return}if(z==="mcp-config"){kd();return}if(z==="skill"){eg0(J,U,q);return}if(z==="mcp"||z==="server"){await fg0(J,q);return}if(z==="probe"){await dg0(J,U,q);return}if(z==="doctor"){await gg0(J,U,q);return}if(z==="test"){await md(J,U,q);return}if(z==="config"){Jg0(J,U,q);return}if(z==="service"){await pd(J,Y,q);return}if(z==="stop"){await pd("stop",Y,q);return}if(z==="http"||z==="serve"){await kg0(q);return}if(z==="update"||z==="changelog"){let G=z==="changelog"||J==="changelog"||J==="log"||J==="history"||J0(q.options.changelog)===!0,H=J==="check"||J0(q.options.check)===!0||J0(q.options["check-only"])===!0,Z=T(q.options.version)??T(q.options.tag)??(!G&&!H&&J&&!J.startsWith("-")?J:void 0);await ZS0 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 ui1=Boolean(m.main==m.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&FS0(process.argv[1])===FS0(P3));if(ui1)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await ki1();else ud().catch(($)=>{console.error($),process.exitCode=1});export{xd as tokenizeCommand,ud as startServer,Si1 as resolveMcpEnabled,yi1 as createServer,hi1 as SEAL_MCP_ENABLED_ENV,vi1 as SEAL_CLI_TOOL_NAME,gi1 as LEGACY_SEAL_MCP_ENABLED_ENV};
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "seal-use Wrapped API",
"version": "0.10.22",
"version": "0.10.24",
"description": "Planned HTTP contract for the seal-use wrapped backend API.\n\nThese endpoints describe the intended stable API for frontend developers and agents once\nthe HTTP adapter is implemented.\nThey are not the raw downstream Seal endpoints. seal-use is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n"
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: seal-use Wrapped API
version: 0.10.22
version: 0.10.24
description: |
Planned HTTP contract for the seal-use wrapped backend API.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.22",
"version": "0.10.24",
"type": "module",
"module": "src/server.ts",
"bin": {
+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`);
+12 -7
View File
@@ -1,12 +1,12 @@
---
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.24: 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.24
short-description: Seal tenant and Hose approval automation (v0.10.24)
---
# Seal Use (v0.10.22)
# Seal Use (v0.10.24)
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.
@@ -43,8 +43,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 +89,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>`.
@@ -159,6 +160,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
+13 -3
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:
@@ -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>;
+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 密钥,不支持此命令。"
}
]
},
+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") {
+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
};
}
+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>;
+152 -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,75 @@ 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);
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 +389,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 });
}
}
});
});
+417 -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,9 @@ export interface ApprovalRunsExportResult {
rejectReasonCount: number;
fileSizeBytes: number;
exportedAt: string;
driftCount?: number;
excludedDeletedCount?: number;
excludedSimulationCount?: number;
}
export function normalizeTimestamp(val?: string | number, endOfDay = false): string | undefined {
@@ -249,12 +267,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 +306,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 +333,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 +378,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 +583,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 +596,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 },
@@ -464,9 +645,104 @@ export async function exportApprovalRunsToExcel(
const statusCounts: Record<string, number> = {};
let rejectReasonCount = 0;
let driftCount = 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);
if (align.auditDrift) driftCount++;
}
} 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 +777,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 +810,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 +859,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 +874,12 @@ export async function exportApprovalRunsToExcel(
thinkingDepth: "标准",
manualStatus,
humanRejectReason,
...(withFlow
? {
eHumanAction,
eHumanComment
}
: {}),
createdAt: createdAtStr,
duration: durationStr,
hitRuleCount: hitRuleIds.length,
@@ -619,21 +913,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 +957,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 +1019,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 +1037,14 @@ 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(),
driftCount,
excludedDeletedCount,
excludedSimulationCount
};
}
+154
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 引用或命中的规则及应用分析",